Optimize code placement in loop to eliminate unconditional branches or move unconditi...
[oota-llvm.git] / lib / CodeGen / CodePlacementOpt.cpp
1 //===-- CodePlacementOpt.cpp - Code Placement pass. -----------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the pass that optimize code placement and align loop
11 // headers to target specific alignment boundary.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "code-placement"
16 #include "llvm/CodeGen/MachineLoopInfo.h"
17 #include "llvm/CodeGen/MachineFunctionPass.h"
18 #include "llvm/CodeGen/Passes.h"
19 #include "llvm/Target/TargetInstrInfo.h"
20 #include "llvm/Target/TargetLowering.h"
21 #include "llvm/Target/TargetMachine.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/Support/Compiler.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/ADT/Statistic.h"
26 using namespace llvm;
27
28 static cl::opt<bool>
29 OptLoopBBPlacement("opt-loop-bb-placement",
30                    cl::init(false), cl::Hidden,
31                    cl::desc("Optimize block placements in loops"));
32
33 STATISTIC(NumHeaderAligned, "Number of loop header aligned");
34 STATISTIC(NumIntraElim,     "Number of intra loop branches eliminated");
35 STATISTIC(NumIntraMoved,    "Number of intra loop branches moved");
36
37 namespace {
38   class CodePlacementOpt : public MachineFunctionPass {
39     const MachineLoopInfo *MLI;
40     const TargetInstrInfo *TII;
41     const TargetLowering  *TLI;
42
43     /// ChangedMBBs - BBs which are modified by OptimizeIntraLoopEdges.
44     SmallPtrSet<MachineBasicBlock*, 8> ChangedMBBs;
45
46     /// UncondJmpMBBs - A list of BBs which are in loops and end with
47     /// unconditional branches.
48     SmallVector<std::pair<MachineBasicBlock*,MachineBasicBlock*>, 4>
49     UncondJmpMBBs;
50
51     /// LoopHeaders - A list of BBs which are loop headers.
52     SmallVector<MachineBasicBlock*, 4> LoopHeaders;
53
54   public:
55     static char ID;
56     CodePlacementOpt() : MachineFunctionPass(&ID) {}
57
58     virtual bool runOnMachineFunction(MachineFunction &MF);
59     virtual const char *getPassName() const {
60       return "Code Placement Optimizater";
61     }
62
63     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
64       AU.addRequired<MachineLoopInfo>();
65       AU.addPreservedID(MachineDominatorsID);
66       MachineFunctionPass::getAnalysisUsage(AU);
67     }
68
69   private:
70     bool OptimizeIntraLoopEdges();
71     bool AlignLoops(MachineFunction &MF);
72   };
73
74   char CodePlacementOpt::ID = 0;
75 } // end anonymous namespace
76
77 FunctionPass *llvm::createCodePlacementOptPass() {
78   return new CodePlacementOpt();
79 }
80
81 /// OptimizeBackEdges - Place loop back edges to move unconditional branches
82 /// out of the loop.
83 ///
84 ///       A:
85 ///       ...
86 ///       <fallthrough to B>
87 ///
88 ///       B:  --> loop header
89 ///       ...
90 ///       jcc <cond> C, [exit]
91 ///
92 ///       C:
93 ///       ...
94 ///       jmp B
95 ///
96 /// ==>
97 ///
98 ///       A:
99 ///       ...
100 ///       jmp B
101 ///
102 ///       C:  --> new loop header
103 ///       ...
104 ///       <fallthough to B>
105 ///       
106 ///       B:
107 ///       ...
108 ///       jcc <cond> C, [exit]
109 ///
110 bool CodePlacementOpt::OptimizeIntraLoopEdges() {
111   if (!OptLoopBBPlacement)
112     return false;
113
114   bool Changed = false;
115   for (unsigned i = 0, e = UncondJmpMBBs.size(); i != e; ++i) {
116     MachineBasicBlock *MBB = UncondJmpMBBs[i].first;
117     MachineBasicBlock *SuccMBB = UncondJmpMBBs[i].second;
118     MachineLoop *L = MLI->getLoopFor(MBB);
119     assert(L && "BB is expected to be in a loop!");
120
121     if (ChangedMBBs.count(MBB)) {
122       // BB has been modified, re-analyze.
123       MachineBasicBlock *TBB = 0, *FBB = 0;
124       SmallVector<MachineOperand, 4> Cond;
125       if (TII->AnalyzeBranch(*MBB, TBB, FBB, Cond) || !Cond.empty())
126         continue;
127       if (MLI->getLoopFor(TBB) != L || TBB->isLandingPad())
128         continue;
129       SuccMBB = TBB;
130     } else {
131       assert(MLI->getLoopFor(SuccMBB) == L &&
132              "Successor is not in the same loop!");
133     }
134
135     if (MBB->isLayoutSuccessor(SuccMBB)) {
136       // Successor is right after MBB, just eliminate the unconditional jmp.
137       // Can this happen?
138       TII->RemoveBranch(*MBB);
139       ChangedMBBs.insert(MBB);
140       ++NumIntraElim;
141       continue;
142     }
143
144     // Now check if the predecessor is fallthrough from any BB. If there is,
145     // that BB should be from outside the loop since edge will become a jmp.
146     bool OkToMove = true;
147     MachineBasicBlock *FtMBB = 0, *FtTBB = 0, *FtFBB = 0;
148     SmallVector<MachineOperand, 4> FtCond;    
149     for (MachineBasicBlock::pred_iterator PI = SuccMBB->pred_begin(),
150            PE = SuccMBB->pred_end(); PI != PE; ++PI) {
151       MachineBasicBlock *PredMBB = *PI;
152       if (PredMBB->isLayoutSuccessor(SuccMBB)) {
153         if (TII->AnalyzeBranch(*PredMBB, FtTBB, FtFBB, FtCond)) {
154           OkToMove = false;
155           break;
156         }
157         if (!FtTBB)
158           FtTBB = SuccMBB;
159         else if (!FtFBB) {
160           assert(FtFBB != SuccMBB && "Unexpected control flow!");
161           FtFBB = SuccMBB;
162         }
163         
164         // A fallthrough.
165         FtMBB = PredMBB;
166         MachineLoop *PL = MLI->getLoopFor(PredMBB);
167         if (PL && (PL == L || PL->getLoopDepth() >= L->getLoopDepth())) {
168           OkToMove = false;
169           break;
170         }
171       }
172     }
173
174     if (!OkToMove)
175       continue;
176
177     // Is it profitable? If SuccMBB can fallthrough itself, that can be changed
178     // into a jmp.
179     MachineBasicBlock *TBB = 0, *FBB = 0;
180     SmallVector<MachineOperand, 4> Cond;
181     if (TII->AnalyzeBranch(*SuccMBB, TBB, FBB, Cond))
182       continue;
183     if (!TBB && Cond.empty())
184       TBB = next(MachineFunction::iterator(SuccMBB));
185     else if (!FBB && !Cond.empty())
186       FBB = next(MachineFunction::iterator(SuccMBB));
187
188     // This calculate the cost of the transformation. Also, it finds the *only*
189     // intra-loop edge if there is one.
190     int Cost = 0;
191     bool HasOneIntraSucc = true;
192     MachineBasicBlock *IntraSucc = 0;
193     for (MachineBasicBlock::succ_iterator SI = SuccMBB->succ_begin(),
194            SE = SuccMBB->succ_end(); SI != SE; ++SI) {
195       MachineBasicBlock *SSMBB = *SI;
196       if (MLI->getLoopFor(SSMBB) == L) {
197         if (!IntraSucc)
198           IntraSucc = SSMBB;
199         else
200           HasOneIntraSucc = false;
201       }
202
203       if (SuccMBB->isLayoutSuccessor(SSMBB))
204         // This will become a jmp.
205         ++Cost;
206       else if (MBB->isLayoutSuccessor(SSMBB))
207         // One of the successor will become the new fallthrough.
208         if (SSMBB == FBB) {
209           FBB = 0;
210           --Cost;
211         } else if (!FBB && SSMBB == TBB && Cond.empty()) {
212           TBB = 0;
213           --Cost;
214         } else if (!TII->ReverseBranchCondition(Cond)) {
215           TBB = FBB;
216           FBB = 0;
217           --Cost;
218         }
219     }
220     if (Cost)
221       continue;
222
223     // Now, let's move the successor to below the BB to eliminate the jmp.
224     SuccMBB->moveAfter(MBB);
225     TII->RemoveBranch(*MBB);
226     TII->RemoveBranch(*SuccMBB);
227     if (TBB)
228       TII->InsertBranch(*SuccMBB, TBB, FBB, Cond);
229     ChangedMBBs.insert(MBB);
230     ChangedMBBs.insert(SuccMBB);
231     if (FtMBB) {
232       TII->RemoveBranch(*FtMBB);
233       TII->InsertBranch(*FtMBB, FtTBB, FtFBB, FtCond);
234       ChangedMBBs.insert(FtMBB);
235     }
236
237     // If BB is the loop latch, we may have a new loop headr.
238     if (MBB == L->getLoopLatch()) {
239       assert(MLI->isLoopHeader(SuccMBB) &&
240              "Only succ of loop latch is not the header?");
241       if (HasOneIntraSucc && IntraSucc)
242         std::replace(LoopHeaders.begin(),LoopHeaders.end(), SuccMBB, IntraSucc);
243     }
244   }
245
246   ++NumIntraMoved;
247   return Changed;
248 }
249
250 /// AlignLoops - Align loop headers to target preferred alignments.
251 ///
252 bool CodePlacementOpt::AlignLoops(MachineFunction &MF) {
253   const Function *F = MF.getFunction();
254   if (F->hasFnAttr(Attribute::OptimizeForSize))
255     return false;
256
257   unsigned Align = TLI->getPrefLoopAlignment();
258   if (!Align)
259     return false;  // Don't care about loop alignment.
260
261   // Make sure blocks are numbered in order
262   MF.RenumberBlocks();
263
264   bool Changed = false;
265   for (unsigned i = 0, e = LoopHeaders.size(); i != e; ++i) {
266     MachineBasicBlock *HeaderMBB = LoopHeaders[i];
267     MachineBasicBlock *PredMBB = prior(MachineFunction::iterator(HeaderMBB));
268     if (MLI->getLoopFor(HeaderMBB) != MLI->getLoopFor(PredMBB)) {
269       // If previously BB is in the same loop, don't align this BB. We want
270       // to prevent adding noop's inside a loop.
271       HeaderMBB->setAlignment(Align);
272       Changed = true;
273       ++NumHeaderAligned;
274     }
275   }
276
277   return Changed;
278 }
279
280 bool CodePlacementOpt::runOnMachineFunction(MachineFunction &MF) {
281   MLI = &getAnalysis<MachineLoopInfo>();
282   if (MLI->empty())
283     return false;  // No loops.
284
285   TLI = MF.getTarget().getTargetLowering();
286   TII = MF.getTarget().getInstrInfo();
287
288   // Analyze the BBs first and keep track of loop headers and BBs that
289   // end with an unconditional jmp to another block in the same loop.
290   for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
291     MachineBasicBlock *MBB = I;
292     if (MBB->isLandingPad())
293       continue;
294     MachineLoop *L = MLI->getLoopFor(MBB);
295     if (!L)
296       continue;
297     if (MLI->isLoopHeader(MBB))
298       LoopHeaders.push_back(MBB);
299
300     MachineBasicBlock *TBB = 0, *FBB = 0;
301     SmallVector<MachineOperand, 4> Cond;
302     if (TII->AnalyzeBranch(*MBB, TBB, FBB, Cond) || !Cond.empty())
303       continue;
304     if (MLI->getLoopFor(TBB) == L && !TBB->isLandingPad())
305       UncondJmpMBBs.push_back(std::make_pair(MBB, TBB));
306   }
307
308   bool Changed = OptimizeIntraLoopEdges();
309
310   Changed |= AlignLoops(MF);
311
312   ChangedMBBs.clear();
313   UncondJmpMBBs.clear();
314   LoopHeaders.clear();
315
316   return Changed;
317 }