Merge branch 'master' into msp430
[llvm/msp430.git] / lib / CodeGen / CodePlacementOpt.cpp
blob919ee54fb3f48752a7a7044872f8b5545663a0f7
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.
13 //===----------------------------------------------------------------------===//
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/Compiler.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/ADT/Statistic.h"
25 using namespace llvm;
27 STATISTIC(NumHeaderAligned, "Number of loop header aligned");
28 STATISTIC(NumIntraElim, "Number of intra loop branches eliminated");
29 STATISTIC(NumIntraMoved, "Number of intra loop branches moved");
31 namespace {
32 class CodePlacementOpt : public MachineFunctionPass {
33 const MachineLoopInfo *MLI;
34 const TargetInstrInfo *TII;
35 const TargetLowering *TLI;
37 /// ChangedMBBs - BBs which are modified by OptimizeIntraLoopEdges.
38 SmallPtrSet<MachineBasicBlock*, 8> ChangedMBBs;
40 /// UncondJmpMBBs - A list of BBs which are in loops and end with
41 /// unconditional branches.
42 SmallVector<std::pair<MachineBasicBlock*,MachineBasicBlock*>, 4>
43 UncondJmpMBBs;
45 /// LoopHeaders - A list of BBs which are loop headers.
46 SmallVector<MachineBasicBlock*, 4> LoopHeaders;
48 public:
49 static char ID;
50 CodePlacementOpt() : MachineFunctionPass(&ID) {}
52 virtual bool runOnMachineFunction(MachineFunction &MF);
53 virtual const char *getPassName() const {
54 return "Code Placement Optimizater";
57 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
58 AU.addRequired<MachineLoopInfo>();
59 AU.addPreservedID(MachineDominatorsID);
60 MachineFunctionPass::getAnalysisUsage(AU);
63 private:
64 bool OptimizeIntraLoopEdges();
65 bool HeaderShouldBeAligned(MachineBasicBlock *MBB, MachineLoop *L,
66 SmallPtrSet<MachineBasicBlock*, 4> &DoNotAlign);
67 bool AlignLoops(MachineFunction &MF);
70 char CodePlacementOpt::ID = 0;
71 } // end anonymous namespace
73 FunctionPass *llvm::createCodePlacementOptPass() {
74 return new CodePlacementOpt();
77 /// OptimizeBackEdges - Place loop back edges to move unconditional branches
78 /// out of the loop.
79 ///
80 /// A:
81 /// ...
82 /// <fallthrough to B>
83 ///
84 /// B: --> loop header
85 /// ...
86 /// jcc <cond> C, [exit]
87 ///
88 /// C:
89 /// ...
90 /// jmp B
91 ///
92 /// ==>
93 ///
94 /// A:
95 /// ...
96 /// jmp B
97 ///
98 /// C: --> new loop header
99 /// ...
100 /// <fallthough to B>
101 ///
102 /// B:
103 /// ...
104 /// jcc <cond> C, [exit]
106 bool CodePlacementOpt::OptimizeIntraLoopEdges() {
107 if (!TLI->shouldOptimizeCodePlacement())
108 return false;
110 bool Changed = false;
111 for (unsigned i = 0, e = UncondJmpMBBs.size(); i != e; ++i) {
112 MachineBasicBlock *MBB = UncondJmpMBBs[i].first;
113 MachineBasicBlock *SuccMBB = UncondJmpMBBs[i].second;
114 MachineLoop *L = MLI->getLoopFor(MBB);
115 assert(L && "BB is expected to be in a loop!");
117 if (ChangedMBBs.count(MBB)) {
118 // BB has been modified, re-analyze.
119 MachineBasicBlock *TBB = 0, *FBB = 0;
120 SmallVector<MachineOperand, 4> Cond;
121 if (TII->AnalyzeBranch(*MBB, TBB, FBB, Cond) || !Cond.empty())
122 continue;
123 if (MLI->getLoopFor(TBB) != L || TBB->isLandingPad())
124 continue;
125 SuccMBB = TBB;
126 } else {
127 assert(MLI->getLoopFor(SuccMBB) == L &&
128 "Successor is not in the same loop!");
131 if (MBB->isLayoutSuccessor(SuccMBB)) {
132 // Successor is right after MBB, just eliminate the unconditional jmp.
133 // Can this happen?
134 TII->RemoveBranch(*MBB);
135 ChangedMBBs.insert(MBB);
136 ++NumIntraElim;
137 continue;
140 // Now check if the predecessor is fallthrough from any BB. If there is,
141 // that BB should be from outside the loop since edge will become a jmp.
142 bool OkToMove = true;
143 MachineBasicBlock *FtMBB = 0, *FtTBB = 0, *FtFBB = 0;
144 SmallVector<MachineOperand, 4> FtCond;
145 for (MachineBasicBlock::pred_iterator PI = SuccMBB->pred_begin(),
146 PE = SuccMBB->pred_end(); PI != PE; ++PI) {
147 MachineBasicBlock *PredMBB = *PI;
148 if (PredMBB->isLayoutSuccessor(SuccMBB)) {
149 if (TII->AnalyzeBranch(*PredMBB, FtTBB, FtFBB, FtCond)) {
150 OkToMove = false;
151 break;
153 if (!FtTBB)
154 FtTBB = SuccMBB;
155 else if (!FtFBB) {
156 assert(FtFBB != SuccMBB && "Unexpected control flow!");
157 FtFBB = SuccMBB;
160 // A fallthrough.
161 FtMBB = PredMBB;
162 MachineLoop *PL = MLI->getLoopFor(PredMBB);
163 if (PL && (PL == L || PL->getLoopDepth() >= L->getLoopDepth()))
164 OkToMove = false;
166 break;
170 if (!OkToMove)
171 continue;
173 // Is it profitable? If SuccMBB can fallthrough itself, that can be changed
174 // into a jmp.
175 MachineBasicBlock *TBB = 0, *FBB = 0;
176 SmallVector<MachineOperand, 4> Cond;
177 if (TII->AnalyzeBranch(*SuccMBB, TBB, FBB, Cond))
178 continue;
179 if (!TBB && Cond.empty())
180 TBB = next(MachineFunction::iterator(SuccMBB));
181 else if (!FBB && !Cond.empty())
182 FBB = next(MachineFunction::iterator(SuccMBB));
184 // This calculate the cost of the transformation. Also, it finds the *only*
185 // intra-loop edge if there is one.
186 int Cost = 0;
187 bool HasOneIntraSucc = true;
188 MachineBasicBlock *IntraSucc = 0;
189 for (MachineBasicBlock::succ_iterator SI = SuccMBB->succ_begin(),
190 SE = SuccMBB->succ_end(); SI != SE; ++SI) {
191 MachineBasicBlock *SSMBB = *SI;
192 if (MLI->getLoopFor(SSMBB) == L) {
193 if (!IntraSucc)
194 IntraSucc = SSMBB;
195 else
196 HasOneIntraSucc = false;
199 if (SuccMBB->isLayoutSuccessor(SSMBB))
200 // This will become a jmp.
201 ++Cost;
202 else if (MBB->isLayoutSuccessor(SSMBB)) {
203 // One of the successor will become the new fallthrough.
204 if (SSMBB == FBB) {
205 FBB = 0;
206 --Cost;
207 } else if (!FBB && SSMBB == TBB && Cond.empty()) {
208 TBB = 0;
209 --Cost;
210 } else if (!Cond.empty() && !TII->ReverseBranchCondition(Cond)) {
211 assert(SSMBB == TBB);
212 TBB = FBB;
213 FBB = 0;
214 --Cost;
218 if (Cost)
219 continue;
221 // Now, let's move the successor to below the BB to eliminate the jmp.
222 SuccMBB->moveAfter(MBB);
223 TII->RemoveBranch(*MBB);
224 TII->RemoveBranch(*SuccMBB);
225 if (TBB)
226 TII->InsertBranch(*SuccMBB, TBB, FBB, Cond);
227 ChangedMBBs.insert(MBB);
228 ChangedMBBs.insert(SuccMBB);
229 if (FtMBB) {
230 TII->RemoveBranch(*FtMBB);
231 TII->InsertBranch(*FtMBB, FtTBB, FtFBB, FtCond);
232 ChangedMBBs.insert(FtMBB);
235 // If BB is the loop latch, we may have a new loop headr.
236 if (MBB == L->getLoopLatch()) {
237 assert(MLI->isLoopHeader(SuccMBB) &&
238 "Only succ of loop latch is not the header?");
239 if (HasOneIntraSucc && IntraSucc)
240 std::replace(LoopHeaders.begin(),LoopHeaders.end(), SuccMBB, IntraSucc);
244 ++NumIntraMoved;
245 return Changed;
248 /// HeaderShouldBeAligned - Return true if the specified loop header block
249 /// should be aligned. For now, we will not align it if all the predcessors
250 /// (i.e. loop back edges) are laid out above the header. FIXME: Do not
251 /// align small loops.
252 bool
253 CodePlacementOpt::HeaderShouldBeAligned(MachineBasicBlock *MBB, MachineLoop *L,
254 SmallPtrSet<MachineBasicBlock*, 4> &DoNotAlign) {
255 if (DoNotAlign.count(MBB))
256 return false;
258 bool BackEdgeBelow = false;
259 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
260 PE = MBB->pred_end(); PI != PE; ++PI) {
261 MachineBasicBlock *PredMBB = *PI;
262 if (PredMBB == MBB || PredMBB->getNumber() > MBB->getNumber()) {
263 BackEdgeBelow = true;
264 break;
268 if (!BackEdgeBelow)
269 return false;
271 // Ok, we are going to align this loop header. If it's an inner loop,
272 // do not align its outer loop.
273 MachineBasicBlock *PreHeader = L->getLoopPreheader();
274 if (PreHeader) {
275 MachineLoop *L = MLI->getLoopFor(PreHeader);
276 if (L) {
277 MachineBasicBlock *HeaderBlock = L->getHeader();
278 HeaderBlock->setAlignment(0);
279 DoNotAlign.insert(HeaderBlock);
282 return true;
285 /// AlignLoops - Align loop headers to target preferred alignments.
287 bool CodePlacementOpt::AlignLoops(MachineFunction &MF) {
288 const Function *F = MF.getFunction();
289 if (F->hasFnAttr(Attribute::OptimizeForSize))
290 return false;
292 unsigned Align = TLI->getPrefLoopAlignment();
293 if (!Align)
294 return false; // Don't care about loop alignment.
296 // Make sure blocks are numbered in order
297 MF.RenumberBlocks();
299 bool Changed = false;
300 SmallPtrSet<MachineBasicBlock*, 4> DoNotAlign;
301 for (unsigned i = 0, e = LoopHeaders.size(); i != e; ++i) {
302 MachineBasicBlock *HeaderMBB = LoopHeaders[i];
303 MachineBasicBlock *PredMBB = prior(MachineFunction::iterator(HeaderMBB));
304 MachineLoop *L = MLI->getLoopFor(HeaderMBB);
305 if (L == MLI->getLoopFor(PredMBB))
306 // If previously BB is in the same loop, don't align this BB. We want
307 // to prevent adding noop's inside a loop.
308 continue;
309 if (HeaderShouldBeAligned(HeaderMBB, L, DoNotAlign)) {
310 HeaderMBB->setAlignment(Align);
311 Changed = true;
312 ++NumHeaderAligned;
316 return Changed;
319 bool CodePlacementOpt::runOnMachineFunction(MachineFunction &MF) {
320 MLI = &getAnalysis<MachineLoopInfo>();
321 if (MLI->empty())
322 return false; // No loops.
324 TLI = MF.getTarget().getTargetLowering();
325 TII = MF.getTarget().getInstrInfo();
327 // Analyze the BBs first and keep track of loop headers and BBs that
328 // end with an unconditional jmp to another block in the same loop.
329 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
330 MachineBasicBlock *MBB = I;
331 if (MBB->isLandingPad())
332 continue;
333 MachineLoop *L = MLI->getLoopFor(MBB);
334 if (!L)
335 continue;
336 if (MLI->isLoopHeader(MBB))
337 LoopHeaders.push_back(MBB);
339 MachineBasicBlock *TBB = 0, *FBB = 0;
340 SmallVector<MachineOperand, 4> Cond;
341 if (TII->AnalyzeBranch(*MBB, TBB, FBB, Cond) || !Cond.empty())
342 continue;
343 if (MLI->getLoopFor(TBB) == L && !TBB->isLandingPad())
344 UncondJmpMBBs.push_back(std::make_pair(MBB, TBB));
347 bool Changed = OptimizeIntraLoopEdges();
349 Changed |= AlignLoops(MF);
351 ChangedMBBs.clear();
352 UncondJmpMBBs.clear();
353 LoopHeaders.clear();
355 return Changed;