blob: 61a8b12860a278bd08c20e02d9071c5af21be33e [file] [log] [blame]
Evan Chengbbf1db72009-05-07 05:42:24 +00001//===-- CodePlacementOpt.cpp - Code Placement pass. -----------------------===//
Evan Chengfb8075d2008-02-28 00:43:03 +00002//
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//
Evan Chengbbf1db72009-05-07 05:42:24 +000010// This file implements the pass that optimize code placement and align loop
11// headers to target specific alignment boundary.
Evan Chengfb8075d2008-02-28 00:43:03 +000012//
13//===----------------------------------------------------------------------===//
14
Evan Chengbbf1db72009-05-07 05:42:24 +000015#define DEBUG_TYPE "code-placement"
Evan Chengfb8075d2008-02-28 00:43:03 +000016#include "llvm/CodeGen/MachineLoopInfo.h"
17#include "llvm/CodeGen/MachineFunctionPass.h"
18#include "llvm/CodeGen/Passes.h"
Evan Cheng45e00102009-05-08 06:34:09 +000019#include "llvm/Target/TargetInstrInfo.h"
Evan Chengfb8075d2008-02-28 00:43:03 +000020#include "llvm/Target/TargetLowering.h"
21#include "llvm/Target/TargetMachine.h"
Evan Chengfb8075d2008-02-28 00:43:03 +000022#include "llvm/Support/Compiler.h"
23#include "llvm/Support/Debug.h"
Evan Cheng45e00102009-05-08 06:34:09 +000024#include "llvm/ADT/Statistic.h"
Evan Chengfb8075d2008-02-28 00:43:03 +000025using namespace llvm;
26
Evan Cheng45e00102009-05-08 06:34:09 +000027STATISTIC(NumHeaderAligned, "Number of loop header aligned");
28STATISTIC(NumIntraElim, "Number of intra loop branches eliminated");
29STATISTIC(NumIntraMoved, "Number of intra loop branches moved");
30
Evan Chengfb8075d2008-02-28 00:43:03 +000031namespace {
Evan Chengbbf1db72009-05-07 05:42:24 +000032 class CodePlacementOpt : public MachineFunctionPass {
Evan Cheng7132e122009-05-07 05:49:39 +000033 const MachineLoopInfo *MLI;
Evan Cheng45e00102009-05-08 06:34:09 +000034 const TargetInstrInfo *TII;
35 const TargetLowering *TLI;
36
37 /// ChangedMBBs - BBs which are modified by OptimizeIntraLoopEdges.
38 SmallPtrSet<MachineBasicBlock*, 8> ChangedMBBs;
39
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;
44
45 /// LoopHeaders - A list of BBs which are loop headers.
46 SmallVector<MachineBasicBlock*, 4> LoopHeaders;
Evan Cheng7132e122009-05-07 05:49:39 +000047
Evan Chengfb8075d2008-02-28 00:43:03 +000048 public:
49 static char ID;
Evan Chengbbf1db72009-05-07 05:42:24 +000050 CodePlacementOpt() : MachineFunctionPass(&ID) {}
Evan Chengfb8075d2008-02-28 00:43:03 +000051
52 virtual bool runOnMachineFunction(MachineFunction &MF);
Evan Chengbbf1db72009-05-07 05:42:24 +000053 virtual const char *getPassName() const {
54 return "Code Placement Optimizater";
55 }
Evan Chengfb8075d2008-02-28 00:43:03 +000056
57 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
58 AU.addRequired<MachineLoopInfo>();
Evan Cheng8b56a902008-09-22 22:21:38 +000059 AU.addPreservedID(MachineDominatorsID);
Evan Chengfb8075d2008-02-28 00:43:03 +000060 MachineFunctionPass::getAnalysisUsage(AU);
61 }
Evan Cheng7132e122009-05-07 05:49:39 +000062
63 private:
Evan Cheng45e00102009-05-08 06:34:09 +000064 bool OptimizeIntraLoopEdges();
Evan Cheng9d3094b2009-05-12 23:58:14 +000065 bool HeaderShouldBeAligned(MachineBasicBlock *MBB, MachineLoop *L,
66 SmallPtrSet<MachineBasicBlock*, 4> &DoNotAlign);
Evan Cheng7132e122009-05-07 05:49:39 +000067 bool AlignLoops(MachineFunction &MF);
Evan Chengfb8075d2008-02-28 00:43:03 +000068 };
69
Evan Chengbbf1db72009-05-07 05:42:24 +000070 char CodePlacementOpt::ID = 0;
Evan Chengfb8075d2008-02-28 00:43:03 +000071} // end anonymous namespace
72
Evan Chengbbf1db72009-05-07 05:42:24 +000073FunctionPass *llvm::createCodePlacementOptPass() {
74 return new CodePlacementOpt();
75}
Evan Chengfb8075d2008-02-28 00:43:03 +000076
Evan Cheng45e00102009-05-08 06:34:09 +000077/// 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]
105///
106bool CodePlacementOpt::OptimizeIntraLoopEdges() {
Evan Cheng45e00102009-05-08 06:34:09 +0000107 bool Changed = false;
108 for (unsigned i = 0, e = UncondJmpMBBs.size(); i != e; ++i) {
109 MachineBasicBlock *MBB = UncondJmpMBBs[i].first;
110 MachineBasicBlock *SuccMBB = UncondJmpMBBs[i].second;
111 MachineLoop *L = MLI->getLoopFor(MBB);
112 assert(L && "BB is expected to be in a loop!");
113
114 if (ChangedMBBs.count(MBB)) {
115 // BB has been modified, re-analyze.
116 MachineBasicBlock *TBB = 0, *FBB = 0;
117 SmallVector<MachineOperand, 4> Cond;
118 if (TII->AnalyzeBranch(*MBB, TBB, FBB, Cond) || !Cond.empty())
119 continue;
120 if (MLI->getLoopFor(TBB) != L || TBB->isLandingPad())
121 continue;
122 SuccMBB = TBB;
123 } else {
124 assert(MLI->getLoopFor(SuccMBB) == L &&
125 "Successor is not in the same loop!");
126 }
127
128 if (MBB->isLayoutSuccessor(SuccMBB)) {
129 // Successor is right after MBB, just eliminate the unconditional jmp.
130 // Can this happen?
131 TII->RemoveBranch(*MBB);
132 ChangedMBBs.insert(MBB);
133 ++NumIntraElim;
134 continue;
135 }
136
137 // Now check if the predecessor is fallthrough from any BB. If there is,
138 // that BB should be from outside the loop since edge will become a jmp.
139 bool OkToMove = true;
140 MachineBasicBlock *FtMBB = 0, *FtTBB = 0, *FtFBB = 0;
141 SmallVector<MachineOperand, 4> FtCond;
142 for (MachineBasicBlock::pred_iterator PI = SuccMBB->pred_begin(),
143 PE = SuccMBB->pred_end(); PI != PE; ++PI) {
144 MachineBasicBlock *PredMBB = *PI;
145 if (PredMBB->isLayoutSuccessor(SuccMBB)) {
146 if (TII->AnalyzeBranch(*PredMBB, FtTBB, FtFBB, FtCond)) {
147 OkToMove = false;
148 break;
149 }
150 if (!FtTBB)
151 FtTBB = SuccMBB;
152 else if (!FtFBB) {
153 assert(FtFBB != SuccMBB && "Unexpected control flow!");
154 FtFBB = SuccMBB;
155 }
156
157 // A fallthrough.
158 FtMBB = PredMBB;
159 MachineLoop *PL = MLI->getLoopFor(PredMBB);
Bob Wilson74b0ccc2009-05-12 03:48:10 +0000160 if (PL && (PL == L || PL->getLoopDepth() >= L->getLoopDepth()))
Evan Cheng45e00102009-05-08 06:34:09 +0000161 OkToMove = false;
Bob Wilson74b0ccc2009-05-12 03:48:10 +0000162
163 break;
Evan Cheng45e00102009-05-08 06:34:09 +0000164 }
165 }
166
167 if (!OkToMove)
168 continue;
169
170 // Is it profitable? If SuccMBB can fallthrough itself, that can be changed
171 // into a jmp.
172 MachineBasicBlock *TBB = 0, *FBB = 0;
173 SmallVector<MachineOperand, 4> Cond;
174 if (TII->AnalyzeBranch(*SuccMBB, TBB, FBB, Cond))
175 continue;
176 if (!TBB && Cond.empty())
177 TBB = next(MachineFunction::iterator(SuccMBB));
178 else if (!FBB && !Cond.empty())
179 FBB = next(MachineFunction::iterator(SuccMBB));
180
181 // This calculate the cost of the transformation. Also, it finds the *only*
182 // intra-loop edge if there is one.
183 int Cost = 0;
184 bool HasOneIntraSucc = true;
185 MachineBasicBlock *IntraSucc = 0;
186 for (MachineBasicBlock::succ_iterator SI = SuccMBB->succ_begin(),
187 SE = SuccMBB->succ_end(); SI != SE; ++SI) {
188 MachineBasicBlock *SSMBB = *SI;
189 if (MLI->getLoopFor(SSMBB) == L) {
190 if (!IntraSucc)
191 IntraSucc = SSMBB;
192 else
193 HasOneIntraSucc = false;
194 }
195
196 if (SuccMBB->isLayoutSuccessor(SSMBB))
197 // This will become a jmp.
198 ++Cost;
Nick Lewycky0ab2dce2009-05-08 06:57:41 +0000199 else if (MBB->isLayoutSuccessor(SSMBB)) {
Evan Cheng45e00102009-05-08 06:34:09 +0000200 // One of the successor will become the new fallthrough.
201 if (SSMBB == FBB) {
202 FBB = 0;
203 --Cost;
204 } else if (!FBB && SSMBB == TBB && Cond.empty()) {
205 TBB = 0;
206 --Cost;
Evan Cheng4b7f7a62009-05-08 09:35:53 +0000207 } else if (!Cond.empty() && !TII->ReverseBranchCondition(Cond)) {
208 assert(SSMBB == TBB);
Evan Cheng45e00102009-05-08 06:34:09 +0000209 TBB = FBB;
210 FBB = 0;
211 --Cost;
212 }
Nick Lewycky0ab2dce2009-05-08 06:57:41 +0000213 }
Evan Cheng45e00102009-05-08 06:34:09 +0000214 }
215 if (Cost)
216 continue;
217
218 // Now, let's move the successor to below the BB to eliminate the jmp.
219 SuccMBB->moveAfter(MBB);
220 TII->RemoveBranch(*MBB);
221 TII->RemoveBranch(*SuccMBB);
222 if (TBB)
223 TII->InsertBranch(*SuccMBB, TBB, FBB, Cond);
224 ChangedMBBs.insert(MBB);
225 ChangedMBBs.insert(SuccMBB);
226 if (FtMBB) {
227 TII->RemoveBranch(*FtMBB);
228 TII->InsertBranch(*FtMBB, FtTBB, FtFBB, FtCond);
229 ChangedMBBs.insert(FtMBB);
230 }
231
232 // If BB is the loop latch, we may have a new loop headr.
233 if (MBB == L->getLoopLatch()) {
234 assert(MLI->isLoopHeader(SuccMBB) &&
235 "Only succ of loop latch is not the header?");
236 if (HasOneIntraSucc && IntraSucc)
237 std::replace(LoopHeaders.begin(),LoopHeaders.end(), SuccMBB, IntraSucc);
238 }
239 }
240
241 ++NumIntraMoved;
242 return Changed;
243}
244
Evan Cheng0269d3c2009-05-08 19:01:44 +0000245/// HeaderShouldBeAligned - Return true if the specified loop header block
246/// should be aligned. For now, we will not align it if all the predcessors
247/// (i.e. loop back edges) are laid out above the header. FIXME: Do not
248/// align small loops.
Evan Cheng9d3094b2009-05-12 23:58:14 +0000249bool
250CodePlacementOpt::HeaderShouldBeAligned(MachineBasicBlock *MBB, MachineLoop *L,
251 SmallPtrSet<MachineBasicBlock*, 4> &DoNotAlign) {
252 if (DoNotAlign.count(MBB))
253 return false;
254
255 bool BackEdgeBelow = false;
Evan Cheng0269d3c2009-05-08 19:01:44 +0000256 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
257 PE = MBB->pred_end(); PI != PE; ++PI) {
258 MachineBasicBlock *PredMBB = *PI;
Evan Cheng9d3094b2009-05-12 23:58:14 +0000259 if (PredMBB == MBB || PredMBB->getNumber() > MBB->getNumber()) {
260 BackEdgeBelow = true;
261 break;
262 }
Evan Cheng0269d3c2009-05-08 19:01:44 +0000263 }
Evan Cheng9d3094b2009-05-12 23:58:14 +0000264
265 if (!BackEdgeBelow)
266 return false;
267
268 // Ok, we are going to align this loop header. If it's an inner loop,
269 // do not align its outer loop.
270 MachineBasicBlock *PreHeader = L->getLoopPreheader();
271 if (PreHeader) {
272 MachineLoop *L = MLI->getLoopFor(PreHeader);
273 if (L) {
274 MachineBasicBlock *HeaderBlock = L->getHeader();
275 HeaderBlock->setAlignment(0);
276 DoNotAlign.insert(HeaderBlock);
277 }
278 }
279 return true;
Evan Cheng0269d3c2009-05-08 19:01:44 +0000280}
281
Evan Cheng7132e122009-05-07 05:49:39 +0000282/// AlignLoops - Align loop headers to target preferred alignments.
283///
284bool CodePlacementOpt::AlignLoops(MachineFunction &MF) {
Evan Cheng45e00102009-05-08 06:34:09 +0000285 const Function *F = MF.getFunction();
286 if (F->hasFnAttr(Attribute::OptimizeForSize))
Evan Cheng4f658e92008-02-29 17:52:15 +0000287 return false;
288
289 unsigned Align = TLI->getPrefLoopAlignment();
Evan Chengfb8075d2008-02-28 00:43:03 +0000290 if (!Align)
291 return false; // Don't care about loop alignment.
292
Evan Cheng45e00102009-05-08 06:34:09 +0000293 // Make sure blocks are numbered in order
294 MF.RenumberBlocks();
Devang Patel4ae641f2008-10-01 23:18:38 +0000295
Evan Cheng7132e122009-05-07 05:49:39 +0000296 bool Changed = false;
Evan Cheng9d3094b2009-05-12 23:58:14 +0000297 SmallPtrSet<MachineBasicBlock*, 4> DoNotAlign;
Evan Cheng45e00102009-05-08 06:34:09 +0000298 for (unsigned i = 0, e = LoopHeaders.size(); i != e; ++i) {
299 MachineBasicBlock *HeaderMBB = LoopHeaders[i];
300 MachineBasicBlock *PredMBB = prior(MachineFunction::iterator(HeaderMBB));
Evan Cheng9d3094b2009-05-12 23:58:14 +0000301 MachineLoop *L = MLI->getLoopFor(HeaderMBB);
302 if (L == MLI->getLoopFor(PredMBB))
Evan Cheng45e00102009-05-08 06:34:09 +0000303 // If previously BB is in the same loop, don't align this BB. We want
304 // to prevent adding noop's inside a loop.
Evan Cheng0269d3c2009-05-08 19:01:44 +0000305 continue;
Evan Cheng9d3094b2009-05-12 23:58:14 +0000306 if (HeaderShouldBeAligned(HeaderMBB, L, DoNotAlign)) {
Evan Cheng45e00102009-05-08 06:34:09 +0000307 HeaderMBB->setAlignment(Align);
Evan Cheng7132e122009-05-07 05:49:39 +0000308 Changed = true;
Evan Cheng45e00102009-05-08 06:34:09 +0000309 ++NumHeaderAligned;
Evan Chengdf908412008-11-27 01:16:00 +0000310 }
Evan Chengfb8075d2008-02-28 00:43:03 +0000311 }
312
Evan Cheng7132e122009-05-07 05:49:39 +0000313 return Changed;
314}
315
316bool CodePlacementOpt::runOnMachineFunction(MachineFunction &MF) {
317 MLI = &getAnalysis<MachineLoopInfo>();
318 if (MLI->empty())
319 return false; // No loops.
320
Evan Cheng45e00102009-05-08 06:34:09 +0000321 TLI = MF.getTarget().getTargetLowering();
322 TII = MF.getTarget().getInstrInfo();
323
324 // Analyze the BBs first and keep track of loop headers and BBs that
325 // end with an unconditional jmp to another block in the same loop.
326 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
327 MachineBasicBlock *MBB = I;
328 if (MBB->isLandingPad())
329 continue;
330 MachineLoop *L = MLI->getLoopFor(MBB);
331 if (!L)
332 continue;
333 if (MLI->isLoopHeader(MBB))
334 LoopHeaders.push_back(MBB);
335
336 MachineBasicBlock *TBB = 0, *FBB = 0;
337 SmallVector<MachineOperand, 4> Cond;
338 if (TII->AnalyzeBranch(*MBB, TBB, FBB, Cond) || !Cond.empty())
339 continue;
340 if (MLI->getLoopFor(TBB) == L && !TBB->isLandingPad())
341 UncondJmpMBBs.push_back(std::make_pair(MBB, TBB));
342 }
343
344 bool Changed = OptimizeIntraLoopEdges();
345
Evan Cheng7132e122009-05-07 05:49:39 +0000346 Changed |= AlignLoops(MF);
347
Evan Cheng45e00102009-05-08 06:34:09 +0000348 ChangedMBBs.clear();
349 UncondJmpMBBs.clear();
350 LoopHeaders.clear();
351
Evan Cheng7132e122009-05-07 05:49:39 +0000352 return Changed;
Evan Chengfb8075d2008-02-28 00:43:03 +0000353}