blob: 757f60b19c1d9e99f2482e664609b1d5049a7958 [file] [log] [blame]
Chris Lattnerc4ce73f2008-01-04 07:36:53 +00001//===-- MachineSink.cpp - Sinking for machine instructions ----------------===//
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//
Bill Wendling05c68372010-06-02 23:04:26 +000010// This pass moves instructions into successor blocks when possible, so that
Dan Gohmana5225ad2009-08-05 01:19:01 +000011// they aren't executed on paths where their results aren't needed.
12//
13// This pass is not intended to be a replacement or a complete alternative
14// for an LLVM-IR-level sinking pass. It is only designed to sink simple
15// constructs that are not exposed before lowering and instruction selection.
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000016//
17//===----------------------------------------------------------------------===//
18
19#define DEBUG_TYPE "machine-sink"
20#include "llvm/CodeGen/Passes.h"
Evan Cheng6edb0ea2010-09-17 22:28:18 +000021#include "llvm/ADT/SmallSet.h"
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000022#include "llvm/ADT/Statistic.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000023#include "llvm/Analysis/AliasAnalysis.h"
24#include "llvm/CodeGen/MachineDominators.h"
25#include "llvm/CodeGen/MachineLoopInfo.h"
26#include "llvm/CodeGen/MachineRegisterInfo.h"
Evan Cheng4dc301a2010-08-19 17:33:11 +000027#include "llvm/Support/CommandLine.h"
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000028#include "llvm/Support/Debug.h"
Bill Wendling1e973aa2009-08-22 20:26:23 +000029#include "llvm/Support/raw_ostream.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000030#include "llvm/Target/TargetInstrInfo.h"
31#include "llvm/Target/TargetMachine.h"
32#include "llvm/Target/TargetRegisterInfo.h"
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000033using namespace llvm;
34
Andrew Trick1df91b02012-02-08 21:22:43 +000035static cl::opt<bool>
Evan Cheng4dc301a2010-08-19 17:33:11 +000036SplitEdges("machine-sink-split",
37 cl::desc("Split critical edges during machine sinking"),
Evan Cheng44be1a82010-09-20 22:52:00 +000038 cl::init(true), cl::Hidden);
Evan Cheng4dc301a2010-08-19 17:33:11 +000039
Evan Cheng6edb0ea2010-09-17 22:28:18 +000040STATISTIC(NumSunk, "Number of machine instructions sunk");
41STATISTIC(NumSplit, "Number of critical edges split");
42STATISTIC(NumCoalesces, "Number of copies coalesced");
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000043
44namespace {
Nick Lewycky6726b6d2009-10-25 06:33:48 +000045 class MachineSinking : public MachineFunctionPass {
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000046 const TargetInstrInfo *TII;
Dan Gohman19778e72009-09-25 22:53:29 +000047 const TargetRegisterInfo *TRI;
Evan Cheng6edb0ea2010-09-17 22:28:18 +000048 MachineRegisterInfo *MRI; // Machine register information
Dan Gohmana5225ad2009-08-05 01:19:01 +000049 MachineDominatorTree *DT; // Machine dominator tree
Jakob Stoklund Olesen626f3d72010-04-15 23:41:02 +000050 MachineLoopInfo *LI;
Dan Gohmana70dca12009-10-09 23:27:56 +000051 AliasAnalysis *AA;
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000052
Evan Cheng6edb0ea2010-09-17 22:28:18 +000053 // Remember which edges have been considered for breaking.
54 SmallSet<std::pair<MachineBasicBlock*,MachineBasicBlock*>, 8>
55 CEBCandidates;
56
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000057 public:
58 static char ID; // Pass identification
Owen Anderson081c34b2010-10-19 17:21:58 +000059 MachineSinking() : MachineFunctionPass(ID) {
60 initializeMachineSinkingPass(*PassRegistry::getPassRegistry());
61 }
Jim Grosbach6ee358b2010-06-03 23:49:57 +000062
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000063 virtual bool runOnMachineFunction(MachineFunction &MF);
Jim Grosbach6ee358b2010-06-03 23:49:57 +000064
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000065 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohman845012e2009-07-31 23:37:33 +000066 AU.setPreservesCFG();
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000067 MachineFunctionPass::getAnalysisUsage(AU);
Dan Gohmana70dca12009-10-09 23:27:56 +000068 AU.addRequired<AliasAnalysis>();
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000069 AU.addRequired<MachineDominatorTree>();
Jakob Stoklund Olesen626f3d72010-04-15 23:41:02 +000070 AU.addRequired<MachineLoopInfo>();
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000071 AU.addPreserved<MachineDominatorTree>();
Jakob Stoklund Olesen626f3d72010-04-15 23:41:02 +000072 AU.addPreserved<MachineLoopInfo>();
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000073 }
Evan Cheng6edb0ea2010-09-17 22:28:18 +000074
75 virtual void releaseMemory() {
76 CEBCandidates.clear();
77 }
78
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000079 private:
80 bool ProcessBlock(MachineBasicBlock &MBB);
Evan Cheng6edb0ea2010-09-17 22:28:18 +000081 bool isWorthBreakingCriticalEdge(MachineInstr *MI,
82 MachineBasicBlock *From,
83 MachineBasicBlock *To);
84 MachineBasicBlock *SplitCriticalEdge(MachineInstr *MI,
85 MachineBasicBlock *From,
86 MachineBasicBlock *To,
Evan Cheng7af6dc42010-09-20 19:12:55 +000087 bool BreakPHIEdge);
Chris Lattneraad193a2008-01-12 00:17:41 +000088 bool SinkInstruction(MachineInstr *MI, bool &SawStore);
Evan Chengc3439ad2010-08-18 23:09:25 +000089 bool AllUsesDominatedByBlock(unsigned Reg, MachineBasicBlock *MBB,
Evan Cheng6edb0ea2010-09-17 22:28:18 +000090 MachineBasicBlock *DefMBB,
Evan Cheng7af6dc42010-09-20 19:12:55 +000091 bool &BreakPHIEdge, bool &LocalUse) const;
Devang Patel52111342011-12-14 23:20:38 +000092 MachineBasicBlock *FindSuccToSinkTo(MachineInstr *MI, MachineBasicBlock *MBB,
93 bool &BreakPHIEdge);
Andrew Trick1df91b02012-02-08 21:22:43 +000094 bool isProfitableToSinkTo(unsigned Reg, MachineInstr *MI,
Devang Patel52111342011-12-14 23:20:38 +000095 MachineBasicBlock *MBB,
96 MachineBasicBlock *SuccToSinkTo);
Devang Patele265bcf2011-12-08 21:48:01 +000097
Evan Cheng6edb0ea2010-09-17 22:28:18 +000098 bool PerformTrivialForwardCoalescing(MachineInstr *MI,
99 MachineBasicBlock *MBB);
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000100 };
Manman Ren53b59d12012-07-31 18:10:39 +0000101
102 // SuccessorSorter - Sort Successors according to their loop depth.
103 struct SuccessorSorter {
104 SuccessorSorter(MachineLoopInfo *LoopInfo) : LI(LoopInfo) {}
105 bool operator()(const MachineBasicBlock *LHS,
106 const MachineBasicBlock *RHS) const {
107 return LI->getLoopDepth(LHS) < LI->getLoopDepth(RHS);
108 }
109 MachineLoopInfo *LI;
110 };
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000111} // end anonymous namespace
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000112
Dan Gohman844731a2008-05-13 00:00:25 +0000113char MachineSinking::ID = 0;
Andrew Trick1dd8c852012-02-08 21:23:13 +0000114char &llvm::MachineSinkingID = MachineSinking::ID;
Owen Anderson2ab36d32010-10-12 19:48:12 +0000115INITIALIZE_PASS_BEGIN(MachineSinking, "machine-sink",
116 "Machine code sinking", false, false)
117INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
118INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
119INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
120INITIALIZE_PASS_END(MachineSinking, "machine-sink",
Owen Andersonce665bd2010-10-07 22:25:06 +0000121 "Machine code sinking", false, false)
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000122
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000123bool MachineSinking::PerformTrivialForwardCoalescing(MachineInstr *MI,
124 MachineBasicBlock *MBB) {
125 if (!MI->isCopy())
126 return false;
127
128 unsigned SrcReg = MI->getOperand(1).getReg();
129 unsigned DstReg = MI->getOperand(0).getReg();
130 if (!TargetRegisterInfo::isVirtualRegister(SrcReg) ||
131 !TargetRegisterInfo::isVirtualRegister(DstReg) ||
132 !MRI->hasOneNonDBGUse(SrcReg))
133 return false;
134
135 const TargetRegisterClass *SRC = MRI->getRegClass(SrcReg);
136 const TargetRegisterClass *DRC = MRI->getRegClass(DstReg);
137 if (SRC != DRC)
138 return false;
139
140 MachineInstr *DefMI = MRI->getVRegDef(SrcReg);
141 if (DefMI->isCopyLike())
142 return false;
143 DEBUG(dbgs() << "Coalescing: " << *DefMI);
144 DEBUG(dbgs() << "*** to: " << *MI);
145 MRI->replaceRegWith(DstReg, SrcReg);
146 MI->eraseFromParent();
147 ++NumCoalesces;
148 return true;
149}
150
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000151/// AllUsesDominatedByBlock - Return true if all uses of the specified register
Evan Chengc3439ad2010-08-18 23:09:25 +0000152/// occur in blocks dominated by the specified block. If any use is in the
153/// definition block, then return false since it is never legal to move def
154/// after uses.
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000155bool
156MachineSinking::AllUsesDominatedByBlock(unsigned Reg,
157 MachineBasicBlock *MBB,
158 MachineBasicBlock *DefMBB,
Evan Cheng7af6dc42010-09-20 19:12:55 +0000159 bool &BreakPHIEdge,
160 bool &LocalUse) const {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000161 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
162 "Only makes sense for vregs");
Evan Cheng23997862010-09-18 06:42:17 +0000163
Devang Patelf5b9a742011-12-09 01:25:04 +0000164 // Ignore debug uses because debug info doesn't affect the code.
Evan Cheng23997862010-09-18 06:42:17 +0000165 if (MRI->use_nodbg_empty(Reg))
166 return true;
167
Evan Cheng7af6dc42010-09-20 19:12:55 +0000168 // BreakPHIEdge is true if all the uses are in the successor MBB being sunken
169 // into and they are all PHI nodes. In this case, machine-sink must break
170 // the critical edge first. e.g.
171 //
Evan Cheng23997862010-09-18 06:42:17 +0000172 // BB#1: derived from LLVM BB %bb4.preheader
173 // Predecessors according to CFG: BB#0
174 // ...
175 // %reg16385<def> = DEC64_32r %reg16437, %EFLAGS<imp-def,dead>
176 // ...
177 // JE_4 <BB#37>, %EFLAGS<imp-use>
178 // Successors according to CFG: BB#37 BB#2
179 //
180 // BB#2: derived from LLVM BB %bb.nph
181 // Predecessors according to CFG: BB#0 BB#1
182 // %reg16386<def> = PHI %reg16434, <BB#0>, %reg16385, <BB#1>
Evan Cheng7af6dc42010-09-20 19:12:55 +0000183 BreakPHIEdge = true;
Evan Cheng23997862010-09-18 06:42:17 +0000184 for (MachineRegisterInfo::use_nodbg_iterator
185 I = MRI->use_nodbg_begin(Reg), E = MRI->use_nodbg_end();
186 I != E; ++I) {
187 MachineInstr *UseInst = &*I;
188 MachineBasicBlock *UseBlock = UseInst->getParent();
189 if (!(UseBlock == MBB && UseInst->isPHI() &&
190 UseInst->getOperand(I.getOperandNo()+1).getMBB() == DefMBB)) {
Evan Cheng7af6dc42010-09-20 19:12:55 +0000191 BreakPHIEdge = false;
Evan Cheng23997862010-09-18 06:42:17 +0000192 break;
193 }
194 }
Evan Cheng7af6dc42010-09-20 19:12:55 +0000195 if (BreakPHIEdge)
Evan Cheng23997862010-09-18 06:42:17 +0000196 return true;
197
Bill Wendling05c68372010-06-02 23:04:26 +0000198 for (MachineRegisterInfo::use_nodbg_iterator
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000199 I = MRI->use_nodbg_begin(Reg), E = MRI->use_nodbg_end();
Bill Wendling05c68372010-06-02 23:04:26 +0000200 I != E; ++I) {
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000201 // Determine the block of the use.
202 MachineInstr *UseInst = &*I;
203 MachineBasicBlock *UseBlock = UseInst->getParent();
Evan Cheng23997862010-09-18 06:42:17 +0000204 if (UseInst->isPHI()) {
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000205 // PHI nodes use the operand in the predecessor block, not the block with
206 // the PHI.
207 UseBlock = UseInst->getOperand(I.getOperandNo()+1).getMBB();
Evan Chenge5e79462010-08-19 18:33:29 +0000208 } else if (UseBlock == DefMBB) {
209 LocalUse = true;
210 return false;
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000211 }
Bill Wendling05c68372010-06-02 23:04:26 +0000212
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000213 // Check that it dominates.
214 if (!DT->dominates(MBB, UseBlock))
215 return false;
216 }
Bill Wendling05c68372010-06-02 23:04:26 +0000217
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000218 return true;
219}
220
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000221bool MachineSinking::runOnMachineFunction(MachineFunction &MF) {
David Greenec19a9cd2010-01-05 01:26:00 +0000222 DEBUG(dbgs() << "******** Machine Sinking ********\n");
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000223
Dan Gohman4e9785e2009-10-19 14:52:05 +0000224 const TargetMachine &TM = MF.getTarget();
225 TII = TM.getInstrInfo();
226 TRI = TM.getRegisterInfo();
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000227 MRI = &MF.getRegInfo();
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000228 DT = &getAnalysis<MachineDominatorTree>();
Jakob Stoklund Olesen626f3d72010-04-15 23:41:02 +0000229 LI = &getAnalysis<MachineLoopInfo>();
Dan Gohmana70dca12009-10-09 23:27:56 +0000230 AA = &getAnalysis<AliasAnalysis>();
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000231
232 bool EverMadeChange = false;
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000233
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000234 while (1) {
235 bool MadeChange = false;
236
237 // Process all basic blocks.
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000238 CEBCandidates.clear();
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000239 for (MachineFunction::iterator I = MF.begin(), E = MF.end();
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000240 I != E; ++I)
241 MadeChange |= ProcessBlock(*I);
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000242
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000243 // If this iteration over the code changed anything, keep iterating.
244 if (!MadeChange) break;
245 EverMadeChange = true;
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000246 }
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000247 return EverMadeChange;
248}
249
250bool MachineSinking::ProcessBlock(MachineBasicBlock &MBB) {
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000251 // Can't sink anything out of a block that has less than two successors.
Chris Lattner296185c2009-04-10 16:38:36 +0000252 if (MBB.succ_size() <= 1 || MBB.empty()) return false;
253
Dan Gohmanc4ae94d2010-04-05 19:17:22 +0000254 // Don't bother sinking code out of unreachable blocks. In addition to being
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000255 // unprofitable, it can also lead to infinite looping, because in an
256 // unreachable loop there may be nowhere to stop.
Dan Gohmanc4ae94d2010-04-05 19:17:22 +0000257 if (!DT->isReachableFromEntry(&MBB)) return false;
258
Chris Lattner296185c2009-04-10 16:38:36 +0000259 bool MadeChange = false;
260
Chris Lattneraad193a2008-01-12 00:17:41 +0000261 // Walk the basic block bottom-up. Remember if we saw a store.
Chris Lattner296185c2009-04-10 16:38:36 +0000262 MachineBasicBlock::iterator I = MBB.end();
263 --I;
264 bool ProcessedBegin, SawStore = false;
265 do {
266 MachineInstr *MI = I; // The instruction to sink.
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000267
Chris Lattner296185c2009-04-10 16:38:36 +0000268 // Predecrement I (if it's not begin) so that it isn't invalidated by
269 // sinking.
270 ProcessedBegin = I == MBB.begin();
271 if (!ProcessedBegin)
272 --I;
Dale Johannesenb0812f12010-03-05 00:02:59 +0000273
274 if (MI->isDebugValue())
275 continue;
276
Evan Chengcfea9852011-04-11 18:47:20 +0000277 bool Joined = PerformTrivialForwardCoalescing(MI, &MBB);
278 if (Joined) {
279 MadeChange = true;
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000280 continue;
Evan Chengcfea9852011-04-11 18:47:20 +0000281 }
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000282
Chris Lattner296185c2009-04-10 16:38:36 +0000283 if (SinkInstruction(MI, SawStore))
284 ++NumSunk, MadeChange = true;
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000285
Chris Lattner296185c2009-04-10 16:38:36 +0000286 // If we just processed the first instruction in the block, we're done.
287 } while (!ProcessedBegin);
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000288
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000289 return MadeChange;
290}
291
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000292bool MachineSinking::isWorthBreakingCriticalEdge(MachineInstr *MI,
293 MachineBasicBlock *From,
294 MachineBasicBlock *To) {
295 // FIXME: Need much better heuristics.
296
297 // If the pass has already considered breaking this edge (during this pass
298 // through the function), then let's go ahead and break it. This means
299 // sinking multiple "cheap" instructions into the same block.
300 if (!CEBCandidates.insert(std::make_pair(From, To)))
301 return true;
302
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000303 if (!MI->isCopy() && !MI->isAsCheapAsAMove())
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000304 return true;
305
306 // MI is cheap, we probably don't want to break the critical edge for it.
307 // However, if this would allow some definitions of its source operands
308 // to be sunk then it's probably worth it.
309 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
310 const MachineOperand &MO = MI->getOperand(i);
311 if (!MO.isReg()) continue;
312 unsigned Reg = MO.getReg();
313 if (Reg == 0 || !TargetRegisterInfo::isPhysicalRegister(Reg))
314 continue;
315 if (MRI->hasOneNonDBGUse(Reg))
316 return true;
317 }
318
319 return false;
320}
321
322MachineBasicBlock *MachineSinking::SplitCriticalEdge(MachineInstr *MI,
323 MachineBasicBlock *FromBB,
324 MachineBasicBlock *ToBB,
Evan Cheng7af6dc42010-09-20 19:12:55 +0000325 bool BreakPHIEdge) {
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000326 if (!isWorthBreakingCriticalEdge(MI, FromBB, ToBB))
327 return 0;
328
Evan Cheng4dc301a2010-08-19 17:33:11 +0000329 // Avoid breaking back edge. From == To means backedge for single BB loop.
Evan Cheng44be1a82010-09-20 22:52:00 +0000330 if (!SplitEdges || FromBB == ToBB)
Evan Cheng4dc301a2010-08-19 17:33:11 +0000331 return 0;
332
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000333 // Check for backedges of more "complex" loops.
334 if (LI->getLoopFor(FromBB) == LI->getLoopFor(ToBB) &&
335 LI->isLoopHeader(ToBB))
336 return 0;
337
338 // It's not always legal to break critical edges and sink the computation
339 // to the edge.
340 //
341 // BB#1:
342 // v1024
343 // Beq BB#3
344 // <fallthrough>
345 // BB#2:
346 // ... no uses of v1024
347 // <fallthrough>
348 // BB#3:
349 // ...
350 // = v1024
351 //
352 // If BB#1 -> BB#3 edge is broken and computation of v1024 is inserted:
353 //
354 // BB#1:
355 // ...
356 // Bne BB#2
357 // BB#4:
358 // v1024 =
359 // B BB#3
360 // BB#2:
361 // ... no uses of v1024
362 // <fallthrough>
363 // BB#3:
364 // ...
365 // = v1024
366 //
367 // This is incorrect since v1024 is not computed along the BB#1->BB#2->BB#3
368 // flow. We need to ensure the new basic block where the computation is
369 // sunk to dominates all the uses.
370 // It's only legal to break critical edge and sink the computation to the
371 // new block if all the predecessors of "To", except for "From", are
372 // not dominated by "From". Given SSA property, this means these
373 // predecessors are dominated by "To".
374 //
375 // There is no need to do this check if all the uses are PHI nodes. PHI
376 // sources are only defined on the specific predecessor edges.
Evan Cheng7af6dc42010-09-20 19:12:55 +0000377 if (!BreakPHIEdge) {
Evan Cheng4dc301a2010-08-19 17:33:11 +0000378 for (MachineBasicBlock::pred_iterator PI = ToBB->pred_begin(),
379 E = ToBB->pred_end(); PI != E; ++PI) {
380 if (*PI == FromBB)
381 continue;
382 if (!DT->dominates(ToBB, *PI))
383 return 0;
384 }
Evan Cheng4dc301a2010-08-19 17:33:11 +0000385 }
386
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000387 return FromBB->SplitCriticalEdge(ToBB, this);
Evan Cheng4dc301a2010-08-19 17:33:11 +0000388}
389
Evan Chengb0cdf8a2010-09-23 06:53:00 +0000390static bool AvoidsSinking(MachineInstr *MI, MachineRegisterInfo *MRI) {
391 return MI->isInsertSubreg() || MI->isSubregToReg() || MI->isRegSequence();
392}
393
Andrew Trick1df91b02012-02-08 21:22:43 +0000394/// collectDebgValues - Scan instructions following MI and collect any
Devang Patel541a81c2011-09-07 00:07:58 +0000395/// matching DBG_VALUEs.
Andrew Trick1df91b02012-02-08 21:22:43 +0000396static void collectDebugValues(MachineInstr *MI,
Devang Patel541a81c2011-09-07 00:07:58 +0000397 SmallVector<MachineInstr *, 2> & DbgValues) {
398 DbgValues.clear();
399 if (!MI->getOperand(0).isReg())
400 return;
401
402 MachineBasicBlock::iterator DI = MI; ++DI;
403 for (MachineBasicBlock::iterator DE = MI->getParent()->end();
404 DI != DE; ++DI) {
405 if (!DI->isDebugValue())
406 return;
407 if (DI->getOperand(0).isReg() &&
408 DI->getOperand(0).getReg() == MI->getOperand(0).getReg())
409 DbgValues.push_back(DI);
410 }
411}
412
Devang Patel52111342011-12-14 23:20:38 +0000413/// isPostDominatedBy - Return true if A is post dominated by B.
414static bool isPostDominatedBy(MachineBasicBlock *A, MachineBasicBlock *B) {
415
416 // FIXME - Use real post dominator.
417 if (A->succ_size() != 2)
418 return false;
419 MachineBasicBlock::succ_iterator I = A->succ_begin();
420 if (B == *I)
421 ++I;
422 MachineBasicBlock *OtherSuccBlock = *I;
423 if (OtherSuccBlock->succ_size() != 1 ||
424 *(OtherSuccBlock->succ_begin()) != B)
425 return false;
426
427 return true;
428}
429
430/// isProfitableToSinkTo - Return true if it is profitable to sink MI.
Andrew Trick1df91b02012-02-08 21:22:43 +0000431bool MachineSinking::isProfitableToSinkTo(unsigned Reg, MachineInstr *MI,
Devang Patel52111342011-12-14 23:20:38 +0000432 MachineBasicBlock *MBB,
433 MachineBasicBlock *SuccToSinkTo) {
434 assert (MI && "Invalid MachineInstr!");
435 assert (SuccToSinkTo && "Invalid SinkTo Candidate BB");
436
437 if (MBB == SuccToSinkTo)
438 return false;
439
440 // It is profitable if SuccToSinkTo does not post dominate current block.
441 if (!isPostDominatedBy(MBB, SuccToSinkTo))
442 return true;
443
444 // Check if only use in post dominated block is PHI instruction.
445 bool NonPHIUse = false;
446 for (MachineRegisterInfo::use_nodbg_iterator
447 I = MRI->use_nodbg_begin(Reg), E = MRI->use_nodbg_end();
448 I != E; ++I) {
449 MachineInstr *UseInst = &*I;
450 MachineBasicBlock *UseBlock = UseInst->getParent();
451 if (UseBlock == SuccToSinkTo && !UseInst->isPHI())
452 NonPHIUse = true;
453 }
454 if (!NonPHIUse)
455 return true;
456
457 // If SuccToSinkTo post dominates then also it may be profitable if MI
458 // can further profitably sinked into another block in next round.
459 bool BreakPHIEdge = false;
460 // FIXME - If finding successor is compile time expensive then catch results.
461 if (MachineBasicBlock *MBB2 = FindSuccToSinkTo(MI, SuccToSinkTo, BreakPHIEdge))
462 return isProfitableToSinkTo(Reg, MI, SuccToSinkTo, MBB2);
463
464 // If SuccToSinkTo is final destination and it is a post dominator of current
465 // block then it is not profitable to sink MI into SuccToSinkTo block.
466 return false;
467}
468
Devang Patele265bcf2011-12-08 21:48:01 +0000469/// FindSuccToSinkTo - Find a successor to sink this instruction to.
470MachineBasicBlock *MachineSinking::FindSuccToSinkTo(MachineInstr *MI,
Devang Patel52111342011-12-14 23:20:38 +0000471 MachineBasicBlock *MBB,
472 bool &BreakPHIEdge) {
473
474 assert (MI && "Invalid MachineInstr!");
475 assert (MBB && "Invalid MachineBasicBlock!");
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000476
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000477 // Loop over all the operands of the specified instruction. If there is
478 // anything we can't handle, bail out.
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000479
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000480 // SuccToSinkTo - This is the successor to sink this instruction to, once we
481 // decide.
482 MachineBasicBlock *SuccToSinkTo = 0;
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000483 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
484 const MachineOperand &MO = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000485 if (!MO.isReg()) continue; // Ignore non-register operands.
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000486
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000487 unsigned Reg = MO.getReg();
488 if (Reg == 0) continue;
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000489
Dan Gohman6f0d0242008-02-10 18:45:23 +0000490 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
Dan Gohman19778e72009-09-25 22:53:29 +0000491 if (MO.isUse()) {
492 // If the physreg has no defs anywhere, it's just an ambient register
Dan Gohman45094e32009-09-26 02:34:00 +0000493 // and we can freely move its uses. Alternatively, if it's allocatable,
494 // it could get allocated to something with a def during allocation.
Jakob Stoklund Olesenc035c942012-01-16 22:34:08 +0000495 if (!MRI->isConstantPhysReg(Reg, *MBB->getParent()))
Devang Patele265bcf2011-12-08 21:48:01 +0000496 return NULL;
Bill Wendling730c07e2010-06-25 20:48:10 +0000497 } else if (!MO.isDead()) {
498 // A def that isn't dead. We can't move it.
Devang Patele265bcf2011-12-08 21:48:01 +0000499 return NULL;
Dan Gohman19778e72009-09-25 22:53:29 +0000500 }
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000501 } else {
502 // Virtual register uses are always safe to sink.
503 if (MO.isUse()) continue;
Evan Chengb6f54172009-02-07 01:21:47 +0000504
505 // If it's not safe to move defs of the register class, then abort.
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000506 if (!TII->isSafeToMoveRegClassDefs(MRI->getRegClass(Reg)))
Devang Patele265bcf2011-12-08 21:48:01 +0000507 return NULL;
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000508
Chris Lattnere430e1c2008-01-05 06:47:58 +0000509 // FIXME: This picks a successor to sink into based on having one
510 // successor that dominates all the uses. However, there are cases where
511 // sinking can happen but where the sink point isn't a successor. For
512 // example:
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000513 //
Chris Lattnere430e1c2008-01-05 06:47:58 +0000514 // x = computation
515 // if () {} else {}
516 // use x
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000517 //
Bill Wendling05c68372010-06-02 23:04:26 +0000518 // the instruction could be sunk over the whole diamond for the
Chris Lattnere430e1c2008-01-05 06:47:58 +0000519 // if/then/else (or loop, etc), allowing it to be sunk into other blocks
520 // after that.
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000521
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000522 // Virtual register defs can only be sunk if all their uses are in blocks
523 // dominated by one of the successors.
524 if (SuccToSinkTo) {
525 // If a previous operand picked a block to sink to, then this operand
526 // must be sinkable to the same block.
Evan Chenge5e79462010-08-19 18:33:29 +0000527 bool LocalUse = false;
Devang Patel52111342011-12-14 23:20:38 +0000528 if (!AllUsesDominatedByBlock(Reg, SuccToSinkTo, MBB,
Evan Cheng7af6dc42010-09-20 19:12:55 +0000529 BreakPHIEdge, LocalUse))
Devang Patele265bcf2011-12-08 21:48:01 +0000530 return NULL;
Bill Wendling05c68372010-06-02 23:04:26 +0000531
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000532 continue;
533 }
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000534
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000535 // Otherwise, we should look at all the successors and decide which one
536 // we should sink to.
Manman Ren53b59d12012-07-31 18:10:39 +0000537 // We give successors with smaller loop depth higher priority.
538 SmallVector<MachineBasicBlock*, 4> Succs(MBB->succ_begin(), MBB->succ_end());
Manman Renf99efdf2012-07-31 20:45:38 +0000539 std::stable_sort(Succs.begin(), Succs.end(), SuccessorSorter(LI));
Craig Topperf22fd3f2013-07-03 05:11:49 +0000540 for (SmallVectorImpl<MachineBasicBlock *>::iterator SI = Succs.begin(),
541 E = Succs.end(); SI != E; ++SI) {
Devang Patel52111342011-12-14 23:20:38 +0000542 MachineBasicBlock *SuccBlock = *SI;
Evan Chenge5e79462010-08-19 18:33:29 +0000543 bool LocalUse = false;
Devang Patel52111342011-12-14 23:20:38 +0000544 if (AllUsesDominatedByBlock(Reg, SuccBlock, MBB,
Evan Cheng7af6dc42010-09-20 19:12:55 +0000545 BreakPHIEdge, LocalUse)) {
Devang Patelcf405ba2011-12-08 21:33:23 +0000546 SuccToSinkTo = SuccBlock;
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000547 break;
548 }
Evan Chengc3439ad2010-08-18 23:09:25 +0000549 if (LocalUse)
550 // Def is used locally, it's never safe to move this def.
Devang Patele265bcf2011-12-08 21:48:01 +0000551 return NULL;
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000552 }
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000553
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000554 // If we couldn't find a block to sink to, ignore this instruction.
555 if (SuccToSinkTo == 0)
Devang Patele265bcf2011-12-08 21:48:01 +0000556 return NULL;
Devang Patel52111342011-12-14 23:20:38 +0000557 else if (!isProfitableToSinkTo(Reg, MI, MBB, SuccToSinkTo))
558 return NULL;
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000559 }
560 }
Devang Patel7f7f0902011-12-08 23:52:00 +0000561
562 // It is not possible to sink an instruction into its own block. This can
563 // happen with loops.
Devang Patel52111342011-12-14 23:20:38 +0000564 if (MBB == SuccToSinkTo)
Devang Patel7f7f0902011-12-08 23:52:00 +0000565 return NULL;
566
567 // It's not safe to sink instructions to EH landing pad. Control flow into
568 // landing pad is implicitly defined.
569 if (SuccToSinkTo && SuccToSinkTo->isLandingPad())
570 return NULL;
571
Devang Patele265bcf2011-12-08 21:48:01 +0000572 return SuccToSinkTo;
573}
574
575/// SinkInstruction - Determine whether it is safe to sink the specified machine
576/// instruction out of its current block into a successor.
577bool MachineSinking::SinkInstruction(MachineInstr *MI, bool &SawStore) {
578 // Don't sink insert_subreg, subreg_to_reg, reg_sequence. These are meant to
579 // be close to the source to make it easier to coalesce.
580 if (AvoidsSinking(MI, MRI))
581 return false;
582
583 // Check if it's safe to move the instruction.
584 if (!MI->isSafeToMove(TII, AA, SawStore))
585 return false;
586
587 // FIXME: This should include support for sinking instructions within the
588 // block they are currently in to shorten the live ranges. We often get
589 // instructions sunk into the top of a large block, but it would be better to
590 // also sink them down before their first use in the block. This xform has to
591 // be careful not to *increase* register pressure though, e.g. sinking
592 // "x = y + z" down if it kills y and z would increase the live ranges of y
593 // and z and only shrink the live range of x.
594
595 bool BreakPHIEdge = false;
Devang Patel52111342011-12-14 23:20:38 +0000596 MachineBasicBlock *ParentBlock = MI->getParent();
597 MachineBasicBlock *SuccToSinkTo = FindSuccToSinkTo(MI, ParentBlock, BreakPHIEdge);
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000598
Chris Lattner9bb459b2008-01-05 01:39:17 +0000599 // If there are no outputs, it must have side-effects.
600 if (SuccToSinkTo == 0)
601 return false;
Evan Chengb5999792009-02-15 08:36:12 +0000602
Bill Wendling869d60d2010-06-03 07:54:20 +0000603
Daniel Dunbard24c9d52010-06-23 00:48:25 +0000604 // If the instruction to move defines a dead physical register which is live
605 // when leaving the basic block, don't move it because it could turn into a
606 // "zombie" define of that preg. E.g., EFLAGS. (<rdar://problem/8030636>)
Bill Wendling730c07e2010-06-25 20:48:10 +0000607 for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
608 const MachineOperand &MO = MI->getOperand(I);
609 if (!MO.isReg()) continue;
610 unsigned Reg = MO.getReg();
611 if (Reg == 0 || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
612 if (SuccToSinkTo->isLiveIn(Reg))
Bill Wendling869d60d2010-06-03 07:54:20 +0000613 return false;
Bill Wendling730c07e2010-06-25 20:48:10 +0000614 }
Bill Wendling869d60d2010-06-03 07:54:20 +0000615
Bill Wendling05c68372010-06-02 23:04:26 +0000616 DEBUG(dbgs() << "Sink instr " << *MI << "\tinto block " << *SuccToSinkTo);
617
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000618 // If the block has multiple predecessors, this would introduce computation on
619 // a path that it doesn't already exist. We could split the critical edge,
620 // but for now we just punt.
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000621 if (SuccToSinkTo->pred_size() > 1) {
Jakob Stoklund Olesen8d171602010-04-13 19:06:14 +0000622 // We cannot sink a load across a critical edge - there may be stores in
623 // other code paths.
Evan Cheng4dc301a2010-08-19 17:33:11 +0000624 bool TryBreak = false;
Jakob Stoklund Olesen8d171602010-04-13 19:06:14 +0000625 bool store = true;
626 if (!MI->isSafeToMove(TII, AA, store)) {
Evan Chengf942c132010-08-19 23:33:02 +0000627 DEBUG(dbgs() << " *** NOTE: Won't sink load along critical edge.\n");
Evan Cheng4dc301a2010-08-19 17:33:11 +0000628 TryBreak = true;
Jakob Stoklund Olesen8d171602010-04-13 19:06:14 +0000629 }
630
631 // We don't want to sink across a critical edge if we don't dominate the
632 // successor. We could be introducing calculations to new code paths.
Evan Cheng4dc301a2010-08-19 17:33:11 +0000633 if (!TryBreak && !DT->dominates(ParentBlock, SuccToSinkTo)) {
Evan Chengf942c132010-08-19 23:33:02 +0000634 DEBUG(dbgs() << " *** NOTE: Critical edge found\n");
Evan Cheng4dc301a2010-08-19 17:33:11 +0000635 TryBreak = true;
Jakob Stoklund Olesen8d171602010-04-13 19:06:14 +0000636 }
637
Jakob Stoklund Olesen626f3d72010-04-15 23:41:02 +0000638 // Don't sink instructions into a loop.
Evan Cheng4dc301a2010-08-19 17:33:11 +0000639 if (!TryBreak && LI->isLoopHeader(SuccToSinkTo)) {
Evan Chengf942c132010-08-19 23:33:02 +0000640 DEBUG(dbgs() << " *** NOTE: Loop header found\n");
Evan Cheng4dc301a2010-08-19 17:33:11 +0000641 TryBreak = true;
Jakob Stoklund Olesen626f3d72010-04-15 23:41:02 +0000642 }
643
Jakob Stoklund Olesen8d171602010-04-13 19:06:14 +0000644 // Otherwise we are OK with sinking along a critical edge.
Evan Cheng4dc301a2010-08-19 17:33:11 +0000645 if (!TryBreak)
646 DEBUG(dbgs() << "Sinking along critical edge.\n");
647 else {
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000648 MachineBasicBlock *NewSucc =
Evan Cheng7af6dc42010-09-20 19:12:55 +0000649 SplitCriticalEdge(MI, ParentBlock, SuccToSinkTo, BreakPHIEdge);
Evan Cheng4dc301a2010-08-19 17:33:11 +0000650 if (!NewSucc) {
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000651 DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
652 "break critical edge\n");
Evan Cheng4dc301a2010-08-19 17:33:11 +0000653 return false;
654 } else {
Evan Chengf942c132010-08-19 23:33:02 +0000655 DEBUG(dbgs() << " *** Splitting critical edge:"
Evan Cheng4dc301a2010-08-19 17:33:11 +0000656 " BB#" << ParentBlock->getNumber()
657 << " -- BB#" << NewSucc->getNumber()
658 << " -- BB#" << SuccToSinkTo->getNumber() << '\n');
Evan Cheng4dc301a2010-08-19 17:33:11 +0000659 SuccToSinkTo = NewSucc;
660 ++NumSplit;
Evan Cheng7af6dc42010-09-20 19:12:55 +0000661 BreakPHIEdge = false;
Evan Cheng4dc301a2010-08-19 17:33:11 +0000662 }
663 }
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000664 }
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000665
Evan Cheng7af6dc42010-09-20 19:12:55 +0000666 if (BreakPHIEdge) {
667 // BreakPHIEdge is true if all the uses are in the successor MBB being
668 // sunken into and they are all PHI nodes. In this case, machine-sink must
669 // break the critical edge first.
Evan Cheng23997862010-09-18 06:42:17 +0000670 MachineBasicBlock *NewSucc = SplitCriticalEdge(MI, ParentBlock,
Evan Cheng7af6dc42010-09-20 19:12:55 +0000671 SuccToSinkTo, BreakPHIEdge);
Evan Cheng23997862010-09-18 06:42:17 +0000672 if (!NewSucc) {
673 DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
674 "break critical edge\n");
675 return false;
676 }
677
678 DEBUG(dbgs() << " *** Splitting critical edge:"
679 " BB#" << ParentBlock->getNumber()
680 << " -- BB#" << NewSucc->getNumber()
681 << " -- BB#" << SuccToSinkTo->getNumber() << '\n');
682 SuccToSinkTo = NewSucc;
683 ++NumSplit;
684 }
685
Bill Wendling05c68372010-06-02 23:04:26 +0000686 // Determine where to insert into. Skip phi nodes.
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000687 MachineBasicBlock::iterator InsertPos = SuccToSinkTo->begin();
Evan Cheng23997862010-09-18 06:42:17 +0000688 while (InsertPos != SuccToSinkTo->end() && InsertPos->isPHI())
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000689 ++InsertPos;
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000690
Devang Patel541a81c2011-09-07 00:07:58 +0000691 // collect matching debug values.
692 SmallVector<MachineInstr *, 2> DbgValuesToSink;
693 collectDebugValues(MI, DbgValuesToSink);
694
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000695 // Move the instruction.
696 SuccToSinkTo->splice(InsertPos, ParentBlock, MI,
697 ++MachineBasicBlock::iterator(MI));
Dan Gohmane6cd7572010-05-13 20:34:42 +0000698
Devang Patel541a81c2011-09-07 00:07:58 +0000699 // Move debug values.
Craig Topperf22fd3f2013-07-03 05:11:49 +0000700 for (SmallVectorImpl<MachineInstr *>::iterator DBI = DbgValuesToSink.begin(),
Devang Patel541a81c2011-09-07 00:07:58 +0000701 DBE = DbgValuesToSink.end(); DBI != DBE; ++DBI) {
702 MachineInstr *DbgMI = *DBI;
703 SuccToSinkTo->splice(InsertPos, ParentBlock, DbgMI,
704 ++MachineBasicBlock::iterator(DbgMI));
705 }
706
Bill Wendling05c68372010-06-02 23:04:26 +0000707 // Conservatively, clear any kill flags, since it's possible that they are no
708 // longer correct.
Dan Gohmane6cd7572010-05-13 20:34:42 +0000709 MI->clearKillInfo();
710
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000711 return true;
712}