blob: 41db2c88ce5052f912c8168b07ec2579570c1698 [file] [log] [blame]
Eugene Zelenko900b6332017-08-29 22:32:07 +00001//===- MachineSink.cpp - Sinking for machine instructions -----------------===//
Chris Lattnerf3edc092008-01-04 07:36:53 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattnerf3edc092008-01-04 07:36:53 +00006//
7//===----------------------------------------------------------------------===//
8//
Bill Wendling7ee730e2010-06-02 23:04:26 +00009// This pass moves instructions into successor blocks when possible, so that
Dan Gohman5d79a2c2009-08-05 01:19:01 +000010// they aren't executed on paths where their results aren't needed.
11//
12// This pass is not intended to be a replacement or a complete alternative
13// for an LLVM-IR-level sinking pass. It is only designed to sink simple
14// constructs that are not exposed before lowering and instruction selection.
Chris Lattnerf3edc092008-01-04 07:36:53 +000015//
16//===----------------------------------------------------------------------===//
17
Quentin Colombet5cded892014-08-11 23:52:01 +000018#include "llvm/ADT/SetVector.h"
Evan Chenge53ab6d2010-09-17 22:28:18 +000019#include "llvm/ADT/SmallSet.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000020#include "llvm/ADT/SmallVector.h"
Matthias Braun352b89c2015-05-16 03:11:07 +000021#include "llvm/ADT/SparseBitVector.h"
Chris Lattnerf3edc092008-01-04 07:36:53 +000022#include "llvm/ADT/Statistic.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000023#include "llvm/Analysis/AliasAnalysis.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000024#include "llvm/CodeGen/MachineBasicBlock.h"
Bruno Cardoso Lopesd04f7592014-09-25 23:14:26 +000025#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
Dehao Chenf03f5152016-10-20 18:06:52 +000026#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000027#include "llvm/CodeGen/MachineDominators.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000028#include "llvm/CodeGen/MachineFunction.h"
29#include "llvm/CodeGen/MachineFunctionPass.h"
30#include "llvm/CodeGen/MachineInstr.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000031#include "llvm/CodeGen/MachineLoopInfo.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000032#include "llvm/CodeGen/MachineOperand.h"
Jingyue Wu29542802014-10-15 03:27:43 +000033#include "llvm/CodeGen/MachinePostDominators.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000034#include "llvm/CodeGen/MachineRegisterInfo.h"
David Blaikie3f833ed2017-11-08 01:01:31 +000035#include "llvm/CodeGen/TargetInstrInfo.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000036#include "llvm/CodeGen/TargetRegisterInfo.h"
37#include "llvm/CodeGen/TargetSubtargetInfo.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000038#include "llvm/IR/BasicBlock.h"
Sanjoy Das16901a32016-01-20 00:06:14 +000039#include "llvm/IR/LLVMContext.h"
Paul Robinson8bd9d6a2017-12-09 00:17:01 +000040#include "llvm/IR/DebugInfoMetadata.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000041#include "llvm/Pass.h"
42#include "llvm/Support/BranchProbability.h"
Evan Chengae9939c2010-08-19 17:33:11 +000043#include "llvm/Support/CommandLine.h"
Chris Lattnerf3edc092008-01-04 07:36:53 +000044#include "llvm/Support/Debug.h"
Bill Wendling63aa0002009-08-22 20:26:23 +000045#include "llvm/Support/raw_ostream.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000046#include <algorithm>
47#include <cassert>
48#include <cstdint>
49#include <map>
50#include <utility>
51#include <vector>
52
Chris Lattnerf3edc092008-01-04 07:36:53 +000053using namespace llvm;
54
Chandler Carruth1b9dde02014-04-22 02:02:50 +000055#define DEBUG_TYPE "machine-sink"
56
Andrew Trick9e761992012-02-08 21:22:43 +000057static cl::opt<bool>
Evan Chengae9939c2010-08-19 17:33:11 +000058SplitEdges("machine-sink-split",
59 cl::desc("Split critical edges during machine sinking"),
Evan Chengf3e9a482010-09-20 22:52:00 +000060 cl::init(true), cl::Hidden);
Evan Chengae9939c2010-08-19 17:33:11 +000061
Bruno Cardoso Lopesd04f7592014-09-25 23:14:26 +000062static cl::opt<bool>
63UseBlockFreqInfo("machine-sink-bfi",
64 cl::desc("Use block frequency info to find successors to sink"),
65 cl::init(true), cl::Hidden);
66
Dehao Chenf03f5152016-10-20 18:06:52 +000067static cl::opt<unsigned> SplitEdgeProbabilityThreshold(
68 "machine-sink-split-probability-threshold",
69 cl::desc(
70 "Percentage threshold for splitting single-instruction critical edge. "
71 "If the branch threshold is higher than this threshold, we allow "
72 "speculative execution of up to 1 instruction to avoid branching to "
73 "splitted critical edge"),
74 cl::init(40), cl::Hidden);
75
Evan Chenge53ab6d2010-09-17 22:28:18 +000076STATISTIC(NumSunk, "Number of machine instructions sunk");
77STATISTIC(NumSplit, "Number of critical edges split");
78STATISTIC(NumCoalesces, "Number of copies coalesced");
Jun Bum Lim2ecb7ba2018-03-22 20:06:47 +000079STATISTIC(NumPostRACopySink, "Number of copies sunk after RA");
Chris Lattnerf3edc092008-01-04 07:36:53 +000080
81namespace {
Eugene Zelenko1804a772016-08-25 00:45:04 +000082
Nick Lewycky02d5f772009-10-25 06:33:48 +000083 class MachineSinking : public MachineFunctionPass {
Chris Lattnerf3edc092008-01-04 07:36:53 +000084 const TargetInstrInfo *TII;
Dan Gohmana3176872009-09-25 22:53:29 +000085 const TargetRegisterInfo *TRI;
Jingyue Wu29542802014-10-15 03:27:43 +000086 MachineRegisterInfo *MRI; // Machine register information
87 MachineDominatorTree *DT; // Machine dominator tree
88 MachinePostDominatorTree *PDT; // Machine post dominator tree
Jakob Stoklund Olesencdc3df42010-04-15 23:41:02 +000089 MachineLoopInfo *LI;
Bruno Cardoso Lopesd04f7592014-09-25 23:14:26 +000090 const MachineBlockFrequencyInfo *MBFI;
Dehao Chenf03f5152016-10-20 18:06:52 +000091 const MachineBranchProbabilityInfo *MBPI;
Dan Gohman87b02d52009-10-09 23:27:56 +000092 AliasAnalysis *AA;
Chris Lattnerf3edc092008-01-04 07:36:53 +000093
Evan Chenge53ab6d2010-09-17 22:28:18 +000094 // Remember which edges have been considered for breaking.
Eugene Zelenko1804a772016-08-25 00:45:04 +000095 SmallSet<std::pair<MachineBasicBlock*, MachineBasicBlock*>, 8>
Evan Chenge53ab6d2010-09-17 22:28:18 +000096 CEBCandidates;
Quentin Colombet5cded892014-08-11 23:52:01 +000097 // Remember which edges we are about to split.
98 // This is different from CEBCandidates since those edges
99 // will be split.
Eugene Zelenko900b6332017-08-29 22:32:07 +0000100 SetVector<std::pair<MachineBasicBlock *, MachineBasicBlock *>> ToSplit;
Evan Chenge53ab6d2010-09-17 22:28:18 +0000101
Matthias Braun352b89c2015-05-16 03:11:07 +0000102 SparseBitVector<> RegsToClearKillFlags;
103
Eugene Zelenko900b6332017-08-29 22:32:07 +0000104 using AllSuccsCache =
105 std::map<MachineBasicBlock *, SmallVector<MachineBasicBlock *, 4>>;
Arnaud A. de Grandmaisond8673ed2015-06-15 09:09:06 +0000106
Chris Lattnerf3edc092008-01-04 07:36:53 +0000107 public:
108 static char ID; // Pass identification
Eugene Zelenko1804a772016-08-25 00:45:04 +0000109
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000110 MachineSinking() : MachineFunctionPass(ID) {
111 initializeMachineSinkingPass(*PassRegistry::getPassRegistry());
112 }
Jim Grosbach01edd682010-06-03 23:49:57 +0000113
Craig Topper4584cd52014-03-07 09:26:03 +0000114 bool runOnMachineFunction(MachineFunction &MF) override;
Jim Grosbach01edd682010-06-03 23:49:57 +0000115
Craig Topper4584cd52014-03-07 09:26:03 +0000116 void getAnalysisUsage(AnalysisUsage &AU) const override {
Dan Gohman04023152009-07-31 23:37:33 +0000117 AU.setPreservesCFG();
Chris Lattnerf3edc092008-01-04 07:36:53 +0000118 MachineFunctionPass::getAnalysisUsage(AU);
Chandler Carruth7b560d42015-09-09 17:55:00 +0000119 AU.addRequired<AAResultsWrapperPass>();
Chris Lattnerf3edc092008-01-04 07:36:53 +0000120 AU.addRequired<MachineDominatorTree>();
Jingyue Wu29542802014-10-15 03:27:43 +0000121 AU.addRequired<MachinePostDominatorTree>();
Jakob Stoklund Olesencdc3df42010-04-15 23:41:02 +0000122 AU.addRequired<MachineLoopInfo>();
Dehao Chenf03f5152016-10-20 18:06:52 +0000123 AU.addRequired<MachineBranchProbabilityInfo>();
Chris Lattnerf3edc092008-01-04 07:36:53 +0000124 AU.addPreserved<MachineDominatorTree>();
Jingyue Wu29542802014-10-15 03:27:43 +0000125 AU.addPreserved<MachinePostDominatorTree>();
Jakob Stoklund Olesencdc3df42010-04-15 23:41:02 +0000126 AU.addPreserved<MachineLoopInfo>();
Bruno Cardoso Lopesd04f7592014-09-25 23:14:26 +0000127 if (UseBlockFreqInfo)
128 AU.addRequired<MachineBlockFrequencyInfo>();
Chris Lattnerf3edc092008-01-04 07:36:53 +0000129 }
Evan Chenge53ab6d2010-09-17 22:28:18 +0000130
Craig Topper4584cd52014-03-07 09:26:03 +0000131 void releaseMemory() override {
Evan Chenge53ab6d2010-09-17 22:28:18 +0000132 CEBCandidates.clear();
133 }
134
Chris Lattnerf3edc092008-01-04 07:36:53 +0000135 private:
136 bool ProcessBlock(MachineBasicBlock &MBB);
Duncan P. N. Exon Smithcb38ffa2016-07-01 00:11:48 +0000137 bool isWorthBreakingCriticalEdge(MachineInstr &MI,
Evan Chenge53ab6d2010-09-17 22:28:18 +0000138 MachineBasicBlock *From,
139 MachineBasicBlock *To);
Eugene Zelenko900b6332017-08-29 22:32:07 +0000140
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000141 /// Postpone the splitting of the given critical
Quentin Colombet5cded892014-08-11 23:52:01 +0000142 /// edge (\p From, \p To).
143 ///
144 /// We do not split the edges on the fly. Indeed, this invalidates
145 /// the dominance information and thus triggers a lot of updates
146 /// of that information underneath.
147 /// Instead, we postpone all the splits after each iteration of
148 /// the main loop. That way, the information is at least valid
149 /// for the lifetime of an iteration.
150 ///
151 /// \return True if the edge is marked as toSplit, false otherwise.
Patrik Hagglundd06de4b2014-12-04 10:36:42 +0000152 /// False can be returned if, for instance, this is not profitable.
Duncan P. N. Exon Smithcb38ffa2016-07-01 00:11:48 +0000153 bool PostponeSplitCriticalEdge(MachineInstr &MI,
Quentin Colombet5cded892014-08-11 23:52:01 +0000154 MachineBasicBlock *From,
155 MachineBasicBlock *To,
156 bool BreakPHIEdge);
Duncan P. N. Exon Smithcb38ffa2016-07-01 00:11:48 +0000157 bool SinkInstruction(MachineInstr &MI, bool &SawStore,
Eugene Zelenko900b6332017-08-29 22:32:07 +0000158
Arnaud A. de Grandmaisonc8a694f2015-06-16 08:57:21 +0000159 AllSuccsCache &AllSuccessors);
Evan Cheng25b60682010-08-18 23:09:25 +0000160 bool AllUsesDominatedByBlock(unsigned Reg, MachineBasicBlock *MBB,
Evan Chenge53ab6d2010-09-17 22:28:18 +0000161 MachineBasicBlock *DefMBB,
Evan Cheng2031b762010-09-20 19:12:55 +0000162 bool &BreakPHIEdge, bool &LocalUse) const;
Duncan P. N. Exon Smithcb38ffa2016-07-01 00:11:48 +0000163 MachineBasicBlock *FindSuccToSinkTo(MachineInstr &MI, MachineBasicBlock *MBB,
Arnaud A. de Grandmaisonc8a694f2015-06-16 08:57:21 +0000164 bool &BreakPHIEdge, AllSuccsCache &AllSuccessors);
Duncan P. N. Exon Smithcb38ffa2016-07-01 00:11:48 +0000165 bool isProfitableToSinkTo(unsigned Reg, MachineInstr &MI,
Devang Patelc2686882011-12-14 23:20:38 +0000166 MachineBasicBlock *MBB,
Arnaud A. de Grandmaisonc8a694f2015-06-16 08:57:21 +0000167 MachineBasicBlock *SuccToSinkTo,
168 AllSuccsCache &AllSuccessors);
Devang Patelb94c9a42011-12-08 21:48:01 +0000169
Duncan P. N. Exon Smithcb38ffa2016-07-01 00:11:48 +0000170 bool PerformTrivialForwardCoalescing(MachineInstr &MI,
Evan Chenge53ab6d2010-09-17 22:28:18 +0000171 MachineBasicBlock *MBB);
Arnaud A. de Grandmaisond8673ed2015-06-15 09:09:06 +0000172
173 SmallVector<MachineBasicBlock *, 4> &
Duncan P. N. Exon Smithcb38ffa2016-07-01 00:11:48 +0000174 GetAllSortedSuccessors(MachineInstr &MI, MachineBasicBlock *MBB,
Arnaud A. de Grandmaisonc8a694f2015-06-16 08:57:21 +0000175 AllSuccsCache &AllSuccessors) const;
Chris Lattnerf3edc092008-01-04 07:36:53 +0000176 };
Eugene Zelenko1804a772016-08-25 00:45:04 +0000177
Chris Lattnerf3edc092008-01-04 07:36:53 +0000178} // end anonymous namespace
Jim Grosbach01edd682010-06-03 23:49:57 +0000179
Dan Gohmand78c4002008-05-13 00:00:25 +0000180char MachineSinking::ID = 0;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000181
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000182char &llvm::MachineSinkingID = MachineSinking::ID;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000183
Matthias Braun1527baa2017-05-25 21:26:32 +0000184INITIALIZE_PASS_BEGIN(MachineSinking, DEBUG_TYPE,
185 "Machine code sinking", false, false)
Dehao Chenf03f5152016-10-20 18:06:52 +0000186INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000187INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
188INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
Chandler Carruth7b560d42015-09-09 17:55:00 +0000189INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
Matthias Braun1527baa2017-05-25 21:26:32 +0000190INITIALIZE_PASS_END(MachineSinking, DEBUG_TYPE,
191 "Machine code sinking", false, false)
Chris Lattnerf3edc092008-01-04 07:36:53 +0000192
Duncan P. N. Exon Smithcb38ffa2016-07-01 00:11:48 +0000193bool MachineSinking::PerformTrivialForwardCoalescing(MachineInstr &MI,
Evan Chenge53ab6d2010-09-17 22:28:18 +0000194 MachineBasicBlock *MBB) {
Duncan P. N. Exon Smithcb38ffa2016-07-01 00:11:48 +0000195 if (!MI.isCopy())
Evan Chenge53ab6d2010-09-17 22:28:18 +0000196 return false;
197
Duncan P. N. Exon Smithcb38ffa2016-07-01 00:11:48 +0000198 unsigned SrcReg = MI.getOperand(1).getReg();
199 unsigned DstReg = MI.getOperand(0).getReg();
Evan Chenge53ab6d2010-09-17 22:28:18 +0000200 if (!TargetRegisterInfo::isVirtualRegister(SrcReg) ||
201 !TargetRegisterInfo::isVirtualRegister(DstReg) ||
202 !MRI->hasOneNonDBGUse(SrcReg))
203 return false;
204
205 const TargetRegisterClass *SRC = MRI->getRegClass(SrcReg);
206 const TargetRegisterClass *DRC = MRI->getRegClass(DstReg);
207 if (SRC != DRC)
208 return false;
209
210 MachineInstr *DefMI = MRI->getVRegDef(SrcReg);
211 if (DefMI->isCopyLike())
212 return false;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000213 LLVM_DEBUG(dbgs() << "Coalescing: " << *DefMI);
214 LLVM_DEBUG(dbgs() << "*** to: " << MI);
Evan Chenge53ab6d2010-09-17 22:28:18 +0000215 MRI->replaceRegWith(DstReg, SrcReg);
Duncan P. N. Exon Smithcb38ffa2016-07-01 00:11:48 +0000216 MI.eraseFromParent();
Patrik Hagglund57d315b2014-09-09 07:47:00 +0000217
218 // Conservatively, clear any kill flags, since it's possible that they are no
219 // longer correct.
220 MRI->clearKillFlags(SrcReg);
221
Evan Chenge53ab6d2010-09-17 22:28:18 +0000222 ++NumCoalesces;
223 return true;
224}
225
Chris Lattnerf3edc092008-01-04 07:36:53 +0000226/// AllUsesDominatedByBlock - Return true if all uses of the specified register
Evan Cheng25b60682010-08-18 23:09:25 +0000227/// occur in blocks dominated by the specified block. If any use is in the
228/// definition block, then return false since it is never legal to move def
229/// after uses.
Evan Chenge53ab6d2010-09-17 22:28:18 +0000230bool
231MachineSinking::AllUsesDominatedByBlock(unsigned Reg,
232 MachineBasicBlock *MBB,
233 MachineBasicBlock *DefMBB,
Evan Cheng2031b762010-09-20 19:12:55 +0000234 bool &BreakPHIEdge,
235 bool &LocalUse) const {
Dan Gohman3a4be0f2008-02-10 18:45:23 +0000236 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
237 "Only makes sense for vregs");
Evan Chengb339f3d2010-09-18 06:42:17 +0000238
Devang Patel706574a2011-12-09 01:25:04 +0000239 // Ignore debug uses because debug info doesn't affect the code.
Evan Chengb339f3d2010-09-18 06:42:17 +0000240 if (MRI->use_nodbg_empty(Reg))
241 return true;
242
Evan Cheng2031b762010-09-20 19:12:55 +0000243 // BreakPHIEdge is true if all the uses are in the successor MBB being sunken
244 // into and they are all PHI nodes. In this case, machine-sink must break
245 // the critical edge first. e.g.
246 //
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000247 // %bb.1: derived from LLVM BB %bb4.preheader
248 // Predecessors according to CFG: %bb.0
Evan Chengb339f3d2010-09-18 06:42:17 +0000249 // ...
Francis Visoiu Mistriha8a83d12017-12-07 10:40:31 +0000250 // %reg16385 = DEC64_32r %reg16437, implicit-def dead %eflags
Evan Chengb339f3d2010-09-18 06:42:17 +0000251 // ...
Francis Visoiu Mistriha8a83d12017-12-07 10:40:31 +0000252 // JE_4 <%bb.37>, implicit %eflags
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000253 // Successors according to CFG: %bb.37 %bb.2
Evan Chengb339f3d2010-09-18 06:42:17 +0000254 //
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000255 // %bb.2: derived from LLVM BB %bb.nph
256 // Predecessors according to CFG: %bb.0 %bb.1
Francis Visoiu Mistriha8a83d12017-12-07 10:40:31 +0000257 // %reg16386 = PHI %reg16434, %bb.0, %reg16385, %bb.1
Evan Cheng2031b762010-09-20 19:12:55 +0000258 BreakPHIEdge = true;
Owen Andersonb36376e2014-03-17 19:36:09 +0000259 for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) {
260 MachineInstr *UseInst = MO.getParent();
261 unsigned OpNo = &MO - &UseInst->getOperand(0);
Evan Chengb339f3d2010-09-18 06:42:17 +0000262 MachineBasicBlock *UseBlock = UseInst->getParent();
263 if (!(UseBlock == MBB && UseInst->isPHI() &&
Owen Andersonb36376e2014-03-17 19:36:09 +0000264 UseInst->getOperand(OpNo+1).getMBB() == DefMBB)) {
Evan Cheng2031b762010-09-20 19:12:55 +0000265 BreakPHIEdge = false;
Evan Chengb339f3d2010-09-18 06:42:17 +0000266 break;
267 }
268 }
Evan Cheng2031b762010-09-20 19:12:55 +0000269 if (BreakPHIEdge)
Evan Chengb339f3d2010-09-18 06:42:17 +0000270 return true;
271
Owen Andersonb36376e2014-03-17 19:36:09 +0000272 for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) {
Chris Lattnerf3edc092008-01-04 07:36:53 +0000273 // Determine the block of the use.
Owen Andersonb36376e2014-03-17 19:36:09 +0000274 MachineInstr *UseInst = MO.getParent();
275 unsigned OpNo = &MO - &UseInst->getOperand(0);
Chris Lattnerf3edc092008-01-04 07:36:53 +0000276 MachineBasicBlock *UseBlock = UseInst->getParent();
Evan Chengb339f3d2010-09-18 06:42:17 +0000277 if (UseInst->isPHI()) {
Chris Lattnerf3edc092008-01-04 07:36:53 +0000278 // PHI nodes use the operand in the predecessor block, not the block with
279 // the PHI.
Owen Andersonb36376e2014-03-17 19:36:09 +0000280 UseBlock = UseInst->getOperand(OpNo+1).getMBB();
Evan Cheng361b9be2010-08-19 18:33:29 +0000281 } else if (UseBlock == DefMBB) {
282 LocalUse = true;
283 return false;
Chris Lattnerf3edc092008-01-04 07:36:53 +0000284 }
Bill Wendling7ee730e2010-06-02 23:04:26 +0000285
Chris Lattnerf3edc092008-01-04 07:36:53 +0000286 // Check that it dominates.
287 if (!DT->dominates(MBB, UseBlock))
288 return false;
289 }
Bill Wendling7ee730e2010-06-02 23:04:26 +0000290
Chris Lattnerf3edc092008-01-04 07:36:53 +0000291 return true;
292}
293
Chris Lattnerf3edc092008-01-04 07:36:53 +0000294bool MachineSinking::runOnMachineFunction(MachineFunction &MF) {
Matthias Braunf1caa282017-12-15 22:22:58 +0000295 if (skipFunction(MF.getFunction()))
Paul Robinson7c99ec52014-03-31 17:43:35 +0000296 return false;
297
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000298 LLVM_DEBUG(dbgs() << "******** Machine Sinking ********\n");
Jim Grosbach01edd682010-06-03 23:49:57 +0000299
Eric Christophereb9e87f2014-10-14 07:00:33 +0000300 TII = MF.getSubtarget().getInstrInfo();
301 TRI = MF.getSubtarget().getRegisterInfo();
Evan Chenge53ab6d2010-09-17 22:28:18 +0000302 MRI = &MF.getRegInfo();
Chris Lattnerf3edc092008-01-04 07:36:53 +0000303 DT = &getAnalysis<MachineDominatorTree>();
Jingyue Wu29542802014-10-15 03:27:43 +0000304 PDT = &getAnalysis<MachinePostDominatorTree>();
Jakob Stoklund Olesencdc3df42010-04-15 23:41:02 +0000305 LI = &getAnalysis<MachineLoopInfo>();
Bruno Cardoso Lopesd04f7592014-09-25 23:14:26 +0000306 MBFI = UseBlockFreqInfo ? &getAnalysis<MachineBlockFrequencyInfo>() : nullptr;
Dehao Chenf03f5152016-10-20 18:06:52 +0000307 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000308 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Chris Lattnerf3edc092008-01-04 07:36:53 +0000309
310 bool EverMadeChange = false;
Jim Grosbach01edd682010-06-03 23:49:57 +0000311
Eugene Zelenko1804a772016-08-25 00:45:04 +0000312 while (true) {
Chris Lattnerf3edc092008-01-04 07:36:53 +0000313 bool MadeChange = false;
314
315 // Process all basic blocks.
Evan Chenge53ab6d2010-09-17 22:28:18 +0000316 CEBCandidates.clear();
Quentin Colombet5cded892014-08-11 23:52:01 +0000317 ToSplit.clear();
Arnaud A. de Grandmaisond8673ed2015-06-15 09:09:06 +0000318 for (auto &MBB: MF)
319 MadeChange |= ProcessBlock(MBB);
Jim Grosbach01edd682010-06-03 23:49:57 +0000320
Quentin Colombet5cded892014-08-11 23:52:01 +0000321 // If we have anything we marked as toSplit, split it now.
322 for (auto &Pair : ToSplit) {
Quentin Colombet23341a82016-04-21 21:01:13 +0000323 auto NewSucc = Pair.first->SplitCriticalEdge(Pair.second, *this);
Quentin Colombet5cded892014-08-11 23:52:01 +0000324 if (NewSucc != nullptr) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000325 LLVM_DEBUG(dbgs() << " *** Splitting critical edge: "
326 << printMBBReference(*Pair.first) << " -- "
327 << printMBBReference(*NewSucc) << " -- "
328 << printMBBReference(*Pair.second) << '\n');
Quentin Colombet5cded892014-08-11 23:52:01 +0000329 MadeChange = true;
330 ++NumSplit;
331 } else
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000332 LLVM_DEBUG(dbgs() << " *** Not legal to break critical edge\n");
Quentin Colombet5cded892014-08-11 23:52:01 +0000333 }
Chris Lattnerf3edc092008-01-04 07:36:53 +0000334 // If this iteration over the code changed anything, keep iterating.
335 if (!MadeChange) break;
336 EverMadeChange = true;
Jim Grosbach01edd682010-06-03 23:49:57 +0000337 }
Matthias Braun352b89c2015-05-16 03:11:07 +0000338
339 // Now clear any kill flags for recorded registers.
340 for (auto I : RegsToClearKillFlags)
341 MRI->clearKillFlags(I);
342 RegsToClearKillFlags.clear();
343
Chris Lattnerf3edc092008-01-04 07:36:53 +0000344 return EverMadeChange;
345}
346
347bool MachineSinking::ProcessBlock(MachineBasicBlock &MBB) {
Chris Lattnerf3edc092008-01-04 07:36:53 +0000348 // Can't sink anything out of a block that has less than two successors.
Chris Lattner30c3de62009-04-10 16:38:36 +0000349 if (MBB.succ_size() <= 1 || MBB.empty()) return false;
350
Dan Gohman918a90a2010-04-05 19:17:22 +0000351 // Don't bother sinking code out of unreachable blocks. In addition to being
Jim Grosbach01edd682010-06-03 23:49:57 +0000352 // unprofitable, it can also lead to infinite looping, because in an
353 // unreachable loop there may be nowhere to stop.
Dan Gohman918a90a2010-04-05 19:17:22 +0000354 if (!DT->isReachableFromEntry(&MBB)) return false;
355
Chris Lattner30c3de62009-04-10 16:38:36 +0000356 bool MadeChange = false;
357
Arnaud A. de Grandmaisonc8a694f2015-06-16 08:57:21 +0000358 // Cache all successors, sorted by frequency info and loop depth.
359 AllSuccsCache AllSuccessors;
Arnaud A. de Grandmaisond8673ed2015-06-15 09:09:06 +0000360
Chris Lattner08af5a92008-01-12 00:17:41 +0000361 // Walk the basic block bottom-up. Remember if we saw a store.
Chris Lattner30c3de62009-04-10 16:38:36 +0000362 MachineBasicBlock::iterator I = MBB.end();
363 --I;
364 bool ProcessedBegin, SawStore = false;
365 do {
Duncan P. N. Exon Smithcb38ffa2016-07-01 00:11:48 +0000366 MachineInstr &MI = *I; // The instruction to sink.
Jim Grosbach01edd682010-06-03 23:49:57 +0000367
Chris Lattner30c3de62009-04-10 16:38:36 +0000368 // Predecrement I (if it's not begin) so that it isn't invalidated by
369 // sinking.
370 ProcessedBegin = I == MBB.begin();
371 if (!ProcessedBegin)
372 --I;
Dale Johannesen2061c842010-03-05 00:02:59 +0000373
Shiva Chen801bf7e2018-05-09 02:42:00 +0000374 if (MI.isDebugInstr())
Dale Johannesen2061c842010-03-05 00:02:59 +0000375 continue;
376
Evan Chengfe917ef2011-04-11 18:47:20 +0000377 bool Joined = PerformTrivialForwardCoalescing(MI, &MBB);
378 if (Joined) {
379 MadeChange = true;
Evan Chenge53ab6d2010-09-17 22:28:18 +0000380 continue;
Evan Chengfe917ef2011-04-11 18:47:20 +0000381 }
Evan Chenge53ab6d2010-09-17 22:28:18 +0000382
Richard Trieu7a083812016-02-18 22:09:30 +0000383 if (SinkInstruction(MI, SawStore, AllSuccessors)) {
384 ++NumSunk;
385 MadeChange = true;
386 }
Jim Grosbach01edd682010-06-03 23:49:57 +0000387
Chris Lattner30c3de62009-04-10 16:38:36 +0000388 // If we just processed the first instruction in the block, we're done.
389 } while (!ProcessedBegin);
Jim Grosbach01edd682010-06-03 23:49:57 +0000390
Chris Lattnerf3edc092008-01-04 07:36:53 +0000391 return MadeChange;
392}
393
Duncan P. N. Exon Smithcb38ffa2016-07-01 00:11:48 +0000394bool MachineSinking::isWorthBreakingCriticalEdge(MachineInstr &MI,
Evan Chenge53ab6d2010-09-17 22:28:18 +0000395 MachineBasicBlock *From,
396 MachineBasicBlock *To) {
397 // FIXME: Need much better heuristics.
398
399 // If the pass has already considered breaking this edge (during this pass
400 // through the function), then let's go ahead and break it. This means
401 // sinking multiple "cheap" instructions into the same block.
David Blaikie70573dc2014-11-19 07:49:26 +0000402 if (!CEBCandidates.insert(std::make_pair(From, To)).second)
Evan Chenge53ab6d2010-09-17 22:28:18 +0000403 return true;
404
Duncan P. N. Exon Smithcb38ffa2016-07-01 00:11:48 +0000405 if (!MI.isCopy() && !TII->isAsCheapAsAMove(MI))
Evan Chenge53ab6d2010-09-17 22:28:18 +0000406 return true;
407
Dehao Chenf03f5152016-10-20 18:06:52 +0000408 if (From->isSuccessor(To) && MBPI->getEdgeProbability(From, To) <=
409 BranchProbability(SplitEdgeProbabilityThreshold, 100))
410 return true;
411
Evan Chenge53ab6d2010-09-17 22:28:18 +0000412 // MI is cheap, we probably don't want to break the critical edge for it.
413 // However, if this would allow some definitions of its source operands
414 // to be sunk then it's probably worth it.
Duncan P. N. Exon Smithcb38ffa2016-07-01 00:11:48 +0000415 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
416 const MachineOperand &MO = MI.getOperand(i);
Will Dietz5cb7f4e2013-10-14 16:57:17 +0000417 if (!MO.isReg() || !MO.isUse())
Evan Chenge53ab6d2010-09-17 22:28:18 +0000418 continue;
Will Dietz5cb7f4e2013-10-14 16:57:17 +0000419 unsigned Reg = MO.getReg();
420 if (Reg == 0)
421 continue;
422
423 // We don't move live definitions of physical registers,
424 // so sinking their uses won't enable any opportunities.
425 if (TargetRegisterInfo::isPhysicalRegister(Reg))
426 continue;
427
428 // If this instruction is the only user of a virtual register,
429 // check if breaking the edge will enable sinking
430 // both this instruction and the defining instruction.
431 if (MRI->hasOneNonDBGUse(Reg)) {
432 // If the definition resides in same MBB,
433 // claim it's likely we can sink these together.
434 // If definition resides elsewhere, we aren't
435 // blocking it from being sunk so don't break the edge.
436 MachineInstr *DefMI = MRI->getVRegDef(Reg);
Duncan P. N. Exon Smithcb38ffa2016-07-01 00:11:48 +0000437 if (DefMI->getParent() == MI.getParent())
Will Dietz5cb7f4e2013-10-14 16:57:17 +0000438 return true;
439 }
Evan Chenge53ab6d2010-09-17 22:28:18 +0000440 }
441
442 return false;
443}
444
Duncan P. N. Exon Smithcb38ffa2016-07-01 00:11:48 +0000445bool MachineSinking::PostponeSplitCriticalEdge(MachineInstr &MI,
Quentin Colombet5cded892014-08-11 23:52:01 +0000446 MachineBasicBlock *FromBB,
447 MachineBasicBlock *ToBB,
448 bool BreakPHIEdge) {
Evan Chenge53ab6d2010-09-17 22:28:18 +0000449 if (!isWorthBreakingCriticalEdge(MI, FromBB, ToBB))
Quentin Colombet5cded892014-08-11 23:52:01 +0000450 return false;
Evan Chenge53ab6d2010-09-17 22:28:18 +0000451
Evan Chengae9939c2010-08-19 17:33:11 +0000452 // Avoid breaking back edge. From == To means backedge for single BB loop.
Evan Chengf3e9a482010-09-20 22:52:00 +0000453 if (!SplitEdges || FromBB == ToBB)
Quentin Colombet5cded892014-08-11 23:52:01 +0000454 return false;
Evan Chengae9939c2010-08-19 17:33:11 +0000455
Evan Chenge53ab6d2010-09-17 22:28:18 +0000456 // Check for backedges of more "complex" loops.
457 if (LI->getLoopFor(FromBB) == LI->getLoopFor(ToBB) &&
458 LI->isLoopHeader(ToBB))
Quentin Colombet5cded892014-08-11 23:52:01 +0000459 return false;
Evan Chenge53ab6d2010-09-17 22:28:18 +0000460
461 // It's not always legal to break critical edges and sink the computation
462 // to the edge.
463 //
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000464 // %bb.1:
Evan Chenge53ab6d2010-09-17 22:28:18 +0000465 // v1024
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000466 // Beq %bb.3
Evan Chenge53ab6d2010-09-17 22:28:18 +0000467 // <fallthrough>
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000468 // %bb.2:
Evan Chenge53ab6d2010-09-17 22:28:18 +0000469 // ... no uses of v1024
470 // <fallthrough>
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000471 // %bb.3:
Evan Chenge53ab6d2010-09-17 22:28:18 +0000472 // ...
473 // = v1024
474 //
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000475 // If %bb.1 -> %bb.3 edge is broken and computation of v1024 is inserted:
Evan Chenge53ab6d2010-09-17 22:28:18 +0000476 //
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000477 // %bb.1:
Evan Chenge53ab6d2010-09-17 22:28:18 +0000478 // ...
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000479 // Bne %bb.2
480 // %bb.4:
Evan Chenge53ab6d2010-09-17 22:28:18 +0000481 // v1024 =
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000482 // B %bb.3
483 // %bb.2:
Evan Chenge53ab6d2010-09-17 22:28:18 +0000484 // ... no uses of v1024
485 // <fallthrough>
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000486 // %bb.3:
Evan Chenge53ab6d2010-09-17 22:28:18 +0000487 // ...
488 // = v1024
489 //
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000490 // This is incorrect since v1024 is not computed along the %bb.1->%bb.2->%bb.3
Evan Chenge53ab6d2010-09-17 22:28:18 +0000491 // flow. We need to ensure the new basic block where the computation is
492 // sunk to dominates all the uses.
493 // It's only legal to break critical edge and sink the computation to the
494 // new block if all the predecessors of "To", except for "From", are
495 // not dominated by "From". Given SSA property, this means these
496 // predecessors are dominated by "To".
497 //
498 // There is no need to do this check if all the uses are PHI nodes. PHI
499 // sources are only defined on the specific predecessor edges.
Evan Cheng2031b762010-09-20 19:12:55 +0000500 if (!BreakPHIEdge) {
Evan Chengae9939c2010-08-19 17:33:11 +0000501 for (MachineBasicBlock::pred_iterator PI = ToBB->pred_begin(),
502 E = ToBB->pred_end(); PI != E; ++PI) {
503 if (*PI == FromBB)
504 continue;
505 if (!DT->dominates(ToBB, *PI))
Quentin Colombet5cded892014-08-11 23:52:01 +0000506 return false;
Evan Chengae9939c2010-08-19 17:33:11 +0000507 }
Evan Chengae9939c2010-08-19 17:33:11 +0000508 }
509
Quentin Colombet5cded892014-08-11 23:52:01 +0000510 ToSplit.insert(std::make_pair(FromBB, ToBB));
Fangrui Songf78650a2018-07-30 19:41:25 +0000511
Quentin Colombet5cded892014-08-11 23:52:01 +0000512 return true;
Evan Chengae9939c2010-08-19 17:33:11 +0000513}
514
Devang Patelc2686882011-12-14 23:20:38 +0000515/// isProfitableToSinkTo - Return true if it is profitable to sink MI.
Duncan P. N. Exon Smithcb38ffa2016-07-01 00:11:48 +0000516bool MachineSinking::isProfitableToSinkTo(unsigned Reg, MachineInstr &MI,
Devang Patelc2686882011-12-14 23:20:38 +0000517 MachineBasicBlock *MBB,
Arnaud A. de Grandmaisonc8a694f2015-06-16 08:57:21 +0000518 MachineBasicBlock *SuccToSinkTo,
519 AllSuccsCache &AllSuccessors) {
Devang Patelc2686882011-12-14 23:20:38 +0000520 assert (SuccToSinkTo && "Invalid SinkTo Candidate BB");
521
522 if (MBB == SuccToSinkTo)
523 return false;
524
525 // It is profitable if SuccToSinkTo does not post dominate current block.
Jingyue Wu29542802014-10-15 03:27:43 +0000526 if (!PDT->dominates(SuccToSinkTo, MBB))
527 return true;
528
529 // It is profitable to sink an instruction from a deeper loop to a shallower
530 // loop, even if the latter post-dominates the former (PR21115).
531 if (LI->getLoopDepth(MBB) > LI->getLoopDepth(SuccToSinkTo))
532 return true;
Devang Patelc2686882011-12-14 23:20:38 +0000533
534 // Check if only use in post dominated block is PHI instruction.
535 bool NonPHIUse = false;
Owen Andersonb36376e2014-03-17 19:36:09 +0000536 for (MachineInstr &UseInst : MRI->use_nodbg_instructions(Reg)) {
537 MachineBasicBlock *UseBlock = UseInst.getParent();
538 if (UseBlock == SuccToSinkTo && !UseInst.isPHI())
Devang Patelc2686882011-12-14 23:20:38 +0000539 NonPHIUse = true;
540 }
541 if (!NonPHIUse)
542 return true;
543
544 // If SuccToSinkTo post dominates then also it may be profitable if MI
545 // can further profitably sinked into another block in next round.
546 bool BreakPHIEdge = false;
Patrik Hagglundd06de4b2014-12-04 10:36:42 +0000547 // FIXME - If finding successor is compile time expensive then cache results.
Arnaud A. de Grandmaisonc8a694f2015-06-16 08:57:21 +0000548 if (MachineBasicBlock *MBB2 =
549 FindSuccToSinkTo(MI, SuccToSinkTo, BreakPHIEdge, AllSuccessors))
550 return isProfitableToSinkTo(Reg, MI, SuccToSinkTo, MBB2, AllSuccessors);
Devang Patelc2686882011-12-14 23:20:38 +0000551
552 // If SuccToSinkTo is final destination and it is a post dominator of current
553 // block then it is not profitable to sink MI into SuccToSinkTo block.
554 return false;
555}
556
Arnaud A. de Grandmaisond8673ed2015-06-15 09:09:06 +0000557/// Get the sorted sequence of successors for this MachineBasicBlock, possibly
558/// computing it if it was not already cached.
559SmallVector<MachineBasicBlock *, 4> &
Duncan P. N. Exon Smithcb38ffa2016-07-01 00:11:48 +0000560MachineSinking::GetAllSortedSuccessors(MachineInstr &MI, MachineBasicBlock *MBB,
Arnaud A. de Grandmaisonc8a694f2015-06-16 08:57:21 +0000561 AllSuccsCache &AllSuccessors) const {
Arnaud A. de Grandmaisond8673ed2015-06-15 09:09:06 +0000562 // Do we have the sorted successors in cache ?
563 auto Succs = AllSuccessors.find(MBB);
564 if (Succs != AllSuccessors.end())
565 return Succs->second;
566
567 SmallVector<MachineBasicBlock *, 4> AllSuccs(MBB->succ_begin(),
568 MBB->succ_end());
569
570 // Handle cases where sinking can happen but where the sink point isn't a
571 // successor. For example:
572 //
573 // x = computation
574 // if () {} else {}
575 // use x
576 //
577 const std::vector<MachineDomTreeNode *> &Children =
578 DT->getNode(MBB)->getChildren();
579 for (const auto &DTChild : Children)
580 // DomTree children of MBB that have MBB as immediate dominator are added.
Duncan P. N. Exon Smithcb38ffa2016-07-01 00:11:48 +0000581 if (DTChild->getIDom()->getBlock() == MI.getParent() &&
Arnaud A. de Grandmaisond8673ed2015-06-15 09:09:06 +0000582 // Skip MBBs already added to the AllSuccs vector above.
583 !MBB->isSuccessor(DTChild->getBlock()))
584 AllSuccs.push_back(DTChild->getBlock());
585
586 // Sort Successors according to their loop depth or block frequency info.
Fangrui Songefd94c52019-04-23 14:51:27 +0000587 llvm::stable_sort(
588 AllSuccs, [this](const MachineBasicBlock *L, const MachineBasicBlock *R) {
Arnaud A. de Grandmaisond8673ed2015-06-15 09:09:06 +0000589 uint64_t LHSFreq = MBFI ? MBFI->getBlockFreq(L).getFrequency() : 0;
590 uint64_t RHSFreq = MBFI ? MBFI->getBlockFreq(R).getFrequency() : 0;
591 bool HasBlockFreq = LHSFreq != 0 && RHSFreq != 0;
592 return HasBlockFreq ? LHSFreq < RHSFreq
593 : LI->getLoopDepth(L) < LI->getLoopDepth(R);
594 });
595
596 auto it = AllSuccessors.insert(std::make_pair(MBB, AllSuccs));
597
598 return it.first->second;
599}
600
Devang Patelb94c9a42011-12-08 21:48:01 +0000601/// FindSuccToSinkTo - Find a successor to sink this instruction to.
Duncan P. N. Exon Smithcb38ffa2016-07-01 00:11:48 +0000602MachineBasicBlock *
603MachineSinking::FindSuccToSinkTo(MachineInstr &MI, MachineBasicBlock *MBB,
604 bool &BreakPHIEdge,
605 AllSuccsCache &AllSuccessors) {
Devang Patelc2686882011-12-14 23:20:38 +0000606 assert (MBB && "Invalid MachineBasicBlock!");
Jim Grosbach01edd682010-06-03 23:49:57 +0000607
Chris Lattnerf3edc092008-01-04 07:36:53 +0000608 // Loop over all the operands of the specified instruction. If there is
609 // anything we can't handle, bail out.
Jim Grosbach01edd682010-06-03 23:49:57 +0000610
Chris Lattnerf3edc092008-01-04 07:36:53 +0000611 // SuccToSinkTo - This is the successor to sink this instruction to, once we
612 // decide.
Craig Topperc0196b12014-04-14 00:51:57 +0000613 MachineBasicBlock *SuccToSinkTo = nullptr;
Duncan P. N. Exon Smithcb38ffa2016-07-01 00:11:48 +0000614 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
615 const MachineOperand &MO = MI.getOperand(i);
Dan Gohman0d1e9a82008-10-03 15:45:36 +0000616 if (!MO.isReg()) continue; // Ignore non-register operands.
Jim Grosbach01edd682010-06-03 23:49:57 +0000617
Chris Lattnerf3edc092008-01-04 07:36:53 +0000618 unsigned Reg = MO.getReg();
619 if (Reg == 0) continue;
Jim Grosbach01edd682010-06-03 23:49:57 +0000620
Dan Gohman3a4be0f2008-02-10 18:45:23 +0000621 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
Dan Gohmana3176872009-09-25 22:53:29 +0000622 if (MO.isUse()) {
623 // If the physreg has no defs anywhere, it's just an ambient register
Dan Gohman2f5bdcb2009-09-26 02:34:00 +0000624 // and we can freely move its uses. Alternatively, if it's allocatable,
625 // it could get allocated to something with a def during allocation.
Matthias Braunde8c1b32016-10-28 18:05:09 +0000626 if (!MRI->isConstantPhysReg(Reg))
Craig Topperc0196b12014-04-14 00:51:57 +0000627 return nullptr;
Bill Wendlinge41e40f2010-06-25 20:48:10 +0000628 } else if (!MO.isDead()) {
629 // A def that isn't dead. We can't move it.
Craig Topperc0196b12014-04-14 00:51:57 +0000630 return nullptr;
Dan Gohmana3176872009-09-25 22:53:29 +0000631 }
Chris Lattnerf3edc092008-01-04 07:36:53 +0000632 } else {
633 // Virtual register uses are always safe to sink.
634 if (MO.isUse()) continue;
Evan Cheng47a65a12009-02-07 01:21:47 +0000635
636 // If it's not safe to move defs of the register class, then abort.
Evan Chenge53ab6d2010-09-17 22:28:18 +0000637 if (!TII->isSafeToMoveRegClassDefs(MRI->getRegClass(Reg)))
Craig Topperc0196b12014-04-14 00:51:57 +0000638 return nullptr;
Jim Grosbach01edd682010-06-03 23:49:57 +0000639
Chris Lattnerf3edc092008-01-04 07:36:53 +0000640 // Virtual register defs can only be sunk if all their uses are in blocks
641 // dominated by one of the successors.
642 if (SuccToSinkTo) {
643 // If a previous operand picked a block to sink to, then this operand
644 // must be sinkable to the same block.
Evan Cheng361b9be2010-08-19 18:33:29 +0000645 bool LocalUse = false;
Devang Patelc2686882011-12-14 23:20:38 +0000646 if (!AllUsesDominatedByBlock(Reg, SuccToSinkTo, MBB,
Evan Cheng2031b762010-09-20 19:12:55 +0000647 BreakPHIEdge, LocalUse))
Craig Topperc0196b12014-04-14 00:51:57 +0000648 return nullptr;
Bill Wendling7ee730e2010-06-02 23:04:26 +0000649
Chris Lattnerf3edc092008-01-04 07:36:53 +0000650 continue;
651 }
Jim Grosbach01edd682010-06-03 23:49:57 +0000652
Chris Lattnerf3edc092008-01-04 07:36:53 +0000653 // Otherwise, we should look at all the successors and decide which one
Bruno Cardoso Lopesd04f7592014-09-25 23:14:26 +0000654 // we should sink to. If we have reliable block frequency information
655 // (frequency != 0) available, give successors with smaller frequencies
656 // higher priority, otherwise prioritize smaller loop depths.
Arnaud A. de Grandmaisonc8a694f2015-06-16 08:57:21 +0000657 for (MachineBasicBlock *SuccBlock :
658 GetAllSortedSuccessors(MI, MBB, AllSuccessors)) {
Evan Cheng361b9be2010-08-19 18:33:29 +0000659 bool LocalUse = false;
Devang Patelc2686882011-12-14 23:20:38 +0000660 if (AllUsesDominatedByBlock(Reg, SuccBlock, MBB,
Evan Cheng2031b762010-09-20 19:12:55 +0000661 BreakPHIEdge, LocalUse)) {
Devang Patel1a3c1692011-12-08 21:33:23 +0000662 SuccToSinkTo = SuccBlock;
Chris Lattnerf3edc092008-01-04 07:36:53 +0000663 break;
664 }
Evan Cheng25b60682010-08-18 23:09:25 +0000665 if (LocalUse)
666 // Def is used locally, it's never safe to move this def.
Craig Topperc0196b12014-04-14 00:51:57 +0000667 return nullptr;
Chris Lattnerf3edc092008-01-04 07:36:53 +0000668 }
Jim Grosbach01edd682010-06-03 23:49:57 +0000669
Chris Lattnerf3edc092008-01-04 07:36:53 +0000670 // If we couldn't find a block to sink to, ignore this instruction.
Craig Topperc0196b12014-04-14 00:51:57 +0000671 if (!SuccToSinkTo)
672 return nullptr;
Arnaud A. de Grandmaisonc8a694f2015-06-16 08:57:21 +0000673 if (!isProfitableToSinkTo(Reg, MI, MBB, SuccToSinkTo, AllSuccessors))
Craig Topperc0196b12014-04-14 00:51:57 +0000674 return nullptr;
Chris Lattnerf3edc092008-01-04 07:36:53 +0000675 }
676 }
Devang Patel202cf2f2011-12-08 23:52:00 +0000677
678 // It is not possible to sink an instruction into its own block. This can
679 // happen with loops.
Devang Patelc2686882011-12-14 23:20:38 +0000680 if (MBB == SuccToSinkTo)
Craig Topperc0196b12014-04-14 00:51:57 +0000681 return nullptr;
Devang Patel202cf2f2011-12-08 23:52:00 +0000682
683 // It's not safe to sink instructions to EH landing pad. Control flow into
684 // landing pad is implicitly defined.
Reid Kleckner0e288232015-08-27 23:27:47 +0000685 if (SuccToSinkTo && SuccToSinkTo->isEHPad())
Craig Topperc0196b12014-04-14 00:51:57 +0000686 return nullptr;
Devang Patel202cf2f2011-12-08 23:52:00 +0000687
Devang Patelb94c9a42011-12-08 21:48:01 +0000688 return SuccToSinkTo;
689}
690
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000691/// Return true if MI is likely to be usable as a memory operation by the
Sanjoy Das16901a32016-01-20 00:06:14 +0000692/// implicit null check optimization.
693///
694/// This is a "best effort" heuristic, and should not be relied upon for
695/// correctness. This returning true does not guarantee that the implicit null
696/// check optimization is legal over MI, and this returning false does not
697/// guarantee MI cannot possibly be used to do a null check.
Duncan P. N. Exon Smithcb38ffa2016-07-01 00:11:48 +0000698static bool SinkingPreventsImplicitNullCheck(MachineInstr &MI,
Sanjoy Das16901a32016-01-20 00:06:14 +0000699 const TargetInstrInfo *TII,
700 const TargetRegisterInfo *TRI) {
Eugene Zelenko900b6332017-08-29 22:32:07 +0000701 using MachineBranchPredicate = TargetInstrInfo::MachineBranchPredicate;
Sanjoy Das16901a32016-01-20 00:06:14 +0000702
Duncan P. N. Exon Smithcb38ffa2016-07-01 00:11:48 +0000703 auto *MBB = MI.getParent();
Sanjoy Das16901a32016-01-20 00:06:14 +0000704 if (MBB->pred_size() != 1)
705 return false;
706
707 auto *PredMBB = *MBB->pred_begin();
708 auto *PredBB = PredMBB->getBasicBlock();
709
710 // Frontends that don't use implicit null checks have no reason to emit
711 // branches with make.implicit metadata, and this function should always
712 // return false for them.
713 if (!PredBB ||
714 !PredBB->getTerminator()->getMetadata(LLVMContext::MD_make_implicit))
715 return false;
716
Bjorn Pettersson238c9d6302019-04-19 09:08:38 +0000717 const MachineOperand *BaseOp;
Chad Rosierc27a18f2016-03-09 16:00:35 +0000718 int64_t Offset;
Francis Visoiu Mistrihd7eebd62018-11-28 12:00:20 +0000719 if (!TII->getMemOperandWithOffset(MI, BaseOp, Offset, TRI))
720 return false;
721
722 if (!BaseOp->isReg())
Sanjoy Das16901a32016-01-20 00:06:14 +0000723 return false;
724
Duncan P. N. Exon Smithcb38ffa2016-07-01 00:11:48 +0000725 if (!(MI.mayLoad() && !MI.isPredicable()))
Sanjoy Das16901a32016-01-20 00:06:14 +0000726 return false;
727
728 MachineBranchPredicate MBP;
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000729 if (TII->analyzeBranchPredicate(*PredMBB, MBP, false))
Sanjoy Das16901a32016-01-20 00:06:14 +0000730 return false;
731
732 return MBP.LHS.isReg() && MBP.RHS.isImm() && MBP.RHS.getImm() == 0 &&
733 (MBP.Predicate == MachineBranchPredicate::PRED_NE ||
734 MBP.Predicate == MachineBranchPredicate::PRED_EQ) &&
Francis Visoiu Mistrihd7eebd62018-11-28 12:00:20 +0000735 MBP.LHS.getReg() == BaseOp->getReg();
Sanjoy Das16901a32016-01-20 00:06:14 +0000736}
737
Jeremy Morsed5383522018-11-02 16:52:48 +0000738/// Sink an instruction and its associated debug instructions. If the debug
739/// instructions to be sunk are already known, they can be provided in DbgVals.
Matt Davisd041f212018-06-21 17:59:52 +0000740static void performSink(MachineInstr &MI, MachineBasicBlock &SuccToSinkTo,
Jeremy Morsed5383522018-11-02 16:52:48 +0000741 MachineBasicBlock::iterator InsertPos,
742 SmallVectorImpl<MachineInstr *> *DbgVals = nullptr) {
743 // If debug values are provided use those, otherwise call collectDebugValues.
Matt Davisd041f212018-06-21 17:59:52 +0000744 SmallVector<MachineInstr *, 2> DbgValuesToSink;
Jeremy Morsed5383522018-11-02 16:52:48 +0000745 if (DbgVals)
746 DbgValuesToSink.insert(DbgValuesToSink.begin(),
747 DbgVals->begin(), DbgVals->end());
748 else
749 MI.collectDebugValues(DbgValuesToSink);
Matt Davisd041f212018-06-21 17:59:52 +0000750
751 // If we cannot find a location to use (merge with), then we erase the debug
752 // location to prevent debug-info driven tools from potentially reporting
753 // wrong location information.
754 if (!SuccToSinkTo.empty() && InsertPos != SuccToSinkTo.end())
755 MI.setDebugLoc(DILocation::getMergedLocation(MI.getDebugLoc(),
756 InsertPos->getDebugLoc()));
757 else
758 MI.setDebugLoc(DebugLoc());
759
760 // Move the instruction.
761 MachineBasicBlock *ParentBlock = MI.getParent();
762 SuccToSinkTo.splice(InsertPos, ParentBlock, MI,
763 ++MachineBasicBlock::iterator(MI));
764
765 // Move previously adjacent debug value instructions to the insert position.
766 for (SmallVectorImpl<MachineInstr *>::iterator DBI = DbgValuesToSink.begin(),
767 DBE = DbgValuesToSink.end();
768 DBI != DBE; ++DBI) {
769 MachineInstr *DbgMI = *DBI;
770 SuccToSinkTo.splice(InsertPos, ParentBlock, DbgMI,
771 ++MachineBasicBlock::iterator(DbgMI));
772 }
773}
774
Devang Patelb94c9a42011-12-08 21:48:01 +0000775/// SinkInstruction - Determine whether it is safe to sink the specified machine
776/// instruction out of its current block into a successor.
Duncan P. N. Exon Smithcb38ffa2016-07-01 00:11:48 +0000777bool MachineSinking::SinkInstruction(MachineInstr &MI, bool &SawStore,
Arnaud A. de Grandmaisonc8a694f2015-06-16 08:57:21 +0000778 AllSuccsCache &AllSuccessors) {
Fiona Glaser44a2f7a2016-03-29 22:44:57 +0000779 // Don't sink instructions that the target prefers not to sink.
Duncan P. N. Exon Smithcb38ffa2016-07-01 00:11:48 +0000780 if (!TII->shouldSink(MI))
Devang Patelb94c9a42011-12-08 21:48:01 +0000781 return false;
782
783 // Check if it's safe to move the instruction.
Duncan P. N. Exon Smithcb38ffa2016-07-01 00:11:48 +0000784 if (!MI.isSafeToMove(AA, SawStore))
Devang Patelb94c9a42011-12-08 21:48:01 +0000785 return false;
786
Owen Andersond95b08a2015-10-09 18:06:13 +0000787 // Convergent operations may not be made control-dependent on additional
788 // values.
Duncan P. N. Exon Smithcb38ffa2016-07-01 00:11:48 +0000789 if (MI.isConvergent())
Owen Anderson55313d22015-06-01 17:26:30 +0000790 return false;
791
Sanjoy Das16901a32016-01-20 00:06:14 +0000792 // Don't break implicit null checks. This is a performance heuristic, and not
793 // required for correctness.
794 if (SinkingPreventsImplicitNullCheck(MI, TII, TRI))
795 return false;
796
Devang Patelb94c9a42011-12-08 21:48:01 +0000797 // FIXME: This should include support for sinking instructions within the
798 // block they are currently in to shorten the live ranges. We often get
799 // instructions sunk into the top of a large block, but it would be better to
800 // also sink them down before their first use in the block. This xform has to
801 // be careful not to *increase* register pressure though, e.g. sinking
802 // "x = y + z" down if it kills y and z would increase the live ranges of y
803 // and z and only shrink the live range of x.
804
805 bool BreakPHIEdge = false;
Duncan P. N. Exon Smithcb38ffa2016-07-01 00:11:48 +0000806 MachineBasicBlock *ParentBlock = MI.getParent();
Arnaud A. de Grandmaisonc8a694f2015-06-16 08:57:21 +0000807 MachineBasicBlock *SuccToSinkTo =
808 FindSuccToSinkTo(MI, ParentBlock, BreakPHIEdge, AllSuccessors);
Jim Grosbach01edd682010-06-03 23:49:57 +0000809
Chris Lattner6ec78272008-01-05 01:39:17 +0000810 // If there are no outputs, it must have side-effects.
Craig Topperc0196b12014-04-14 00:51:57 +0000811 if (!SuccToSinkTo)
Chris Lattner6ec78272008-01-05 01:39:17 +0000812 return false;
Evan Cheng25104362009-02-15 08:36:12 +0000813
Daniel Dunbaref5a4382010-06-23 00:48:25 +0000814 // If the instruction to move defines a dead physical register which is live
815 // when leaving the basic block, don't move it because it could turn into a
816 // "zombie" define of that preg. E.g., EFLAGS. (<rdar://problem/8030636>)
Duncan P. N. Exon Smithcb38ffa2016-07-01 00:11:48 +0000817 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) {
818 const MachineOperand &MO = MI.getOperand(I);
Bill Wendlinge41e40f2010-06-25 20:48:10 +0000819 if (!MO.isReg()) continue;
820 unsigned Reg = MO.getReg();
821 if (Reg == 0 || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
822 if (SuccToSinkTo->isLiveIn(Reg))
Bill Wendlingf82aea62010-06-03 07:54:20 +0000823 return false;
Bill Wendlinge41e40f2010-06-25 20:48:10 +0000824 }
Bill Wendlingf82aea62010-06-03 07:54:20 +0000825
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000826 LLVM_DEBUG(dbgs() << "Sink instr " << MI << "\tinto block " << *SuccToSinkTo);
Bill Wendling7ee730e2010-06-02 23:04:26 +0000827
Will Dietz5cb7f4e2013-10-14 16:57:17 +0000828 // If the block has multiple predecessors, this is a critical edge.
829 // Decide if we can sink along it or need to break the edge.
Chris Lattnerf3edc092008-01-04 07:36:53 +0000830 if (SuccToSinkTo->pred_size() > 1) {
Jakob Stoklund Olesen20b71e22010-04-13 19:06:14 +0000831 // We cannot sink a load across a critical edge - there may be stores in
832 // other code paths.
Evan Chengae9939c2010-08-19 17:33:11 +0000833 bool TryBreak = false;
Jakob Stoklund Olesen20b71e22010-04-13 19:06:14 +0000834 bool store = true;
Duncan P. N. Exon Smithcb38ffa2016-07-01 00:11:48 +0000835 if (!MI.isSafeToMove(AA, store)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000836 LLVM_DEBUG(dbgs() << " *** NOTE: Won't sink load along critical edge.\n");
Evan Chengae9939c2010-08-19 17:33:11 +0000837 TryBreak = true;
Jakob Stoklund Olesen20b71e22010-04-13 19:06:14 +0000838 }
839
840 // We don't want to sink across a critical edge if we don't dominate the
841 // successor. We could be introducing calculations to new code paths.
Evan Chengae9939c2010-08-19 17:33:11 +0000842 if (!TryBreak && !DT->dominates(ParentBlock, SuccToSinkTo)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000843 LLVM_DEBUG(dbgs() << " *** NOTE: Critical edge found\n");
Evan Chengae9939c2010-08-19 17:33:11 +0000844 TryBreak = true;
Jakob Stoklund Olesen20b71e22010-04-13 19:06:14 +0000845 }
846
Jakob Stoklund Olesencdc3df42010-04-15 23:41:02 +0000847 // Don't sink instructions into a loop.
Evan Chengae9939c2010-08-19 17:33:11 +0000848 if (!TryBreak && LI->isLoopHeader(SuccToSinkTo)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000849 LLVM_DEBUG(dbgs() << " *** NOTE: Loop header found\n");
Evan Chengae9939c2010-08-19 17:33:11 +0000850 TryBreak = true;
Jakob Stoklund Olesencdc3df42010-04-15 23:41:02 +0000851 }
852
Jakob Stoklund Olesen20b71e22010-04-13 19:06:14 +0000853 // Otherwise we are OK with sinking along a critical edge.
Evan Chengae9939c2010-08-19 17:33:11 +0000854 if (!TryBreak)
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000855 LLVM_DEBUG(dbgs() << "Sinking along critical edge.\n");
Evan Chengae9939c2010-08-19 17:33:11 +0000856 else {
Quentin Colombet5cded892014-08-11 23:52:01 +0000857 // Mark this edge as to be split.
858 // If the edge can actually be split, the next iteration of the main loop
859 // will sink MI in the newly created block.
860 bool Status =
861 PostponeSplitCriticalEdge(MI, ParentBlock, SuccToSinkTo, BreakPHIEdge);
862 if (!Status)
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000863 LLVM_DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
864 "break critical edge\n");
Quentin Colombet5cded892014-08-11 23:52:01 +0000865 // The instruction will not be sunk this time.
866 return false;
Evan Chengae9939c2010-08-19 17:33:11 +0000867 }
Chris Lattnerf3edc092008-01-04 07:36:53 +0000868 }
Jim Grosbach01edd682010-06-03 23:49:57 +0000869
Evan Cheng2031b762010-09-20 19:12:55 +0000870 if (BreakPHIEdge) {
871 // BreakPHIEdge is true if all the uses are in the successor MBB being
872 // sunken into and they are all PHI nodes. In this case, machine-sink must
873 // break the critical edge first.
Quentin Colombet5cded892014-08-11 23:52:01 +0000874 bool Status = PostponeSplitCriticalEdge(MI, ParentBlock,
875 SuccToSinkTo, BreakPHIEdge);
876 if (!Status)
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000877 LLVM_DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
878 "break critical edge\n");
Quentin Colombet5cded892014-08-11 23:52:01 +0000879 // The instruction will not be sunk this time.
880 return false;
Evan Chengb339f3d2010-09-18 06:42:17 +0000881 }
882
Bill Wendling7ee730e2010-06-02 23:04:26 +0000883 // Determine where to insert into. Skip phi nodes.
Chris Lattnerf3edc092008-01-04 07:36:53 +0000884 MachineBasicBlock::iterator InsertPos = SuccToSinkTo->begin();
Evan Chengb339f3d2010-09-18 06:42:17 +0000885 while (InsertPos != SuccToSinkTo->end() && InsertPos->isPHI())
Chris Lattnerf3edc092008-01-04 07:36:53 +0000886 ++InsertPos;
Jim Grosbach01edd682010-06-03 23:49:57 +0000887
Matt Davisd041f212018-06-21 17:59:52 +0000888 performSink(MI, *SuccToSinkTo, InsertPos);
Devang Patel9de7a7d2011-09-07 00:07:58 +0000889
Juergen Ributzka4bea4942014-09-04 02:07:36 +0000890 // Conservatively, clear any kill flags, since it's possible that they are no
891 // longer correct.
Pete Cooper85b1c482015-05-08 17:54:32 +0000892 // Note that we have to clear the kill flags for any register this instruction
893 // uses as we may sink over another instruction which currently kills the
894 // used registers.
Duncan P. N. Exon Smithcb38ffa2016-07-01 00:11:48 +0000895 for (MachineOperand &MO : MI.operands()) {
Pete Cooper85b1c482015-05-08 17:54:32 +0000896 if (MO.isReg() && MO.isUse())
Matthias Braun352b89c2015-05-16 03:11:07 +0000897 RegsToClearKillFlags.set(MO.getReg()); // Remember to clear kill flags.
Pete Cooper85b1c482015-05-08 17:54:32 +0000898 }
Dan Gohmanc90f51c2010-05-13 20:34:42 +0000899
Chris Lattnerf3edc092008-01-04 07:36:53 +0000900 return true;
901}
Jun Bum Lim2ecb7ba2018-03-22 20:06:47 +0000902
903//===----------------------------------------------------------------------===//
904// This pass is not intended to be a replacement or a complete alternative
905// for the pre-ra machine sink pass. It is only designed to sink COPY
906// instructions which should be handled after RA.
907//
908// This pass sinks COPY instructions into a successor block, if the COPY is not
909// used in the current block and the COPY is live-in to a single successor
910// (i.e., doesn't require the COPY to be duplicated). This avoids executing the
911// copy on paths where their results aren't needed. This also exposes
912// additional opportunites for dead copy elimination and shrink wrapping.
913//
914// These copies were either not handled by or are inserted after the MachineSink
915// pass. As an example of the former case, the MachineSink pass cannot sink
916// COPY instructions with allocatable source registers; for AArch64 these type
917// of copy instructions are frequently used to move function parameters (PhyReg)
918// into virtual registers in the entry block.
919//
920// For the machine IR below, this pass will sink %w19 in the entry into its
921// successor (%bb.1) because %w19 is only live-in in %bb.1.
922// %bb.0:
923// %wzr = SUBSWri %w1, 1
924// %w19 = COPY %w0
925// Bcc 11, %bb.2
926// %bb.1:
927// Live Ins: %w19
928// BL @fun
929// %w0 = ADDWrr %w0, %w19
930// RET %w0
931// %bb.2:
932// %w0 = COPY %wzr
933// RET %w0
934// As we sink %w19 (CSR in AArch64) into %bb.1, the shrink-wrapping pass will be
935// able to see %bb.0 as a candidate.
936//===----------------------------------------------------------------------===//
937namespace {
938
939class PostRAMachineSinking : public MachineFunctionPass {
940public:
941 bool runOnMachineFunction(MachineFunction &MF) override;
942
943 static char ID;
944 PostRAMachineSinking() : MachineFunctionPass(ID) {}
945 StringRef getPassName() const override { return "PostRA Machine Sink"; }
946
Jun Bum Limf90fe702018-03-28 19:56:26 +0000947 void getAnalysisUsage(AnalysisUsage &AU) const override {
948 AU.setPreservesCFG();
949 MachineFunctionPass::getAnalysisUsage(AU);
950 }
951
Jun Bum Lim7ab1b322018-04-03 18:17:34 +0000952 MachineFunctionProperties getRequiredProperties() const override {
953 return MachineFunctionProperties().set(
Jun Bum Lim06073bf2018-04-13 14:23:09 +0000954 MachineFunctionProperties::Property::NoVRegs);
Jun Bum Lim7ab1b322018-04-03 18:17:34 +0000955 }
956
Jun Bum Lim2ecb7ba2018-03-22 20:06:47 +0000957private:
Jun Bum Lim47aece12018-04-27 18:44:37 +0000958 /// Track which register units have been modified and used.
959 LiveRegUnits ModifiedRegUnits, UsedRegUnits;
Jun Bum Lim2ecb7ba2018-03-22 20:06:47 +0000960
Jeremy Morsed5383522018-11-02 16:52:48 +0000961 /// Track DBG_VALUEs of (unmodified) register units.
962 DenseMap<unsigned, TinyPtrVector<MachineInstr*>> SeenDbgInstrs;
963
Jun Bum Lim2ecb7ba2018-03-22 20:06:47 +0000964 /// Sink Copy instructions unused in the same block close to their uses in
965 /// successors.
966 bool tryToSinkCopy(MachineBasicBlock &BB, MachineFunction &MF,
967 const TargetRegisterInfo *TRI, const TargetInstrInfo *TII);
968};
969} // namespace
970
971char PostRAMachineSinking::ID = 0;
972char &llvm::PostRAMachineSinkingID = PostRAMachineSinking::ID;
973
974INITIALIZE_PASS(PostRAMachineSinking, "postra-machine-sink",
975 "PostRA Machine Sink", false, false)
976
Jun Bum Lim47aece12018-04-27 18:44:37 +0000977static bool aliasWithRegsInLiveIn(MachineBasicBlock &MBB, unsigned Reg,
978 const TargetRegisterInfo *TRI) {
979 LiveRegUnits LiveInRegUnits(*TRI);
980 LiveInRegUnits.addLiveIns(MBB);
981 return !LiveInRegUnits.available(Reg);
Jun Bum Lim06073bf2018-04-13 14:23:09 +0000982}
983
Jun Bum Lim2ecb7ba2018-03-22 20:06:47 +0000984static MachineBasicBlock *
985getSingleLiveInSuccBB(MachineBasicBlock &CurBB,
Jun Bum Lim9e3e14b2018-04-27 19:59:20 +0000986 const SmallPtrSetImpl<MachineBasicBlock *> &SinkableBBs,
987 unsigned Reg, const TargetRegisterInfo *TRI) {
Jun Bum Lim2ecb7ba2018-03-22 20:06:47 +0000988 // Try to find a single sinkable successor in which Reg is live-in.
989 MachineBasicBlock *BB = nullptr;
990 for (auto *SI : SinkableBBs) {
Jun Bum Lim9e3e14b2018-04-27 19:59:20 +0000991 if (aliasWithRegsInLiveIn(*SI, Reg, TRI)) {
Jun Bum Lim2ecb7ba2018-03-22 20:06:47 +0000992 // If BB is set here, Reg is live-in to at least two sinkable successors,
993 // so quit.
994 if (BB)
995 return nullptr;
996 BB = SI;
997 }
998 }
999 // Reg is not live-in to any sinkable successors.
1000 if (!BB)
1001 return nullptr;
1002
1003 // Check if any register aliased with Reg is live-in in other successors.
1004 for (auto *SI : CurBB.successors()) {
Jun Bum Lim9e3e14b2018-04-27 19:59:20 +00001005 if (!SinkableBBs.count(SI) && aliasWithRegsInLiveIn(*SI, Reg, TRI))
Jun Bum Lim06073bf2018-04-13 14:23:09 +00001006 return nullptr;
Jun Bum Lim2ecb7ba2018-03-22 20:06:47 +00001007 }
1008 return BB;
1009}
1010
Jun Bum Lim9e3e14b2018-04-27 19:59:20 +00001011static MachineBasicBlock *
1012getSingleLiveInSuccBB(MachineBasicBlock &CurBB,
1013 const SmallPtrSetImpl<MachineBasicBlock *> &SinkableBBs,
1014 ArrayRef<unsigned> DefedRegsInCopy,
1015 const TargetRegisterInfo *TRI) {
Jun Bum Lim06073bf2018-04-13 14:23:09 +00001016 MachineBasicBlock *SingleBB = nullptr;
1017 for (auto DefReg : DefedRegsInCopy) {
1018 MachineBasicBlock *BB =
1019 getSingleLiveInSuccBB(CurBB, SinkableBBs, DefReg, TRI);
1020 if (!BB || (SingleBB && SingleBB != BB))
1021 return nullptr;
1022 SingleBB = BB;
1023 }
1024 return SingleBB;
1025}
1026
1027static void clearKillFlags(MachineInstr *MI, MachineBasicBlock &CurBB,
1028 SmallVectorImpl<unsigned> &UsedOpsInCopy,
Jun Bum Lim47aece12018-04-27 18:44:37 +00001029 LiveRegUnits &UsedRegUnits,
1030 const TargetRegisterInfo *TRI) {
Jun Bum Lim06073bf2018-04-13 14:23:09 +00001031 for (auto U : UsedOpsInCopy) {
1032 MachineOperand &MO = MI->getOperand(U);
1033 unsigned SrcReg = MO.getReg();
Jun Bum Lim47aece12018-04-27 18:44:37 +00001034 if (!UsedRegUnits.available(SrcReg)) {
Jun Bum Lim06073bf2018-04-13 14:23:09 +00001035 MachineBasicBlock::iterator NI = std::next(MI->getIterator());
1036 for (MachineInstr &UI : make_range(NI, CurBB.end())) {
1037 if (UI.killsRegister(SrcReg, TRI)) {
1038 UI.clearRegisterKills(SrcReg, TRI);
1039 MO.setIsKill(true);
1040 break;
1041 }
1042 }
1043 }
1044 }
1045}
1046
1047static void updateLiveIn(MachineInstr *MI, MachineBasicBlock *SuccBB,
1048 SmallVectorImpl<unsigned> &UsedOpsInCopy,
1049 SmallVectorImpl<unsigned> &DefedRegsInCopy) {
Krzysztof Parzyszekc1e2f392018-09-18 16:10:51 +00001050 MachineFunction &MF = *SuccBB->getParent();
1051 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1052 for (unsigned DefReg : DefedRegsInCopy)
1053 for (MCSubRegIterator S(DefReg, TRI, true); S.isValid(); ++S)
1054 SuccBB->removeLiveIn(*S);
Jun Bum Lim06073bf2018-04-13 14:23:09 +00001055 for (auto U : UsedOpsInCopy) {
1056 unsigned Reg = MI->getOperand(U).getReg();
1057 if (!SuccBB->isLiveIn(Reg))
1058 SuccBB->addLiveIn(Reg);
1059 }
1060}
1061
1062static bool hasRegisterDependency(MachineInstr *MI,
1063 SmallVectorImpl<unsigned> &UsedOpsInCopy,
1064 SmallVectorImpl<unsigned> &DefedRegsInCopy,
Jun Bum Lim47aece12018-04-27 18:44:37 +00001065 LiveRegUnits &ModifiedRegUnits,
1066 LiveRegUnits &UsedRegUnits) {
Jun Bum Lim06073bf2018-04-13 14:23:09 +00001067 bool HasRegDependency = false;
1068 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1069 MachineOperand &MO = MI->getOperand(i);
1070 if (!MO.isReg())
1071 continue;
1072 unsigned Reg = MO.getReg();
1073 if (!Reg)
1074 continue;
1075 if (MO.isDef()) {
Jun Bum Lim47aece12018-04-27 18:44:37 +00001076 if (!ModifiedRegUnits.available(Reg) || !UsedRegUnits.available(Reg)) {
Jun Bum Lim06073bf2018-04-13 14:23:09 +00001077 HasRegDependency = true;
1078 break;
1079 }
1080 DefedRegsInCopy.push_back(Reg);
1081
1082 // FIXME: instead of isUse(), readsReg() would be a better fix here,
1083 // For example, we can ignore modifications in reg with undef. However,
1084 // it's not perfectly clear if skipping the internal read is safe in all
1085 // other targets.
1086 } else if (MO.isUse()) {
Jun Bum Lim47aece12018-04-27 18:44:37 +00001087 if (!ModifiedRegUnits.available(Reg)) {
Jun Bum Lim06073bf2018-04-13 14:23:09 +00001088 HasRegDependency = true;
1089 break;
1090 }
1091 UsedOpsInCopy.push_back(i);
1092 }
1093 }
1094 return HasRegDependency;
1095}
1096
Jun Bum Lim2ecb7ba2018-03-22 20:06:47 +00001097bool PostRAMachineSinking::tryToSinkCopy(MachineBasicBlock &CurBB,
1098 MachineFunction &MF,
1099 const TargetRegisterInfo *TRI,
1100 const TargetInstrInfo *TII) {
Jun Bum Lim9e3e14b2018-04-27 19:59:20 +00001101 SmallPtrSet<MachineBasicBlock *, 2> SinkableBBs;
Jun Bum Lim2ecb7ba2018-03-22 20:06:47 +00001102 // FIXME: For now, we sink only to a successor which has a single predecessor
1103 // so that we can directly sink COPY instructions to the successor without
1104 // adding any new block or branch instruction.
1105 for (MachineBasicBlock *SI : CurBB.successors())
1106 if (!SI->livein_empty() && SI->pred_size() == 1)
Jun Bum Lim9e3e14b2018-04-27 19:59:20 +00001107 SinkableBBs.insert(SI);
Jun Bum Lim2ecb7ba2018-03-22 20:06:47 +00001108
1109 if (SinkableBBs.empty())
1110 return false;
1111
1112 bool Changed = false;
1113
1114 // Track which registers have been modified and used between the end of the
1115 // block and the current instruction.
Jun Bum Lim47aece12018-04-27 18:44:37 +00001116 ModifiedRegUnits.clear();
1117 UsedRegUnits.clear();
Jeremy Morsed5383522018-11-02 16:52:48 +00001118 SeenDbgInstrs.clear();
Jun Bum Lim2ecb7ba2018-03-22 20:06:47 +00001119
1120 for (auto I = CurBB.rbegin(), E = CurBB.rend(); I != E;) {
1121 MachineInstr *MI = &*I;
1122 ++I;
1123
Jeremy Morsed5383522018-11-02 16:52:48 +00001124 // Track the operand index for use in Copy.
1125 SmallVector<unsigned, 2> UsedOpsInCopy;
1126 // Track the register number defed in Copy.
1127 SmallVector<unsigned, 2> DefedRegsInCopy;
1128
1129 // We must sink this DBG_VALUE if its operand is sunk. To avoid searching
1130 // for DBG_VALUEs later, record them when they're encountered.
1131 if (MI->isDebugValue()) {
1132 auto &MO = MI->getOperand(0);
1133 if (MO.isReg() && TRI->isPhysicalRegister(MO.getReg())) {
1134 // Bail if we can already tell the sink would be rejected, rather
1135 // than needlessly accumulating lots of DBG_VALUEs.
1136 if (hasRegisterDependency(MI, UsedOpsInCopy, DefedRegsInCopy,
1137 ModifiedRegUnits, UsedRegUnits))
1138 continue;
1139
1140 // Record debug use of this register.
1141 SeenDbgInstrs[MO.getReg()].push_back(MI);
1142 }
1143 continue;
1144 }
1145
Matt Davisd041f212018-06-21 17:59:52 +00001146 if (MI->isDebugInstr())
1147 continue;
1148
Jun Bum Lim2ecb7ba2018-03-22 20:06:47 +00001149 // Do not move any instruction across function call.
1150 if (MI->isCall())
1151 return false;
1152
1153 if (!MI->isCopy() || !MI->getOperand(0).isRenamable()) {
Jun Bum Lim47aece12018-04-27 18:44:37 +00001154 LiveRegUnits::accumulateUsedDefed(*MI, ModifiedRegUnits, UsedRegUnits,
1155 TRI);
Jun Bum Lim2ecb7ba2018-03-22 20:06:47 +00001156 continue;
1157 }
1158
Jun Bum Lim2ecb7ba2018-03-22 20:06:47 +00001159 // Don't sink the COPY if it would violate a register dependency.
Jun Bum Lim47aece12018-04-27 18:44:37 +00001160 if (hasRegisterDependency(MI, UsedOpsInCopy, DefedRegsInCopy,
1161 ModifiedRegUnits, UsedRegUnits)) {
1162 LiveRegUnits::accumulateUsedDefed(*MI, ModifiedRegUnits, UsedRegUnits,
1163 TRI);
Jun Bum Lim2ecb7ba2018-03-22 20:06:47 +00001164 continue;
1165 }
Jun Bum Lim06073bf2018-04-13 14:23:09 +00001166 assert((!UsedOpsInCopy.empty() && !DefedRegsInCopy.empty()) &&
1167 "Unexpect SrcReg or DefReg");
Jun Bum Lim2ecb7ba2018-03-22 20:06:47 +00001168 MachineBasicBlock *SuccBB =
Jun Bum Lim06073bf2018-04-13 14:23:09 +00001169 getSingleLiveInSuccBB(CurBB, SinkableBBs, DefedRegsInCopy, TRI);
Jun Bum Lim2ecb7ba2018-03-22 20:06:47 +00001170 // Don't sink if we cannot find a single sinkable successor in which Reg
1171 // is live-in.
1172 if (!SuccBB) {
Jun Bum Lim47aece12018-04-27 18:44:37 +00001173 LiveRegUnits::accumulateUsedDefed(*MI, ModifiedRegUnits, UsedRegUnits,
1174 TRI);
Jun Bum Lim2ecb7ba2018-03-22 20:06:47 +00001175 continue;
1176 }
1177 assert((SuccBB->pred_size() == 1 && *SuccBB->pred_begin() == &CurBB) &&
1178 "Unexpected predecessor");
1179
Jeremy Morsed5383522018-11-02 16:52:48 +00001180 // Collect DBG_VALUEs that must sink with this copy.
1181 SmallVector<MachineInstr *, 4> DbgValsToSink;
1182 for (auto &MO : MI->operands()) {
1183 if (!MO.isReg() || !MO.isDef())
1184 continue;
1185 unsigned reg = MO.getReg();
1186 for (auto *MI : SeenDbgInstrs.lookup(reg))
1187 DbgValsToSink.push_back(MI);
1188 }
1189
Jun Bum Lim2ecb7ba2018-03-22 20:06:47 +00001190 // Clear the kill flag if SrcReg is killed between MI and the end of the
1191 // block.
Jun Bum Lim47aece12018-04-27 18:44:37 +00001192 clearKillFlags(MI, CurBB, UsedOpsInCopy, UsedRegUnits, TRI);
Jun Bum Lim2ecb7ba2018-03-22 20:06:47 +00001193 MachineBasicBlock::iterator InsertPos = SuccBB->getFirstNonPHI();
Jeremy Morsed5383522018-11-02 16:52:48 +00001194 performSink(*MI, *SuccBB, InsertPos, &DbgValsToSink);
Jun Bum Lim06073bf2018-04-13 14:23:09 +00001195 updateLiveIn(MI, SuccBB, UsedOpsInCopy, DefedRegsInCopy);
Jun Bum Lim2ecb7ba2018-03-22 20:06:47 +00001196
1197 Changed = true;
1198 ++NumPostRACopySink;
1199 }
1200 return Changed;
1201}
1202
1203bool PostRAMachineSinking::runOnMachineFunction(MachineFunction &MF) {
Xin Tong2d84c002019-02-21 02:11:06 +00001204 if (skipFunction(MF.getFunction()))
1205 return false;
1206
Jun Bum Lim2ecb7ba2018-03-22 20:06:47 +00001207 bool Changed = false;
1208 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1209 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
Jun Bum Lim2ecb7ba2018-03-22 20:06:47 +00001210
Jun Bum Lim47aece12018-04-27 18:44:37 +00001211 ModifiedRegUnits.init(*TRI);
1212 UsedRegUnits.init(*TRI);
Jun Bum Lim2ecb7ba2018-03-22 20:06:47 +00001213 for (auto &BB : MF)
1214 Changed |= tryToSinkCopy(BB, MF, TRI, TII);
1215
1216 return Changed;
1217}