blob: 29cfb49953b9a227573daa61b6c172d5acfc202b [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"
21#include "llvm/CodeGen/MachineRegisterInfo.h"
22#include "llvm/CodeGen/MachineDominators.h"
Jakob Stoklund Olesen626f3d72010-04-15 23:41:02 +000023#include "llvm/CodeGen/MachineLoopInfo.h"
Dan Gohmana70dca12009-10-09 23:27:56 +000024#include "llvm/Analysis/AliasAnalysis.h"
Dan Gohman6f0d0242008-02-10 18:45:23 +000025#include "llvm/Target/TargetRegisterInfo.h"
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000026#include "llvm/Target/TargetInstrInfo.h"
27#include "llvm/Target/TargetMachine.h"
Evan Cheng6edb0ea2010-09-17 22:28:18 +000028#include "llvm/ADT/SmallSet.h"
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000029#include "llvm/ADT/Statistic.h"
Evan Cheng4dc301a2010-08-19 17:33:11 +000030#include "llvm/Support/CommandLine.h"
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000031#include "llvm/Support/Debug.h"
Bill Wendling1e973aa2009-08-22 20:26:23 +000032#include "llvm/Support/raw_ostream.h"
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000033using namespace llvm;
34
Evan Cheng4dc301a2010-08-19 17:33:11 +000035static cl::opt<bool>
36SplitEdges("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;
Dan Gohman45094e32009-09-26 02:34:00 +000052 BitVector AllocatableSet; // Which physregs are allocatable?
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000053
Evan Cheng6edb0ea2010-09-17 22:28:18 +000054 // Remember which edges have been considered for breaking.
55 SmallSet<std::pair<MachineBasicBlock*,MachineBasicBlock*>, 8>
56 CEBCandidates;
57
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000058 public:
59 static char ID; // Pass identification
Owen Anderson081c34b2010-10-19 17:21:58 +000060 MachineSinking() : MachineFunctionPass(ID) {
61 initializeMachineSinkingPass(*PassRegistry::getPassRegistry());
62 }
Jim Grosbach6ee358b2010-06-03 23:49:57 +000063
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000064 virtual bool runOnMachineFunction(MachineFunction &MF);
Jim Grosbach6ee358b2010-06-03 23:49:57 +000065
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000066 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohman845012e2009-07-31 23:37:33 +000067 AU.setPreservesCFG();
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000068 MachineFunctionPass::getAnalysisUsage(AU);
Dan Gohmana70dca12009-10-09 23:27:56 +000069 AU.addRequired<AliasAnalysis>();
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000070 AU.addRequired<MachineDominatorTree>();
Jakob Stoklund Olesen626f3d72010-04-15 23:41:02 +000071 AU.addRequired<MachineLoopInfo>();
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000072 AU.addPreserved<MachineDominatorTree>();
Jakob Stoklund Olesen626f3d72010-04-15 23:41:02 +000073 AU.addPreserved<MachineLoopInfo>();
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000074 }
Evan Cheng6edb0ea2010-09-17 22:28:18 +000075
76 virtual void releaseMemory() {
77 CEBCandidates.clear();
78 }
79
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000080 private:
81 bool ProcessBlock(MachineBasicBlock &MBB);
Evan Cheng6edb0ea2010-09-17 22:28:18 +000082 bool isWorthBreakingCriticalEdge(MachineInstr *MI,
83 MachineBasicBlock *From,
84 MachineBasicBlock *To);
85 MachineBasicBlock *SplitCriticalEdge(MachineInstr *MI,
86 MachineBasicBlock *From,
87 MachineBasicBlock *To,
Evan Cheng7af6dc42010-09-20 19:12:55 +000088 bool BreakPHIEdge);
Chris Lattneraad193a2008-01-12 00:17:41 +000089 bool SinkInstruction(MachineInstr *MI, bool &SawStore);
Evan Chengc3439ad2010-08-18 23:09:25 +000090 bool AllUsesDominatedByBlock(unsigned Reg, MachineBasicBlock *MBB,
Evan Cheng6edb0ea2010-09-17 22:28:18 +000091 MachineBasicBlock *DefMBB,
Evan Cheng7af6dc42010-09-20 19:12:55 +000092 bool &BreakPHIEdge, bool &LocalUse) const;
Evan Cheng6edb0ea2010-09-17 22:28:18 +000093 bool PerformTrivialForwardCoalescing(MachineInstr *MI,
94 MachineBasicBlock *MBB);
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000095 };
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000096} // end anonymous namespace
Jim Grosbach6ee358b2010-06-03 23:49:57 +000097
Dan Gohman844731a2008-05-13 00:00:25 +000098char MachineSinking::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +000099INITIALIZE_PASS_BEGIN(MachineSinking, "machine-sink",
100 "Machine code sinking", false, false)
101INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
102INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
103INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
104INITIALIZE_PASS_END(MachineSinking, "machine-sink",
Owen Andersonce665bd2010-10-07 22:25:06 +0000105 "Machine code sinking", false, false)
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000106
107FunctionPass *llvm::createMachineSinkingPass() { return new MachineSinking(); }
108
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000109bool MachineSinking::PerformTrivialForwardCoalescing(MachineInstr *MI,
110 MachineBasicBlock *MBB) {
111 if (!MI->isCopy())
112 return false;
113
114 unsigned SrcReg = MI->getOperand(1).getReg();
115 unsigned DstReg = MI->getOperand(0).getReg();
116 if (!TargetRegisterInfo::isVirtualRegister(SrcReg) ||
117 !TargetRegisterInfo::isVirtualRegister(DstReg) ||
118 !MRI->hasOneNonDBGUse(SrcReg))
119 return false;
120
121 const TargetRegisterClass *SRC = MRI->getRegClass(SrcReg);
122 const TargetRegisterClass *DRC = MRI->getRegClass(DstReg);
123 if (SRC != DRC)
124 return false;
125
126 MachineInstr *DefMI = MRI->getVRegDef(SrcReg);
127 if (DefMI->isCopyLike())
128 return false;
129 DEBUG(dbgs() << "Coalescing: " << *DefMI);
130 DEBUG(dbgs() << "*** to: " << *MI);
131 MRI->replaceRegWith(DstReg, SrcReg);
132 MI->eraseFromParent();
133 ++NumCoalesces;
134 return true;
135}
136
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000137/// AllUsesDominatedByBlock - Return true if all uses of the specified register
Evan Chengc3439ad2010-08-18 23:09:25 +0000138/// occur in blocks dominated by the specified block. If any use is in the
139/// definition block, then return false since it is never legal to move def
140/// after uses.
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000141bool
142MachineSinking::AllUsesDominatedByBlock(unsigned Reg,
143 MachineBasicBlock *MBB,
144 MachineBasicBlock *DefMBB,
Evan Cheng7af6dc42010-09-20 19:12:55 +0000145 bool &BreakPHIEdge,
146 bool &LocalUse) const {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000147 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
148 "Only makes sense for vregs");
Evan Cheng23997862010-09-18 06:42:17 +0000149
150 if (MRI->use_nodbg_empty(Reg))
151 return true;
152
Dale Johannesenb0812f12010-03-05 00:02:59 +0000153 // Ignoring debug uses is necessary so debug info doesn't affect the code.
154 // This may leave a referencing dbg_value in the original block, before
155 // the definition of the vreg. Dwarf generator handles this although the
156 // user might not get the right info at runtime.
Evan Cheng23997862010-09-18 06:42:17 +0000157
Evan Cheng7af6dc42010-09-20 19:12:55 +0000158 // BreakPHIEdge is true if all the uses are in the successor MBB being sunken
159 // into and they are all PHI nodes. In this case, machine-sink must break
160 // the critical edge first. e.g.
161 //
Evan Cheng23997862010-09-18 06:42:17 +0000162 // BB#1: derived from LLVM BB %bb4.preheader
163 // Predecessors according to CFG: BB#0
164 // ...
165 // %reg16385<def> = DEC64_32r %reg16437, %EFLAGS<imp-def,dead>
166 // ...
167 // JE_4 <BB#37>, %EFLAGS<imp-use>
168 // Successors according to CFG: BB#37 BB#2
169 //
170 // BB#2: derived from LLVM BB %bb.nph
171 // Predecessors according to CFG: BB#0 BB#1
172 // %reg16386<def> = PHI %reg16434, <BB#0>, %reg16385, <BB#1>
Evan Cheng7af6dc42010-09-20 19:12:55 +0000173 BreakPHIEdge = true;
Evan Cheng23997862010-09-18 06:42:17 +0000174 for (MachineRegisterInfo::use_nodbg_iterator
175 I = MRI->use_nodbg_begin(Reg), E = MRI->use_nodbg_end();
176 I != E; ++I) {
177 MachineInstr *UseInst = &*I;
178 MachineBasicBlock *UseBlock = UseInst->getParent();
179 if (!(UseBlock == MBB && UseInst->isPHI() &&
180 UseInst->getOperand(I.getOperandNo()+1).getMBB() == DefMBB)) {
Evan Cheng7af6dc42010-09-20 19:12:55 +0000181 BreakPHIEdge = false;
Evan Cheng23997862010-09-18 06:42:17 +0000182 break;
183 }
184 }
Evan Cheng7af6dc42010-09-20 19:12:55 +0000185 if (BreakPHIEdge)
Evan Cheng23997862010-09-18 06:42:17 +0000186 return true;
187
Bill Wendling05c68372010-06-02 23:04:26 +0000188 for (MachineRegisterInfo::use_nodbg_iterator
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000189 I = MRI->use_nodbg_begin(Reg), E = MRI->use_nodbg_end();
Bill Wendling05c68372010-06-02 23:04:26 +0000190 I != E; ++I) {
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000191 // Determine the block of the use.
192 MachineInstr *UseInst = &*I;
193 MachineBasicBlock *UseBlock = UseInst->getParent();
Evan Cheng23997862010-09-18 06:42:17 +0000194 if (UseInst->isPHI()) {
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000195 // PHI nodes use the operand in the predecessor block, not the block with
196 // the PHI.
197 UseBlock = UseInst->getOperand(I.getOperandNo()+1).getMBB();
Evan Chenge5e79462010-08-19 18:33:29 +0000198 } else if (UseBlock == DefMBB) {
199 LocalUse = true;
200 return false;
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000201 }
Bill Wendling05c68372010-06-02 23:04:26 +0000202
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000203 // Check that it dominates.
204 if (!DT->dominates(MBB, UseBlock))
205 return false;
206 }
Bill Wendling05c68372010-06-02 23:04:26 +0000207
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000208 return true;
209}
210
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000211bool MachineSinking::runOnMachineFunction(MachineFunction &MF) {
David Greenec19a9cd2010-01-05 01:26:00 +0000212 DEBUG(dbgs() << "******** Machine Sinking ********\n");
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000213
Dan Gohman4e9785e2009-10-19 14:52:05 +0000214 const TargetMachine &TM = MF.getTarget();
215 TII = TM.getInstrInfo();
216 TRI = TM.getRegisterInfo();
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000217 MRI = &MF.getRegInfo();
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000218 DT = &getAnalysis<MachineDominatorTree>();
Jakob Stoklund Olesen626f3d72010-04-15 23:41:02 +0000219 LI = &getAnalysis<MachineLoopInfo>();
Dan Gohmana70dca12009-10-09 23:27:56 +0000220 AA = &getAnalysis<AliasAnalysis>();
Dan Gohman4e9785e2009-10-19 14:52:05 +0000221 AllocatableSet = TRI->getAllocatableSet(MF);
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000222
223 bool EverMadeChange = false;
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000224
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000225 while (1) {
226 bool MadeChange = false;
227
228 // Process all basic blocks.
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000229 CEBCandidates.clear();
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000230 for (MachineFunction::iterator I = MF.begin(), E = MF.end();
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000231 I != E; ++I)
232 MadeChange |= ProcessBlock(*I);
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000233
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000234 // If this iteration over the code changed anything, keep iterating.
235 if (!MadeChange) break;
236 EverMadeChange = true;
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000237 }
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000238 return EverMadeChange;
239}
240
241bool MachineSinking::ProcessBlock(MachineBasicBlock &MBB) {
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000242 // Can't sink anything out of a block that has less than two successors.
Chris Lattner296185c2009-04-10 16:38:36 +0000243 if (MBB.succ_size() <= 1 || MBB.empty()) return false;
244
Dan Gohmanc4ae94d2010-04-05 19:17:22 +0000245 // Don't bother sinking code out of unreachable blocks. In addition to being
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000246 // unprofitable, it can also lead to infinite looping, because in an
247 // unreachable loop there may be nowhere to stop.
Dan Gohmanc4ae94d2010-04-05 19:17:22 +0000248 if (!DT->isReachableFromEntry(&MBB)) return false;
249
Chris Lattner296185c2009-04-10 16:38:36 +0000250 bool MadeChange = false;
251
Chris Lattneraad193a2008-01-12 00:17:41 +0000252 // Walk the basic block bottom-up. Remember if we saw a store.
Chris Lattner296185c2009-04-10 16:38:36 +0000253 MachineBasicBlock::iterator I = MBB.end();
254 --I;
255 bool ProcessedBegin, SawStore = false;
256 do {
257 MachineInstr *MI = I; // The instruction to sink.
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000258
Chris Lattner296185c2009-04-10 16:38:36 +0000259 // Predecrement I (if it's not begin) so that it isn't invalidated by
260 // sinking.
261 ProcessedBegin = I == MBB.begin();
262 if (!ProcessedBegin)
263 --I;
Dale Johannesenb0812f12010-03-05 00:02:59 +0000264
265 if (MI->isDebugValue())
266 continue;
267
Evan Chengcfea9852011-04-11 18:47:20 +0000268 bool Joined = PerformTrivialForwardCoalescing(MI, &MBB);
269 if (Joined) {
270 MadeChange = true;
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000271 continue;
Evan Chengcfea9852011-04-11 18:47:20 +0000272 }
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000273
Chris Lattner296185c2009-04-10 16:38:36 +0000274 if (SinkInstruction(MI, SawStore))
275 ++NumSunk, MadeChange = true;
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000276
Chris Lattner296185c2009-04-10 16:38:36 +0000277 // If we just processed the first instruction in the block, we're done.
278 } while (!ProcessedBegin);
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000279
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000280 return MadeChange;
281}
282
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000283bool MachineSinking::isWorthBreakingCriticalEdge(MachineInstr *MI,
284 MachineBasicBlock *From,
285 MachineBasicBlock *To) {
286 // FIXME: Need much better heuristics.
287
288 // If the pass has already considered breaking this edge (during this pass
289 // through the function), then let's go ahead and break it. This means
290 // sinking multiple "cheap" instructions into the same block.
291 if (!CEBCandidates.insert(std::make_pair(From, To)))
292 return true;
293
Evan Chengb0cdf8a2010-09-23 06:53:00 +0000294 if (!MI->isCopy() && !MI->getDesc().isAsCheapAsAMove())
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000295 return true;
296
297 // MI is cheap, we probably don't want to break the critical edge for it.
298 // However, if this would allow some definitions of its source operands
299 // to be sunk then it's probably worth it.
300 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
301 const MachineOperand &MO = MI->getOperand(i);
302 if (!MO.isReg()) continue;
303 unsigned Reg = MO.getReg();
304 if (Reg == 0 || !TargetRegisterInfo::isPhysicalRegister(Reg))
305 continue;
306 if (MRI->hasOneNonDBGUse(Reg))
307 return true;
308 }
309
310 return false;
311}
312
313MachineBasicBlock *MachineSinking::SplitCriticalEdge(MachineInstr *MI,
314 MachineBasicBlock *FromBB,
315 MachineBasicBlock *ToBB,
Evan Cheng7af6dc42010-09-20 19:12:55 +0000316 bool BreakPHIEdge) {
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000317 if (!isWorthBreakingCriticalEdge(MI, FromBB, ToBB))
318 return 0;
319
Evan Cheng4dc301a2010-08-19 17:33:11 +0000320 // Avoid breaking back edge. From == To means backedge for single BB loop.
Evan Cheng44be1a82010-09-20 22:52:00 +0000321 if (!SplitEdges || FromBB == ToBB)
Evan Cheng4dc301a2010-08-19 17:33:11 +0000322 return 0;
323
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000324 // Check for backedges of more "complex" loops.
325 if (LI->getLoopFor(FromBB) == LI->getLoopFor(ToBB) &&
326 LI->isLoopHeader(ToBB))
327 return 0;
328
329 // It's not always legal to break critical edges and sink the computation
330 // to the edge.
331 //
332 // BB#1:
333 // v1024
334 // Beq BB#3
335 // <fallthrough>
336 // BB#2:
337 // ... no uses of v1024
338 // <fallthrough>
339 // BB#3:
340 // ...
341 // = v1024
342 //
343 // If BB#1 -> BB#3 edge is broken and computation of v1024 is inserted:
344 //
345 // BB#1:
346 // ...
347 // Bne BB#2
348 // BB#4:
349 // v1024 =
350 // B BB#3
351 // BB#2:
352 // ... no uses of v1024
353 // <fallthrough>
354 // BB#3:
355 // ...
356 // = v1024
357 //
358 // This is incorrect since v1024 is not computed along the BB#1->BB#2->BB#3
359 // flow. We need to ensure the new basic block where the computation is
360 // sunk to dominates all the uses.
361 // It's only legal to break critical edge and sink the computation to the
362 // new block if all the predecessors of "To", except for "From", are
363 // not dominated by "From". Given SSA property, this means these
364 // predecessors are dominated by "To".
365 //
366 // There is no need to do this check if all the uses are PHI nodes. PHI
367 // sources are only defined on the specific predecessor edges.
Evan Cheng7af6dc42010-09-20 19:12:55 +0000368 if (!BreakPHIEdge) {
Evan Cheng4dc301a2010-08-19 17:33:11 +0000369 for (MachineBasicBlock::pred_iterator PI = ToBB->pred_begin(),
370 E = ToBB->pred_end(); PI != E; ++PI) {
371 if (*PI == FromBB)
372 continue;
373 if (!DT->dominates(ToBB, *PI))
374 return 0;
375 }
Evan Cheng4dc301a2010-08-19 17:33:11 +0000376 }
377
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000378 return FromBB->SplitCriticalEdge(ToBB, this);
Evan Cheng4dc301a2010-08-19 17:33:11 +0000379}
380
Evan Chengb0cdf8a2010-09-23 06:53:00 +0000381static bool AvoidsSinking(MachineInstr *MI, MachineRegisterInfo *MRI) {
382 return MI->isInsertSubreg() || MI->isSubregToReg() || MI->isRegSequence();
383}
384
Devang Patel541a81c2011-09-07 00:07:58 +0000385/// collectDebgValues - Scan instructions following MI and collect any
386/// matching DBG_VALUEs.
387static void collectDebugValues(MachineInstr *MI,
388 SmallVector<MachineInstr *, 2> & DbgValues) {
389 DbgValues.clear();
390 if (!MI->getOperand(0).isReg())
391 return;
392
393 MachineBasicBlock::iterator DI = MI; ++DI;
394 for (MachineBasicBlock::iterator DE = MI->getParent()->end();
395 DI != DE; ++DI) {
396 if (!DI->isDebugValue())
397 return;
398 if (DI->getOperand(0).isReg() &&
399 DI->getOperand(0).getReg() == MI->getOperand(0).getReg())
400 DbgValues.push_back(DI);
401 }
402}
403
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000404/// SinkInstruction - Determine whether it is safe to sink the specified machine
405/// instruction out of its current block into a successor.
Chris Lattneraad193a2008-01-12 00:17:41 +0000406bool MachineSinking::SinkInstruction(MachineInstr *MI, bool &SawStore) {
Evan Chengb0cdf8a2010-09-23 06:53:00 +0000407 // Don't sink insert_subreg, subreg_to_reg, reg_sequence. These are meant to
408 // be close to the source to make it easier to coalesce.
409 if (AvoidsSinking(MI, MRI))
410 return false;
411
Evan Chengb27087f2008-03-13 00:44:09 +0000412 // Check if it's safe to move the instruction.
Evan Chengac1abde2010-03-02 19:03:01 +0000413 if (!MI->isSafeToMove(TII, AA, SawStore))
Chris Lattneraad193a2008-01-12 00:17:41 +0000414 return false;
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000415
Chris Lattnere430e1c2008-01-05 06:47:58 +0000416 // FIXME: This should include support for sinking instructions within the
417 // block they are currently in to shorten the live ranges. We often get
418 // instructions sunk into the top of a large block, but it would be better to
419 // also sink them down before their first use in the block. This xform has to
420 // be careful not to *increase* register pressure though, e.g. sinking
421 // "x = y + z" down if it kills y and z would increase the live ranges of y
Dan Gohmana5225ad2009-08-05 01:19:01 +0000422 // and z and only shrink the live range of x.
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000423
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000424 // Loop over all the operands of the specified instruction. If there is
425 // anything we can't handle, bail out.
426 MachineBasicBlock *ParentBlock = MI->getParent();
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000427
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000428 // SuccToSinkTo - This is the successor to sink this instruction to, once we
429 // decide.
430 MachineBasicBlock *SuccToSinkTo = 0;
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000431
Evan Cheng7af6dc42010-09-20 19:12:55 +0000432 bool BreakPHIEdge = false;
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000433 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
434 const MachineOperand &MO = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000435 if (!MO.isReg()) continue; // Ignore non-register operands.
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000436
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000437 unsigned Reg = MO.getReg();
438 if (Reg == 0) continue;
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000439
Dan Gohman6f0d0242008-02-10 18:45:23 +0000440 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
Dan Gohman19778e72009-09-25 22:53:29 +0000441 if (MO.isUse()) {
442 // If the physreg has no defs anywhere, it's just an ambient register
Dan Gohman45094e32009-09-26 02:34:00 +0000443 // and we can freely move its uses. Alternatively, if it's allocatable,
444 // it could get allocated to something with a def during allocation.
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000445 if (!MRI->def_empty(Reg))
Dan Gohman19778e72009-09-25 22:53:29 +0000446 return false;
Bill Wendling05c68372010-06-02 23:04:26 +0000447
Dan Gohman45094e32009-09-26 02:34:00 +0000448 if (AllocatableSet.test(Reg))
449 return false;
Bill Wendling05c68372010-06-02 23:04:26 +0000450
Dan Gohman19778e72009-09-25 22:53:29 +0000451 // Check for a def among the register's aliases too.
Dan Gohman45094e32009-09-26 02:34:00 +0000452 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
453 unsigned AliasReg = *Alias;
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000454 if (!MRI->def_empty(AliasReg))
Dan Gohman19778e72009-09-25 22:53:29 +0000455 return false;
Bill Wendling05c68372010-06-02 23:04:26 +0000456
Dan Gohman45094e32009-09-26 02:34:00 +0000457 if (AllocatableSet.test(AliasReg))
458 return false;
459 }
Bill Wendling730c07e2010-06-25 20:48:10 +0000460 } else if (!MO.isDead()) {
461 // A def that isn't dead. We can't move it.
462 return false;
Dan Gohman19778e72009-09-25 22:53:29 +0000463 }
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000464 } else {
465 // Virtual register uses are always safe to sink.
466 if (MO.isUse()) continue;
Evan Chengb6f54172009-02-07 01:21:47 +0000467
468 // If it's not safe to move defs of the register class, then abort.
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000469 if (!TII->isSafeToMoveRegClassDefs(MRI->getRegClass(Reg)))
Evan Chengb6f54172009-02-07 01:21:47 +0000470 return false;
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000471
Chris Lattnere430e1c2008-01-05 06:47:58 +0000472 // FIXME: This picks a successor to sink into based on having one
473 // successor that dominates all the uses. However, there are cases where
474 // sinking can happen but where the sink point isn't a successor. For
475 // example:
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000476 //
Chris Lattnere430e1c2008-01-05 06:47:58 +0000477 // x = computation
478 // if () {} else {}
479 // use x
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000480 //
Bill Wendling05c68372010-06-02 23:04:26 +0000481 // the instruction could be sunk over the whole diamond for the
Chris Lattnere430e1c2008-01-05 06:47:58 +0000482 // if/then/else (or loop, etc), allowing it to be sunk into other blocks
483 // after that.
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000484
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000485 // Virtual register defs can only be sunk if all their uses are in blocks
486 // dominated by one of the successors.
487 if (SuccToSinkTo) {
488 // If a previous operand picked a block to sink to, then this operand
489 // must be sinkable to the same block.
Evan Chenge5e79462010-08-19 18:33:29 +0000490 bool LocalUse = false;
Evan Cheng23997862010-09-18 06:42:17 +0000491 if (!AllUsesDominatedByBlock(Reg, SuccToSinkTo, ParentBlock,
Evan Cheng7af6dc42010-09-20 19:12:55 +0000492 BreakPHIEdge, LocalUse))
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000493 return false;
Bill Wendling05c68372010-06-02 23:04:26 +0000494
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000495 continue;
496 }
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000497
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000498 // Otherwise, we should look at all the successors and decide which one
499 // we should sink to.
500 for (MachineBasicBlock::succ_iterator SI = ParentBlock->succ_begin(),
501 E = ParentBlock->succ_end(); SI != E; ++SI) {
Evan Chenge5e79462010-08-19 18:33:29 +0000502 bool LocalUse = false;
Evan Cheng23997862010-09-18 06:42:17 +0000503 if (AllUsesDominatedByBlock(Reg, *SI, ParentBlock,
Evan Cheng7af6dc42010-09-20 19:12:55 +0000504 BreakPHIEdge, LocalUse)) {
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000505 SuccToSinkTo = *SI;
506 break;
507 }
Evan Chengc3439ad2010-08-18 23:09:25 +0000508 if (LocalUse)
509 // Def is used locally, it's never safe to move this def.
510 return false;
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000511 }
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000512
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000513 // If we couldn't find a block to sink to, ignore this instruction.
514 if (SuccToSinkTo == 0)
515 return false;
516 }
517 }
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000518
Chris Lattner9bb459b2008-01-05 01:39:17 +0000519 // If there are no outputs, it must have side-effects.
520 if (SuccToSinkTo == 0)
521 return false;
Evan Chengb5999792009-02-15 08:36:12 +0000522
523 // It's not safe to sink instructions to EH landing pad. Control flow into
524 // landing pad is implicitly defined.
525 if (SuccToSinkTo->isLandingPad())
526 return false;
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000527
Dan Gohmandfffba62009-10-19 14:56:05 +0000528 // It is not possible to sink an instruction into its own block. This can
Chris Lattner296185c2009-04-10 16:38:36 +0000529 // happen with loops.
530 if (MI->getParent() == SuccToSinkTo)
531 return false;
Bill Wendling869d60d2010-06-03 07:54:20 +0000532
Daniel Dunbard24c9d52010-06-23 00:48:25 +0000533 // If the instruction to move defines a dead physical register which is live
534 // when leaving the basic block, don't move it because it could turn into a
535 // "zombie" define of that preg. E.g., EFLAGS. (<rdar://problem/8030636>)
Bill Wendling730c07e2010-06-25 20:48:10 +0000536 for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
537 const MachineOperand &MO = MI->getOperand(I);
538 if (!MO.isReg()) continue;
539 unsigned Reg = MO.getReg();
540 if (Reg == 0 || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
541 if (SuccToSinkTo->isLiveIn(Reg))
Bill Wendling869d60d2010-06-03 07:54:20 +0000542 return false;
Bill Wendling730c07e2010-06-25 20:48:10 +0000543 }
Bill Wendling869d60d2010-06-03 07:54:20 +0000544
Bill Wendling05c68372010-06-02 23:04:26 +0000545 DEBUG(dbgs() << "Sink instr " << *MI << "\tinto block " << *SuccToSinkTo);
546
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000547 // If the block has multiple predecessors, this would introduce computation on
548 // a path that it doesn't already exist. We could split the critical edge,
549 // but for now we just punt.
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000550 if (SuccToSinkTo->pred_size() > 1) {
Jakob Stoklund Olesen8d171602010-04-13 19:06:14 +0000551 // We cannot sink a load across a critical edge - there may be stores in
552 // other code paths.
Evan Cheng4dc301a2010-08-19 17:33:11 +0000553 bool TryBreak = false;
Jakob Stoklund Olesen8d171602010-04-13 19:06:14 +0000554 bool store = true;
555 if (!MI->isSafeToMove(TII, AA, store)) {
Evan Chengf942c132010-08-19 23:33:02 +0000556 DEBUG(dbgs() << " *** NOTE: Won't sink load along critical edge.\n");
Evan Cheng4dc301a2010-08-19 17:33:11 +0000557 TryBreak = true;
Jakob Stoklund Olesen8d171602010-04-13 19:06:14 +0000558 }
559
560 // We don't want to sink across a critical edge if we don't dominate the
561 // successor. We could be introducing calculations to new code paths.
Evan Cheng4dc301a2010-08-19 17:33:11 +0000562 if (!TryBreak && !DT->dominates(ParentBlock, SuccToSinkTo)) {
Evan Chengf942c132010-08-19 23:33:02 +0000563 DEBUG(dbgs() << " *** NOTE: Critical edge found\n");
Evan Cheng4dc301a2010-08-19 17:33:11 +0000564 TryBreak = true;
Jakob Stoklund Olesen8d171602010-04-13 19:06:14 +0000565 }
566
Jakob Stoklund Olesen626f3d72010-04-15 23:41:02 +0000567 // Don't sink instructions into a loop.
Evan Cheng4dc301a2010-08-19 17:33:11 +0000568 if (!TryBreak && LI->isLoopHeader(SuccToSinkTo)) {
Evan Chengf942c132010-08-19 23:33:02 +0000569 DEBUG(dbgs() << " *** NOTE: Loop header found\n");
Evan Cheng4dc301a2010-08-19 17:33:11 +0000570 TryBreak = true;
Jakob Stoklund Olesen626f3d72010-04-15 23:41:02 +0000571 }
572
Jakob Stoklund Olesen8d171602010-04-13 19:06:14 +0000573 // Otherwise we are OK with sinking along a critical edge.
Evan Cheng4dc301a2010-08-19 17:33:11 +0000574 if (!TryBreak)
575 DEBUG(dbgs() << "Sinking along critical edge.\n");
576 else {
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000577 MachineBasicBlock *NewSucc =
Evan Cheng7af6dc42010-09-20 19:12:55 +0000578 SplitCriticalEdge(MI, ParentBlock, SuccToSinkTo, BreakPHIEdge);
Evan Cheng4dc301a2010-08-19 17:33:11 +0000579 if (!NewSucc) {
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000580 DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
581 "break critical edge\n");
Evan Cheng4dc301a2010-08-19 17:33:11 +0000582 return false;
583 } else {
Evan Chengf942c132010-08-19 23:33:02 +0000584 DEBUG(dbgs() << " *** Splitting critical edge:"
Evan Cheng4dc301a2010-08-19 17:33:11 +0000585 " BB#" << ParentBlock->getNumber()
586 << " -- BB#" << NewSucc->getNumber()
587 << " -- BB#" << SuccToSinkTo->getNumber() << '\n');
Evan Cheng4dc301a2010-08-19 17:33:11 +0000588 SuccToSinkTo = NewSucc;
589 ++NumSplit;
Evan Cheng7af6dc42010-09-20 19:12:55 +0000590 BreakPHIEdge = false;
Evan Cheng4dc301a2010-08-19 17:33:11 +0000591 }
592 }
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000593 }
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000594
Evan Cheng7af6dc42010-09-20 19:12:55 +0000595 if (BreakPHIEdge) {
596 // BreakPHIEdge is true if all the uses are in the successor MBB being
597 // sunken into and they are all PHI nodes. In this case, machine-sink must
598 // break the critical edge first.
Evan Cheng23997862010-09-18 06:42:17 +0000599 MachineBasicBlock *NewSucc = SplitCriticalEdge(MI, ParentBlock,
Evan Cheng7af6dc42010-09-20 19:12:55 +0000600 SuccToSinkTo, BreakPHIEdge);
Evan Cheng23997862010-09-18 06:42:17 +0000601 if (!NewSucc) {
602 DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
603 "break critical edge\n");
604 return false;
605 }
606
607 DEBUG(dbgs() << " *** Splitting critical edge:"
608 " BB#" << ParentBlock->getNumber()
609 << " -- BB#" << NewSucc->getNumber()
610 << " -- BB#" << SuccToSinkTo->getNumber() << '\n');
611 SuccToSinkTo = NewSucc;
612 ++NumSplit;
613 }
614
Bill Wendling05c68372010-06-02 23:04:26 +0000615 // Determine where to insert into. Skip phi nodes.
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000616 MachineBasicBlock::iterator InsertPos = SuccToSinkTo->begin();
Evan Cheng23997862010-09-18 06:42:17 +0000617 while (InsertPos != SuccToSinkTo->end() && InsertPos->isPHI())
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000618 ++InsertPos;
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000619
Devang Patel541a81c2011-09-07 00:07:58 +0000620 // collect matching debug values.
621 SmallVector<MachineInstr *, 2> DbgValuesToSink;
622 collectDebugValues(MI, DbgValuesToSink);
623
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000624 // Move the instruction.
625 SuccToSinkTo->splice(InsertPos, ParentBlock, MI,
626 ++MachineBasicBlock::iterator(MI));
Dan Gohmane6cd7572010-05-13 20:34:42 +0000627
Devang Patel541a81c2011-09-07 00:07:58 +0000628 // Move debug values.
629 for (SmallVector<MachineInstr *, 2>::iterator DBI = DbgValuesToSink.begin(),
630 DBE = DbgValuesToSink.end(); DBI != DBE; ++DBI) {
631 MachineInstr *DbgMI = *DBI;
632 SuccToSinkTo->splice(InsertPos, ParentBlock, DbgMI,
633 ++MachineBasicBlock::iterator(DbgMI));
634 }
635
Bill Wendling05c68372010-06-02 23:04:26 +0000636 // Conservatively, clear any kill flags, since it's possible that they are no
637 // longer correct.
Dan Gohmane6cd7572010-05-13 20:34:42 +0000638 MI->clearKillInfo();
639
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000640 return true;
641}