blob: b1f3875880b6815a09c720c6f9299fe4c434591f [file] [log] [blame]
Chris Lattnerf3edc092008-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 Wendling7ee730e2010-06-02 23:04:26 +000010// This pass moves instructions into successor blocks when possible, so that
Dan Gohman5d79a2c2009-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 Lattnerf3edc092008-01-04 07:36:53 +000016//
17//===----------------------------------------------------------------------===//
18
Chris Lattnerf3edc092008-01-04 07:36:53 +000019#include "llvm/CodeGen/Passes.h"
Quentin Colombet5cded892014-08-11 23:52:01 +000020#include "llvm/ADT/SetVector.h"
Evan Chenge53ab6d2010-09-17 22:28:18 +000021#include "llvm/ADT/SmallSet.h"
Matthias Braun352b89c2015-05-16 03:11:07 +000022#include "llvm/ADT/SparseBitVector.h"
Chris Lattnerf3edc092008-01-04 07:36:53 +000023#include "llvm/ADT/Statistic.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000024#include "llvm/Analysis/AliasAnalysis.h"
Bruno Cardoso Lopesd04f7592014-09-25 23:14:26 +000025#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000026#include "llvm/CodeGen/MachineDominators.h"
27#include "llvm/CodeGen/MachineLoopInfo.h"
Jingyue Wu29542802014-10-15 03:27:43 +000028#include "llvm/CodeGen/MachinePostDominators.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000029#include "llvm/CodeGen/MachineRegisterInfo.h"
Sanjoy Das16901a32016-01-20 00:06:14 +000030#include "llvm/IR/LLVMContext.h"
Evan Chengae9939c2010-08-19 17:33:11 +000031#include "llvm/Support/CommandLine.h"
Chris Lattnerf3edc092008-01-04 07:36:53 +000032#include "llvm/Support/Debug.h"
Bill Wendling63aa0002009-08-22 20:26:23 +000033#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000034#include "llvm/Target/TargetInstrInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000035#include "llvm/Target/TargetRegisterInfo.h"
Eric Christopherd9134482014-08-04 21:25:23 +000036#include "llvm/Target/TargetSubtargetInfo.h"
Chris Lattnerf3edc092008-01-04 07:36:53 +000037using namespace llvm;
38
Chandler Carruth1b9dde02014-04-22 02:02:50 +000039#define DEBUG_TYPE "machine-sink"
40
Andrew Trick9e761992012-02-08 21:22:43 +000041static cl::opt<bool>
Evan Chengae9939c2010-08-19 17:33:11 +000042SplitEdges("machine-sink-split",
43 cl::desc("Split critical edges during machine sinking"),
Evan Chengf3e9a482010-09-20 22:52:00 +000044 cl::init(true), cl::Hidden);
Evan Chengae9939c2010-08-19 17:33:11 +000045
Bruno Cardoso Lopesd04f7592014-09-25 23:14:26 +000046static cl::opt<bool>
47UseBlockFreqInfo("machine-sink-bfi",
48 cl::desc("Use block frequency info to find successors to sink"),
49 cl::init(true), cl::Hidden);
50
51
Evan Chenge53ab6d2010-09-17 22:28:18 +000052STATISTIC(NumSunk, "Number of machine instructions sunk");
53STATISTIC(NumSplit, "Number of critical edges split");
54STATISTIC(NumCoalesces, "Number of copies coalesced");
Chris Lattnerf3edc092008-01-04 07:36:53 +000055
56namespace {
Nick Lewycky02d5f772009-10-25 06:33:48 +000057 class MachineSinking : public MachineFunctionPass {
Chris Lattnerf3edc092008-01-04 07:36:53 +000058 const TargetInstrInfo *TII;
Dan Gohmana3176872009-09-25 22:53:29 +000059 const TargetRegisterInfo *TRI;
Jingyue Wu29542802014-10-15 03:27:43 +000060 MachineRegisterInfo *MRI; // Machine register information
61 MachineDominatorTree *DT; // Machine dominator tree
62 MachinePostDominatorTree *PDT; // Machine post dominator tree
Jakob Stoklund Olesencdc3df42010-04-15 23:41:02 +000063 MachineLoopInfo *LI;
Bruno Cardoso Lopesd04f7592014-09-25 23:14:26 +000064 const MachineBlockFrequencyInfo *MBFI;
Dan Gohman87b02d52009-10-09 23:27:56 +000065 AliasAnalysis *AA;
Chris Lattnerf3edc092008-01-04 07:36:53 +000066
Evan Chenge53ab6d2010-09-17 22:28:18 +000067 // Remember which edges have been considered for breaking.
68 SmallSet<std::pair<MachineBasicBlock*,MachineBasicBlock*>, 8>
69 CEBCandidates;
Quentin Colombet5cded892014-08-11 23:52:01 +000070 // Remember which edges we are about to split.
71 // This is different from CEBCandidates since those edges
72 // will be split.
73 SetVector<std::pair<MachineBasicBlock*,MachineBasicBlock*> > ToSplit;
Evan Chenge53ab6d2010-09-17 22:28:18 +000074
Matthias Braun352b89c2015-05-16 03:11:07 +000075 SparseBitVector<> RegsToClearKillFlags;
76
Arnaud A. de Grandmaisonc8a694f2015-06-16 08:57:21 +000077 typedef std::map<MachineBasicBlock *, SmallVector<MachineBasicBlock *, 4>>
78 AllSuccsCache;
Arnaud A. de Grandmaisond8673ed2015-06-15 09:09:06 +000079
Chris Lattnerf3edc092008-01-04 07:36:53 +000080 public:
81 static char ID; // Pass identification
Owen Anderson6c18d1a2010-10-19 17:21:58 +000082 MachineSinking() : MachineFunctionPass(ID) {
83 initializeMachineSinkingPass(*PassRegistry::getPassRegistry());
84 }
Jim Grosbach01edd682010-06-03 23:49:57 +000085
Craig Topper4584cd52014-03-07 09:26:03 +000086 bool runOnMachineFunction(MachineFunction &MF) override;
Jim Grosbach01edd682010-06-03 23:49:57 +000087
Craig Topper4584cd52014-03-07 09:26:03 +000088 void getAnalysisUsage(AnalysisUsage &AU) const override {
Dan Gohman04023152009-07-31 23:37:33 +000089 AU.setPreservesCFG();
Chris Lattnerf3edc092008-01-04 07:36:53 +000090 MachineFunctionPass::getAnalysisUsage(AU);
Chandler Carruth7b560d42015-09-09 17:55:00 +000091 AU.addRequired<AAResultsWrapperPass>();
Chris Lattnerf3edc092008-01-04 07:36:53 +000092 AU.addRequired<MachineDominatorTree>();
Jingyue Wu29542802014-10-15 03:27:43 +000093 AU.addRequired<MachinePostDominatorTree>();
Jakob Stoklund Olesencdc3df42010-04-15 23:41:02 +000094 AU.addRequired<MachineLoopInfo>();
Chris Lattnerf3edc092008-01-04 07:36:53 +000095 AU.addPreserved<MachineDominatorTree>();
Jingyue Wu29542802014-10-15 03:27:43 +000096 AU.addPreserved<MachinePostDominatorTree>();
Jakob Stoklund Olesencdc3df42010-04-15 23:41:02 +000097 AU.addPreserved<MachineLoopInfo>();
Bruno Cardoso Lopesd04f7592014-09-25 23:14:26 +000098 if (UseBlockFreqInfo)
99 AU.addRequired<MachineBlockFrequencyInfo>();
Chris Lattnerf3edc092008-01-04 07:36:53 +0000100 }
Evan Chenge53ab6d2010-09-17 22:28:18 +0000101
Craig Topper4584cd52014-03-07 09:26:03 +0000102 void releaseMemory() override {
Evan Chenge53ab6d2010-09-17 22:28:18 +0000103 CEBCandidates.clear();
104 }
105
Chris Lattnerf3edc092008-01-04 07:36:53 +0000106 private:
107 bool ProcessBlock(MachineBasicBlock &MBB);
Evan Chenge53ab6d2010-09-17 22:28:18 +0000108 bool isWorthBreakingCriticalEdge(MachineInstr *MI,
109 MachineBasicBlock *From,
110 MachineBasicBlock *To);
Quentin Colombet5cded892014-08-11 23:52:01 +0000111 /// \brief Postpone the splitting of the given critical
112 /// edge (\p From, \p To).
113 ///
114 /// We do not split the edges on the fly. Indeed, this invalidates
115 /// the dominance information and thus triggers a lot of updates
116 /// of that information underneath.
117 /// Instead, we postpone all the splits after each iteration of
118 /// the main loop. That way, the information is at least valid
119 /// for the lifetime of an iteration.
120 ///
121 /// \return True if the edge is marked as toSplit, false otherwise.
Patrik Hagglundd06de4b2014-12-04 10:36:42 +0000122 /// False can be returned if, for instance, this is not profitable.
Quentin Colombet5cded892014-08-11 23:52:01 +0000123 bool PostponeSplitCriticalEdge(MachineInstr *MI,
124 MachineBasicBlock *From,
125 MachineBasicBlock *To,
126 bool BreakPHIEdge);
Arnaud A. de Grandmaisonc8a694f2015-06-16 08:57:21 +0000127 bool SinkInstruction(MachineInstr *MI, bool &SawStore,
128 AllSuccsCache &AllSuccessors);
Evan Cheng25b60682010-08-18 23:09:25 +0000129 bool AllUsesDominatedByBlock(unsigned Reg, MachineBasicBlock *MBB,
Evan Chenge53ab6d2010-09-17 22:28:18 +0000130 MachineBasicBlock *DefMBB,
Evan Cheng2031b762010-09-20 19:12:55 +0000131 bool &BreakPHIEdge, bool &LocalUse) const;
Devang Patelc2686882011-12-14 23:20:38 +0000132 MachineBasicBlock *FindSuccToSinkTo(MachineInstr *MI, MachineBasicBlock *MBB,
Arnaud A. de Grandmaisonc8a694f2015-06-16 08:57:21 +0000133 bool &BreakPHIEdge, AllSuccsCache &AllSuccessors);
Andrew Trick9e761992012-02-08 21:22:43 +0000134 bool isProfitableToSinkTo(unsigned Reg, MachineInstr *MI,
Devang Patelc2686882011-12-14 23:20:38 +0000135 MachineBasicBlock *MBB,
Arnaud A. de Grandmaisonc8a694f2015-06-16 08:57:21 +0000136 MachineBasicBlock *SuccToSinkTo,
137 AllSuccsCache &AllSuccessors);
Devang Patelb94c9a42011-12-08 21:48:01 +0000138
Evan Chenge53ab6d2010-09-17 22:28:18 +0000139 bool PerformTrivialForwardCoalescing(MachineInstr *MI,
140 MachineBasicBlock *MBB);
Arnaud A. de Grandmaisond8673ed2015-06-15 09:09:06 +0000141
142 SmallVector<MachineBasicBlock *, 4> &
Arnaud A. de Grandmaisonc8a694f2015-06-16 08:57:21 +0000143 GetAllSortedSuccessors(MachineInstr *MI, MachineBasicBlock *MBB,
144 AllSuccsCache &AllSuccessors) const;
Chris Lattnerf3edc092008-01-04 07:36:53 +0000145 };
Chris Lattnerf3edc092008-01-04 07:36:53 +0000146} // end anonymous namespace
Jim Grosbach01edd682010-06-03 23:49:57 +0000147
Dan Gohmand78c4002008-05-13 00:00:25 +0000148char MachineSinking::ID = 0;
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000149char &llvm::MachineSinkingID = MachineSinking::ID;
Owen Anderson8ac477f2010-10-12 19:48:12 +0000150INITIALIZE_PASS_BEGIN(MachineSinking, "machine-sink",
151 "Machine code sinking", false, false)
152INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
153INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
Chandler Carruth7b560d42015-09-09 17:55:00 +0000154INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000155INITIALIZE_PASS_END(MachineSinking, "machine-sink",
Owen Andersondf7a4f22010-10-07 22:25:06 +0000156 "Machine code sinking", false, false)
Chris Lattnerf3edc092008-01-04 07:36:53 +0000157
Evan Chenge53ab6d2010-09-17 22:28:18 +0000158bool MachineSinking::PerformTrivialForwardCoalescing(MachineInstr *MI,
159 MachineBasicBlock *MBB) {
160 if (!MI->isCopy())
161 return false;
162
163 unsigned SrcReg = MI->getOperand(1).getReg();
164 unsigned DstReg = MI->getOperand(0).getReg();
165 if (!TargetRegisterInfo::isVirtualRegister(SrcReg) ||
166 !TargetRegisterInfo::isVirtualRegister(DstReg) ||
167 !MRI->hasOneNonDBGUse(SrcReg))
168 return false;
169
170 const TargetRegisterClass *SRC = MRI->getRegClass(SrcReg);
171 const TargetRegisterClass *DRC = MRI->getRegClass(DstReg);
172 if (SRC != DRC)
173 return false;
174
175 MachineInstr *DefMI = MRI->getVRegDef(SrcReg);
176 if (DefMI->isCopyLike())
177 return false;
178 DEBUG(dbgs() << "Coalescing: " << *DefMI);
179 DEBUG(dbgs() << "*** to: " << *MI);
180 MRI->replaceRegWith(DstReg, SrcReg);
181 MI->eraseFromParent();
Patrik Hagglund57d315b2014-09-09 07:47:00 +0000182
183 // Conservatively, clear any kill flags, since it's possible that they are no
184 // longer correct.
185 MRI->clearKillFlags(SrcReg);
186
Evan Chenge53ab6d2010-09-17 22:28:18 +0000187 ++NumCoalesces;
188 return true;
189}
190
Chris Lattnerf3edc092008-01-04 07:36:53 +0000191/// AllUsesDominatedByBlock - Return true if all uses of the specified register
Evan Cheng25b60682010-08-18 23:09:25 +0000192/// occur in blocks dominated by the specified block. If any use is in the
193/// definition block, then return false since it is never legal to move def
194/// after uses.
Evan Chenge53ab6d2010-09-17 22:28:18 +0000195bool
196MachineSinking::AllUsesDominatedByBlock(unsigned Reg,
197 MachineBasicBlock *MBB,
198 MachineBasicBlock *DefMBB,
Evan Cheng2031b762010-09-20 19:12:55 +0000199 bool &BreakPHIEdge,
200 bool &LocalUse) const {
Dan Gohman3a4be0f2008-02-10 18:45:23 +0000201 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
202 "Only makes sense for vregs");
Evan Chengb339f3d2010-09-18 06:42:17 +0000203
Devang Patel706574a2011-12-09 01:25:04 +0000204 // Ignore debug uses because debug info doesn't affect the code.
Evan Chengb339f3d2010-09-18 06:42:17 +0000205 if (MRI->use_nodbg_empty(Reg))
206 return true;
207
Evan Cheng2031b762010-09-20 19:12:55 +0000208 // BreakPHIEdge is true if all the uses are in the successor MBB being sunken
209 // into and they are all PHI nodes. In this case, machine-sink must break
210 // the critical edge first. e.g.
211 //
Evan Chengb339f3d2010-09-18 06:42:17 +0000212 // BB#1: derived from LLVM BB %bb4.preheader
213 // Predecessors according to CFG: BB#0
214 // ...
215 // %reg16385<def> = DEC64_32r %reg16437, %EFLAGS<imp-def,dead>
216 // ...
217 // JE_4 <BB#37>, %EFLAGS<imp-use>
218 // Successors according to CFG: BB#37 BB#2
219 //
220 // BB#2: derived from LLVM BB %bb.nph
221 // Predecessors according to CFG: BB#0 BB#1
222 // %reg16386<def> = PHI %reg16434, <BB#0>, %reg16385, <BB#1>
Evan Cheng2031b762010-09-20 19:12:55 +0000223 BreakPHIEdge = true;
Owen Andersonb36376e2014-03-17 19:36:09 +0000224 for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) {
225 MachineInstr *UseInst = MO.getParent();
226 unsigned OpNo = &MO - &UseInst->getOperand(0);
Evan Chengb339f3d2010-09-18 06:42:17 +0000227 MachineBasicBlock *UseBlock = UseInst->getParent();
228 if (!(UseBlock == MBB && UseInst->isPHI() &&
Owen Andersonb36376e2014-03-17 19:36:09 +0000229 UseInst->getOperand(OpNo+1).getMBB() == DefMBB)) {
Evan Cheng2031b762010-09-20 19:12:55 +0000230 BreakPHIEdge = false;
Evan Chengb339f3d2010-09-18 06:42:17 +0000231 break;
232 }
233 }
Evan Cheng2031b762010-09-20 19:12:55 +0000234 if (BreakPHIEdge)
Evan Chengb339f3d2010-09-18 06:42:17 +0000235 return true;
236
Owen Andersonb36376e2014-03-17 19:36:09 +0000237 for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) {
Chris Lattnerf3edc092008-01-04 07:36:53 +0000238 // Determine the block of the use.
Owen Andersonb36376e2014-03-17 19:36:09 +0000239 MachineInstr *UseInst = MO.getParent();
240 unsigned OpNo = &MO - &UseInst->getOperand(0);
Chris Lattnerf3edc092008-01-04 07:36:53 +0000241 MachineBasicBlock *UseBlock = UseInst->getParent();
Evan Chengb339f3d2010-09-18 06:42:17 +0000242 if (UseInst->isPHI()) {
Chris Lattnerf3edc092008-01-04 07:36:53 +0000243 // PHI nodes use the operand in the predecessor block, not the block with
244 // the PHI.
Owen Andersonb36376e2014-03-17 19:36:09 +0000245 UseBlock = UseInst->getOperand(OpNo+1).getMBB();
Evan Cheng361b9be2010-08-19 18:33:29 +0000246 } else if (UseBlock == DefMBB) {
247 LocalUse = true;
248 return false;
Chris Lattnerf3edc092008-01-04 07:36:53 +0000249 }
Bill Wendling7ee730e2010-06-02 23:04:26 +0000250
Chris Lattnerf3edc092008-01-04 07:36:53 +0000251 // Check that it dominates.
252 if (!DT->dominates(MBB, UseBlock))
253 return false;
254 }
Bill Wendling7ee730e2010-06-02 23:04:26 +0000255
Chris Lattnerf3edc092008-01-04 07:36:53 +0000256 return true;
257}
258
Chris Lattnerf3edc092008-01-04 07:36:53 +0000259bool MachineSinking::runOnMachineFunction(MachineFunction &MF) {
Paul Robinson7c99ec52014-03-31 17:43:35 +0000260 if (skipOptnoneFunction(*MF.getFunction()))
261 return false;
262
David Greene4b7aa242010-01-05 01:26:00 +0000263 DEBUG(dbgs() << "******** Machine Sinking ********\n");
Jim Grosbach01edd682010-06-03 23:49:57 +0000264
Eric Christophereb9e87f2014-10-14 07:00:33 +0000265 TII = MF.getSubtarget().getInstrInfo();
266 TRI = MF.getSubtarget().getRegisterInfo();
Evan Chenge53ab6d2010-09-17 22:28:18 +0000267 MRI = &MF.getRegInfo();
Chris Lattnerf3edc092008-01-04 07:36:53 +0000268 DT = &getAnalysis<MachineDominatorTree>();
Jingyue Wu29542802014-10-15 03:27:43 +0000269 PDT = &getAnalysis<MachinePostDominatorTree>();
Jakob Stoklund Olesencdc3df42010-04-15 23:41:02 +0000270 LI = &getAnalysis<MachineLoopInfo>();
Bruno Cardoso Lopesd04f7592014-09-25 23:14:26 +0000271 MBFI = UseBlockFreqInfo ? &getAnalysis<MachineBlockFrequencyInfo>() : nullptr;
Chandler Carruth7b560d42015-09-09 17:55:00 +0000272 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Chris Lattnerf3edc092008-01-04 07:36:53 +0000273
274 bool EverMadeChange = false;
Jim Grosbach01edd682010-06-03 23:49:57 +0000275
Chris Lattnerf3edc092008-01-04 07:36:53 +0000276 while (1) {
277 bool MadeChange = false;
278
279 // Process all basic blocks.
Evan Chenge53ab6d2010-09-17 22:28:18 +0000280 CEBCandidates.clear();
Quentin Colombet5cded892014-08-11 23:52:01 +0000281 ToSplit.clear();
Arnaud A. de Grandmaisond8673ed2015-06-15 09:09:06 +0000282 for (auto &MBB: MF)
283 MadeChange |= ProcessBlock(MBB);
Jim Grosbach01edd682010-06-03 23:49:57 +0000284
Quentin Colombet5cded892014-08-11 23:52:01 +0000285 // If we have anything we marked as toSplit, split it now.
286 for (auto &Pair : ToSplit) {
287 auto NewSucc = Pair.first->SplitCriticalEdge(Pair.second, this);
288 if (NewSucc != nullptr) {
289 DEBUG(dbgs() << " *** Splitting critical edge:"
290 " BB#" << Pair.first->getNumber()
291 << " -- BB#" << NewSucc->getNumber()
292 << " -- BB#" << Pair.second->getNumber() << '\n');
293 MadeChange = true;
294 ++NumSplit;
295 } else
296 DEBUG(dbgs() << " *** Not legal to break critical edge\n");
297 }
Chris Lattnerf3edc092008-01-04 07:36:53 +0000298 // If this iteration over the code changed anything, keep iterating.
299 if (!MadeChange) break;
300 EverMadeChange = true;
Jim Grosbach01edd682010-06-03 23:49:57 +0000301 }
Matthias Braun352b89c2015-05-16 03:11:07 +0000302
303 // Now clear any kill flags for recorded registers.
304 for (auto I : RegsToClearKillFlags)
305 MRI->clearKillFlags(I);
306 RegsToClearKillFlags.clear();
307
Chris Lattnerf3edc092008-01-04 07:36:53 +0000308 return EverMadeChange;
309}
310
311bool MachineSinking::ProcessBlock(MachineBasicBlock &MBB) {
Chris Lattnerf3edc092008-01-04 07:36:53 +0000312 // Can't sink anything out of a block that has less than two successors.
Chris Lattner30c3de62009-04-10 16:38:36 +0000313 if (MBB.succ_size() <= 1 || MBB.empty()) return false;
314
Dan Gohman918a90a2010-04-05 19:17:22 +0000315 // Don't bother sinking code out of unreachable blocks. In addition to being
Jim Grosbach01edd682010-06-03 23:49:57 +0000316 // unprofitable, it can also lead to infinite looping, because in an
317 // unreachable loop there may be nowhere to stop.
Dan Gohman918a90a2010-04-05 19:17:22 +0000318 if (!DT->isReachableFromEntry(&MBB)) return false;
319
Chris Lattner30c3de62009-04-10 16:38:36 +0000320 bool MadeChange = false;
321
Arnaud A. de Grandmaisonc8a694f2015-06-16 08:57:21 +0000322 // Cache all successors, sorted by frequency info and loop depth.
323 AllSuccsCache AllSuccessors;
Arnaud A. de Grandmaisond8673ed2015-06-15 09:09:06 +0000324
Chris Lattner08af5a92008-01-12 00:17:41 +0000325 // Walk the basic block bottom-up. Remember if we saw a store.
Chris Lattner30c3de62009-04-10 16:38:36 +0000326 MachineBasicBlock::iterator I = MBB.end();
327 --I;
328 bool ProcessedBegin, SawStore = false;
329 do {
330 MachineInstr *MI = I; // The instruction to sink.
Jim Grosbach01edd682010-06-03 23:49:57 +0000331
Chris Lattner30c3de62009-04-10 16:38:36 +0000332 // Predecrement I (if it's not begin) so that it isn't invalidated by
333 // sinking.
334 ProcessedBegin = I == MBB.begin();
335 if (!ProcessedBegin)
336 --I;
Dale Johannesen2061c842010-03-05 00:02:59 +0000337
338 if (MI->isDebugValue())
339 continue;
340
Evan Chengfe917ef2011-04-11 18:47:20 +0000341 bool Joined = PerformTrivialForwardCoalescing(MI, &MBB);
342 if (Joined) {
343 MadeChange = true;
Evan Chenge53ab6d2010-09-17 22:28:18 +0000344 continue;
Evan Chengfe917ef2011-04-11 18:47:20 +0000345 }
Evan Chenge53ab6d2010-09-17 22:28:18 +0000346
Richard Trieu7a083812016-02-18 22:09:30 +0000347 if (SinkInstruction(MI, SawStore, AllSuccessors)) {
348 ++NumSunk;
349 MadeChange = true;
350 }
Jim Grosbach01edd682010-06-03 23:49:57 +0000351
Chris Lattner30c3de62009-04-10 16:38:36 +0000352 // If we just processed the first instruction in the block, we're done.
353 } while (!ProcessedBegin);
Jim Grosbach01edd682010-06-03 23:49:57 +0000354
Chris Lattnerf3edc092008-01-04 07:36:53 +0000355 return MadeChange;
356}
357
Evan Chenge53ab6d2010-09-17 22:28:18 +0000358bool MachineSinking::isWorthBreakingCriticalEdge(MachineInstr *MI,
359 MachineBasicBlock *From,
360 MachineBasicBlock *To) {
361 // FIXME: Need much better heuristics.
362
363 // If the pass has already considered breaking this edge (during this pass
364 // through the function), then let's go ahead and break it. This means
365 // sinking multiple "cheap" instructions into the same block.
David Blaikie70573dc2014-11-19 07:49:26 +0000366 if (!CEBCandidates.insert(std::make_pair(From, To)).second)
Evan Chenge53ab6d2010-09-17 22:28:18 +0000367 return true;
368
Jiangning Liuc3053122014-07-29 01:55:19 +0000369 if (!MI->isCopy() && !TII->isAsCheapAsAMove(MI))
Evan Chenge53ab6d2010-09-17 22:28:18 +0000370 return true;
371
372 // MI is cheap, we probably don't want to break the critical edge for it.
373 // However, if this would allow some definitions of its source operands
374 // to be sunk then it's probably worth it.
375 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
376 const MachineOperand &MO = MI->getOperand(i);
Will Dietz5cb7f4e2013-10-14 16:57:17 +0000377 if (!MO.isReg() || !MO.isUse())
Evan Chenge53ab6d2010-09-17 22:28:18 +0000378 continue;
Will Dietz5cb7f4e2013-10-14 16:57:17 +0000379 unsigned Reg = MO.getReg();
380 if (Reg == 0)
381 continue;
382
383 // We don't move live definitions of physical registers,
384 // so sinking their uses won't enable any opportunities.
385 if (TargetRegisterInfo::isPhysicalRegister(Reg))
386 continue;
387
388 // If this instruction is the only user of a virtual register,
389 // check if breaking the edge will enable sinking
390 // both this instruction and the defining instruction.
391 if (MRI->hasOneNonDBGUse(Reg)) {
392 // If the definition resides in same MBB,
393 // claim it's likely we can sink these together.
394 // If definition resides elsewhere, we aren't
395 // blocking it from being sunk so don't break the edge.
396 MachineInstr *DefMI = MRI->getVRegDef(Reg);
397 if (DefMI->getParent() == MI->getParent())
398 return true;
399 }
Evan Chenge53ab6d2010-09-17 22:28:18 +0000400 }
401
402 return false;
403}
404
Quentin Colombet5cded892014-08-11 23:52:01 +0000405bool MachineSinking::PostponeSplitCriticalEdge(MachineInstr *MI,
406 MachineBasicBlock *FromBB,
407 MachineBasicBlock *ToBB,
408 bool BreakPHIEdge) {
Evan Chenge53ab6d2010-09-17 22:28:18 +0000409 if (!isWorthBreakingCriticalEdge(MI, FromBB, ToBB))
Quentin Colombet5cded892014-08-11 23:52:01 +0000410 return false;
Evan Chenge53ab6d2010-09-17 22:28:18 +0000411
Evan Chengae9939c2010-08-19 17:33:11 +0000412 // Avoid breaking back edge. From == To means backedge for single BB loop.
Evan Chengf3e9a482010-09-20 22:52:00 +0000413 if (!SplitEdges || FromBB == ToBB)
Quentin Colombet5cded892014-08-11 23:52:01 +0000414 return false;
Evan Chengae9939c2010-08-19 17:33:11 +0000415
Evan Chenge53ab6d2010-09-17 22:28:18 +0000416 // Check for backedges of more "complex" loops.
417 if (LI->getLoopFor(FromBB) == LI->getLoopFor(ToBB) &&
418 LI->isLoopHeader(ToBB))
Quentin Colombet5cded892014-08-11 23:52:01 +0000419 return false;
Evan Chenge53ab6d2010-09-17 22:28:18 +0000420
421 // It's not always legal to break critical edges and sink the computation
422 // to the edge.
423 //
424 // BB#1:
425 // v1024
426 // Beq BB#3
427 // <fallthrough>
428 // BB#2:
429 // ... no uses of v1024
430 // <fallthrough>
431 // BB#3:
432 // ...
433 // = v1024
434 //
435 // If BB#1 -> BB#3 edge is broken and computation of v1024 is inserted:
436 //
437 // BB#1:
438 // ...
439 // Bne BB#2
440 // BB#4:
441 // v1024 =
442 // B BB#3
443 // BB#2:
444 // ... no uses of v1024
445 // <fallthrough>
446 // BB#3:
447 // ...
448 // = v1024
449 //
450 // This is incorrect since v1024 is not computed along the BB#1->BB#2->BB#3
451 // flow. We need to ensure the new basic block where the computation is
452 // sunk to dominates all the uses.
453 // It's only legal to break critical edge and sink the computation to the
454 // new block if all the predecessors of "To", except for "From", are
455 // not dominated by "From". Given SSA property, this means these
456 // predecessors are dominated by "To".
457 //
458 // There is no need to do this check if all the uses are PHI nodes. PHI
459 // sources are only defined on the specific predecessor edges.
Evan Cheng2031b762010-09-20 19:12:55 +0000460 if (!BreakPHIEdge) {
Evan Chengae9939c2010-08-19 17:33:11 +0000461 for (MachineBasicBlock::pred_iterator PI = ToBB->pred_begin(),
462 E = ToBB->pred_end(); PI != E; ++PI) {
463 if (*PI == FromBB)
464 continue;
465 if (!DT->dominates(ToBB, *PI))
Quentin Colombet5cded892014-08-11 23:52:01 +0000466 return false;
Evan Chengae9939c2010-08-19 17:33:11 +0000467 }
Evan Chengae9939c2010-08-19 17:33:11 +0000468 }
469
Quentin Colombet5cded892014-08-11 23:52:01 +0000470 ToSplit.insert(std::make_pair(FromBB, ToBB));
471
472 return true;
Evan Chengae9939c2010-08-19 17:33:11 +0000473}
474
Evan Chengd4b31a72010-09-23 06:53:00 +0000475static bool AvoidsSinking(MachineInstr *MI, MachineRegisterInfo *MRI) {
476 return MI->isInsertSubreg() || MI->isSubregToReg() || MI->isRegSequence();
477}
478
Andrew Trick9e761992012-02-08 21:22:43 +0000479/// collectDebgValues - Scan instructions following MI and collect any
Devang Patel9de7a7d2011-09-07 00:07:58 +0000480/// matching DBG_VALUEs.
Andrew Trick9e761992012-02-08 21:22:43 +0000481static void collectDebugValues(MachineInstr *MI,
Craig Topperb94011f2013-07-14 04:42:23 +0000482 SmallVectorImpl<MachineInstr *> &DbgValues) {
Devang Patel9de7a7d2011-09-07 00:07:58 +0000483 DbgValues.clear();
484 if (!MI->getOperand(0).isReg())
485 return;
486
487 MachineBasicBlock::iterator DI = MI; ++DI;
488 for (MachineBasicBlock::iterator DE = MI->getParent()->end();
489 DI != DE; ++DI) {
490 if (!DI->isDebugValue())
491 return;
492 if (DI->getOperand(0).isReg() &&
493 DI->getOperand(0).getReg() == MI->getOperand(0).getReg())
494 DbgValues.push_back(DI);
495 }
496}
497
Devang Patelc2686882011-12-14 23:20:38 +0000498/// isProfitableToSinkTo - Return true if it is profitable to sink MI.
Andrew Trick9e761992012-02-08 21:22:43 +0000499bool MachineSinking::isProfitableToSinkTo(unsigned Reg, MachineInstr *MI,
Devang Patelc2686882011-12-14 23:20:38 +0000500 MachineBasicBlock *MBB,
Arnaud A. de Grandmaisonc8a694f2015-06-16 08:57:21 +0000501 MachineBasicBlock *SuccToSinkTo,
502 AllSuccsCache &AllSuccessors) {
Devang Patelc2686882011-12-14 23:20:38 +0000503 assert (MI && "Invalid MachineInstr!");
504 assert (SuccToSinkTo && "Invalid SinkTo Candidate BB");
505
506 if (MBB == SuccToSinkTo)
507 return false;
508
509 // It is profitable if SuccToSinkTo does not post dominate current block.
Jingyue Wu29542802014-10-15 03:27:43 +0000510 if (!PDT->dominates(SuccToSinkTo, MBB))
511 return true;
512
513 // It is profitable to sink an instruction from a deeper loop to a shallower
514 // loop, even if the latter post-dominates the former (PR21115).
515 if (LI->getLoopDepth(MBB) > LI->getLoopDepth(SuccToSinkTo))
516 return true;
Devang Patelc2686882011-12-14 23:20:38 +0000517
518 // Check if only use in post dominated block is PHI instruction.
519 bool NonPHIUse = false;
Owen Andersonb36376e2014-03-17 19:36:09 +0000520 for (MachineInstr &UseInst : MRI->use_nodbg_instructions(Reg)) {
521 MachineBasicBlock *UseBlock = UseInst.getParent();
522 if (UseBlock == SuccToSinkTo && !UseInst.isPHI())
Devang Patelc2686882011-12-14 23:20:38 +0000523 NonPHIUse = true;
524 }
525 if (!NonPHIUse)
526 return true;
527
528 // If SuccToSinkTo post dominates then also it may be profitable if MI
529 // can further profitably sinked into another block in next round.
530 bool BreakPHIEdge = false;
Patrik Hagglundd06de4b2014-12-04 10:36:42 +0000531 // FIXME - If finding successor is compile time expensive then cache results.
Arnaud A. de Grandmaisonc8a694f2015-06-16 08:57:21 +0000532 if (MachineBasicBlock *MBB2 =
533 FindSuccToSinkTo(MI, SuccToSinkTo, BreakPHIEdge, AllSuccessors))
534 return isProfitableToSinkTo(Reg, MI, SuccToSinkTo, MBB2, AllSuccessors);
Devang Patelc2686882011-12-14 23:20:38 +0000535
536 // If SuccToSinkTo is final destination and it is a post dominator of current
537 // block then it is not profitable to sink MI into SuccToSinkTo block.
538 return false;
539}
540
Arnaud A. de Grandmaisond8673ed2015-06-15 09:09:06 +0000541/// Get the sorted sequence of successors for this MachineBasicBlock, possibly
542/// computing it if it was not already cached.
543SmallVector<MachineBasicBlock *, 4> &
Arnaud A. de Grandmaisonc8a694f2015-06-16 08:57:21 +0000544MachineSinking::GetAllSortedSuccessors(MachineInstr *MI, MachineBasicBlock *MBB,
545 AllSuccsCache &AllSuccessors) const {
Arnaud A. de Grandmaisond8673ed2015-06-15 09:09:06 +0000546
547 // Do we have the sorted successors in cache ?
548 auto Succs = AllSuccessors.find(MBB);
549 if (Succs != AllSuccessors.end())
550 return Succs->second;
551
552 SmallVector<MachineBasicBlock *, 4> AllSuccs(MBB->succ_begin(),
553 MBB->succ_end());
554
555 // Handle cases where sinking can happen but where the sink point isn't a
556 // successor. For example:
557 //
558 // x = computation
559 // if () {} else {}
560 // use x
561 //
562 const std::vector<MachineDomTreeNode *> &Children =
563 DT->getNode(MBB)->getChildren();
564 for (const auto &DTChild : Children)
565 // DomTree children of MBB that have MBB as immediate dominator are added.
566 if (DTChild->getIDom()->getBlock() == MI->getParent() &&
567 // Skip MBBs already added to the AllSuccs vector above.
568 !MBB->isSuccessor(DTChild->getBlock()))
569 AllSuccs.push_back(DTChild->getBlock());
570
571 // Sort Successors according to their loop depth or block frequency info.
572 std::stable_sort(
573 AllSuccs.begin(), AllSuccs.end(),
574 [this](const MachineBasicBlock *L, const MachineBasicBlock *R) {
575 uint64_t LHSFreq = MBFI ? MBFI->getBlockFreq(L).getFrequency() : 0;
576 uint64_t RHSFreq = MBFI ? MBFI->getBlockFreq(R).getFrequency() : 0;
577 bool HasBlockFreq = LHSFreq != 0 && RHSFreq != 0;
578 return HasBlockFreq ? LHSFreq < RHSFreq
579 : LI->getLoopDepth(L) < LI->getLoopDepth(R);
580 });
581
582 auto it = AllSuccessors.insert(std::make_pair(MBB, AllSuccs));
583
584 return it.first->second;
585}
586
Devang Patelb94c9a42011-12-08 21:48:01 +0000587/// FindSuccToSinkTo - Find a successor to sink this instruction to.
588MachineBasicBlock *MachineSinking::FindSuccToSinkTo(MachineInstr *MI,
Devang Patelc2686882011-12-14 23:20:38 +0000589 MachineBasicBlock *MBB,
Arnaud A. de Grandmaisonc8a694f2015-06-16 08:57:21 +0000590 bool &BreakPHIEdge,
591 AllSuccsCache &AllSuccessors) {
Devang Patelc2686882011-12-14 23:20:38 +0000592
593 assert (MI && "Invalid MachineInstr!");
594 assert (MBB && "Invalid MachineBasicBlock!");
Jim Grosbach01edd682010-06-03 23:49:57 +0000595
Chris Lattnerf3edc092008-01-04 07:36:53 +0000596 // Loop over all the operands of the specified instruction. If there is
597 // anything we can't handle, bail out.
Jim Grosbach01edd682010-06-03 23:49:57 +0000598
Chris Lattnerf3edc092008-01-04 07:36:53 +0000599 // SuccToSinkTo - This is the successor to sink this instruction to, once we
600 // decide.
Craig Topperc0196b12014-04-14 00:51:57 +0000601 MachineBasicBlock *SuccToSinkTo = nullptr;
Chris Lattnerf3edc092008-01-04 07:36:53 +0000602 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
603 const MachineOperand &MO = MI->getOperand(i);
Dan Gohman0d1e9a82008-10-03 15:45:36 +0000604 if (!MO.isReg()) continue; // Ignore non-register operands.
Jim Grosbach01edd682010-06-03 23:49:57 +0000605
Chris Lattnerf3edc092008-01-04 07:36:53 +0000606 unsigned Reg = MO.getReg();
607 if (Reg == 0) continue;
Jim Grosbach01edd682010-06-03 23:49:57 +0000608
Dan Gohman3a4be0f2008-02-10 18:45:23 +0000609 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
Dan Gohmana3176872009-09-25 22:53:29 +0000610 if (MO.isUse()) {
611 // If the physreg has no defs anywhere, it's just an ambient register
Dan Gohman2f5bdcb2009-09-26 02:34:00 +0000612 // and we can freely move its uses. Alternatively, if it's allocatable,
613 // it could get allocated to something with a def during allocation.
Jakob Stoklund Olesen86ae07f2012-01-16 22:34:08 +0000614 if (!MRI->isConstantPhysReg(Reg, *MBB->getParent()))
Craig Topperc0196b12014-04-14 00:51:57 +0000615 return nullptr;
Bill Wendlinge41e40f2010-06-25 20:48:10 +0000616 } else if (!MO.isDead()) {
617 // A def that isn't dead. We can't move it.
Craig Topperc0196b12014-04-14 00:51:57 +0000618 return nullptr;
Dan Gohmana3176872009-09-25 22:53:29 +0000619 }
Chris Lattnerf3edc092008-01-04 07:36:53 +0000620 } else {
621 // Virtual register uses are always safe to sink.
622 if (MO.isUse()) continue;
Evan Cheng47a65a12009-02-07 01:21:47 +0000623
624 // If it's not safe to move defs of the register class, then abort.
Evan Chenge53ab6d2010-09-17 22:28:18 +0000625 if (!TII->isSafeToMoveRegClassDefs(MRI->getRegClass(Reg)))
Craig Topperc0196b12014-04-14 00:51:57 +0000626 return nullptr;
Jim Grosbach01edd682010-06-03 23:49:57 +0000627
Chris Lattnerf3edc092008-01-04 07:36:53 +0000628 // Virtual register defs can only be sunk if all their uses are in blocks
629 // dominated by one of the successors.
630 if (SuccToSinkTo) {
631 // If a previous operand picked a block to sink to, then this operand
632 // must be sinkable to the same block.
Evan Cheng361b9be2010-08-19 18:33:29 +0000633 bool LocalUse = false;
Devang Patelc2686882011-12-14 23:20:38 +0000634 if (!AllUsesDominatedByBlock(Reg, SuccToSinkTo, MBB,
Evan Cheng2031b762010-09-20 19:12:55 +0000635 BreakPHIEdge, LocalUse))
Craig Topperc0196b12014-04-14 00:51:57 +0000636 return nullptr;
Bill Wendling7ee730e2010-06-02 23:04:26 +0000637
Chris Lattnerf3edc092008-01-04 07:36:53 +0000638 continue;
639 }
Jim Grosbach01edd682010-06-03 23:49:57 +0000640
Chris Lattnerf3edc092008-01-04 07:36:53 +0000641 // Otherwise, we should look at all the successors and decide which one
Bruno Cardoso Lopesd04f7592014-09-25 23:14:26 +0000642 // we should sink to. If we have reliable block frequency information
643 // (frequency != 0) available, give successors with smaller frequencies
644 // higher priority, otherwise prioritize smaller loop depths.
Arnaud A. de Grandmaisonc8a694f2015-06-16 08:57:21 +0000645 for (MachineBasicBlock *SuccBlock :
646 GetAllSortedSuccessors(MI, MBB, AllSuccessors)) {
Evan Cheng361b9be2010-08-19 18:33:29 +0000647 bool LocalUse = false;
Devang Patelc2686882011-12-14 23:20:38 +0000648 if (AllUsesDominatedByBlock(Reg, SuccBlock, MBB,
Evan Cheng2031b762010-09-20 19:12:55 +0000649 BreakPHIEdge, LocalUse)) {
Devang Patel1a3c1692011-12-08 21:33:23 +0000650 SuccToSinkTo = SuccBlock;
Chris Lattnerf3edc092008-01-04 07:36:53 +0000651 break;
652 }
Evan Cheng25b60682010-08-18 23:09:25 +0000653 if (LocalUse)
654 // Def is used locally, it's never safe to move this def.
Craig Topperc0196b12014-04-14 00:51:57 +0000655 return nullptr;
Chris Lattnerf3edc092008-01-04 07:36:53 +0000656 }
Jim Grosbach01edd682010-06-03 23:49:57 +0000657
Chris Lattnerf3edc092008-01-04 07:36:53 +0000658 // If we couldn't find a block to sink to, ignore this instruction.
Craig Topperc0196b12014-04-14 00:51:57 +0000659 if (!SuccToSinkTo)
660 return nullptr;
Arnaud A. de Grandmaisonc8a694f2015-06-16 08:57:21 +0000661 if (!isProfitableToSinkTo(Reg, MI, MBB, SuccToSinkTo, AllSuccessors))
Craig Topperc0196b12014-04-14 00:51:57 +0000662 return nullptr;
Chris Lattnerf3edc092008-01-04 07:36:53 +0000663 }
664 }
Devang Patel202cf2f2011-12-08 23:52:00 +0000665
666 // It is not possible to sink an instruction into its own block. This can
667 // happen with loops.
Devang Patelc2686882011-12-14 23:20:38 +0000668 if (MBB == SuccToSinkTo)
Craig Topperc0196b12014-04-14 00:51:57 +0000669 return nullptr;
Devang Patel202cf2f2011-12-08 23:52:00 +0000670
671 // It's not safe to sink instructions to EH landing pad. Control flow into
672 // landing pad is implicitly defined.
Reid Kleckner0e288232015-08-27 23:27:47 +0000673 if (SuccToSinkTo && SuccToSinkTo->isEHPad())
Craig Topperc0196b12014-04-14 00:51:57 +0000674 return nullptr;
Devang Patel202cf2f2011-12-08 23:52:00 +0000675
Devang Patelb94c9a42011-12-08 21:48:01 +0000676 return SuccToSinkTo;
677}
678
Sanjoy Das16901a32016-01-20 00:06:14 +0000679/// \brief Return true if MI is likely to be usable as a memory operation by the
680/// implicit null check optimization.
681///
682/// This is a "best effort" heuristic, and should not be relied upon for
683/// correctness. This returning true does not guarantee that the implicit null
684/// check optimization is legal over MI, and this returning false does not
685/// guarantee MI cannot possibly be used to do a null check.
686static bool SinkingPreventsImplicitNullCheck(MachineInstr *MI,
687 const TargetInstrInfo *TII,
688 const TargetRegisterInfo *TRI) {
689 typedef TargetInstrInfo::MachineBranchPredicate MachineBranchPredicate;
690
691 auto *MBB = MI->getParent();
692 if (MBB->pred_size() != 1)
693 return false;
694
695 auto *PredMBB = *MBB->pred_begin();
696 auto *PredBB = PredMBB->getBasicBlock();
697
698 // Frontends that don't use implicit null checks have no reason to emit
699 // branches with make.implicit metadata, and this function should always
700 // return false for them.
701 if (!PredBB ||
702 !PredBB->getTerminator()->getMetadata(LLVMContext::MD_make_implicit))
703 return false;
704
705 unsigned BaseReg, Offset;
706 if (!TII->getMemOpBaseRegImmOfs(MI, BaseReg, Offset, TRI))
707 return false;
708
709 if (!(MI->mayLoad() && !MI->isPredicable()))
710 return false;
711
712 MachineBranchPredicate MBP;
713 if (TII->AnalyzeBranchPredicate(*PredMBB, MBP, false))
714 return false;
715
716 return MBP.LHS.isReg() && MBP.RHS.isImm() && MBP.RHS.getImm() == 0 &&
717 (MBP.Predicate == MachineBranchPredicate::PRED_NE ||
718 MBP.Predicate == MachineBranchPredicate::PRED_EQ) &&
719 MBP.LHS.getReg() == BaseReg;
720}
721
Devang Patelb94c9a42011-12-08 21:48:01 +0000722/// SinkInstruction - Determine whether it is safe to sink the specified machine
723/// instruction out of its current block into a successor.
Arnaud A. de Grandmaisonc8a694f2015-06-16 08:57:21 +0000724bool MachineSinking::SinkInstruction(MachineInstr *MI, bool &SawStore,
725 AllSuccsCache &AllSuccessors) {
Devang Patelb94c9a42011-12-08 21:48:01 +0000726 // Don't sink insert_subreg, subreg_to_reg, reg_sequence. These are meant to
727 // be close to the source to make it easier to coalesce.
728 if (AvoidsSinking(MI, MRI))
729 return false;
730
731 // Check if it's safe to move the instruction.
Matthias Braun07066cc2015-05-19 21:22:20 +0000732 if (!MI->isSafeToMove(AA, SawStore))
Devang Patelb94c9a42011-12-08 21:48:01 +0000733 return false;
734
Owen Andersond95b08a2015-10-09 18:06:13 +0000735 // Convergent operations may not be made control-dependent on additional
736 // values.
Owen Anderson55313d22015-06-01 17:26:30 +0000737 if (MI->isConvergent())
738 return false;
739
Sanjoy Das16901a32016-01-20 00:06:14 +0000740 // Don't break implicit null checks. This is a performance heuristic, and not
741 // required for correctness.
742 if (SinkingPreventsImplicitNullCheck(MI, TII, TRI))
743 return false;
744
Devang Patelb94c9a42011-12-08 21:48:01 +0000745 // FIXME: This should include support for sinking instructions within the
746 // block they are currently in to shorten the live ranges. We often get
747 // instructions sunk into the top of a large block, but it would be better to
748 // also sink them down before their first use in the block. This xform has to
749 // be careful not to *increase* register pressure though, e.g. sinking
750 // "x = y + z" down if it kills y and z would increase the live ranges of y
751 // and z and only shrink the live range of x.
752
753 bool BreakPHIEdge = false;
Devang Patelc2686882011-12-14 23:20:38 +0000754 MachineBasicBlock *ParentBlock = MI->getParent();
Arnaud A. de Grandmaisonc8a694f2015-06-16 08:57:21 +0000755 MachineBasicBlock *SuccToSinkTo =
756 FindSuccToSinkTo(MI, ParentBlock, BreakPHIEdge, AllSuccessors);
Jim Grosbach01edd682010-06-03 23:49:57 +0000757
Chris Lattner6ec78272008-01-05 01:39:17 +0000758 // If there are no outputs, it must have side-effects.
Craig Topperc0196b12014-04-14 00:51:57 +0000759 if (!SuccToSinkTo)
Chris Lattner6ec78272008-01-05 01:39:17 +0000760 return false;
Evan Cheng25104362009-02-15 08:36:12 +0000761
Bill Wendlingf82aea62010-06-03 07:54:20 +0000762
Daniel Dunbaref5a4382010-06-23 00:48:25 +0000763 // If the instruction to move defines a dead physical register which is live
764 // when leaving the basic block, don't move it because it could turn into a
765 // "zombie" define of that preg. E.g., EFLAGS. (<rdar://problem/8030636>)
Bill Wendlinge41e40f2010-06-25 20:48:10 +0000766 for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
767 const MachineOperand &MO = MI->getOperand(I);
768 if (!MO.isReg()) continue;
769 unsigned Reg = MO.getReg();
770 if (Reg == 0 || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
771 if (SuccToSinkTo->isLiveIn(Reg))
Bill Wendlingf82aea62010-06-03 07:54:20 +0000772 return false;
Bill Wendlinge41e40f2010-06-25 20:48:10 +0000773 }
Bill Wendlingf82aea62010-06-03 07:54:20 +0000774
Bill Wendling7ee730e2010-06-02 23:04:26 +0000775 DEBUG(dbgs() << "Sink instr " << *MI << "\tinto block " << *SuccToSinkTo);
776
Will Dietz5cb7f4e2013-10-14 16:57:17 +0000777 // If the block has multiple predecessors, this is a critical edge.
778 // Decide if we can sink along it or need to break the edge.
Chris Lattnerf3edc092008-01-04 07:36:53 +0000779 if (SuccToSinkTo->pred_size() > 1) {
Jakob Stoklund Olesen20b71e22010-04-13 19:06:14 +0000780 // We cannot sink a load across a critical edge - there may be stores in
781 // other code paths.
Evan Chengae9939c2010-08-19 17:33:11 +0000782 bool TryBreak = false;
Jakob Stoklund Olesen20b71e22010-04-13 19:06:14 +0000783 bool store = true;
Matthias Braun07066cc2015-05-19 21:22:20 +0000784 if (!MI->isSafeToMove(AA, store)) {
Evan Chenge5af9302010-08-19 23:33:02 +0000785 DEBUG(dbgs() << " *** NOTE: Won't sink load along critical edge.\n");
Evan Chengae9939c2010-08-19 17:33:11 +0000786 TryBreak = true;
Jakob Stoklund Olesen20b71e22010-04-13 19:06:14 +0000787 }
788
789 // We don't want to sink across a critical edge if we don't dominate the
790 // successor. We could be introducing calculations to new code paths.
Evan Chengae9939c2010-08-19 17:33:11 +0000791 if (!TryBreak && !DT->dominates(ParentBlock, SuccToSinkTo)) {
Evan Chenge5af9302010-08-19 23:33:02 +0000792 DEBUG(dbgs() << " *** NOTE: Critical edge found\n");
Evan Chengae9939c2010-08-19 17:33:11 +0000793 TryBreak = true;
Jakob Stoklund Olesen20b71e22010-04-13 19:06:14 +0000794 }
795
Jakob Stoklund Olesencdc3df42010-04-15 23:41:02 +0000796 // Don't sink instructions into a loop.
Evan Chengae9939c2010-08-19 17:33:11 +0000797 if (!TryBreak && LI->isLoopHeader(SuccToSinkTo)) {
Evan Chenge5af9302010-08-19 23:33:02 +0000798 DEBUG(dbgs() << " *** NOTE: Loop header found\n");
Evan Chengae9939c2010-08-19 17:33:11 +0000799 TryBreak = true;
Jakob Stoklund Olesencdc3df42010-04-15 23:41:02 +0000800 }
801
Jakob Stoklund Olesen20b71e22010-04-13 19:06:14 +0000802 // Otherwise we are OK with sinking along a critical edge.
Evan Chengae9939c2010-08-19 17:33:11 +0000803 if (!TryBreak)
804 DEBUG(dbgs() << "Sinking along critical edge.\n");
805 else {
Quentin Colombet5cded892014-08-11 23:52:01 +0000806 // Mark this edge as to be split.
807 // If the edge can actually be split, the next iteration of the main loop
808 // will sink MI in the newly created block.
809 bool Status =
810 PostponeSplitCriticalEdge(MI, ParentBlock, SuccToSinkTo, BreakPHIEdge);
811 if (!Status)
Evan Chenge53ab6d2010-09-17 22:28:18 +0000812 DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
Quentin Colombet5cded892014-08-11 23:52:01 +0000813 "break critical edge\n");
814 // The instruction will not be sunk this time.
815 return false;
Evan Chengae9939c2010-08-19 17:33:11 +0000816 }
Chris Lattnerf3edc092008-01-04 07:36:53 +0000817 }
Jim Grosbach01edd682010-06-03 23:49:57 +0000818
Evan Cheng2031b762010-09-20 19:12:55 +0000819 if (BreakPHIEdge) {
820 // BreakPHIEdge is true if all the uses are in the successor MBB being
821 // sunken into and they are all PHI nodes. In this case, machine-sink must
822 // break the critical edge first.
Quentin Colombet5cded892014-08-11 23:52:01 +0000823 bool Status = PostponeSplitCriticalEdge(MI, ParentBlock,
824 SuccToSinkTo, BreakPHIEdge);
825 if (!Status)
Evan Chengb339f3d2010-09-18 06:42:17 +0000826 DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
827 "break critical edge\n");
Quentin Colombet5cded892014-08-11 23:52:01 +0000828 // The instruction will not be sunk this time.
829 return false;
Evan Chengb339f3d2010-09-18 06:42:17 +0000830 }
831
Bill Wendling7ee730e2010-06-02 23:04:26 +0000832 // Determine where to insert into. Skip phi nodes.
Chris Lattnerf3edc092008-01-04 07:36:53 +0000833 MachineBasicBlock::iterator InsertPos = SuccToSinkTo->begin();
Evan Chengb339f3d2010-09-18 06:42:17 +0000834 while (InsertPos != SuccToSinkTo->end() && InsertPos->isPHI())
Chris Lattnerf3edc092008-01-04 07:36:53 +0000835 ++InsertPos;
Jim Grosbach01edd682010-06-03 23:49:57 +0000836
Devang Patel9de7a7d2011-09-07 00:07:58 +0000837 // collect matching debug values.
838 SmallVector<MachineInstr *, 2> DbgValuesToSink;
839 collectDebugValues(MI, DbgValuesToSink);
840
Chris Lattnerf3edc092008-01-04 07:36:53 +0000841 // Move the instruction.
842 SuccToSinkTo->splice(InsertPos, ParentBlock, MI,
843 ++MachineBasicBlock::iterator(MI));
Dan Gohmanc90f51c2010-05-13 20:34:42 +0000844
Devang Patel9de7a7d2011-09-07 00:07:58 +0000845 // Move debug values.
Craig Toppere1c1d362013-07-03 05:11:49 +0000846 for (SmallVectorImpl<MachineInstr *>::iterator DBI = DbgValuesToSink.begin(),
Devang Patel9de7a7d2011-09-07 00:07:58 +0000847 DBE = DbgValuesToSink.end(); DBI != DBE; ++DBI) {
848 MachineInstr *DbgMI = *DBI;
849 SuccToSinkTo->splice(InsertPos, ParentBlock, DbgMI,
850 ++MachineBasicBlock::iterator(DbgMI));
851 }
852
Juergen Ributzka4bea4942014-09-04 02:07:36 +0000853 // Conservatively, clear any kill flags, since it's possible that they are no
854 // longer correct.
Pete Cooper85b1c482015-05-08 17:54:32 +0000855 // Note that we have to clear the kill flags for any register this instruction
856 // uses as we may sink over another instruction which currently kills the
857 // used registers.
858 for (MachineOperand &MO : MI->operands()) {
859 if (MO.isReg() && MO.isUse())
Matthias Braun352b89c2015-05-16 03:11:07 +0000860 RegsToClearKillFlags.set(MO.getReg()); // Remember to clear kill flags.
Pete Cooper85b1c482015-05-08 17:54:32 +0000861 }
Dan Gohmanc90f51c2010-05-13 20:34:42 +0000862
Chris Lattnerf3edc092008-01-04 07:36:53 +0000863 return true;
864}