blob: 7740a75e42749f55ae25c8085e7560363191e904 [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;
Devang Patele265bcf2011-12-08 21:48:01 +000093 MachineBasicBlock *FindSuccToSinkTo(MachineInstr *MI, bool &BreakPHIEdge);
94
Evan Cheng6edb0ea2010-09-17 22:28:18 +000095 bool PerformTrivialForwardCoalescing(MachineInstr *MI,
96 MachineBasicBlock *MBB);
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000097 };
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000098} // end anonymous namespace
Jim Grosbach6ee358b2010-06-03 23:49:57 +000099
Dan Gohman844731a2008-05-13 00:00:25 +0000100char MachineSinking::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +0000101INITIALIZE_PASS_BEGIN(MachineSinking, "machine-sink",
102 "Machine code sinking", false, false)
103INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
104INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
105INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
106INITIALIZE_PASS_END(MachineSinking, "machine-sink",
Owen Andersonce665bd2010-10-07 22:25:06 +0000107 "Machine code sinking", false, false)
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000108
109FunctionPass *llvm::createMachineSinkingPass() { return new MachineSinking(); }
110
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000111bool MachineSinking::PerformTrivialForwardCoalescing(MachineInstr *MI,
112 MachineBasicBlock *MBB) {
113 if (!MI->isCopy())
114 return false;
115
116 unsigned SrcReg = MI->getOperand(1).getReg();
117 unsigned DstReg = MI->getOperand(0).getReg();
118 if (!TargetRegisterInfo::isVirtualRegister(SrcReg) ||
119 !TargetRegisterInfo::isVirtualRegister(DstReg) ||
120 !MRI->hasOneNonDBGUse(SrcReg))
121 return false;
122
123 const TargetRegisterClass *SRC = MRI->getRegClass(SrcReg);
124 const TargetRegisterClass *DRC = MRI->getRegClass(DstReg);
125 if (SRC != DRC)
126 return false;
127
128 MachineInstr *DefMI = MRI->getVRegDef(SrcReg);
129 if (DefMI->isCopyLike())
130 return false;
131 DEBUG(dbgs() << "Coalescing: " << *DefMI);
132 DEBUG(dbgs() << "*** to: " << *MI);
133 MRI->replaceRegWith(DstReg, SrcReg);
134 MI->eraseFromParent();
135 ++NumCoalesces;
136 return true;
137}
138
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000139/// AllUsesDominatedByBlock - Return true if all uses of the specified register
Evan Chengc3439ad2010-08-18 23:09:25 +0000140/// occur in blocks dominated by the specified block. If any use is in the
141/// definition block, then return false since it is never legal to move def
142/// after uses.
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000143bool
144MachineSinking::AllUsesDominatedByBlock(unsigned Reg,
145 MachineBasicBlock *MBB,
146 MachineBasicBlock *DefMBB,
Evan Cheng7af6dc42010-09-20 19:12:55 +0000147 bool &BreakPHIEdge,
148 bool &LocalUse) const {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000149 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
150 "Only makes sense for vregs");
Evan Cheng23997862010-09-18 06:42:17 +0000151
152 if (MRI->use_nodbg_empty(Reg))
153 return true;
154
Dale Johannesenb0812f12010-03-05 00:02:59 +0000155 // Ignoring debug uses is necessary so debug info doesn't affect the code.
156 // This may leave a referencing dbg_value in the original block, before
157 // the definition of the vreg. Dwarf generator handles this although the
158 // user might not get the right info at runtime.
Evan Cheng23997862010-09-18 06:42:17 +0000159
Evan Cheng7af6dc42010-09-20 19:12:55 +0000160 // BreakPHIEdge is true if all the uses are in the successor MBB being sunken
161 // into and they are all PHI nodes. In this case, machine-sink must break
162 // the critical edge first. e.g.
163 //
Evan Cheng23997862010-09-18 06:42:17 +0000164 // BB#1: derived from LLVM BB %bb4.preheader
165 // Predecessors according to CFG: BB#0
166 // ...
167 // %reg16385<def> = DEC64_32r %reg16437, %EFLAGS<imp-def,dead>
168 // ...
169 // JE_4 <BB#37>, %EFLAGS<imp-use>
170 // Successors according to CFG: BB#37 BB#2
171 //
172 // BB#2: derived from LLVM BB %bb.nph
173 // Predecessors according to CFG: BB#0 BB#1
174 // %reg16386<def> = PHI %reg16434, <BB#0>, %reg16385, <BB#1>
Evan Cheng7af6dc42010-09-20 19:12:55 +0000175 BreakPHIEdge = true;
Evan Cheng23997862010-09-18 06:42:17 +0000176 for (MachineRegisterInfo::use_nodbg_iterator
177 I = MRI->use_nodbg_begin(Reg), E = MRI->use_nodbg_end();
178 I != E; ++I) {
179 MachineInstr *UseInst = &*I;
180 MachineBasicBlock *UseBlock = UseInst->getParent();
181 if (!(UseBlock == MBB && UseInst->isPHI() &&
182 UseInst->getOperand(I.getOperandNo()+1).getMBB() == DefMBB)) {
Evan Cheng7af6dc42010-09-20 19:12:55 +0000183 BreakPHIEdge = false;
Evan Cheng23997862010-09-18 06:42:17 +0000184 break;
185 }
186 }
Evan Cheng7af6dc42010-09-20 19:12:55 +0000187 if (BreakPHIEdge)
Evan Cheng23997862010-09-18 06:42:17 +0000188 return true;
189
Bill Wendling05c68372010-06-02 23:04:26 +0000190 for (MachineRegisterInfo::use_nodbg_iterator
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000191 I = MRI->use_nodbg_begin(Reg), E = MRI->use_nodbg_end();
Bill Wendling05c68372010-06-02 23:04:26 +0000192 I != E; ++I) {
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000193 // Determine the block of the use.
194 MachineInstr *UseInst = &*I;
195 MachineBasicBlock *UseBlock = UseInst->getParent();
Evan Cheng23997862010-09-18 06:42:17 +0000196 if (UseInst->isPHI()) {
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000197 // PHI nodes use the operand in the predecessor block, not the block with
198 // the PHI.
199 UseBlock = UseInst->getOperand(I.getOperandNo()+1).getMBB();
Evan Chenge5e79462010-08-19 18:33:29 +0000200 } else if (UseBlock == DefMBB) {
201 LocalUse = true;
202 return false;
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000203 }
Bill Wendling05c68372010-06-02 23:04:26 +0000204
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000205 // Check that it dominates.
206 if (!DT->dominates(MBB, UseBlock))
207 return false;
208 }
Bill Wendling05c68372010-06-02 23:04:26 +0000209
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000210 return true;
211}
212
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000213bool MachineSinking::runOnMachineFunction(MachineFunction &MF) {
David Greenec19a9cd2010-01-05 01:26:00 +0000214 DEBUG(dbgs() << "******** Machine Sinking ********\n");
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000215
Dan Gohman4e9785e2009-10-19 14:52:05 +0000216 const TargetMachine &TM = MF.getTarget();
217 TII = TM.getInstrInfo();
218 TRI = TM.getRegisterInfo();
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000219 MRI = &MF.getRegInfo();
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000220 DT = &getAnalysis<MachineDominatorTree>();
Jakob Stoklund Olesen626f3d72010-04-15 23:41:02 +0000221 LI = &getAnalysis<MachineLoopInfo>();
Dan Gohmana70dca12009-10-09 23:27:56 +0000222 AA = &getAnalysis<AliasAnalysis>();
Dan Gohman4e9785e2009-10-19 14:52:05 +0000223 AllocatableSet = TRI->getAllocatableSet(MF);
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000224
225 bool EverMadeChange = false;
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000226
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000227 while (1) {
228 bool MadeChange = false;
229
230 // Process all basic blocks.
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000231 CEBCandidates.clear();
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000232 for (MachineFunction::iterator I = MF.begin(), E = MF.end();
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000233 I != E; ++I)
234 MadeChange |= ProcessBlock(*I);
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000235
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000236 // If this iteration over the code changed anything, keep iterating.
237 if (!MadeChange) break;
238 EverMadeChange = true;
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000239 }
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000240 return EverMadeChange;
241}
242
243bool MachineSinking::ProcessBlock(MachineBasicBlock &MBB) {
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000244 // Can't sink anything out of a block that has less than two successors.
Chris Lattner296185c2009-04-10 16:38:36 +0000245 if (MBB.succ_size() <= 1 || MBB.empty()) return false;
246
Dan Gohmanc4ae94d2010-04-05 19:17:22 +0000247 // Don't bother sinking code out of unreachable blocks. In addition to being
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000248 // unprofitable, it can also lead to infinite looping, because in an
249 // unreachable loop there may be nowhere to stop.
Dan Gohmanc4ae94d2010-04-05 19:17:22 +0000250 if (!DT->isReachableFromEntry(&MBB)) return false;
251
Chris Lattner296185c2009-04-10 16:38:36 +0000252 bool MadeChange = false;
253
Chris Lattneraad193a2008-01-12 00:17:41 +0000254 // Walk the basic block bottom-up. Remember if we saw a store.
Chris Lattner296185c2009-04-10 16:38:36 +0000255 MachineBasicBlock::iterator I = MBB.end();
256 --I;
257 bool ProcessedBegin, SawStore = false;
258 do {
259 MachineInstr *MI = I; // The instruction to sink.
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000260
Chris Lattner296185c2009-04-10 16:38:36 +0000261 // Predecrement I (if it's not begin) so that it isn't invalidated by
262 // sinking.
263 ProcessedBegin = I == MBB.begin();
264 if (!ProcessedBegin)
265 --I;
Dale Johannesenb0812f12010-03-05 00:02:59 +0000266
267 if (MI->isDebugValue())
268 continue;
269
Evan Chengcfea9852011-04-11 18:47:20 +0000270 bool Joined = PerformTrivialForwardCoalescing(MI, &MBB);
271 if (Joined) {
272 MadeChange = true;
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000273 continue;
Evan Chengcfea9852011-04-11 18:47:20 +0000274 }
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000275
Chris Lattner296185c2009-04-10 16:38:36 +0000276 if (SinkInstruction(MI, SawStore))
277 ++NumSunk, MadeChange = true;
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000278
Chris Lattner296185c2009-04-10 16:38:36 +0000279 // If we just processed the first instruction in the block, we're done.
280 } while (!ProcessedBegin);
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000281
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000282 return MadeChange;
283}
284
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000285bool MachineSinking::isWorthBreakingCriticalEdge(MachineInstr *MI,
286 MachineBasicBlock *From,
287 MachineBasicBlock *To) {
288 // FIXME: Need much better heuristics.
289
290 // If the pass has already considered breaking this edge (during this pass
291 // through the function), then let's go ahead and break it. This means
292 // sinking multiple "cheap" instructions into the same block.
293 if (!CEBCandidates.insert(std::make_pair(From, To)))
294 return true;
295
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000296 if (!MI->isCopy() && !MI->isAsCheapAsAMove())
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000297 return true;
298
299 // MI is cheap, we probably don't want to break the critical edge for it.
300 // However, if this would allow some definitions of its source operands
301 // to be sunk then it's probably worth it.
302 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
303 const MachineOperand &MO = MI->getOperand(i);
304 if (!MO.isReg()) continue;
305 unsigned Reg = MO.getReg();
306 if (Reg == 0 || !TargetRegisterInfo::isPhysicalRegister(Reg))
307 continue;
308 if (MRI->hasOneNonDBGUse(Reg))
309 return true;
310 }
311
312 return false;
313}
314
315MachineBasicBlock *MachineSinking::SplitCriticalEdge(MachineInstr *MI,
316 MachineBasicBlock *FromBB,
317 MachineBasicBlock *ToBB,
Evan Cheng7af6dc42010-09-20 19:12:55 +0000318 bool BreakPHIEdge) {
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000319 if (!isWorthBreakingCriticalEdge(MI, FromBB, ToBB))
320 return 0;
321
Evan Cheng4dc301a2010-08-19 17:33:11 +0000322 // Avoid breaking back edge. From == To means backedge for single BB loop.
Evan Cheng44be1a82010-09-20 22:52:00 +0000323 if (!SplitEdges || FromBB == ToBB)
Evan Cheng4dc301a2010-08-19 17:33:11 +0000324 return 0;
325
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000326 // Check for backedges of more "complex" loops.
327 if (LI->getLoopFor(FromBB) == LI->getLoopFor(ToBB) &&
328 LI->isLoopHeader(ToBB))
329 return 0;
330
331 // It's not always legal to break critical edges and sink the computation
332 // to the edge.
333 //
334 // BB#1:
335 // v1024
336 // Beq BB#3
337 // <fallthrough>
338 // BB#2:
339 // ... no uses of v1024
340 // <fallthrough>
341 // BB#3:
342 // ...
343 // = v1024
344 //
345 // If BB#1 -> BB#3 edge is broken and computation of v1024 is inserted:
346 //
347 // BB#1:
348 // ...
349 // Bne BB#2
350 // BB#4:
351 // v1024 =
352 // B BB#3
353 // BB#2:
354 // ... no uses of v1024
355 // <fallthrough>
356 // BB#3:
357 // ...
358 // = v1024
359 //
360 // This is incorrect since v1024 is not computed along the BB#1->BB#2->BB#3
361 // flow. We need to ensure the new basic block where the computation is
362 // sunk to dominates all the uses.
363 // It's only legal to break critical edge and sink the computation to the
364 // new block if all the predecessors of "To", except for "From", are
365 // not dominated by "From". Given SSA property, this means these
366 // predecessors are dominated by "To".
367 //
368 // There is no need to do this check if all the uses are PHI nodes. PHI
369 // sources are only defined on the specific predecessor edges.
Evan Cheng7af6dc42010-09-20 19:12:55 +0000370 if (!BreakPHIEdge) {
Evan Cheng4dc301a2010-08-19 17:33:11 +0000371 for (MachineBasicBlock::pred_iterator PI = ToBB->pred_begin(),
372 E = ToBB->pred_end(); PI != E; ++PI) {
373 if (*PI == FromBB)
374 continue;
375 if (!DT->dominates(ToBB, *PI))
376 return 0;
377 }
Evan Cheng4dc301a2010-08-19 17:33:11 +0000378 }
379
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000380 return FromBB->SplitCriticalEdge(ToBB, this);
Evan Cheng4dc301a2010-08-19 17:33:11 +0000381}
382
Evan Chengb0cdf8a2010-09-23 06:53:00 +0000383static bool AvoidsSinking(MachineInstr *MI, MachineRegisterInfo *MRI) {
384 return MI->isInsertSubreg() || MI->isSubregToReg() || MI->isRegSequence();
385}
386
Devang Patel541a81c2011-09-07 00:07:58 +0000387/// collectDebgValues - Scan instructions following MI and collect any
388/// matching DBG_VALUEs.
389static void collectDebugValues(MachineInstr *MI,
390 SmallVector<MachineInstr *, 2> & DbgValues) {
391 DbgValues.clear();
392 if (!MI->getOperand(0).isReg())
393 return;
394
395 MachineBasicBlock::iterator DI = MI; ++DI;
396 for (MachineBasicBlock::iterator DE = MI->getParent()->end();
397 DI != DE; ++DI) {
398 if (!DI->isDebugValue())
399 return;
400 if (DI->getOperand(0).isReg() &&
401 DI->getOperand(0).getReg() == MI->getOperand(0).getReg())
402 DbgValues.push_back(DI);
403 }
404}
405
Devang Patele265bcf2011-12-08 21:48:01 +0000406/// FindSuccToSinkTo - Find a successor to sink this instruction to.
407MachineBasicBlock *MachineSinking::FindSuccToSinkTo(MachineInstr *MI,
408 bool &BreakPHIEdge) {
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000409
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000410 // Loop over all the operands of the specified instruction. If there is
411 // anything we can't handle, bail out.
412 MachineBasicBlock *ParentBlock = MI->getParent();
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000413
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000414 // SuccToSinkTo - This is the successor to sink this instruction to, once we
415 // decide.
416 MachineBasicBlock *SuccToSinkTo = 0;
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000417
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000418 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
419 const MachineOperand &MO = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000420 if (!MO.isReg()) continue; // Ignore non-register operands.
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000421
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000422 unsigned Reg = MO.getReg();
423 if (Reg == 0) continue;
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000424
Dan Gohman6f0d0242008-02-10 18:45:23 +0000425 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
Dan Gohman19778e72009-09-25 22:53:29 +0000426 if (MO.isUse()) {
427 // If the physreg has no defs anywhere, it's just an ambient register
Dan Gohman45094e32009-09-26 02:34:00 +0000428 // and we can freely move its uses. Alternatively, if it's allocatable,
429 // it could get allocated to something with a def during allocation.
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000430 if (!MRI->def_empty(Reg))
Devang Patele265bcf2011-12-08 21:48:01 +0000431 return NULL;
Bill Wendling05c68372010-06-02 23:04:26 +0000432
Dan Gohman45094e32009-09-26 02:34:00 +0000433 if (AllocatableSet.test(Reg))
Devang Patele265bcf2011-12-08 21:48:01 +0000434 return NULL;
Bill Wendling05c68372010-06-02 23:04:26 +0000435
Dan Gohman19778e72009-09-25 22:53:29 +0000436 // Check for a def among the register's aliases too.
Dan Gohman45094e32009-09-26 02:34:00 +0000437 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
438 unsigned AliasReg = *Alias;
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000439 if (!MRI->def_empty(AliasReg))
Devang Patele265bcf2011-12-08 21:48:01 +0000440 return NULL;
Bill Wendling05c68372010-06-02 23:04:26 +0000441
Dan Gohman45094e32009-09-26 02:34:00 +0000442 if (AllocatableSet.test(AliasReg))
Devang Patele265bcf2011-12-08 21:48:01 +0000443 return NULL;
Dan Gohman45094e32009-09-26 02:34:00 +0000444 }
Bill Wendling730c07e2010-06-25 20:48:10 +0000445 } else if (!MO.isDead()) {
446 // A def that isn't dead. We can't move it.
Devang Patele265bcf2011-12-08 21:48:01 +0000447 return NULL;
Dan Gohman19778e72009-09-25 22:53:29 +0000448 }
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000449 } else {
450 // Virtual register uses are always safe to sink.
451 if (MO.isUse()) continue;
Evan Chengb6f54172009-02-07 01:21:47 +0000452
453 // If it's not safe to move defs of the register class, then abort.
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000454 if (!TII->isSafeToMoveRegClassDefs(MRI->getRegClass(Reg)))
Devang Patele265bcf2011-12-08 21:48:01 +0000455 return NULL;
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000456
Chris Lattnere430e1c2008-01-05 06:47:58 +0000457 // FIXME: This picks a successor to sink into based on having one
458 // successor that dominates all the uses. However, there are cases where
459 // sinking can happen but where the sink point isn't a successor. For
460 // example:
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000461 //
Chris Lattnere430e1c2008-01-05 06:47:58 +0000462 // x = computation
463 // if () {} else {}
464 // use x
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000465 //
Bill Wendling05c68372010-06-02 23:04:26 +0000466 // the instruction could be sunk over the whole diamond for the
Chris Lattnere430e1c2008-01-05 06:47:58 +0000467 // if/then/else (or loop, etc), allowing it to be sunk into other blocks
468 // after that.
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000469
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000470 // Virtual register defs can only be sunk if all their uses are in blocks
471 // dominated by one of the successors.
472 if (SuccToSinkTo) {
473 // If a previous operand picked a block to sink to, then this operand
474 // must be sinkable to the same block.
Evan Chenge5e79462010-08-19 18:33:29 +0000475 bool LocalUse = false;
Evan Cheng23997862010-09-18 06:42:17 +0000476 if (!AllUsesDominatedByBlock(Reg, SuccToSinkTo, ParentBlock,
Evan Cheng7af6dc42010-09-20 19:12:55 +0000477 BreakPHIEdge, LocalUse))
Devang Patele265bcf2011-12-08 21:48:01 +0000478 return NULL;
Bill Wendling05c68372010-06-02 23:04:26 +0000479
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000480 continue;
481 }
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000482
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000483 // Otherwise, we should look at all the successors and decide which one
484 // we should sink to.
485 for (MachineBasicBlock::succ_iterator SI = ParentBlock->succ_begin(),
486 E = ParentBlock->succ_end(); SI != E; ++SI) {
Devang Patelcf405ba2011-12-08 21:33:23 +0000487 MachineBasicBlock *SuccBlock = *SI;
488 // It is not possible to sink an instruction into its own block. This can
489 // happen with loops.
490 if (ParentBlock == SuccBlock)
491 continue;
492
493 // It's not safe to sink instructions to EH landing pad. Control flow into
494 // landing pad is implicitly defined.
495 if (SuccBlock->isLandingPad())
496 continue;
497
Evan Chenge5e79462010-08-19 18:33:29 +0000498 bool LocalUse = false;
Devang Patelcf405ba2011-12-08 21:33:23 +0000499 if (AllUsesDominatedByBlock(Reg, SuccBlock, ParentBlock,
Evan Cheng7af6dc42010-09-20 19:12:55 +0000500 BreakPHIEdge, LocalUse)) {
Devang Patelcf405ba2011-12-08 21:33:23 +0000501 SuccToSinkTo = SuccBlock;
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000502 break;
503 }
Evan Chengc3439ad2010-08-18 23:09:25 +0000504 if (LocalUse)
505 // Def is used locally, it's never safe to move this def.
Devang Patele265bcf2011-12-08 21:48:01 +0000506 return NULL;
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000507 }
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000508
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000509 // If we couldn't find a block to sink to, ignore this instruction.
510 if (SuccToSinkTo == 0)
Devang Patele265bcf2011-12-08 21:48:01 +0000511 return NULL;
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000512 }
513 }
Devang Patele265bcf2011-12-08 21:48:01 +0000514 return SuccToSinkTo;
515}
516
517/// SinkInstruction - Determine whether it is safe to sink the specified machine
518/// instruction out of its current block into a successor.
519bool MachineSinking::SinkInstruction(MachineInstr *MI, bool &SawStore) {
520 // Don't sink insert_subreg, subreg_to_reg, reg_sequence. These are meant to
521 // be close to the source to make it easier to coalesce.
522 if (AvoidsSinking(MI, MRI))
523 return false;
524
525 // Check if it's safe to move the instruction.
526 if (!MI->isSafeToMove(TII, AA, SawStore))
527 return false;
528
529 // FIXME: This should include support for sinking instructions within the
530 // block they are currently in to shorten the live ranges. We often get
531 // instructions sunk into the top of a large block, but it would be better to
532 // also sink them down before their first use in the block. This xform has to
533 // be careful not to *increase* register pressure though, e.g. sinking
534 // "x = y + z" down if it kills y and z would increase the live ranges of y
535 // and z and only shrink the live range of x.
536
537 bool BreakPHIEdge = false;
538 MachineBasicBlock *SuccToSinkTo = FindSuccToSinkTo(MI, BreakPHIEdge);
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000539
Chris Lattner9bb459b2008-01-05 01:39:17 +0000540 // If there are no outputs, it must have side-effects.
541 if (SuccToSinkTo == 0)
542 return false;
Evan Chengb5999792009-02-15 08:36:12 +0000543
Bill Wendling869d60d2010-06-03 07:54:20 +0000544
Daniel Dunbard24c9d52010-06-23 00:48:25 +0000545 // If the instruction to move defines a dead physical register which is live
546 // when leaving the basic block, don't move it because it could turn into a
547 // "zombie" define of that preg. E.g., EFLAGS. (<rdar://problem/8030636>)
Bill Wendling730c07e2010-06-25 20:48:10 +0000548 for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
549 const MachineOperand &MO = MI->getOperand(I);
550 if (!MO.isReg()) continue;
551 unsigned Reg = MO.getReg();
552 if (Reg == 0 || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
553 if (SuccToSinkTo->isLiveIn(Reg))
Bill Wendling869d60d2010-06-03 07:54:20 +0000554 return false;
Bill Wendling730c07e2010-06-25 20:48:10 +0000555 }
Bill Wendling869d60d2010-06-03 07:54:20 +0000556
Bill Wendling05c68372010-06-02 23:04:26 +0000557 DEBUG(dbgs() << "Sink instr " << *MI << "\tinto block " << *SuccToSinkTo);
558
Devang Patele265bcf2011-12-08 21:48:01 +0000559 MachineBasicBlock *ParentBlock = MI->getParent();
560
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000561 // If the block has multiple predecessors, this would introduce computation on
562 // a path that it doesn't already exist. We could split the critical edge,
563 // but for now we just punt.
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000564 if (SuccToSinkTo->pred_size() > 1) {
Jakob Stoklund Olesen8d171602010-04-13 19:06:14 +0000565 // We cannot sink a load across a critical edge - there may be stores in
566 // other code paths.
Evan Cheng4dc301a2010-08-19 17:33:11 +0000567 bool TryBreak = false;
Jakob Stoklund Olesen8d171602010-04-13 19:06:14 +0000568 bool store = true;
569 if (!MI->isSafeToMove(TII, AA, store)) {
Evan Chengf942c132010-08-19 23:33:02 +0000570 DEBUG(dbgs() << " *** NOTE: Won't sink load along critical edge.\n");
Evan Cheng4dc301a2010-08-19 17:33:11 +0000571 TryBreak = true;
Jakob Stoklund Olesen8d171602010-04-13 19:06:14 +0000572 }
573
574 // We don't want to sink across a critical edge if we don't dominate the
575 // successor. We could be introducing calculations to new code paths.
Evan Cheng4dc301a2010-08-19 17:33:11 +0000576 if (!TryBreak && !DT->dominates(ParentBlock, SuccToSinkTo)) {
Evan Chengf942c132010-08-19 23:33:02 +0000577 DEBUG(dbgs() << " *** NOTE: Critical edge found\n");
Evan Cheng4dc301a2010-08-19 17:33:11 +0000578 TryBreak = true;
Jakob Stoklund Olesen8d171602010-04-13 19:06:14 +0000579 }
580
Jakob Stoklund Olesen626f3d72010-04-15 23:41:02 +0000581 // Don't sink instructions into a loop.
Evan Cheng4dc301a2010-08-19 17:33:11 +0000582 if (!TryBreak && LI->isLoopHeader(SuccToSinkTo)) {
Evan Chengf942c132010-08-19 23:33:02 +0000583 DEBUG(dbgs() << " *** NOTE: Loop header found\n");
Evan Cheng4dc301a2010-08-19 17:33:11 +0000584 TryBreak = true;
Jakob Stoklund Olesen626f3d72010-04-15 23:41:02 +0000585 }
586
Jakob Stoklund Olesen8d171602010-04-13 19:06:14 +0000587 // Otherwise we are OK with sinking along a critical edge.
Evan Cheng4dc301a2010-08-19 17:33:11 +0000588 if (!TryBreak)
589 DEBUG(dbgs() << "Sinking along critical edge.\n");
590 else {
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000591 MachineBasicBlock *NewSucc =
Evan Cheng7af6dc42010-09-20 19:12:55 +0000592 SplitCriticalEdge(MI, ParentBlock, SuccToSinkTo, BreakPHIEdge);
Evan Cheng4dc301a2010-08-19 17:33:11 +0000593 if (!NewSucc) {
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000594 DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
595 "break critical edge\n");
Evan Cheng4dc301a2010-08-19 17:33:11 +0000596 return false;
597 } else {
Evan Chengf942c132010-08-19 23:33:02 +0000598 DEBUG(dbgs() << " *** Splitting critical edge:"
Evan Cheng4dc301a2010-08-19 17:33:11 +0000599 " BB#" << ParentBlock->getNumber()
600 << " -- BB#" << NewSucc->getNumber()
601 << " -- BB#" << SuccToSinkTo->getNumber() << '\n');
Evan Cheng4dc301a2010-08-19 17:33:11 +0000602 SuccToSinkTo = NewSucc;
603 ++NumSplit;
Evan Cheng7af6dc42010-09-20 19:12:55 +0000604 BreakPHIEdge = false;
Evan Cheng4dc301a2010-08-19 17:33:11 +0000605 }
606 }
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000607 }
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000608
Evan Cheng7af6dc42010-09-20 19:12:55 +0000609 if (BreakPHIEdge) {
610 // BreakPHIEdge is true if all the uses are in the successor MBB being
611 // sunken into and they are all PHI nodes. In this case, machine-sink must
612 // break the critical edge first.
Evan Cheng23997862010-09-18 06:42:17 +0000613 MachineBasicBlock *NewSucc = SplitCriticalEdge(MI, ParentBlock,
Evan Cheng7af6dc42010-09-20 19:12:55 +0000614 SuccToSinkTo, BreakPHIEdge);
Evan Cheng23997862010-09-18 06:42:17 +0000615 if (!NewSucc) {
616 DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
617 "break critical edge\n");
618 return false;
619 }
620
621 DEBUG(dbgs() << " *** Splitting critical edge:"
622 " BB#" << ParentBlock->getNumber()
623 << " -- BB#" << NewSucc->getNumber()
624 << " -- BB#" << SuccToSinkTo->getNumber() << '\n');
625 SuccToSinkTo = NewSucc;
626 ++NumSplit;
627 }
628
Bill Wendling05c68372010-06-02 23:04:26 +0000629 // Determine where to insert into. Skip phi nodes.
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000630 MachineBasicBlock::iterator InsertPos = SuccToSinkTo->begin();
Evan Cheng23997862010-09-18 06:42:17 +0000631 while (InsertPos != SuccToSinkTo->end() && InsertPos->isPHI())
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000632 ++InsertPos;
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000633
Devang Patel541a81c2011-09-07 00:07:58 +0000634 // collect matching debug values.
635 SmallVector<MachineInstr *, 2> DbgValuesToSink;
636 collectDebugValues(MI, DbgValuesToSink);
637
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000638 // Move the instruction.
639 SuccToSinkTo->splice(InsertPos, ParentBlock, MI,
640 ++MachineBasicBlock::iterator(MI));
Dan Gohmane6cd7572010-05-13 20:34:42 +0000641
Devang Patel541a81c2011-09-07 00:07:58 +0000642 // Move debug values.
643 for (SmallVector<MachineInstr *, 2>::iterator DBI = DbgValuesToSink.begin(),
644 DBE = DbgValuesToSink.end(); DBI != DBE; ++DBI) {
645 MachineInstr *DbgMI = *DBI;
646 SuccToSinkTo->splice(InsertPos, ParentBlock, DbgMI,
647 ++MachineBasicBlock::iterator(DbgMI));
648 }
649
Bill Wendling05c68372010-06-02 23:04:26 +0000650 // Conservatively, clear any kill flags, since it's possible that they are no
651 // longer correct.
Dan Gohmane6cd7572010-05-13 20:34:42 +0000652 MI->clearKillInfo();
653
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000654 return true;
655}