blob: 0ae495c55a81072d2e35d67494af21df7aefc3ac [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
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000019#include "llvm/CodeGen/Passes.h"
Evan Cheng6edb0ea2010-09-17 22:28:18 +000020#include "llvm/ADT/SmallSet.h"
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000021#include "llvm/ADT/Statistic.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000022#include "llvm/Analysis/AliasAnalysis.h"
23#include "llvm/CodeGen/MachineDominators.h"
24#include "llvm/CodeGen/MachineLoopInfo.h"
25#include "llvm/CodeGen/MachineRegisterInfo.h"
Evan Cheng4dc301a2010-08-19 17:33:11 +000026#include "llvm/Support/CommandLine.h"
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000027#include "llvm/Support/Debug.h"
Bill Wendling1e973aa2009-08-22 20:26:23 +000028#include "llvm/Support/raw_ostream.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000029#include "llvm/Target/TargetInstrInfo.h"
30#include "llvm/Target/TargetMachine.h"
31#include "llvm/Target/TargetRegisterInfo.h"
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000032using namespace llvm;
33
Stephen Hinesdce4a402014-05-29 02:49:00 -070034#define DEBUG_TYPE "machine-sink"
35
Andrew Trick1df91b02012-02-08 21:22:43 +000036static cl::opt<bool>
Evan Cheng4dc301a2010-08-19 17:33:11 +000037SplitEdges("machine-sink-split",
38 cl::desc("Split critical edges during machine sinking"),
Evan Cheng44be1a82010-09-20 22:52:00 +000039 cl::init(true), cl::Hidden);
Evan Cheng4dc301a2010-08-19 17:33:11 +000040
Evan Cheng6edb0ea2010-09-17 22:28:18 +000041STATISTIC(NumSunk, "Number of machine instructions sunk");
42STATISTIC(NumSplit, "Number of critical edges split");
43STATISTIC(NumCoalesces, "Number of copies coalesced");
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000044
45namespace {
Nick Lewycky6726b6d2009-10-25 06:33:48 +000046 class MachineSinking : public MachineFunctionPass {
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000047 const TargetInstrInfo *TII;
Dan Gohman19778e72009-09-25 22:53:29 +000048 const TargetRegisterInfo *TRI;
Evan Cheng6edb0ea2010-09-17 22:28:18 +000049 MachineRegisterInfo *MRI; // Machine register information
Dan Gohmana5225ad2009-08-05 01:19:01 +000050 MachineDominatorTree *DT; // Machine dominator tree
Jakob Stoklund Olesen626f3d72010-04-15 23:41:02 +000051 MachineLoopInfo *LI;
Dan Gohmana70dca12009-10-09 23:27:56 +000052 AliasAnalysis *AA;
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
Stephen Hines36b56882014-04-23 16:57:46 -070064 bool runOnMachineFunction(MachineFunction &MF) override;
Jim Grosbach6ee358b2010-06-03 23:49:57 +000065
Stephen Hines36b56882014-04-23 16:57:46 -070066 void getAnalysisUsage(AnalysisUsage &AU) const override {
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
Stephen Hines36b56882014-04-23 16:57:46 -070076 void releaseMemory() override {
Evan Cheng6edb0ea2010-09-17 22:28:18 +000077 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 Patel52111342011-12-14 23:20:38 +000093 MachineBasicBlock *FindSuccToSinkTo(MachineInstr *MI, MachineBasicBlock *MBB,
94 bool &BreakPHIEdge);
Andrew Trick1df91b02012-02-08 21:22:43 +000095 bool isProfitableToSinkTo(unsigned Reg, MachineInstr *MI,
Devang Patel52111342011-12-14 23:20:38 +000096 MachineBasicBlock *MBB,
97 MachineBasicBlock *SuccToSinkTo);
Devang Patele265bcf2011-12-08 21:48:01 +000098
Evan Cheng6edb0ea2010-09-17 22:28:18 +000099 bool PerformTrivialForwardCoalescing(MachineInstr *MI,
100 MachineBasicBlock *MBB);
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000101 };
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000102} // end anonymous namespace
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000103
Dan Gohman844731a2008-05-13 00:00:25 +0000104char MachineSinking::ID = 0;
Andrew Trick1dd8c852012-02-08 21:23:13 +0000105char &llvm::MachineSinkingID = MachineSinking::ID;
Owen Anderson2ab36d32010-10-12 19:48:12 +0000106INITIALIZE_PASS_BEGIN(MachineSinking, "machine-sink",
107 "Machine code sinking", false, false)
108INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
109INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
110INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
111INITIALIZE_PASS_END(MachineSinking, "machine-sink",
Owen Andersonce665bd2010-10-07 22:25:06 +0000112 "Machine code sinking", false, false)
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000113
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000114bool MachineSinking::PerformTrivialForwardCoalescing(MachineInstr *MI,
115 MachineBasicBlock *MBB) {
116 if (!MI->isCopy())
117 return false;
118
119 unsigned SrcReg = MI->getOperand(1).getReg();
120 unsigned DstReg = MI->getOperand(0).getReg();
121 if (!TargetRegisterInfo::isVirtualRegister(SrcReg) ||
122 !TargetRegisterInfo::isVirtualRegister(DstReg) ||
123 !MRI->hasOneNonDBGUse(SrcReg))
124 return false;
125
126 const TargetRegisterClass *SRC = MRI->getRegClass(SrcReg);
127 const TargetRegisterClass *DRC = MRI->getRegClass(DstReg);
128 if (SRC != DRC)
129 return false;
130
131 MachineInstr *DefMI = MRI->getVRegDef(SrcReg);
132 if (DefMI->isCopyLike())
133 return false;
134 DEBUG(dbgs() << "Coalescing: " << *DefMI);
135 DEBUG(dbgs() << "*** to: " << *MI);
136 MRI->replaceRegWith(DstReg, SrcReg);
137 MI->eraseFromParent();
138 ++NumCoalesces;
139 return true;
140}
141
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000142/// AllUsesDominatedByBlock - Return true if all uses of the specified register
Evan Chengc3439ad2010-08-18 23:09:25 +0000143/// occur in blocks dominated by the specified block. If any use is in the
144/// definition block, then return false since it is never legal to move def
145/// after uses.
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000146bool
147MachineSinking::AllUsesDominatedByBlock(unsigned Reg,
148 MachineBasicBlock *MBB,
149 MachineBasicBlock *DefMBB,
Evan Cheng7af6dc42010-09-20 19:12:55 +0000150 bool &BreakPHIEdge,
151 bool &LocalUse) const {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000152 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
153 "Only makes sense for vregs");
Evan Cheng23997862010-09-18 06:42:17 +0000154
Devang Patelf5b9a742011-12-09 01:25:04 +0000155 // Ignore debug uses because debug info doesn't affect the code.
Evan Cheng23997862010-09-18 06:42:17 +0000156 if (MRI->use_nodbg_empty(Reg))
157 return true;
158
Evan Cheng7af6dc42010-09-20 19:12:55 +0000159 // BreakPHIEdge is true if all the uses are in the successor MBB being sunken
160 // into and they are all PHI nodes. In this case, machine-sink must break
161 // the critical edge first. e.g.
162 //
Evan Cheng23997862010-09-18 06:42:17 +0000163 // BB#1: derived from LLVM BB %bb4.preheader
164 // Predecessors according to CFG: BB#0
165 // ...
166 // %reg16385<def> = DEC64_32r %reg16437, %EFLAGS<imp-def,dead>
167 // ...
168 // JE_4 <BB#37>, %EFLAGS<imp-use>
169 // Successors according to CFG: BB#37 BB#2
170 //
171 // BB#2: derived from LLVM BB %bb.nph
172 // Predecessors according to CFG: BB#0 BB#1
173 // %reg16386<def> = PHI %reg16434, <BB#0>, %reg16385, <BB#1>
Evan Cheng7af6dc42010-09-20 19:12:55 +0000174 BreakPHIEdge = true;
Stephen Hines36b56882014-04-23 16:57:46 -0700175 for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) {
176 MachineInstr *UseInst = MO.getParent();
177 unsigned OpNo = &MO - &UseInst->getOperand(0);
Evan Cheng23997862010-09-18 06:42:17 +0000178 MachineBasicBlock *UseBlock = UseInst->getParent();
179 if (!(UseBlock == MBB && UseInst->isPHI() &&
Stephen Hines36b56882014-04-23 16:57:46 -0700180 UseInst->getOperand(OpNo+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
Stephen Hines36b56882014-04-23 16:57:46 -0700188 for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) {
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000189 // Determine the block of the use.
Stephen Hines36b56882014-04-23 16:57:46 -0700190 MachineInstr *UseInst = MO.getParent();
191 unsigned OpNo = &MO - &UseInst->getOperand(0);
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000192 MachineBasicBlock *UseBlock = UseInst->getParent();
Evan Cheng23997862010-09-18 06:42:17 +0000193 if (UseInst->isPHI()) {
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000194 // PHI nodes use the operand in the predecessor block, not the block with
195 // the PHI.
Stephen Hines36b56882014-04-23 16:57:46 -0700196 UseBlock = UseInst->getOperand(OpNo+1).getMBB();
Evan Chenge5e79462010-08-19 18:33:29 +0000197 } else if (UseBlock == DefMBB) {
198 LocalUse = true;
199 return false;
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000200 }
Bill Wendling05c68372010-06-02 23:04:26 +0000201
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000202 // Check that it dominates.
203 if (!DT->dominates(MBB, UseBlock))
204 return false;
205 }
Bill Wendling05c68372010-06-02 23:04:26 +0000206
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000207 return true;
208}
209
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000210bool MachineSinking::runOnMachineFunction(MachineFunction &MF) {
Stephen Hines36b56882014-04-23 16:57:46 -0700211 if (skipOptnoneFunction(*MF.getFunction()))
212 return false;
213
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>();
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000223
224 bool EverMadeChange = false;
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000225
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000226 while (1) {
227 bool MadeChange = false;
228
229 // Process all basic blocks.
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000230 CEBCandidates.clear();
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000231 for (MachineFunction::iterator I = MF.begin(), E = MF.end();
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000232 I != E; ++I)
233 MadeChange |= ProcessBlock(*I);
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000234
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000235 // If this iteration over the code changed anything, keep iterating.
236 if (!MadeChange) break;
237 EverMadeChange = true;
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000238 }
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000239 return EverMadeChange;
240}
241
242bool MachineSinking::ProcessBlock(MachineBasicBlock &MBB) {
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000243 // Can't sink anything out of a block that has less than two successors.
Chris Lattner296185c2009-04-10 16:38:36 +0000244 if (MBB.succ_size() <= 1 || MBB.empty()) return false;
245
Dan Gohmanc4ae94d2010-04-05 19:17:22 +0000246 // Don't bother sinking code out of unreachable blocks. In addition to being
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000247 // unprofitable, it can also lead to infinite looping, because in an
248 // unreachable loop there may be nowhere to stop.
Dan Gohmanc4ae94d2010-04-05 19:17:22 +0000249 if (!DT->isReachableFromEntry(&MBB)) return false;
250
Chris Lattner296185c2009-04-10 16:38:36 +0000251 bool MadeChange = false;
252
Chris Lattneraad193a2008-01-12 00:17:41 +0000253 // Walk the basic block bottom-up. Remember if we saw a store.
Chris Lattner296185c2009-04-10 16:38:36 +0000254 MachineBasicBlock::iterator I = MBB.end();
255 --I;
256 bool ProcessedBegin, SawStore = false;
257 do {
258 MachineInstr *MI = I; // The instruction to sink.
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000259
Chris Lattner296185c2009-04-10 16:38:36 +0000260 // Predecrement I (if it's not begin) so that it isn't invalidated by
261 // sinking.
262 ProcessedBegin = I == MBB.begin();
263 if (!ProcessedBegin)
264 --I;
Dale Johannesenb0812f12010-03-05 00:02:59 +0000265
266 if (MI->isDebugValue())
267 continue;
268
Evan Chengcfea9852011-04-11 18:47:20 +0000269 bool Joined = PerformTrivialForwardCoalescing(MI, &MBB);
270 if (Joined) {
271 MadeChange = true;
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000272 continue;
Evan Chengcfea9852011-04-11 18:47:20 +0000273 }
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000274
Chris Lattner296185c2009-04-10 16:38:36 +0000275 if (SinkInstruction(MI, SawStore))
276 ++NumSunk, MadeChange = true;
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000277
Chris Lattner296185c2009-04-10 16:38:36 +0000278 // If we just processed the first instruction in the block, we're done.
279 } while (!ProcessedBegin);
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000280
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000281 return MadeChange;
282}
283
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000284bool MachineSinking::isWorthBreakingCriticalEdge(MachineInstr *MI,
285 MachineBasicBlock *From,
286 MachineBasicBlock *To) {
287 // FIXME: Need much better heuristics.
288
289 // If the pass has already considered breaking this edge (during this pass
290 // through the function), then let's go ahead and break it. This means
291 // sinking multiple "cheap" instructions into the same block.
292 if (!CEBCandidates.insert(std::make_pair(From, To)))
293 return true;
294
Stephen Hinesbfc2d682014-10-17 08:47:43 -0700295 if (!MI->isCopy() && !TII->isAsCheapAsAMove(MI))
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000296 return true;
297
298 // MI is cheap, we probably don't want to break the critical edge for it.
299 // However, if this would allow some definitions of its source operands
300 // to be sunk then it's probably worth it.
301 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
302 const MachineOperand &MO = MI->getOperand(i);
Will Dietze4b44c12013-10-14 16:57:17 +0000303 if (!MO.isReg() || !MO.isUse())
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000304 continue;
Will Dietze4b44c12013-10-14 16:57:17 +0000305 unsigned Reg = MO.getReg();
306 if (Reg == 0)
307 continue;
308
309 // We don't move live definitions of physical registers,
310 // so sinking their uses won't enable any opportunities.
311 if (TargetRegisterInfo::isPhysicalRegister(Reg))
312 continue;
313
314 // If this instruction is the only user of a virtual register,
315 // check if breaking the edge will enable sinking
316 // both this instruction and the defining instruction.
317 if (MRI->hasOneNonDBGUse(Reg)) {
318 // If the definition resides in same MBB,
319 // claim it's likely we can sink these together.
320 // If definition resides elsewhere, we aren't
321 // blocking it from being sunk so don't break the edge.
322 MachineInstr *DefMI = MRI->getVRegDef(Reg);
323 if (DefMI->getParent() == MI->getParent())
324 return true;
325 }
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000326 }
327
328 return false;
329}
330
331MachineBasicBlock *MachineSinking::SplitCriticalEdge(MachineInstr *MI,
332 MachineBasicBlock *FromBB,
333 MachineBasicBlock *ToBB,
Evan Cheng7af6dc42010-09-20 19:12:55 +0000334 bool BreakPHIEdge) {
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000335 if (!isWorthBreakingCriticalEdge(MI, FromBB, ToBB))
Stephen Hinesdce4a402014-05-29 02:49:00 -0700336 return nullptr;
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000337
Evan Cheng4dc301a2010-08-19 17:33:11 +0000338 // Avoid breaking back edge. From == To means backedge for single BB loop.
Evan Cheng44be1a82010-09-20 22:52:00 +0000339 if (!SplitEdges || FromBB == ToBB)
Stephen Hinesdce4a402014-05-29 02:49:00 -0700340 return nullptr;
Evan Cheng4dc301a2010-08-19 17:33:11 +0000341
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000342 // Check for backedges of more "complex" loops.
343 if (LI->getLoopFor(FromBB) == LI->getLoopFor(ToBB) &&
344 LI->isLoopHeader(ToBB))
Stephen Hinesdce4a402014-05-29 02:49:00 -0700345 return nullptr;
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000346
347 // It's not always legal to break critical edges and sink the computation
348 // to the edge.
349 //
350 // BB#1:
351 // v1024
352 // Beq BB#3
353 // <fallthrough>
354 // BB#2:
355 // ... no uses of v1024
356 // <fallthrough>
357 // BB#3:
358 // ...
359 // = v1024
360 //
361 // If BB#1 -> BB#3 edge is broken and computation of v1024 is inserted:
362 //
363 // BB#1:
364 // ...
365 // Bne BB#2
366 // BB#4:
367 // v1024 =
368 // B BB#3
369 // BB#2:
370 // ... no uses of v1024
371 // <fallthrough>
372 // BB#3:
373 // ...
374 // = v1024
375 //
376 // This is incorrect since v1024 is not computed along the BB#1->BB#2->BB#3
377 // flow. We need to ensure the new basic block where the computation is
378 // sunk to dominates all the uses.
379 // It's only legal to break critical edge and sink the computation to the
380 // new block if all the predecessors of "To", except for "From", are
381 // not dominated by "From". Given SSA property, this means these
382 // predecessors are dominated by "To".
383 //
384 // There is no need to do this check if all the uses are PHI nodes. PHI
385 // sources are only defined on the specific predecessor edges.
Evan Cheng7af6dc42010-09-20 19:12:55 +0000386 if (!BreakPHIEdge) {
Evan Cheng4dc301a2010-08-19 17:33:11 +0000387 for (MachineBasicBlock::pred_iterator PI = ToBB->pred_begin(),
388 E = ToBB->pred_end(); PI != E; ++PI) {
389 if (*PI == FromBB)
390 continue;
391 if (!DT->dominates(ToBB, *PI))
Stephen Hinesdce4a402014-05-29 02:49:00 -0700392 return nullptr;
Evan Cheng4dc301a2010-08-19 17:33:11 +0000393 }
Evan Cheng4dc301a2010-08-19 17:33:11 +0000394 }
395
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000396 return FromBB->SplitCriticalEdge(ToBB, this);
Evan Cheng4dc301a2010-08-19 17:33:11 +0000397}
398
Evan Chengb0cdf8a2010-09-23 06:53:00 +0000399static bool AvoidsSinking(MachineInstr *MI, MachineRegisterInfo *MRI) {
400 return MI->isInsertSubreg() || MI->isSubregToReg() || MI->isRegSequence();
401}
402
Andrew Trick1df91b02012-02-08 21:22:43 +0000403/// collectDebgValues - Scan instructions following MI and collect any
Devang Patel541a81c2011-09-07 00:07:58 +0000404/// matching DBG_VALUEs.
Andrew Trick1df91b02012-02-08 21:22:43 +0000405static void collectDebugValues(MachineInstr *MI,
Craig Toppera0ec3f92013-07-14 04:42:23 +0000406 SmallVectorImpl<MachineInstr *> &DbgValues) {
Devang Patel541a81c2011-09-07 00:07:58 +0000407 DbgValues.clear();
408 if (!MI->getOperand(0).isReg())
409 return;
410
411 MachineBasicBlock::iterator DI = MI; ++DI;
412 for (MachineBasicBlock::iterator DE = MI->getParent()->end();
413 DI != DE; ++DI) {
414 if (!DI->isDebugValue())
415 return;
416 if (DI->getOperand(0).isReg() &&
417 DI->getOperand(0).getReg() == MI->getOperand(0).getReg())
418 DbgValues.push_back(DI);
419 }
420}
421
Devang Patel52111342011-12-14 23:20:38 +0000422/// isPostDominatedBy - Return true if A is post dominated by B.
423static bool isPostDominatedBy(MachineBasicBlock *A, MachineBasicBlock *B) {
424
425 // FIXME - Use real post dominator.
426 if (A->succ_size() != 2)
427 return false;
428 MachineBasicBlock::succ_iterator I = A->succ_begin();
429 if (B == *I)
430 ++I;
431 MachineBasicBlock *OtherSuccBlock = *I;
432 if (OtherSuccBlock->succ_size() != 1 ||
433 *(OtherSuccBlock->succ_begin()) != B)
434 return false;
435
436 return true;
437}
438
439/// isProfitableToSinkTo - Return true if it is profitable to sink MI.
Andrew Trick1df91b02012-02-08 21:22:43 +0000440bool MachineSinking::isProfitableToSinkTo(unsigned Reg, MachineInstr *MI,
Devang Patel52111342011-12-14 23:20:38 +0000441 MachineBasicBlock *MBB,
442 MachineBasicBlock *SuccToSinkTo) {
443 assert (MI && "Invalid MachineInstr!");
444 assert (SuccToSinkTo && "Invalid SinkTo Candidate BB");
445
446 if (MBB == SuccToSinkTo)
447 return false;
448
449 // It is profitable if SuccToSinkTo does not post dominate current block.
450 if (!isPostDominatedBy(MBB, SuccToSinkTo))
451 return true;
452
453 // Check if only use in post dominated block is PHI instruction.
454 bool NonPHIUse = false;
Stephen Hines36b56882014-04-23 16:57:46 -0700455 for (MachineInstr &UseInst : MRI->use_nodbg_instructions(Reg)) {
456 MachineBasicBlock *UseBlock = UseInst.getParent();
457 if (UseBlock == SuccToSinkTo && !UseInst.isPHI())
Devang Patel52111342011-12-14 23:20:38 +0000458 NonPHIUse = true;
459 }
460 if (!NonPHIUse)
461 return true;
462
463 // If SuccToSinkTo post dominates then also it may be profitable if MI
464 // can further profitably sinked into another block in next round.
465 bool BreakPHIEdge = false;
466 // FIXME - If finding successor is compile time expensive then catch results.
467 if (MachineBasicBlock *MBB2 = FindSuccToSinkTo(MI, SuccToSinkTo, BreakPHIEdge))
468 return isProfitableToSinkTo(Reg, MI, SuccToSinkTo, MBB2);
469
470 // If SuccToSinkTo is final destination and it is a post dominator of current
471 // block then it is not profitable to sink MI into SuccToSinkTo block.
472 return false;
473}
474
Devang Patele265bcf2011-12-08 21:48:01 +0000475/// FindSuccToSinkTo - Find a successor to sink this instruction to.
476MachineBasicBlock *MachineSinking::FindSuccToSinkTo(MachineInstr *MI,
Devang Patel52111342011-12-14 23:20:38 +0000477 MachineBasicBlock *MBB,
478 bool &BreakPHIEdge) {
479
480 assert (MI && "Invalid MachineInstr!");
481 assert (MBB && "Invalid MachineBasicBlock!");
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000482
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000483 // Loop over all the operands of the specified instruction. If there is
484 // anything we can't handle, bail out.
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000485
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000486 // SuccToSinkTo - This is the successor to sink this instruction to, once we
487 // decide.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700488 MachineBasicBlock *SuccToSinkTo = nullptr;
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000489 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
490 const MachineOperand &MO = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000491 if (!MO.isReg()) continue; // Ignore non-register operands.
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000492
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000493 unsigned Reg = MO.getReg();
494 if (Reg == 0) continue;
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000495
Dan Gohman6f0d0242008-02-10 18:45:23 +0000496 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
Dan Gohman19778e72009-09-25 22:53:29 +0000497 if (MO.isUse()) {
498 // If the physreg has no defs anywhere, it's just an ambient register
Dan Gohman45094e32009-09-26 02:34:00 +0000499 // and we can freely move its uses. Alternatively, if it's allocatable,
500 // it could get allocated to something with a def during allocation.
Jakob Stoklund Olesenc035c942012-01-16 22:34:08 +0000501 if (!MRI->isConstantPhysReg(Reg, *MBB->getParent()))
Stephen Hinesdce4a402014-05-29 02:49:00 -0700502 return nullptr;
Bill Wendling730c07e2010-06-25 20:48:10 +0000503 } else if (!MO.isDead()) {
504 // A def that isn't dead. We can't move it.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700505 return nullptr;
Dan Gohman19778e72009-09-25 22:53:29 +0000506 }
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000507 } else {
508 // Virtual register uses are always safe to sink.
509 if (MO.isUse()) continue;
Evan Chengb6f54172009-02-07 01:21:47 +0000510
511 // If it's not safe to move defs of the register class, then abort.
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000512 if (!TII->isSafeToMoveRegClassDefs(MRI->getRegClass(Reg)))
Stephen Hinesdce4a402014-05-29 02:49:00 -0700513 return nullptr;
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000514
Chris Lattnere430e1c2008-01-05 06:47:58 +0000515 // FIXME: This picks a successor to sink into based on having one
516 // successor that dominates all the uses. However, there are cases where
517 // sinking can happen but where the sink point isn't a successor. For
518 // example:
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000519 //
Chris Lattnere430e1c2008-01-05 06:47:58 +0000520 // x = computation
521 // if () {} else {}
522 // use x
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000523 //
Bill Wendling05c68372010-06-02 23:04:26 +0000524 // the instruction could be sunk over the whole diamond for the
Chris Lattnere430e1c2008-01-05 06:47:58 +0000525 // if/then/else (or loop, etc), allowing it to be sunk into other blocks
526 // after that.
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000527
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000528 // Virtual register defs can only be sunk if all their uses are in blocks
529 // dominated by one of the successors.
530 if (SuccToSinkTo) {
531 // If a previous operand picked a block to sink to, then this operand
532 // must be sinkable to the same block.
Evan Chenge5e79462010-08-19 18:33:29 +0000533 bool LocalUse = false;
Devang Patel52111342011-12-14 23:20:38 +0000534 if (!AllUsesDominatedByBlock(Reg, SuccToSinkTo, MBB,
Evan Cheng7af6dc42010-09-20 19:12:55 +0000535 BreakPHIEdge, LocalUse))
Stephen Hinesdce4a402014-05-29 02:49:00 -0700536 return nullptr;
Bill Wendling05c68372010-06-02 23:04:26 +0000537
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000538 continue;
539 }
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000540
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000541 // Otherwise, we should look at all the successors and decide which one
542 // we should sink to.
Manman Ren53b59d12012-07-31 18:10:39 +0000543 // We give successors with smaller loop depth higher priority.
544 SmallVector<MachineBasicBlock*, 4> Succs(MBB->succ_begin(), MBB->succ_end());
Stephen Hines36b56882014-04-23 16:57:46 -0700545 // Sort Successors according to their loop depth.
546 std::stable_sort(
547 Succs.begin(), Succs.end(),
548 [this](const MachineBasicBlock *LHS, const MachineBasicBlock *RHS) {
549 return LI->getLoopDepth(LHS) < LI->getLoopDepth(RHS);
550 });
Craig Topperf22fd3f2013-07-03 05:11:49 +0000551 for (SmallVectorImpl<MachineBasicBlock *>::iterator SI = Succs.begin(),
552 E = Succs.end(); SI != E; ++SI) {
Devang Patel52111342011-12-14 23:20:38 +0000553 MachineBasicBlock *SuccBlock = *SI;
Evan Chenge5e79462010-08-19 18:33:29 +0000554 bool LocalUse = false;
Devang Patel52111342011-12-14 23:20:38 +0000555 if (AllUsesDominatedByBlock(Reg, SuccBlock, MBB,
Evan Cheng7af6dc42010-09-20 19:12:55 +0000556 BreakPHIEdge, LocalUse)) {
Devang Patelcf405ba2011-12-08 21:33:23 +0000557 SuccToSinkTo = SuccBlock;
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000558 break;
559 }
Evan Chengc3439ad2010-08-18 23:09:25 +0000560 if (LocalUse)
561 // Def is used locally, it's never safe to move this def.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700562 return nullptr;
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000563 }
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000564
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000565 // If we couldn't find a block to sink to, ignore this instruction.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700566 if (!SuccToSinkTo)
567 return nullptr;
568 if (!isProfitableToSinkTo(Reg, MI, MBB, SuccToSinkTo))
569 return nullptr;
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000570 }
571 }
Devang Patel7f7f0902011-12-08 23:52:00 +0000572
573 // It is not possible to sink an instruction into its own block. This can
574 // happen with loops.
Devang Patel52111342011-12-14 23:20:38 +0000575 if (MBB == SuccToSinkTo)
Stephen Hinesdce4a402014-05-29 02:49:00 -0700576 return nullptr;
Devang Patel7f7f0902011-12-08 23:52:00 +0000577
578 // It's not safe to sink instructions to EH landing pad. Control flow into
579 // landing pad is implicitly defined.
580 if (SuccToSinkTo && SuccToSinkTo->isLandingPad())
Stephen Hinesdce4a402014-05-29 02:49:00 -0700581 return nullptr;
Devang Patel7f7f0902011-12-08 23:52:00 +0000582
Devang Patele265bcf2011-12-08 21:48:01 +0000583 return SuccToSinkTo;
584}
585
586/// SinkInstruction - Determine whether it is safe to sink the specified machine
587/// instruction out of its current block into a successor.
588bool MachineSinking::SinkInstruction(MachineInstr *MI, bool &SawStore) {
589 // Don't sink insert_subreg, subreg_to_reg, reg_sequence. These are meant to
590 // be close to the source to make it easier to coalesce.
591 if (AvoidsSinking(MI, MRI))
592 return false;
593
594 // Check if it's safe to move the instruction.
595 if (!MI->isSafeToMove(TII, AA, SawStore))
596 return false;
597
598 // FIXME: This should include support for sinking instructions within the
599 // block they are currently in to shorten the live ranges. We often get
600 // instructions sunk into the top of a large block, but it would be better to
601 // also sink them down before their first use in the block. This xform has to
602 // be careful not to *increase* register pressure though, e.g. sinking
603 // "x = y + z" down if it kills y and z would increase the live ranges of y
604 // and z and only shrink the live range of x.
605
606 bool BreakPHIEdge = false;
Devang Patel52111342011-12-14 23:20:38 +0000607 MachineBasicBlock *ParentBlock = MI->getParent();
608 MachineBasicBlock *SuccToSinkTo = FindSuccToSinkTo(MI, ParentBlock, BreakPHIEdge);
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000609
Chris Lattner9bb459b2008-01-05 01:39:17 +0000610 // If there are no outputs, it must have side-effects.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700611 if (!SuccToSinkTo)
Chris Lattner9bb459b2008-01-05 01:39:17 +0000612 return false;
Evan Chengb5999792009-02-15 08:36:12 +0000613
Bill Wendling869d60d2010-06-03 07:54:20 +0000614
Daniel Dunbard24c9d52010-06-23 00:48:25 +0000615 // If the instruction to move defines a dead physical register which is live
616 // when leaving the basic block, don't move it because it could turn into a
617 // "zombie" define of that preg. E.g., EFLAGS. (<rdar://problem/8030636>)
Bill Wendling730c07e2010-06-25 20:48:10 +0000618 for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
619 const MachineOperand &MO = MI->getOperand(I);
620 if (!MO.isReg()) continue;
621 unsigned Reg = MO.getReg();
622 if (Reg == 0 || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
623 if (SuccToSinkTo->isLiveIn(Reg))
Bill Wendling869d60d2010-06-03 07:54:20 +0000624 return false;
Bill Wendling730c07e2010-06-25 20:48:10 +0000625 }
Bill Wendling869d60d2010-06-03 07:54:20 +0000626
Bill Wendling05c68372010-06-02 23:04:26 +0000627 DEBUG(dbgs() << "Sink instr " << *MI << "\tinto block " << *SuccToSinkTo);
628
Will Dietze4b44c12013-10-14 16:57:17 +0000629 // If the block has multiple predecessors, this is a critical edge.
630 // Decide if we can sink along it or need to break the edge.
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000631 if (SuccToSinkTo->pred_size() > 1) {
Jakob Stoklund Olesen8d171602010-04-13 19:06:14 +0000632 // We cannot sink a load across a critical edge - there may be stores in
633 // other code paths.
Evan Cheng4dc301a2010-08-19 17:33:11 +0000634 bool TryBreak = false;
Jakob Stoklund Olesen8d171602010-04-13 19:06:14 +0000635 bool store = true;
636 if (!MI->isSafeToMove(TII, AA, store)) {
Evan Chengf942c132010-08-19 23:33:02 +0000637 DEBUG(dbgs() << " *** NOTE: Won't sink load along critical edge.\n");
Evan Cheng4dc301a2010-08-19 17:33:11 +0000638 TryBreak = true;
Jakob Stoklund Olesen8d171602010-04-13 19:06:14 +0000639 }
640
641 // We don't want to sink across a critical edge if we don't dominate the
642 // successor. We could be introducing calculations to new code paths.
Evan Cheng4dc301a2010-08-19 17:33:11 +0000643 if (!TryBreak && !DT->dominates(ParentBlock, SuccToSinkTo)) {
Evan Chengf942c132010-08-19 23:33:02 +0000644 DEBUG(dbgs() << " *** NOTE: Critical edge found\n");
Evan Cheng4dc301a2010-08-19 17:33:11 +0000645 TryBreak = true;
Jakob Stoklund Olesen8d171602010-04-13 19:06:14 +0000646 }
647
Jakob Stoklund Olesen626f3d72010-04-15 23:41:02 +0000648 // Don't sink instructions into a loop.
Evan Cheng4dc301a2010-08-19 17:33:11 +0000649 if (!TryBreak && LI->isLoopHeader(SuccToSinkTo)) {
Evan Chengf942c132010-08-19 23:33:02 +0000650 DEBUG(dbgs() << " *** NOTE: Loop header found\n");
Evan Cheng4dc301a2010-08-19 17:33:11 +0000651 TryBreak = true;
Jakob Stoklund Olesen626f3d72010-04-15 23:41:02 +0000652 }
653
Jakob Stoklund Olesen8d171602010-04-13 19:06:14 +0000654 // Otherwise we are OK with sinking along a critical edge.
Evan Cheng4dc301a2010-08-19 17:33:11 +0000655 if (!TryBreak)
656 DEBUG(dbgs() << "Sinking along critical edge.\n");
657 else {
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000658 MachineBasicBlock *NewSucc =
Evan Cheng7af6dc42010-09-20 19:12:55 +0000659 SplitCriticalEdge(MI, ParentBlock, SuccToSinkTo, BreakPHIEdge);
Evan Cheng4dc301a2010-08-19 17:33:11 +0000660 if (!NewSucc) {
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000661 DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
662 "break critical edge\n");
Evan Cheng4dc301a2010-08-19 17:33:11 +0000663 return false;
664 } else {
Evan Chengf942c132010-08-19 23:33:02 +0000665 DEBUG(dbgs() << " *** Splitting critical edge:"
Evan Cheng4dc301a2010-08-19 17:33:11 +0000666 " BB#" << ParentBlock->getNumber()
667 << " -- BB#" << NewSucc->getNumber()
668 << " -- BB#" << SuccToSinkTo->getNumber() << '\n');
Evan Cheng4dc301a2010-08-19 17:33:11 +0000669 SuccToSinkTo = NewSucc;
670 ++NumSplit;
Evan Cheng7af6dc42010-09-20 19:12:55 +0000671 BreakPHIEdge = false;
Evan Cheng4dc301a2010-08-19 17:33:11 +0000672 }
673 }
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000674 }
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000675
Evan Cheng7af6dc42010-09-20 19:12:55 +0000676 if (BreakPHIEdge) {
677 // BreakPHIEdge is true if all the uses are in the successor MBB being
678 // sunken into and they are all PHI nodes. In this case, machine-sink must
679 // break the critical edge first.
Evan Cheng23997862010-09-18 06:42:17 +0000680 MachineBasicBlock *NewSucc = SplitCriticalEdge(MI, ParentBlock,
Evan Cheng7af6dc42010-09-20 19:12:55 +0000681 SuccToSinkTo, BreakPHIEdge);
Evan Cheng23997862010-09-18 06:42:17 +0000682 if (!NewSucc) {
683 DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
684 "break critical edge\n");
685 return false;
686 }
687
688 DEBUG(dbgs() << " *** Splitting critical edge:"
689 " BB#" << ParentBlock->getNumber()
690 << " -- BB#" << NewSucc->getNumber()
691 << " -- BB#" << SuccToSinkTo->getNumber() << '\n');
692 SuccToSinkTo = NewSucc;
693 ++NumSplit;
694 }
695
Bill Wendling05c68372010-06-02 23:04:26 +0000696 // Determine where to insert into. Skip phi nodes.
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000697 MachineBasicBlock::iterator InsertPos = SuccToSinkTo->begin();
Evan Cheng23997862010-09-18 06:42:17 +0000698 while (InsertPos != SuccToSinkTo->end() && InsertPos->isPHI())
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000699 ++InsertPos;
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000700
Devang Patel541a81c2011-09-07 00:07:58 +0000701 // collect matching debug values.
702 SmallVector<MachineInstr *, 2> DbgValuesToSink;
703 collectDebugValues(MI, DbgValuesToSink);
704
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000705 // Move the instruction.
706 SuccToSinkTo->splice(InsertPos, ParentBlock, MI,
707 ++MachineBasicBlock::iterator(MI));
Dan Gohmane6cd7572010-05-13 20:34:42 +0000708
Devang Patel541a81c2011-09-07 00:07:58 +0000709 // Move debug values.
Craig Topperf22fd3f2013-07-03 05:11:49 +0000710 for (SmallVectorImpl<MachineInstr *>::iterator DBI = DbgValuesToSink.begin(),
Devang Patel541a81c2011-09-07 00:07:58 +0000711 DBE = DbgValuesToSink.end(); DBI != DBE; ++DBI) {
712 MachineInstr *DbgMI = *DBI;
713 SuccToSinkTo->splice(InsertPos, ParentBlock, DbgMI,
714 ++MachineBasicBlock::iterator(DbgMI));
715 }
716
Bill Wendling05c68372010-06-02 23:04:26 +0000717 // Conservatively, clear any kill flags, since it's possible that they are no
718 // longer correct.
Dan Gohmane6cd7572010-05-13 20:34:42 +0000719 MI->clearKillInfo();
720
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000721 return true;
722}