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