blob: e8762dc96fb64fcba7032cfcef48b63d71055574 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- LoopUnswitch.cpp - Hoist loop-invariant conditionals in loop ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass transforms loops that contain branches on loop-invariant conditions
11// to have multiple loops. For example, it turns the left into the right code:
12//
13// for (...) if (lic)
14// A for (...)
15// if (lic) A; B; C
16// B else
17// C for (...)
18// A; C
19//
20// This can increase the size of the code exponentially (doubling it every time
21// a loop is unswitched) so we only unswitch if the resultant code will be
22// smaller than a threshold.
23//
24// This pass expects LICM to be run before it to hoist invariant conditions out
25// of the loop, to make the unswitching opportunity obvious.
26//
27//===----------------------------------------------------------------------===//
28
29#define DEBUG_TYPE "loop-unswitch"
30#include "llvm/Transforms/Scalar.h"
31#include "llvm/Constants.h"
32#include "llvm/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/ADT/PostOrderIterator.h"
45#include "llvm/Support/CommandLine.h"
46#include "llvm/Support/Compiler.h"
47#include "llvm/Support/Debug.h"
48#include <algorithm>
49#include <set>
50using namespace llvm;
51
52STATISTIC(NumBranches, "Number of branches unswitched");
53STATISTIC(NumSwitches, "Number of switches unswitched");
54STATISTIC(NumSelects , "Number of selects unswitched");
55STATISTIC(NumTrivial , "Number of unswitches that are trivial");
56STATISTIC(NumSimplify, "Number of simplifications of unswitched code");
57
58namespace {
59 cl::opt<unsigned>
60 Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"),
61 cl::init(10), cl::Hidden);
62
63 class VISIBILITY_HIDDEN LoopUnswitch : public LoopPass {
64 LoopInfo *LI; // Loop information
65 LPPassManager *LPM;
66
67 // LoopProcessWorklist - Used to check if second loop needs processing
68 // after RewriteLoopBodyWithConditionConstant rewrites first loop.
69 std::vector<Loop*> LoopProcessWorklist;
70 SmallPtrSet<Value *,8> UnswitchedVals;
71
72 bool OptimizeForSize;
Devang Pateleec0d372007-07-30 23:07:10 +000073 bool redoLoop;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000074 public:
75 static char ID; // Pass ID, replacement for typeid
76 LoopUnswitch(bool Os = false) :
Devang Pateleec0d372007-07-30 23:07:10 +000077 LoopPass((intptr_t)&ID), OptimizeForSize(Os), redoLoop(false) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +000078
79 bool runOnLoop(Loop *L, LPPassManager &LPM);
Devang Pateleec0d372007-07-30 23:07:10 +000080 bool processLoop(Loop *L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000081
82 /// This transformation requires natural loop information & requires that
83 /// loop preheaders be inserted into the CFG...
84 ///
85 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
86 AU.addRequiredID(LoopSimplifyID);
87 AU.addPreservedID(LoopSimplifyID);
88 AU.addRequired<LoopInfo>();
89 AU.addPreserved<LoopInfo>();
90 AU.addRequiredID(LCSSAID);
91 }
92
93 private:
94 /// RemoveLoopFromWorklist - If the specified loop is on the loop worklist,
95 /// remove it.
96 void RemoveLoopFromWorklist(Loop *L) {
97 std::vector<Loop*>::iterator I = std::find(LoopProcessWorklist.begin(),
98 LoopProcessWorklist.end(), L);
99 if (I != LoopProcessWorklist.end())
100 LoopProcessWorklist.erase(I);
101 }
102
103 bool UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L);
104 unsigned getLoopUnswitchCost(Loop *L, Value *LIC);
105 void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
106 BasicBlock *ExitBlock);
107 void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L);
108
109 void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
110 Constant *Val, bool isEqual);
111
112 void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
113 BasicBlock *TrueDest,
114 BasicBlock *FalseDest,
115 Instruction *InsertPt);
116
117 void SimplifyCode(std::vector<Instruction*> &Worklist);
118 void RemoveBlockIfDead(BasicBlock *BB,
119 std::vector<Instruction*> &Worklist);
120 void RemoveLoopFromHierarchy(Loop *L);
121 };
122 char LoopUnswitch::ID = 0;
123 RegisterPass<LoopUnswitch> X("loop-unswitch", "Unswitch loops");
124}
125
126LoopPass *llvm::createLoopUnswitchPass(bool Os) {
127 return new LoopUnswitch(Os);
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.
133static 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
156bool LoopUnswitch::runOnLoop(Loop *L, LPPassManager &LPM_Ref) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000157 LI = &getAnalysis<LoopInfo>();
158 LPM = &LPM_Ref;
159 bool Changed = false;
Devang Pateleec0d372007-07-30 23:07:10 +0000160
161 do {
162 redoLoop = false;
163 Changed |= processLoop(L);
164 } while(redoLoop);
165
166 return Changed;
167}
168
169/// processLoop - Do actual work and unswitch loop if possible and profitable.
170bool LoopUnswitch::processLoop(Loop *L) {
171 assert(L->isLCSSAForm());
172 bool Changed = false;
173
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000174 // Loop over all of the basic blocks in the loop. If we find an interior
175 // block that is branching on a loop-invariant condition, we can unswitch this
176 // loop.
177 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
178 I != E; ++I) {
179 TerminatorInst *TI = (*I)->getTerminator();
180 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
181 // If this isn't branching on an invariant condition, we can't unswitch
182 // it.
183 if (BI->isConditional()) {
184 // See if this, or some part of it, is loop invariant. If so, we can
185 // unswitch on it if we desire.
186 Value *LoopCond = FindLIVLoopCondition(BI->getCondition(), L, Changed);
187 if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(),
188 L)) {
189 ++NumBranches;
190 return true;
191 }
192 }
193 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
194 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
195 if (LoopCond && SI->getNumCases() > 1) {
196 // Find a value to unswitch on:
197 // FIXME: this should chose the most expensive case!
198 Constant *UnswitchVal = SI->getCaseValue(1);
199 // Do not process same value again and again.
200 if (!UnswitchedVals.insert(UnswitchVal))
201 continue;
202
203 if (UnswitchIfProfitable(LoopCond, UnswitchVal, L)) {
204 ++NumSwitches;
205 return true;
206 }
207 }
208 }
209
210 // Scan the instructions to check for unswitchable values.
211 for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
212 BBI != E; ++BBI)
213 if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
214 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
215 if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(),
216 L)) {
217 ++NumSelects;
218 return true;
219 }
220 }
221 }
222
223 assert(L->isLCSSAForm());
224
225 return Changed;
226}
227
228/// isTrivialLoopExitBlock - Check to see if all paths from BB either:
229/// 1. Exit the loop with no side effects.
230/// 2. Branch to the latch block with no side-effects.
231///
232/// If these conditions are true, we return true and set ExitBB to the block we
233/// exit through.
234///
235static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
236 BasicBlock *&ExitBB,
237 std::set<BasicBlock*> &Visited) {
238 if (!Visited.insert(BB).second) {
239 // Already visited and Ok, end of recursion.
240 return true;
241 } else if (!L->contains(BB)) {
242 // Otherwise, this is a loop exit, this is fine so long as this is the
243 // first exit.
244 if (ExitBB != 0) return false;
245 ExitBB = BB;
246 return true;
247 }
248
249 // Otherwise, this is an unvisited intra-loop node. Check all successors.
250 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
251 // Check to see if the successor is a trivial loop exit.
252 if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
253 return false;
254 }
255
256 // Okay, everything after this looks good, check to make sure that this block
257 // doesn't include any side effects.
258 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
259 if (I->mayWriteToMemory())
260 return false;
261
262 return true;
263}
264
265/// isTrivialLoopExitBlock - Return true if the specified block unconditionally
266/// leads to an exit from the specified loop, and has no side-effects in the
267/// process. If so, return the block that is exited to, otherwise return null.
268static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
269 std::set<BasicBlock*> Visited;
270 Visited.insert(L->getHeader()); // Branches to header are ok.
271 BasicBlock *ExitBB = 0;
272 if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
273 return ExitBB;
274 return 0;
275}
276
277/// IsTrivialUnswitchCondition - Check to see if this unswitch condition is
278/// trivial: that is, that the condition controls whether or not the loop does
279/// anything at all. If this is a trivial condition, unswitching produces no
280/// code duplications (equivalently, it produces a simpler loop and a new empty
281/// loop, which gets deleted).
282///
283/// If this is a trivial condition, return true, otherwise return false. When
284/// returning true, this sets Cond and Val to the condition that controls the
285/// trivial condition: when Cond dynamically equals Val, the loop is known to
286/// exit. Finally, this sets LoopExit to the BB that the loop exits to when
287/// Cond == Val.
288///
289static bool IsTrivialUnswitchCondition(Loop *L, Value *Cond, Constant **Val = 0,
290 BasicBlock **LoopExit = 0) {
291 BasicBlock *Header = L->getHeader();
292 TerminatorInst *HeaderTerm = Header->getTerminator();
293
294 BasicBlock *LoopExitBB = 0;
295 if (BranchInst *BI = dyn_cast<BranchInst>(HeaderTerm)) {
296 // If the header block doesn't end with a conditional branch on Cond, we
297 // can't handle it.
298 if (!BI->isConditional() || BI->getCondition() != Cond)
299 return false;
300
301 // Check to see if a successor of the branch is guaranteed to go to the
302 // latch block or exit through a one exit block without having any
303 // side-effects. If so, determine the value of Cond that causes it to do
304 // this.
305 if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(0)))) {
306 if (Val) *Val = ConstantInt::getTrue();
307 } else if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(1)))) {
308 if (Val) *Val = ConstantInt::getFalse();
309 }
310 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(HeaderTerm)) {
311 // If this isn't a switch on Cond, we can't handle it.
312 if (SI->getCondition() != Cond) return false;
313
314 // Check to see if a successor of the switch is guaranteed to go to the
315 // latch block or exit through a one exit block without having any
316 // side-effects. If so, determine the value of Cond that causes it to do
317 // this. Note that we can't trivially unswitch on the default case.
318 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
319 if ((LoopExitBB = isTrivialLoopExitBlock(L, SI->getSuccessor(i)))) {
320 // Okay, we found a trivial case, remember the value that is trivial.
321 if (Val) *Val = SI->getCaseValue(i);
322 break;
323 }
324 }
325
326 // If we didn't find a single unique LoopExit block, or if the loop exit block
327 // contains phi nodes, this isn't trivial.
328 if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
329 return false; // Can't handle this.
330
331 if (LoopExit) *LoopExit = LoopExitBB;
332
333 // We already know that nothing uses any scalar values defined inside of this
334 // loop. As such, we just have to check to see if this loop will execute any
335 // side-effecting instructions (e.g. stores, calls, volatile loads) in the
336 // part of the loop that the code *would* execute. We already checked the
337 // tail, check the header now.
338 for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I)
339 if (I->mayWriteToMemory())
340 return false;
341 return true;
342}
343
344/// getLoopUnswitchCost - Return the cost (code size growth) that will happen if
345/// we choose to unswitch the specified loop on the specified value.
346///
347unsigned LoopUnswitch::getLoopUnswitchCost(Loop *L, Value *LIC) {
348 // If the condition is trivial, always unswitch. There is no code growth for
349 // this case.
350 if (IsTrivialUnswitchCondition(L, LIC))
351 return 0;
352
353 // FIXME: This is really overly conservative. However, more liberal
354 // estimations have thus far resulted in excessive unswitching, which is bad
355 // both in compile time and in code size. This should be replaced once
356 // someone figures out how a good estimation.
357 return L->getBlocks().size();
358
359 unsigned Cost = 0;
360 // FIXME: this is brain dead. It should take into consideration code
361 // shrinkage.
362 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
363 I != E; ++I) {
364 BasicBlock *BB = *I;
365 // Do not include empty blocks in the cost calculation. This happen due to
366 // loop canonicalization and will be removed.
367 if (BB->begin() == BasicBlock::iterator(BB->getTerminator()))
368 continue;
369
370 // Count basic blocks.
371 ++Cost;
372 }
373
374 return Cost;
375}
376
377/// UnswitchIfProfitable - We have found that we can unswitch L when
378/// LoopCond == Val to simplify the loop. If we decide that this is profitable,
379/// unswitch the loop, reprocess the pieces, then return true.
380bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L){
381 // Check to see if it would be profitable to unswitch this loop.
382 unsigned Cost = getLoopUnswitchCost(L, LoopCond);
383
384 // Do not do non-trivial unswitch while optimizing for size.
385 if (Cost && OptimizeForSize)
386 return false;
387
388 if (Cost > Threshold) {
389 // FIXME: this should estimate growth by the amount of code shared by the
390 // resultant unswitched loops.
391 //
392 DOUT << "NOT unswitching loop %"
393 << L->getHeader()->getName() << ", cost too high: "
394 << L->getBlocks().size() << "\n";
395 return false;
396 }
397
398 // If this is a trivial condition to unswitch (which results in no code
399 // duplication), do it now.
400 Constant *CondVal;
401 BasicBlock *ExitBlock;
402 if (IsTrivialUnswitchCondition(L, LoopCond, &CondVal, &ExitBlock)) {
403 UnswitchTrivialCondition(L, LoopCond, CondVal, ExitBlock);
404 } else {
405 UnswitchNontrivialCondition(LoopCond, Val, L);
406 }
407
408 return true;
409}
410
411// RemapInstruction - Convert the instruction operands from referencing the
412// current values into those specified by ValueMap.
413//
414static inline void RemapInstruction(Instruction *I,
415 DenseMap<const Value *, Value*> &ValueMap) {
416 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
417 Value *Op = I->getOperand(op);
418 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(Op);
419 if (It != ValueMap.end()) Op = It->second;
420 I->setOperand(op, Op);
421 }
422}
423
424// CloneDomInfo - NewBB is cloned from Orig basic block. Now clone Dominator Info.
Devang Patelf9739582007-07-18 23:48:20 +0000425//
426// If Orig block's immediate dominator is mapped in VM then use corresponding
427// immediate dominator from the map. Otherwise Orig block's dominator is also
428// NewBB's dominator.
429//
Devang Pateld6868a72007-07-18 23:50:19 +0000430// OrigPreheader is loop pre-header before this pass started
Devang Patelf9739582007-07-18 23:48:20 +0000431// updating CFG. NewPrehader is loops new pre-header. However, after CFG
Devang Pateld6868a72007-07-18 23:50:19 +0000432// manipulation, loop L may not exist. So rely on input parameter NewPreheader.
Devang Patelf9739582007-07-18 23:48:20 +0000433void CloneDomInfo(BasicBlock *NewBB, BasicBlock *Orig,
434 BasicBlock *NewPreheader, BasicBlock *OrigPreheader,
435 BasicBlock *OrigHeader,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000436 DominatorTree *DT, DominanceFrontier *DF,
437 DenseMap<const Value*, Value*> &VM) {
438
Devang Patelf9739582007-07-18 23:48:20 +0000439 // If NewBB alreay has found its place in domiantor tree then no need to do
440 // anything.
441 if (DT->getNode(NewBB))
442 return;
443
444 // If Orig does not have any immediate domiantor then its clone, NewBB, does
445 // not need any immediate dominator.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000446 DomTreeNode *OrigNode = DT->getNode(Orig);
447 if (!OrigNode)
448 return;
Devang Patelf9739582007-07-18 23:48:20 +0000449 DomTreeNode *OrigIDomNode = OrigNode->getIDom();
450 if (!OrigIDomNode)
451 return;
452
453 BasicBlock *OrigIDom = NULL;
454
455 // If Orig is original loop header then its immediate dominator is
456 // NewPreheader.
457 if (Orig == OrigHeader)
458 OrigIDom = NewPreheader;
459
460 // If Orig is new pre-header then its immediate dominator is
461 // original pre-header.
462 else if (Orig == NewPreheader)
463 OrigIDom = OrigPreheader;
464
465 // Other as DT to find Orig's immediate dominator.
466 else
467 OrigIDom = OrigIDomNode->getBlock();
468
Devang Patelc5685122007-07-30 21:10:44 +0000469 // Initially use Orig's immediate dominator as NewBB's immediate dominator.
470 BasicBlock *NewIDom = OrigIDom;
471 DenseMap<const Value*, Value*>::iterator I = VM.find(OrigIDom);
472 if (I != VM.end()) {
473 NewIDom = cast<BasicBlock>(I->second);
474
475 // If NewIDom does not have corresponding dominatore tree node then
476 // get one.
477 if (!DT->getNode(NewIDom))
Devang Patelf9739582007-07-18 23:48:20 +0000478 CloneDomInfo(NewIDom, OrigIDom, NewPreheader, OrigPreheader,
479 OrigHeader, DT, DF, VM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000480 }
Devang Patelc5685122007-07-30 21:10:44 +0000481
482 DT->addNewBlock(NewBB, NewIDom);
483
484 // Copy cloned dominance frontiner set
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000485 DominanceFrontier::DomSetType NewDFSet;
486 if (DF) {
487 DominanceFrontier::iterator DFI = DF->find(Orig);
488 if ( DFI != DF->end()) {
489 DominanceFrontier::DomSetType S = DFI->second;
490 for (DominanceFrontier::DomSetType::iterator I = S.begin(), E = S.end();
491 I != E; ++I) {
492 BasicBlock *BB = *I;
Chuck Rose III9a2da442007-07-27 18:26:35 +0000493 DenseMap<const Value*, Value*>::iterator IDM = VM.find(BB);
494 if (IDM != VM.end())
495 NewDFSet.insert(cast<BasicBlock>(IDM->second));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000496 else
497 NewDFSet.insert(BB);
498 }
499 }
500 DF->addBasicBlock(NewBB, NewDFSet);
501 }
502}
503
504/// CloneLoop - Recursively clone the specified loop and all of its children,
505/// mapping the blocks with the specified map.
506static Loop *CloneLoop(Loop *L, Loop *PL, DenseMap<const Value*, Value*> &VM,
507 LoopInfo *LI, LPPassManager *LPM) {
508 Loop *New = new Loop();
509
510 LPM->insertLoop(New, PL);
511
512 // Add all of the blocks in L to the new loop.
513 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
514 I != E; ++I)
515 if (LI->getLoopFor(*I) == L)
516 New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI);
517
518 // Add all of the subloops to the new loop.
519 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
520 CloneLoop(*I, New, VM, LI, LPM);
521
522 return New;
523}
524
525/// EmitPreheaderBranchOnCondition - Emit a conditional branch on two values
526/// if LIC == Val, branch to TrueDst, otherwise branch to FalseDest. Insert the
527/// code immediately before InsertPt.
528void LoopUnswitch::EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
529 BasicBlock *TrueDest,
530 BasicBlock *FalseDest,
531 Instruction *InsertPt) {
532 // Insert a conditional branch on LIC to the two preheaders. The original
533 // code is the true version and the new code is the false version.
534 Value *BranchVal = LIC;
535 if (!isa<ConstantInt>(Val) || Val->getType() != Type::Int1Ty)
536 BranchVal = new ICmpInst(ICmpInst::ICMP_EQ, LIC, Val, "tmp", InsertPt);
537 else if (Val != ConstantInt::getTrue())
538 // We want to enter the new loop when the condition is true.
539 std::swap(TrueDest, FalseDest);
540
541 // Insert the new branch.
542 BranchInst *BRI = new BranchInst(TrueDest, FalseDest, BranchVal, InsertPt);
543
544 // Update dominator info.
545 // BranchVal is a new preheader so it dominates true and false destination
546 // loop headers.
547 if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>()) {
548 DT->changeImmediateDominator(TrueDest, BRI->getParent());
549 DT->changeImmediateDominator(FalseDest, BRI->getParent());
550 }
551 // No need to update DominanceFrontier. BRI->getParent() dominated TrueDest
552 // and FalseDest anyway. Now it immediately dominates them.
553}
554
555
556/// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable
557/// condition in it (a cond branch from its header block to its latch block,
558/// where the path through the loop that doesn't execute its body has no
559/// side-effects), unswitch it. This doesn't involve any code duplication, just
560/// moving the conditional branch outside of the loop and updating loop info.
561void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond,
562 Constant *Val,
563 BasicBlock *ExitBlock) {
564 DOUT << "loop-unswitch: Trivial-Unswitch loop %"
565 << L->getHeader()->getName() << " [" << L->getBlocks().size()
566 << " blocks] in Function " << L->getHeader()->getParent()->getName()
567 << " on cond: " << *Val << " == " << *Cond << "\n";
568
569 // First step, split the preheader, so that we know that there is a safe place
570 // to insert the conditional branch. We will change 'OrigPH' to have a
571 // conditional branch on Cond.
572 BasicBlock *OrigPH = L->getLoopPreheader();
573 BasicBlock *NewPH = SplitEdge(OrigPH, L->getHeader(), this);
574
575 // Now that we have a place to insert the conditional branch, create a place
576 // to branch to: this is the exit block out of the loop that we should
577 // short-circuit to.
578
579 // Split this block now, so that the loop maintains its exit block, and so
580 // that the jump from the preheader can execute the contents of the exit block
581 // without actually branching to it (the exit block should be dominated by the
582 // loop header, not the preheader).
583 assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
584 BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin(), this);
585
586 // Okay, now we have a position to branch from and a position to branch to,
587 // insert the new conditional branch.
588 EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH,
589 OrigPH->getTerminator());
590 OrigPH->getTerminator()->eraseFromParent();
591
592 // We need to reprocess this loop, it could be unswitched again.
Devang Pateleec0d372007-07-30 23:07:10 +0000593 redoLoop = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000594
595 // Now that we know that the loop is never entered when this condition is a
596 // particular value, rewrite the loop with this info. We know that this will
597 // at least eliminate the old branch.
598 RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
599 ++NumTrivial;
600}
601
602/// VersionLoop - We determined that the loop is profitable to unswitch when LIC
603/// equal Val. Split it into loop versions and test the condition outside of
604/// either loop. Return the loops created as Out1/Out2.
605void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
606 Loop *L) {
607 Function *F = L->getHeader()->getParent();
608 DOUT << "loop-unswitch: Unswitching loop %"
609 << L->getHeader()->getName() << " [" << L->getBlocks().size()
610 << " blocks] in Function " << F->getName()
611 << " when '" << *Val << "' == " << *LIC << "\n";
612
613 // LoopBlocks contains all of the basic blocks of the loop, including the
614 // preheader of the loop, the body of the loop, and the exit blocks of the
615 // loop, in that order.
616 std::vector<BasicBlock*> LoopBlocks;
617
618 // First step, split the preheader and exit blocks, and add these blocks to
619 // the LoopBlocks list.
Devang Patelf9739582007-07-18 23:48:20 +0000620 BasicBlock *OrigHeader = L->getHeader();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000621 BasicBlock *OrigPreheader = L->getLoopPreheader();
Devang Patelf9739582007-07-18 23:48:20 +0000622 BasicBlock *NewPreheader = SplitEdge(OrigPreheader, L->getHeader(), this);
623 LoopBlocks.push_back(NewPreheader);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000624
625 // We want the loop to come after the preheader, but before the exit blocks.
626 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
627
628 std::vector<BasicBlock*> ExitBlocks;
629 L->getUniqueExitBlocks(ExitBlocks);
630
631 // Split all of the edges from inside the loop to their exit blocks. Update
632 // the appropriate Phi nodes as we do so.
633 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
634 BasicBlock *ExitBlock = ExitBlocks[i];
635 std::vector<BasicBlock*> Preds(pred_begin(ExitBlock), pred_end(ExitBlock));
636
637 for (unsigned j = 0, e = Preds.size(); j != e; ++j) {
638 BasicBlock* MiddleBlock = SplitEdge(Preds[j], ExitBlock, this);
639 BasicBlock* StartBlock = Preds[j];
640 BasicBlock* EndBlock;
641 if (MiddleBlock->getSinglePredecessor() == ExitBlock) {
642 EndBlock = MiddleBlock;
643 MiddleBlock = EndBlock->getSinglePredecessor();;
644 } else {
645 EndBlock = ExitBlock;
646 }
647
648 std::set<PHINode*> InsertedPHIs;
649 PHINode* OldLCSSA = 0;
650 for (BasicBlock::iterator I = EndBlock->begin();
651 (OldLCSSA = dyn_cast<PHINode>(I)); ++I) {
652 Value* OldValue = OldLCSSA->getIncomingValueForBlock(MiddleBlock);
653 PHINode* NewLCSSA = new PHINode(OldLCSSA->getType(),
654 OldLCSSA->getName() + ".us-lcssa",
655 MiddleBlock->getTerminator());
656 NewLCSSA->addIncoming(OldValue, StartBlock);
657 OldLCSSA->setIncomingValue(OldLCSSA->getBasicBlockIndex(MiddleBlock),
658 NewLCSSA);
659 InsertedPHIs.insert(NewLCSSA);
660 }
661
662 BasicBlock::iterator InsertPt = EndBlock->begin();
663 while (dyn_cast<PHINode>(InsertPt)) ++InsertPt;
664 for (BasicBlock::iterator I = MiddleBlock->begin();
665 (OldLCSSA = dyn_cast<PHINode>(I)) && InsertedPHIs.count(OldLCSSA) == 0;
666 ++I) {
667 PHINode *NewLCSSA = new PHINode(OldLCSSA->getType(),
668 OldLCSSA->getName() + ".us-lcssa",
669 InsertPt);
670 OldLCSSA->replaceAllUsesWith(NewLCSSA);
671 NewLCSSA->addIncoming(OldLCSSA, MiddleBlock);
672 }
673 }
674 }
675
676 // The exit blocks may have been changed due to edge splitting, recompute.
677 ExitBlocks.clear();
678 L->getUniqueExitBlocks(ExitBlocks);
679
680 // Add exit blocks to the loop blocks.
681 LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
682
683 // Next step, clone all of the basic blocks that make up the loop (including
684 // the loop preheader and exit blocks), keeping track of the mapping between
685 // the instructions and blocks.
686 std::vector<BasicBlock*> NewBlocks;
687 NewBlocks.reserve(LoopBlocks.size());
688 DenseMap<const Value*, Value*> ValueMap;
689 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
690 BasicBlock *New = CloneBasicBlock(LoopBlocks[i], ValueMap, ".us", F);
691 NewBlocks.push_back(New);
692 ValueMap[LoopBlocks[i]] = New; // Keep the BB mapping.
693 }
694
695 // Update dominator info
696 DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>();
697 if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>())
698 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
699 BasicBlock *LBB = LoopBlocks[i];
700 BasicBlock *NBB = NewBlocks[i];
Devang Patelf9739582007-07-18 23:48:20 +0000701 CloneDomInfo(NBB, LBB, NewPreheader, OrigPreheader,
702 OrigHeader, DT, DF, ValueMap);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000703 }
704
705 // Splice the newly inserted blocks into the function right before the
706 // original preheader.
707 F->getBasicBlockList().splice(LoopBlocks[0], F->getBasicBlockList(),
708 NewBlocks[0], F->end());
709
710 // Now we create the new Loop object for the versioned loop.
711 Loop *NewLoop = CloneLoop(L, L->getParentLoop(), ValueMap, LI, LPM);
712 Loop *ParentLoop = L->getParentLoop();
713 if (ParentLoop) {
714 // Make sure to add the cloned preheader and exit blocks to the parent loop
715 // as well.
716 ParentLoop->addBasicBlockToLoop(NewBlocks[0], *LI);
717 }
718
719 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
720 BasicBlock *NewExit = cast<BasicBlock>(ValueMap[ExitBlocks[i]]);
721 // The new exit block should be in the same loop as the old one.
722 if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
723 ExitBBLoop->addBasicBlockToLoop(NewExit, *LI);
724
725 assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
726 "Exit block should have been split to have one successor!");
727 BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
728
729 // If the successor of the exit block had PHI nodes, add an entry for
730 // NewExit.
731 PHINode *PN;
732 for (BasicBlock::iterator I = ExitSucc->begin();
733 (PN = dyn_cast<PHINode>(I)); ++I) {
734 Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
735 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(V);
736 if (It != ValueMap.end()) V = It->second;
737 PN->addIncoming(V, NewExit);
738 }
739 }
740
741 // Rewrite the code to refer to itself.
742 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
743 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
744 E = NewBlocks[i]->end(); I != E; ++I)
745 RemapInstruction(I, ValueMap);
746
747 // Rewrite the original preheader to select between versions of the loop.
748 BranchInst *OldBR = cast<BranchInst>(OrigPreheader->getTerminator());
749 assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
750 "Preheader splitting did not work correctly!");
751
752 // Emit the new branch that selects between the two versions of this loop.
753 EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR);
754 OldBR->eraseFromParent();
755
756 LoopProcessWorklist.push_back(NewLoop);
Devang Pateleec0d372007-07-30 23:07:10 +0000757 redoLoop = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000758
759 // Now we rewrite the original code to know that the condition is true and the
760 // new code to know that the condition is false.
761 RewriteLoopBodyWithConditionConstant(L , LIC, Val, false);
762
763 // It's possible that simplifying one loop could cause the other to be
764 // deleted. If so, don't simplify it.
765 if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop)
766 RewriteLoopBodyWithConditionConstant(NewLoop, LIC, Val, true);
767}
768
769/// RemoveFromWorklist - Remove all instances of I from the worklist vector
770/// specified.
771static void RemoveFromWorklist(Instruction *I,
772 std::vector<Instruction*> &Worklist) {
773 std::vector<Instruction*>::iterator WI = std::find(Worklist.begin(),
774 Worklist.end(), I);
775 while (WI != Worklist.end()) {
776 unsigned Offset = WI-Worklist.begin();
777 Worklist.erase(WI);
778 WI = std::find(Worklist.begin()+Offset, Worklist.end(), I);
779 }
780}
781
782/// ReplaceUsesOfWith - When we find that I really equals V, remove I from the
783/// program, replacing all uses with V and update the worklist.
784static void ReplaceUsesOfWith(Instruction *I, Value *V,
785 std::vector<Instruction*> &Worklist) {
786 DOUT << "Replace with '" << *V << "': " << *I;
787
788 // Add uses to the worklist, which may be dead now.
789 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
790 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
791 Worklist.push_back(Use);
792
793 // Add users to the worklist which may be simplified now.
794 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
795 UI != E; ++UI)
796 Worklist.push_back(cast<Instruction>(*UI));
797 I->replaceAllUsesWith(V);
798 I->eraseFromParent();
799 RemoveFromWorklist(I, Worklist);
800 ++NumSimplify;
801}
802
803/// RemoveBlockIfDead - If the specified block is dead, remove it, update loop
804/// information, and remove any dead successors it has.
805///
806void LoopUnswitch::RemoveBlockIfDead(BasicBlock *BB,
807 std::vector<Instruction*> &Worklist) {
808 if (pred_begin(BB) != pred_end(BB)) {
809 // This block isn't dead, since an edge to BB was just removed, see if there
810 // are any easy simplifications we can do now.
811 if (BasicBlock *Pred = BB->getSinglePredecessor()) {
812 // If it has one pred, fold phi nodes in BB.
813 while (isa<PHINode>(BB->begin()))
814 ReplaceUsesOfWith(BB->begin(),
815 cast<PHINode>(BB->begin())->getIncomingValue(0),
816 Worklist);
817
818 // If this is the header of a loop and the only pred is the latch, we now
819 // have an unreachable loop.
820 if (Loop *L = LI->getLoopFor(BB))
821 if (L->getHeader() == BB && L->contains(Pred)) {
822 // Remove the branch from the latch to the header block, this makes
823 // the header dead, which will make the latch dead (because the header
824 // dominates the latch).
825 Pred->getTerminator()->eraseFromParent();
826 new UnreachableInst(Pred);
827
828 // The loop is now broken, remove it from LI.
829 RemoveLoopFromHierarchy(L);
830
831 // Reprocess the header, which now IS dead.
832 RemoveBlockIfDead(BB, Worklist);
833 return;
834 }
835
836 // If pred ends in a uncond branch, add uncond branch to worklist so that
837 // the two blocks will get merged.
838 if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator()))
839 if (BI->isUnconditional())
840 Worklist.push_back(BI);
841 }
842 return;
843 }
844
845 DOUT << "Nuking dead block: " << *BB;
846
847 // Remove the instructions in the basic block from the worklist.
848 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
849 RemoveFromWorklist(I, Worklist);
850
851 // Anything that uses the instructions in this basic block should have their
852 // uses replaced with undefs.
853 if (!I->use_empty())
854 I->replaceAllUsesWith(UndefValue::get(I->getType()));
855 }
856
857 // If this is the edge to the header block for a loop, remove the loop and
858 // promote all subloops.
859 if (Loop *BBLoop = LI->getLoopFor(BB)) {
860 if (BBLoop->getLoopLatch() == BB)
861 RemoveLoopFromHierarchy(BBLoop);
862 }
863
864 // Remove the block from the loop info, which removes it from any loops it
865 // was in.
866 LI->removeBlock(BB);
867
868
869 // Remove phi node entries in successors for this block.
870 TerminatorInst *TI = BB->getTerminator();
871 std::vector<BasicBlock*> Succs;
872 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
873 Succs.push_back(TI->getSuccessor(i));
874 TI->getSuccessor(i)->removePredecessor(BB);
875 }
876
877 // Unique the successors, remove anything with multiple uses.
878 std::sort(Succs.begin(), Succs.end());
879 Succs.erase(std::unique(Succs.begin(), Succs.end()), Succs.end());
880
881 // Remove the basic block, including all of the instructions contained in it.
882 BB->eraseFromParent();
883
884 // Remove successor blocks here that are not dead, so that we know we only
885 // have dead blocks in this list. Nondead blocks have a way of becoming dead,
886 // then getting removed before we revisit them, which is badness.
887 //
888 for (unsigned i = 0; i != Succs.size(); ++i)
889 if (pred_begin(Succs[i]) != pred_end(Succs[i])) {
890 // One exception is loop headers. If this block was the preheader for a
891 // loop, then we DO want to visit the loop so the loop gets deleted.
892 // We know that if the successor is a loop header, that this loop had to
893 // be the preheader: the case where this was the latch block was handled
894 // above and headers can only have two predecessors.
895 if (!LI->isLoopHeader(Succs[i])) {
896 Succs.erase(Succs.begin()+i);
897 --i;
898 }
899 }
900
901 for (unsigned i = 0, e = Succs.size(); i != e; ++i)
902 RemoveBlockIfDead(Succs[i], Worklist);
903}
904
905/// RemoveLoopFromHierarchy - We have discovered that the specified loop has
906/// become unwrapped, either because the backedge was deleted, or because the
907/// edge into the header was removed. If the edge into the header from the
908/// latch block was removed, the loop is unwrapped but subloops are still alive,
909/// so they just reparent loops. If the loops are actually dead, they will be
910/// removed later.
911void LoopUnswitch::RemoveLoopFromHierarchy(Loop *L) {
912 LPM->deleteLoopFromQueue(L);
913 RemoveLoopFromWorklist(L);
914}
915
916
917
918// RewriteLoopBodyWithConditionConstant - We know either that the value LIC has
919// the value specified by Val in the specified loop, or we know it does NOT have
920// that value. Rewrite any uses of LIC or of properties correlated to it.
921void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
922 Constant *Val,
923 bool IsEqual) {
924 assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
925
926 // FIXME: Support correlated properties, like:
927 // for (...)
928 // if (li1 < li2)
929 // ...
930 // if (li1 > li2)
931 // ...
932
933 // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches,
934 // selects, switches.
935 std::vector<User*> Users(LIC->use_begin(), LIC->use_end());
936 std::vector<Instruction*> Worklist;
937
938 // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
939 // in the loop with the appropriate one directly.
940 if (IsEqual || (isa<ConstantInt>(Val) && Val->getType() == Type::Int1Ty)) {
941 Value *Replacement;
942 if (IsEqual)
943 Replacement = Val;
944 else
945 Replacement = ConstantInt::get(Type::Int1Ty,
946 !cast<ConstantInt>(Val)->getZExtValue());
947
948 for (unsigned i = 0, e = Users.size(); i != e; ++i)
949 if (Instruction *U = cast<Instruction>(Users[i])) {
950 if (!L->contains(U->getParent()))
951 continue;
952 U->replaceUsesOfWith(LIC, Replacement);
953 Worklist.push_back(U);
954 }
955 } else {
956 // Otherwise, we don't know the precise value of LIC, but we do know that it
957 // is certainly NOT "Val". As such, simplify any uses in the loop that we
958 // can. This case occurs when we unswitch switch statements.
959 for (unsigned i = 0, e = Users.size(); i != e; ++i)
960 if (Instruction *U = cast<Instruction>(Users[i])) {
961 if (!L->contains(U->getParent()))
962 continue;
963
964 Worklist.push_back(U);
965
966 // If we know that LIC is not Val, use this info to simplify code.
967 if (SwitchInst *SI = dyn_cast<SwitchInst>(U)) {
968 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) {
969 if (SI->getCaseValue(i) == Val) {
970 // Found a dead case value. Don't remove PHI nodes in the
971 // successor if they become single-entry, those PHI nodes may
972 // be in the Users list.
973
974 // FIXME: This is a hack. We need to keep the successor around
975 // and hooked up so as to preserve the loop structure, because
976 // trying to update it is complicated. So instead we preserve the
977 // loop structure and put the block on an dead code path.
978
979 BasicBlock* Old = SI->getParent();
980 BasicBlock* Split = SplitBlock(Old, SI, this);
981
982 Instruction* OldTerm = Old->getTerminator();
983 new BranchInst(Split, SI->getSuccessor(i),
984 ConstantInt::getTrue(), OldTerm);
985
986 Old->getTerminator()->eraseFromParent();
987
988
989 PHINode *PN;
990 for (BasicBlock::iterator II = SI->getSuccessor(i)->begin();
991 (PN = dyn_cast<PHINode>(II)); ++II) {
992 Value *InVal = PN->removeIncomingValue(Split, false);
993 PN->addIncoming(InVal, Old);
994 }
995
996 SI->removeCase(i);
997 break;
998 }
999 }
1000 }
1001
1002 // TODO: We could do other simplifications, for example, turning
1003 // LIC == Val -> false.
1004 }
1005 }
1006
1007 SimplifyCode(Worklist);
1008}
1009
1010/// SimplifyCode - Okay, now that we have simplified some instructions in the
1011/// loop, walk over it and constant prop, dce, and fold control flow where
1012/// possible. Note that this is effectively a very simple loop-structure-aware
1013/// optimizer. During processing of this loop, L could very well be deleted, so
1014/// it must not be used.
1015///
1016/// FIXME: When the loop optimizer is more mature, separate this out to a new
1017/// pass.
1018///
1019void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist) {
1020 while (!Worklist.empty()) {
1021 Instruction *I = Worklist.back();
1022 Worklist.pop_back();
1023
1024 // Simple constant folding.
1025 if (Constant *C = ConstantFoldInstruction(I)) {
1026 ReplaceUsesOfWith(I, C, Worklist);
1027 continue;
1028 }
1029
1030 // Simple DCE.
1031 if (isInstructionTriviallyDead(I)) {
1032 DOUT << "Remove dead instruction '" << *I;
1033
1034 // Add uses to the worklist, which may be dead now.
1035 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1036 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1037 Worklist.push_back(Use);
1038 I->eraseFromParent();
1039 RemoveFromWorklist(I, Worklist);
1040 ++NumSimplify;
1041 continue;
1042 }
1043
1044 // Special case hacks that appear commonly in unswitched code.
1045 switch (I->getOpcode()) {
1046 case Instruction::Select:
1047 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(0))) {
1048 ReplaceUsesOfWith(I, I->getOperand(!CB->getZExtValue()+1), Worklist);
1049 continue;
1050 }
1051 break;
1052 case Instruction::And:
1053 if (isa<ConstantInt>(I->getOperand(0)) &&
1054 I->getOperand(0)->getType() == Type::Int1Ty) // constant -> RHS
1055 cast<BinaryOperator>(I)->swapOperands();
1056 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
1057 if (CB->getType() == Type::Int1Ty) {
1058 if (CB->isOne()) // X & 1 -> X
1059 ReplaceUsesOfWith(I, I->getOperand(0), Worklist);
1060 else // X & 0 -> 0
1061 ReplaceUsesOfWith(I, I->getOperand(1), Worklist);
1062 continue;
1063 }
1064 break;
1065 case Instruction::Or:
1066 if (isa<ConstantInt>(I->getOperand(0)) &&
1067 I->getOperand(0)->getType() == Type::Int1Ty) // constant -> RHS
1068 cast<BinaryOperator>(I)->swapOperands();
1069 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
1070 if (CB->getType() == Type::Int1Ty) {
1071 if (CB->isOne()) // X | 1 -> 1
1072 ReplaceUsesOfWith(I, I->getOperand(1), Worklist);
1073 else // X | 0 -> X
1074 ReplaceUsesOfWith(I, I->getOperand(0), Worklist);
1075 continue;
1076 }
1077 break;
1078 case Instruction::Br: {
1079 BranchInst *BI = cast<BranchInst>(I);
1080 if (BI->isUnconditional()) {
1081 // If BI's parent is the only pred of the successor, fold the two blocks
1082 // together.
1083 BasicBlock *Pred = BI->getParent();
1084 BasicBlock *Succ = BI->getSuccessor(0);
1085 BasicBlock *SinglePred = Succ->getSinglePredecessor();
1086 if (!SinglePred) continue; // Nothing to do.
1087 assert(SinglePred == Pred && "CFG broken");
1088
1089 DOUT << "Merging blocks: " << Pred->getName() << " <- "
1090 << Succ->getName() << "\n";
1091
1092 // Resolve any single entry PHI nodes in Succ.
1093 while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
1094 ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist);
1095
1096 // Move all of the successor contents from Succ to Pred.
1097 Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
1098 Succ->end());
1099 BI->eraseFromParent();
1100 RemoveFromWorklist(BI, Worklist);
1101
1102 // If Succ has any successors with PHI nodes, update them to have
1103 // entries coming from Pred instead of Succ.
1104 Succ->replaceAllUsesWith(Pred);
1105
1106 // Remove Succ from the loop tree.
1107 LI->removeBlock(Succ);
1108 Succ->eraseFromParent();
1109 ++NumSimplify;
1110 } else if (ConstantInt *CB = dyn_cast<ConstantInt>(BI->getCondition())){
1111 // Conditional branch. Turn it into an unconditional branch, then
1112 // remove dead blocks.
1113 break; // FIXME: Enable.
1114
1115 DOUT << "Folded branch: " << *BI;
1116 BasicBlock *DeadSucc = BI->getSuccessor(CB->getZExtValue());
1117 BasicBlock *LiveSucc = BI->getSuccessor(!CB->getZExtValue());
1118 DeadSucc->removePredecessor(BI->getParent(), true);
1119 Worklist.push_back(new BranchInst(LiveSucc, BI));
1120 BI->eraseFromParent();
1121 RemoveFromWorklist(BI, Worklist);
1122 ++NumSimplify;
1123
1124 RemoveBlockIfDead(DeadSucc, Worklist);
1125 }
1126 break;
1127 }
1128 }
1129 }
1130}