1 //===-- CodePlacementOpt.cpp - Code Placement pass. -----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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"
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");
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>
45 /// LoopHeaders - A list of BBs which are loop headers.
46 SmallVector<MachineBasicBlock*, 4> LoopHeaders;
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);
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
82 /// <fallthrough to B>
84 /// B: --> loop header
86 /// jcc <cond> C, [exit]
98 /// C: --> new loop header
100 /// <fallthough to B>
104 /// jcc <cond> C, [exit]
106 bool CodePlacementOpt::OptimizeIntraLoopEdges() {
107 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!");
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())
120 if (MLI->getLoopFor(TBB) != L || TBB->isLandingPad())
124 assert(MLI->getLoopFor(SuccMBB) == L &&
125 "Successor is not in the same loop!");
128 if (MBB->isLayoutSuccessor(SuccMBB)) {
129 // Successor is right after MBB, just eliminate the unconditional jmp.
131 TII->RemoveBranch(*MBB);
132 ChangedMBBs.insert(MBB);
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)) {
153 assert(FtFBB != SuccMBB && "Unexpected control flow!");
159 MachineLoop *PL = MLI->getLoopFor(PredMBB);
160 if (PL && (PL == L || PL->getLoopDepth() >= L->getLoopDepth()))
170 // Is it profitable? If SuccMBB can fallthrough itself, that can be changed
172 MachineBasicBlock *TBB = 0, *FBB = 0;
173 SmallVector<MachineOperand, 4> Cond;
174 if (TII->AnalyzeBranch(*SuccMBB, TBB, FBB, Cond))
176 if (!TBB && Cond.empty())
177 TBB = next(MachineFunction::iterator(SuccMBB));
178 else if (!FBB && !Cond.empty())
179 FBB = next(MachineFunction::iterator(SuccMBB));
181 // This calculate the cost of the transformation. Also, it finds the *only*
182 // intra-loop edge if there is one.
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) {
193 HasOneIntraSucc = false;
196 if (SuccMBB->isLayoutSuccessor(SSMBB))
197 // This will become a jmp.
199 else if (MBB->isLayoutSuccessor(SSMBB)) {
200 // One of the successor will become the new fallthrough.
204 } else if (!FBB && SSMBB == TBB && Cond.empty()) {
207 } else if (!Cond.empty() && !TII->ReverseBranchCondition(Cond)) {
208 assert(SSMBB == TBB);
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);
223 TII->InsertBranch(*SuccMBB, TBB, FBB, Cond);
224 ChangedMBBs.insert(MBB);
225 ChangedMBBs.insert(SuccMBB);
227 TII->RemoveBranch(*FtMBB);
228 TII->InsertBranch(*FtMBB, FtTBB, FtFBB, FtCond);
229 ChangedMBBs.insert(FtMBB);
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);
245 /// 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.
250 CodePlacementOpt::HeaderShouldBeAligned(MachineBasicBlock *MBB, MachineLoop *L,
251 SmallPtrSet<MachineBasicBlock*, 4> &DoNotAlign) {
252 if (DoNotAlign.count(MBB))
255 bool BackEdgeBelow = false;
256 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
257 PE = MBB->pred_end(); PI != PE; ++PI) {
258 MachineBasicBlock *PredMBB = *PI;
259 if (PredMBB == MBB || PredMBB->getNumber() > MBB->getNumber()) {
260 BackEdgeBelow = true;
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();
272 MachineLoop *L = MLI->getLoopFor(PreHeader);
274 MachineBasicBlock *HeaderBlock = L->getHeader();
275 HeaderBlock->setAlignment(0);
276 DoNotAlign.insert(HeaderBlock);
282 /// AlignLoops - Align loop headers to target preferred alignments.
284 bool CodePlacementOpt::AlignLoops(MachineFunction &MF) {
285 const Function *F = MF.getFunction();
286 if (F->hasFnAttr(Attribute::OptimizeForSize))
289 unsigned Align = TLI->getPrefLoopAlignment();
291 return false; // Don't care about loop alignment.
293 // Make sure blocks are numbered in order
296 bool Changed = false;
297 SmallPtrSet<MachineBasicBlock*, 4> DoNotAlign;
298 for (unsigned i = 0, e = LoopHeaders.size(); i != e; ++i) {
299 MachineBasicBlock *HeaderMBB = LoopHeaders[i];
300 MachineBasicBlock *PredMBB = prior(MachineFunction::iterator(HeaderMBB));
301 MachineLoop *L = MLI->getLoopFor(HeaderMBB);
302 if (L == MLI->getLoopFor(PredMBB))
303 // If previously BB is in the same loop, don't align this BB. We want
304 // to prevent adding noop's inside a loop.
306 if (HeaderShouldBeAligned(HeaderMBB, L, DoNotAlign)) {
307 HeaderMBB->setAlignment(Align);
316 bool CodePlacementOpt::runOnMachineFunction(MachineFunction &MF) {
317 MLI = &getAnalysis<MachineLoopInfo>();
319 return false; // No loops.
321 TLI = MF.getTarget().getTargetLowering();
322 TII = MF.getTarget().getInstrInfo();
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())
330 MachineLoop *L = MLI->getLoopFor(MBB);
333 if (MLI->isLoopHeader(MBB))
334 LoopHeaders.push_back(MBB);
336 MachineBasicBlock *TBB = 0, *FBB = 0;
337 SmallVector<MachineOperand, 4> Cond;
338 if (TII->AnalyzeBranch(*MBB, TBB, FBB, Cond) || !Cond.empty())
340 if (MLI->getLoopFor(TBB) == L && !TBB->isLandingPad())
341 UncondJmpMBBs.push_back(std::make_pair(MBB, TBB));
344 bool Changed = OptimizeIntraLoopEdges();
346 Changed |= AlignLoops(MF);
349 UncondJmpMBBs.clear();