blob: 5a5960b16130b317a300d6c8149fb4c155aa4042 [file] [log] [blame]
Eugene Zelenko94348112017-09-29 21:55:49 +00001//===- CriticalAntiDepBreaker.cpp - Anti-dep breaker ----------------------===//
David Goodwin2e7be612009-10-26 16:59:04 +00002//
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//
10// This file implements the CriticalAntiDepBreaker class, which
11// implements register anti-dependence breaking along a blocks
12// critical path during post-RA scheduler.
13//
14//===----------------------------------------------------------------------===//
15
David Goodwin2e7be612009-10-26 16:59:04 +000016#include "CriticalAntiDepBreaker.h"
Eugene Zelenko94348112017-09-29 21:55:49 +000017#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/BitVector.h"
19#include "llvm/ADT/DenseMap.h"
20#include "llvm/ADT/SmallVector.h"
David Goodwin2e7be612009-10-26 16:59:04 +000021#include "llvm/CodeGen/MachineBasicBlock.h"
22#include "llvm/CodeGen/MachineFrameInfo.h"
Eugene Zelenko94348112017-09-29 21:55:49 +000023#include "llvm/CodeGen/MachineFunction.h"
24#include "llvm/CodeGen/MachineInstr.h"
25#include "llvm/CodeGen/MachineOperand.h"
26#include "llvm/CodeGen/MachineRegisterInfo.h"
27#include "llvm/CodeGen/RegisterClassInfo.h"
28#include "llvm/CodeGen/ScheduleDAG.h"
David Blaikie48319232017-11-08 01:01:31 +000029#include "llvm/CodeGen/TargetInstrInfo.h"
David Blaikiee3a9b4c2017-11-17 01:07:10 +000030#include "llvm/CodeGen/TargetRegisterInfo.h"
31#include "llvm/CodeGen/TargetSubtargetInfo.h"
Eugene Zelenko94348112017-09-29 21:55:49 +000032#include "llvm/MC/MCInstrDesc.h"
33#include "llvm/MC/MCRegisterInfo.h"
David Goodwin2e7be612009-10-26 16:59:04 +000034#include "llvm/Support/Debug.h"
David Goodwin2e7be612009-10-26 16:59:04 +000035#include "llvm/Support/raw_ostream.h"
Eugene Zelenko94348112017-09-29 21:55:49 +000036#include <cassert>
37#include <map>
38#include <utility>
39#include <vector>
David Goodwin2e7be612009-10-26 16:59:04 +000040
41using namespace llvm;
42
Chandler Carruth8677f2f2014-04-22 02:02:50 +000043#define DEBUG_TYPE "post-RA-sched"
44
Eric Christopher9f85dcc2014-08-04 21:25:23 +000045CriticalAntiDepBreaker::CriticalAntiDepBreaker(MachineFunction &MFi,
46 const RegisterClassInfo &RCI)
47 : AntiDepBreaker(), MF(MFi), MRI(MF.getRegInfo()),
Eric Christopher60355182014-08-05 02:39:49 +000048 TII(MF.getSubtarget().getInstrInfo()),
49 TRI(MF.getSubtarget().getRegisterInfo()), RegClassInfo(RCI),
50 Classes(TRI->getNumRegs(), nullptr), KillIndices(TRI->getNumRegs(), 0),
51 DefIndices(TRI->getNumRegs(), 0), KeepRegs(TRI->getNumRegs(), false) {}
David Goodwin2e7be612009-10-26 16:59:04 +000052
Eugene Zelenko94348112017-09-29 21:55:49 +000053CriticalAntiDepBreaker::~CriticalAntiDepBreaker() = default;
David Goodwin2e7be612009-10-26 16:59:04 +000054
55void CriticalAntiDepBreaker::StartBlock(MachineBasicBlock *BB) {
David Goodwin990d2852009-12-09 17:18:22 +000056 const unsigned BBSize = BB->size();
Bill Wendling9c2a0342010-07-15 19:58:14 +000057 for (unsigned i = 0, e = TRI->getNumRegs(); i != e; ++i) {
58 // Clear out the register class data.
Craig Topper4ba84432014-04-14 00:51:57 +000059 Classes[i] = nullptr;
Bill Wendling9c2a0342010-07-15 19:58:14 +000060
61 // Initialize the indices to indicate that no registers are live.
David Goodwin990d2852009-12-09 17:18:22 +000062 KillIndices[i] = ~0u;
63 DefIndices[i] = BBSize;
64 }
David Goodwin2e7be612009-10-26 16:59:04 +000065
66 // Clear "do not change" set.
Benjamin Kramercff4ad72012-03-17 20:22:57 +000067 KeepRegs.reset();
David Goodwin2e7be612009-10-26 16:59:04 +000068
Matthias Braun63daa142015-09-25 21:25:19 +000069 bool IsReturnBlock = BB->isReturnBlock();
David Goodwin2e7be612009-10-26 16:59:04 +000070
Jakob Stoklund Olesenb45e4de2013-02-05 18:21:52 +000071 // Examine the live-in regs of all successors.
Evan Cheng46df4eb2010-06-16 07:35:02 +000072 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
73 SE = BB->succ_end(); SI != SE; ++SI)
Matthias Braunaf5ff602015-09-09 18:08:03 +000074 for (const auto &LI : (*SI)->liveins()) {
75 for (MCRegAliasIterator AI(LI.PhysReg, TRI, true); AI.isValid(); ++AI) {
Jakob Stoklund Olesenf152fe82012-06-01 20:36:54 +000076 unsigned Reg = *AI;
77 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
78 KillIndices[Reg] = BBSize;
79 DefIndices[Reg] = ~0u;
Evan Cheng46df4eb2010-06-16 07:35:02 +000080 }
81 }
82
David Goodwin2e7be612009-10-26 16:59:04 +000083 // Mark live-out callee-saved registers. In a return block this is
84 // all callee-saved registers. In non-return this is any
85 // callee-saved register that is not saved in the prolog.
Matthias Braunf79c57a2016-07-28 18:40:00 +000086 const MachineFrameInfo &MFI = MF.getFrameInfo();
87 BitVector Pristine = MFI.getPristineRegs(MF);
Oren Ben Simhon6095a792017-03-14 09:09:26 +000088 for (const MCPhysReg *I = MF.getRegInfo().getCalleeSavedRegs(); *I;
89 ++I) {
Eric Christopher95604f92017-03-30 22:34:20 +000090 unsigned Reg = *I;
Tim Shen400ba832017-05-30 22:26:52 +000091 if (!IsReturnBlock && !Pristine.test(Reg))
Eric Christopher95604f92017-03-30 22:34:20 +000092 continue;
Jakob Stoklund Olesenf152fe82012-06-01 20:36:54 +000093 for (MCRegAliasIterator AI(*I, TRI, true); AI.isValid(); ++AI) {
94 unsigned Reg = *AI;
95 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
96 KillIndices[Reg] = BBSize;
97 DefIndices[Reg] = ~0u;
David Goodwin2e7be612009-10-26 16:59:04 +000098 }
99 }
100}
101
102void CriticalAntiDepBreaker::FinishBlock() {
103 RegRefs.clear();
Benjamin Kramercff4ad72012-03-17 20:22:57 +0000104 KeepRegs.reset();
David Goodwin2e7be612009-10-26 16:59:04 +0000105}
106
Duncan P. N. Exon Smitha26cd9c2016-02-27 19:33:37 +0000107void CriticalAntiDepBreaker::Observe(MachineInstr &MI, unsigned Count,
David Goodwin2e7be612009-10-26 16:59:04 +0000108 unsigned InsertPosIndex) {
Sanjay Patel3deb3e32014-08-20 18:03:00 +0000109 // Kill instructions can define registers but are really nops, and there might
110 // be a real definition earlier that needs to be paired with uses dominated by
111 // this kill.
112
113 // FIXME: It may be possible to remove the isKill() restriction once PR18663
114 // has been properly fixed. There can be value in processing kills as seen in
115 // the AggressiveAntiDepBreaker class.
Shiva Chen24abe712018-05-09 02:42:00 +0000116 if (MI.isDebugInstr() || MI.isKill())
Dale Johannesenb0812f12010-03-05 00:02:59 +0000117 return;
David Goodwin2e7be612009-10-26 16:59:04 +0000118 assert(Count < InsertPosIndex && "Instruction index out of expected range!");
119
Bob Wilsonf70007e2010-10-02 01:49:29 +0000120 for (unsigned Reg = 0; Reg != TRI->getNumRegs(); ++Reg) {
121 if (KillIndices[Reg] != ~0u) {
122 // If Reg is currently live, then mark that it can't be renamed as
123 // we don't know the extent of its live-range anymore (now that it
124 // has been scheduled).
125 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
126 KillIndices[Reg] = Count;
127 } else if (DefIndices[Reg] < InsertPosIndex && DefIndices[Reg] >= Count) {
128 // Any register which was defined within the previous scheduling region
129 // may have been rescheduled and its lifetime may overlap with registers
130 // in ways not reflected in our current liveness state. For each such
131 // register, adjust the liveness state to be conservatively correct.
David Goodwin2e7be612009-10-26 16:59:04 +0000132 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
Bill Wendling9c2a0342010-07-15 19:58:14 +0000133
David Goodwin2e7be612009-10-26 16:59:04 +0000134 // Move the def index to the end of the previous region, to reflect
135 // that the def could theoretically have been scheduled at the end.
136 DefIndices[Reg] = InsertPosIndex;
137 }
Bob Wilsonf70007e2010-10-02 01:49:29 +0000138 }
David Goodwin2e7be612009-10-26 16:59:04 +0000139
140 PrescanInstruction(MI);
141 ScanInstruction(MI, Count);
142}
143
144/// CriticalPathStep - Return the next SUnit after SU on the bottom-up
145/// critical path.
Dan Gohman66db3a02010-04-19 23:11:58 +0000146static const SDep *CriticalPathStep(const SUnit *SU) {
Craig Topper4ba84432014-04-14 00:51:57 +0000147 const SDep *Next = nullptr;
David Goodwin2e7be612009-10-26 16:59:04 +0000148 unsigned NextDepth = 0;
149 // Find the predecessor edge with the greatest depth.
Dan Gohman66db3a02010-04-19 23:11:58 +0000150 for (SUnit::const_pred_iterator P = SU->Preds.begin(), PE = SU->Preds.end();
David Goodwin2e7be612009-10-26 16:59:04 +0000151 P != PE; ++P) {
Dan Gohman66db3a02010-04-19 23:11:58 +0000152 const SUnit *PredSU = P->getSUnit();
David Goodwin2e7be612009-10-26 16:59:04 +0000153 unsigned PredLatency = P->getLatency();
154 unsigned PredTotalLatency = PredSU->getDepth() + PredLatency;
155 // In the case of a latency tie, prefer an anti-dependency edge over
156 // other types of edges.
157 if (NextDepth < PredTotalLatency ||
158 (NextDepth == PredTotalLatency && P->getKind() == SDep::Anti)) {
159 NextDepth = PredTotalLatency;
160 Next = &*P;
161 }
162 }
163 return Next;
164}
165
Duncan P. N. Exon Smitha26cd9c2016-02-27 19:33:37 +0000166void CriticalAntiDepBreaker::PrescanInstruction(MachineInstr &MI) {
Evan Cheng46df4eb2010-06-16 07:35:02 +0000167 // It's not safe to change register allocation for source operands of
Sanjay Patel00295342014-06-24 21:11:51 +0000168 // instructions that have special allocation requirements. Also assume all
169 // registers used in a call must not be changed (ABI).
Evan Cheng46df4eb2010-06-16 07:35:02 +0000170 // FIXME: The issue with predicated instruction is more complex. We are being
Bob Wilson59718a42010-09-10 22:42:21 +0000171 // conservative here because the kill markers cannot be trusted after
Evan Cheng46df4eb2010-06-16 07:35:02 +0000172 // if-conversion:
Francis Visoiu Mistrih2cba0cc2018-01-09 17:31:07 +0000173 // %r6 = LDR %sp, %reg0, 92, 14, %reg0; mem:LD4[FixedStack14]
Evan Cheng46df4eb2010-06-16 07:35:02 +0000174 // ...
Francis Visoiu Mistrih2cba0cc2018-01-09 17:31:07 +0000175 // STR %r0, killed %r6, %reg0, 0, 0, %cpsr; mem:ST4[%395]
176 // %r6 = LDR %sp, %reg0, 100, 0, %cpsr; mem:LD4[FixedStack12]
177 // STR %r0, killed %r6, %reg0, 0, 14, %reg0; mem:ST4[%396](align=8)
Evan Cheng46df4eb2010-06-16 07:35:02 +0000178 //
179 // The first R6 kill is not really a kill since it's killed by a predicated
180 // instruction which may not be executed. The second R6 def may or may not
181 // re-define R6 so it's not safe to change it since the last R6 use cannot be
182 // changed.
Duncan P. N. Exon Smith5b9b80e2016-02-23 02:46:52 +0000183 bool Special =
Duncan P. N. Exon Smitha26cd9c2016-02-27 19:33:37 +0000184 MI.isCall() || MI.hasExtraSrcRegAllocReq() || TII->isPredicated(MI);
Evan Cheng46df4eb2010-06-16 07:35:02 +0000185
David Goodwin2e7be612009-10-26 16:59:04 +0000186 // Scan the register operands for this instruction and update
187 // Classes and RegRefs.
Duncan P. N. Exon Smitha26cd9c2016-02-27 19:33:37 +0000188 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
189 MachineOperand &MO = MI.getOperand(i);
David Goodwin2e7be612009-10-26 16:59:04 +0000190 if (!MO.isReg()) continue;
191 unsigned Reg = MO.getReg();
192 if (Reg == 0) continue;
Craig Topper4ba84432014-04-14 00:51:57 +0000193 const TargetRegisterClass *NewRC = nullptr;
Jim Grosbach01384ef2010-05-14 21:20:46 +0000194
Duncan P. N. Exon Smitha26cd9c2016-02-27 19:33:37 +0000195 if (i < MI.getDesc().getNumOperands())
196 NewRC = TII->getRegClass(MI.getDesc(), i, TRI, MF);
David Goodwin2e7be612009-10-26 16:59:04 +0000197
198 // For now, only allow the register to be changed if its register
199 // class is consistent across all uses.
200 if (!Classes[Reg] && NewRC)
201 Classes[Reg] = NewRC;
202 else if (!NewRC || Classes[Reg] != NewRC)
203 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
204
205 // Now check for aliases.
Jakob Stoklund Olesen396618b2012-06-01 23:28:30 +0000206 for (MCRegAliasIterator AI(Reg, TRI, false); AI.isValid(); ++AI) {
David Goodwin2e7be612009-10-26 16:59:04 +0000207 // If an alias of the reg is used during the live range, give up.
208 // Note that this allows us to skip checking if AntiDepReg
209 // overlaps with any of the aliases, among other things.
Jakob Stoklund Olesen396618b2012-06-01 23:28:30 +0000210 unsigned AliasReg = *AI;
David Goodwin2e7be612009-10-26 16:59:04 +0000211 if (Classes[AliasReg]) {
212 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
213 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
214 }
215 }
216
217 // If we're still willing to consider this register, note the reference.
218 if (Classes[Reg] != reinterpret_cast<TargetRegisterClass *>(-1))
219 RegRefs.insert(std::make_pair(Reg, &MO));
220
Sanjay Patel1a699b62014-07-03 15:19:40 +0000221 // If this reg is tied and live (Classes[Reg] is set to -1), we can't change
222 // it or any of its sub or super regs. We need to use KeepRegs to mark the
223 // reg because not all uses of the same reg within an instruction are
224 // necessarily tagged as tied.
225 // Example: an x86 "xor %eax, %eax" will have one source operand tied to the
226 // def register but not the second (see PR20020 for details).
227 // FIXME: can this check be relaxed to account for undef uses
228 // of a register? In the above 'xor' example, the uses of %eax are undef, so
229 // earlier instructions could still replace %eax even though the 'xor'
230 // itself can't be changed.
Duncan P. N. Exon Smitha26cd9c2016-02-27 19:33:37 +0000231 if (MI.isRegTiedToUseOperand(i) &&
Sanjay Patel1a699b62014-07-03 15:19:40 +0000232 Classes[Reg] == reinterpret_cast<TargetRegisterClass *>(-1)) {
233 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
234 SubRegs.isValid(); ++SubRegs) {
235 KeepRegs.set(*SubRegs);
236 }
237 for (MCSuperRegIterator SuperRegs(Reg, TRI);
238 SuperRegs.isValid(); ++SuperRegs) {
239 KeepRegs.set(*SuperRegs);
240 }
241 }
242
Evan Cheng46df4eb2010-06-16 07:35:02 +0000243 if (MO.isUse() && Special) {
Benjamin Kramercff4ad72012-03-17 20:22:57 +0000244 if (!KeepRegs.test(Reg)) {
Chad Rosier62c320a2013-05-22 23:17:36 +0000245 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
246 SubRegs.isValid(); ++SubRegs)
Jakob Stoklund Olesen396618b2012-06-01 23:28:30 +0000247 KeepRegs.set(*SubRegs);
David Goodwin2e7be612009-10-26 16:59:04 +0000248 }
249 }
250 }
251}
252
Duncan P. N. Exon Smitha26cd9c2016-02-27 19:33:37 +0000253void CriticalAntiDepBreaker::ScanInstruction(MachineInstr &MI, unsigned Count) {
David Goodwin2e7be612009-10-26 16:59:04 +0000254 // Update liveness.
Benjamin Kramerd9b0b022012-06-02 10:20:22 +0000255 // Proceeding upwards, registers that are defed but not used in this
David Goodwin2e7be612009-10-26 16:59:04 +0000256 // instruction are now dead.
Duncan P. N. Exon Smitha26cd9c2016-02-27 19:33:37 +0000257 assert(!MI.isKill() && "Attempting to scan a kill instruction");
David Goodwin2e7be612009-10-26 16:59:04 +0000258
Duncan P. N. Exon Smitha26cd9c2016-02-27 19:33:37 +0000259 if (!TII->isPredicated(MI)) {
Evan Cheng46df4eb2010-06-16 07:35:02 +0000260 // Predicated defs are modeled as read + write, i.e. similar to two
261 // address updates.
Duncan P. N. Exon Smitha26cd9c2016-02-27 19:33:37 +0000262 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
263 MachineOperand &MO = MI.getOperand(i);
Jakob Stoklund Olesenbbad2f12012-02-23 01:15:26 +0000264
265 if (MO.isRegMask())
266 for (unsigned i = 0, e = TRI->getNumRegs(); i != e; ++i)
267 if (MO.clobbersPhysReg(i)) {
268 DefIndices[i] = Count;
269 KillIndices[i] = ~0u;
Benjamin Kramercff4ad72012-03-17 20:22:57 +0000270 KeepRegs.reset(i);
Craig Topper4ba84432014-04-14 00:51:57 +0000271 Classes[i] = nullptr;
Jakob Stoklund Olesenbbad2f12012-02-23 01:15:26 +0000272 RegRefs.erase(i);
273 }
274
Evan Cheng46df4eb2010-06-16 07:35:02 +0000275 if (!MO.isReg()) continue;
276 unsigned Reg = MO.getReg();
277 if (Reg == 0) continue;
278 if (!MO.isDef()) continue;
Sanjay Patel1a699b62014-07-03 15:19:40 +0000279
Evan Cheng46df4eb2010-06-16 07:35:02 +0000280 // Ignore two-addr defs.
Duncan P. N. Exon Smitha26cd9c2016-02-27 19:33:37 +0000281 if (MI.isRegTiedToUseOperand(i))
282 continue;
Evan Cheng46df4eb2010-06-16 07:35:02 +0000283
Mitch Bodartf688cf72016-05-26 23:08:52 +0000284 // If we've already marked this reg as unchangeable, don't remove
285 // it or any of its subregs from KeepRegs.
286 bool Keep = KeepRegs.test(Reg);
287
Sanjay Patel72a8b112014-08-06 15:58:15 +0000288 // For the reg itself and all subregs: update the def to current;
289 // reset the kill state, any restrictions, and references.
290 for (MCSubRegIterator SRI(Reg, TRI, true); SRI.isValid(); ++SRI) {
291 unsigned SubregReg = *SRI;
Evan Cheng46df4eb2010-06-16 07:35:02 +0000292 DefIndices[SubregReg] = Count;
293 KillIndices[SubregReg] = ~0u;
Craig Topper4ba84432014-04-14 00:51:57 +0000294 Classes[SubregReg] = nullptr;
Evan Cheng46df4eb2010-06-16 07:35:02 +0000295 RegRefs.erase(SubregReg);
Mitch Bodartf688cf72016-05-26 23:08:52 +0000296 if (!Keep)
297 KeepRegs.reset(SubregReg);
Evan Cheng46df4eb2010-06-16 07:35:02 +0000298 }
299 // Conservatively mark super-registers as unusable.
Jakob Stoklund Olesen396618b2012-06-01 23:28:30 +0000300 for (MCSuperRegIterator SR(Reg, TRI); SR.isValid(); ++SR)
301 Classes[*SR] = reinterpret_cast<TargetRegisterClass *>(-1);
David Goodwin2e7be612009-10-26 16:59:04 +0000302 }
303 }
Duncan P. N. Exon Smitha26cd9c2016-02-27 19:33:37 +0000304 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
305 MachineOperand &MO = MI.getOperand(i);
David Goodwin2e7be612009-10-26 16:59:04 +0000306 if (!MO.isReg()) continue;
307 unsigned Reg = MO.getReg();
308 if (Reg == 0) continue;
309 if (!MO.isUse()) continue;
310
Craig Topper4ba84432014-04-14 00:51:57 +0000311 const TargetRegisterClass *NewRC = nullptr;
Duncan P. N. Exon Smitha26cd9c2016-02-27 19:33:37 +0000312 if (i < MI.getDesc().getNumOperands())
313 NewRC = TII->getRegClass(MI.getDesc(), i, TRI, MF);
David Goodwin2e7be612009-10-26 16:59:04 +0000314
315 // For now, only allow the register to be changed if its register
316 // class is consistent across all uses.
317 if (!Classes[Reg] && NewRC)
318 Classes[Reg] = NewRC;
319 else if (!NewRC || Classes[Reg] != NewRC)
320 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
321
322 RegRefs.insert(std::make_pair(Reg, &MO));
323
324 // It wasn't previously live but now it is, this is a kill.
Sanjay Patel72a8b112014-08-06 15:58:15 +0000325 // Repeat for all aliases.
326 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) {
Jakob Stoklund Olesen396618b2012-06-01 23:28:30 +0000327 unsigned AliasReg = *AI;
David Goodwin2e7be612009-10-26 16:59:04 +0000328 if (KillIndices[AliasReg] == ~0u) {
329 KillIndices[AliasReg] = Count;
330 DefIndices[AliasReg] = ~0u;
331 }
332 }
333 }
334}
335
Andrew Trickbc4bd922011-02-08 17:39:46 +0000336// Check all machine operands that reference the antidependent register and must
337// be replaced by NewReg. Return true if any of their parent instructions may
338// clobber the new register.
339//
340// Note: AntiDepReg may be referenced by a two-address instruction such that
341// it's use operand is tied to a def operand. We guard against the case in which
342// the two-address instruction also defines NewReg, as may happen with
343// pre/postincrement loads. In this case, both the use and def operands are in
344// RegRefs because the def is inserted by PrescanInstruction and not erased
Sanjay Patel00295342014-06-24 21:11:51 +0000345// during ScanInstruction. So checking for an instruction with definitions of
Andrew Trickbc4bd922011-02-08 17:39:46 +0000346// both NewReg and AntiDepReg covers it.
Andrew Trick46388522010-11-02 18:16:45 +0000347bool
Andrew Trickbc4bd922011-02-08 17:39:46 +0000348CriticalAntiDepBreaker::isNewRegClobberedByRefs(RegRefIter RegRefBegin,
349 RegRefIter RegRefEnd,
Eugene Zelenko94348112017-09-29 21:55:49 +0000350 unsigned NewReg) {
Andrew Trick46388522010-11-02 18:16:45 +0000351 for (RegRefIter I = RegRefBegin; I != RegRefEnd; ++I ) {
Andrew Trickbc4bd922011-02-08 17:39:46 +0000352 MachineOperand *RefOper = I->second;
353
354 // Don't allow the instruction defining AntiDepReg to earlyclobber its
355 // operands, in case they may be assigned to NewReg. In this case antidep
356 // breaking must fail, but it's too rare to bother optimizing.
357 if (RefOper->isDef() && RefOper->isEarlyClobber())
Andrew Trick46388522010-11-02 18:16:45 +0000358 return true;
Andrew Trickbc4bd922011-02-08 17:39:46 +0000359
Sanjay Patel00295342014-06-24 21:11:51 +0000360 // Handle cases in which this instruction defines NewReg.
Andrew Trickbc4bd922011-02-08 17:39:46 +0000361 MachineInstr *MI = RefOper->getParent();
362 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
363 const MachineOperand &CheckOper = MI->getOperand(i);
364
Jakob Stoklund Olesenbbad2f12012-02-23 01:15:26 +0000365 if (CheckOper.isRegMask() && CheckOper.clobbersPhysReg(NewReg))
366 return true;
367
Andrew Trickbc4bd922011-02-08 17:39:46 +0000368 if (!CheckOper.isReg() || !CheckOper.isDef() ||
369 CheckOper.getReg() != NewReg)
370 continue;
371
372 // Don't allow the instruction to define NewReg and AntiDepReg.
373 // When AntiDepReg is renamed it will be an illegal op.
374 if (RefOper->isDef())
375 return true;
376
377 // Don't allow an instruction using AntiDepReg to be earlyclobbered by
Sanjay Patel00295342014-06-24 21:11:51 +0000378 // NewReg.
Andrew Trickbc4bd922011-02-08 17:39:46 +0000379 if (CheckOper.isEarlyClobber())
380 return true;
381
Sanjay Patel00295342014-06-24 21:11:51 +0000382 // Don't allow inline asm to define NewReg at all. Who knows what it's
Andrew Trickbc4bd922011-02-08 17:39:46 +0000383 // doing with it.
384 if (MI->isInlineAsm())
385 return true;
386 }
Andrew Trick46388522010-11-02 18:16:45 +0000387 }
388 return false;
389}
390
Bill Schmidt5ff776b2013-01-28 18:36:58 +0000391unsigned CriticalAntiDepBreaker::
392findSuitableFreeRegister(RegRefIter RegRefBegin,
393 RegRefIter RegRefEnd,
394 unsigned AntiDepReg,
395 unsigned LastNewReg,
396 const TargetRegisterClass *RC,
Eugene Zelenko94348112017-09-29 21:55:49 +0000397 SmallVectorImpl<unsigned> &Forbid) {
Jakob Stoklund Olesen39b5c0c2012-11-29 03:34:17 +0000398 ArrayRef<MCPhysReg> Order = RegClassInfo.getOrder(RC);
Jakob Stoklund Olesenfa796dd2011-06-16 21:56:21 +0000399 for (unsigned i = 0; i != Order.size(); ++i) {
400 unsigned NewReg = Order[i];
David Goodwin2e7be612009-10-26 16:59:04 +0000401 // Don't replace a register with itself.
402 if (NewReg == AntiDepReg) continue;
403 // Don't replace a register with one that was recently used to repair
404 // an anti-dependence with this AntiDepReg, because that would
405 // re-introduce that anti-dependence.
406 if (NewReg == LastNewReg) continue;
Andrew Trick46388522010-11-02 18:16:45 +0000407 // If any instructions that define AntiDepReg also define the NewReg, it's
408 // not suitable. For example, Instruction with multiple definitions can
409 // result in this condition.
Andrew Trickbc4bd922011-02-08 17:39:46 +0000410 if (isNewRegClobberedByRefs(RegRefBegin, RegRefEnd, NewReg)) continue;
David Goodwin2e7be612009-10-26 16:59:04 +0000411 // If NewReg is dead and NewReg's most recent def is not before
412 // AntiDepReg's kill, it's safe to replace AntiDepReg with NewReg.
Jim Grosbach2973b572010-01-06 16:48:02 +0000413 assert(((KillIndices[AntiDepReg] == ~0u) != (DefIndices[AntiDepReg] == ~0u))
414 && "Kill and Def maps aren't consistent for AntiDepReg!");
415 assert(((KillIndices[NewReg] == ~0u) != (DefIndices[NewReg] == ~0u))
416 && "Kill and Def maps aren't consistent for NewReg!");
David Goodwin2e7be612009-10-26 16:59:04 +0000417 if (KillIndices[NewReg] != ~0u ||
418 Classes[NewReg] == reinterpret_cast<TargetRegisterClass *>(-1) ||
419 KillIndices[AntiDepReg] > DefIndices[NewReg])
420 continue;
Bill Schmidt5ff776b2013-01-28 18:36:58 +0000421 // If NewReg overlaps any of the forbidden registers, we can't use it.
422 bool Forbidden = false;
Craig Topperf22fd3f2013-07-03 05:11:49 +0000423 for (SmallVectorImpl<unsigned>::iterator it = Forbid.begin(),
Bill Schmidt5ff776b2013-01-28 18:36:58 +0000424 ite = Forbid.end(); it != ite; ++it)
425 if (TRI->regsOverlap(NewReg, *it)) {
426 Forbidden = true;
427 break;
428 }
429 if (Forbidden) continue;
David Goodwin2e7be612009-10-26 16:59:04 +0000430 return NewReg;
431 }
432
433 // No registers are free and available!
434 return 0;
435}
436
437unsigned CriticalAntiDepBreaker::
Eugene Zelenko94348112017-09-29 21:55:49 +0000438BreakAntiDependencies(const std::vector<SUnit> &SUnits,
Dan Gohman66db3a02010-04-19 23:11:58 +0000439 MachineBasicBlock::iterator Begin,
440 MachineBasicBlock::iterator End,
Devang Patele29e8e12011-06-02 21:26:52 +0000441 unsigned InsertPosIndex,
442 DbgValueVector &DbgValues) {
David Goodwin2e7be612009-10-26 16:59:04 +0000443 // The code below assumes that there is at least one instruction,
444 // so just duck out immediately if the block is empty.
445 if (SUnits.empty()) return 0;
446
Jim Grosbach533934e2010-06-01 23:48:44 +0000447 // Keep a map of the MachineInstr*'s back to the SUnit representing them.
448 // This is used for updating debug information.
Andrew Trickb4566a92012-02-22 06:08:11 +0000449 //
450 // FIXME: Replace this with the existing map in ScheduleDAGInstrs::MISUnitMap
Eugene Zelenko94348112017-09-29 21:55:49 +0000451 DenseMap<MachineInstr *, const SUnit *> MISUnitMap;
Jim Grosbach533934e2010-06-01 23:48:44 +0000452
David Goodwin2e7be612009-10-26 16:59:04 +0000453 // Find the node at the bottom of the critical path.
Craig Topper4ba84432014-04-14 00:51:57 +0000454 const SUnit *Max = nullptr;
David Goodwin2e7be612009-10-26 16:59:04 +0000455 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
Dan Gohman66db3a02010-04-19 23:11:58 +0000456 const SUnit *SU = &SUnits[i];
Jim Grosbach533934e2010-06-01 23:48:44 +0000457 MISUnitMap[SU->getInstr()] = SU;
David Goodwin2e7be612009-10-26 16:59:04 +0000458 if (!Max || SU->getDepth() + SU->Latency > Max->getDepth() + Max->Latency)
459 Max = SU;
460 }
461
462#ifndef NDEBUG
463 {
Nicola Zaghen0818e782018-05-14 12:53:11 +0000464 LLVM_DEBUG(dbgs() << "Critical path has total latency "
465 << (Max->getDepth() + Max->Latency) << "\n");
466 LLVM_DEBUG(dbgs() << "Available regs:");
David Goodwin2e7be612009-10-26 16:59:04 +0000467 for (unsigned Reg = 0; Reg < TRI->getNumRegs(); ++Reg) {
468 if (KillIndices[Reg] == ~0u)
Nicola Zaghen0818e782018-05-14 12:53:11 +0000469 LLVM_DEBUG(dbgs() << " " << printReg(Reg, TRI));
David Goodwin2e7be612009-10-26 16:59:04 +0000470 }
Nicola Zaghen0818e782018-05-14 12:53:11 +0000471 LLVM_DEBUG(dbgs() << '\n');
David Goodwin2e7be612009-10-26 16:59:04 +0000472 }
473#endif
474
475 // Track progress along the critical path through the SUnit graph as we walk
476 // the instructions.
Dan Gohman66db3a02010-04-19 23:11:58 +0000477 const SUnit *CriticalPathSU = Max;
David Goodwin2e7be612009-10-26 16:59:04 +0000478 MachineInstr *CriticalPathMI = CriticalPathSU->getInstr();
479
480 // Consider this pattern:
481 // A = ...
482 // ... = A
483 // A = ...
484 // ... = A
485 // A = ...
486 // ... = A
487 // A = ...
488 // ... = A
489 // There are three anti-dependencies here, and without special care,
490 // we'd break all of them using the same register:
491 // A = ...
492 // ... = A
493 // B = ...
494 // ... = B
495 // B = ...
496 // ... = B
497 // B = ...
498 // ... = B
499 // because at each anti-dependence, B is the first register that
500 // isn't A which is free. This re-introduces anti-dependencies
501 // at all but one of the original anti-dependencies that we were
502 // trying to break. To avoid this, keep track of the most recent
503 // register that each register was replaced with, avoid
504 // using it to repair an anti-dependence on the same register.
505 // This lets us produce this:
506 // A = ...
507 // ... = A
508 // B = ...
509 // ... = B
510 // C = ...
511 // ... = C
512 // B = ...
513 // ... = B
514 // This still has an anti-dependence on B, but at least it isn't on the
515 // original critical path.
516 //
517 // TODO: If we tracked more than one register here, we could potentially
518 // fix that remaining critical edge too. This is a little more involved,
519 // because unlike the most recent register, less recent registers should
520 // still be considered, though only if no other registers are available.
Bill Wendling9c2a0342010-07-15 19:58:14 +0000521 std::vector<unsigned> LastNewReg(TRI->getNumRegs(), 0);
David Goodwin2e7be612009-10-26 16:59:04 +0000522
523 // Attempt to break anti-dependence edges on the critical path. Walk the
524 // instructions from the bottom up, tracking information about liveness
525 // as we go to help determine which registers are available.
526 unsigned Broken = 0;
527 unsigned Count = InsertPosIndex - 1;
Sanjay Patel00295342014-06-24 21:11:51 +0000528 for (MachineBasicBlock::iterator I = End, E = Begin; I != E; --Count) {
Duncan P. N. Exon Smitha26cd9c2016-02-27 19:33:37 +0000529 MachineInstr &MI = *--I;
Sanjay Patel3deb3e32014-08-20 18:03:00 +0000530 // Kill instructions can define registers but are really nops, and there
531 // might be a real definition earlier that needs to be paired with uses
532 // dominated by this kill.
Fangrui Songaf7b1832018-07-30 19:41:25 +0000533
Sanjay Patel3deb3e32014-08-20 18:03:00 +0000534 // FIXME: It may be possible to remove the isKill() restriction once PR18663
535 // has been properly fixed. There can be value in processing kills as seen
536 // in the AggressiveAntiDepBreaker class.
Shiva Chen24abe712018-05-09 02:42:00 +0000537 if (MI.isDebugInstr() || MI.isKill())
Dale Johannesenb0812f12010-03-05 00:02:59 +0000538 continue;
David Goodwin2e7be612009-10-26 16:59:04 +0000539
540 // Check if this instruction has a dependence on the critical path that
541 // is an anti-dependence that we may be able to break. If it is, set
542 // AntiDepReg to the non-zero register associated with the anti-dependence.
543 //
544 // We limit our attention to the critical path as a heuristic to avoid
545 // breaking anti-dependence edges that aren't going to significantly
546 // impact the overall schedule. There are a limited number of registers
547 // and we want to save them for the important edges.
Jim Grosbach01384ef2010-05-14 21:20:46 +0000548 //
David Goodwin2e7be612009-10-26 16:59:04 +0000549 // TODO: Instructions with multiple defs could have multiple
550 // anti-dependencies. The current code here only knows how to break one
551 // edge per instruction. Note that we'd have to be able to break all of
552 // the anti-dependencies in an instruction in order to be effective.
553 unsigned AntiDepReg = 0;
Duncan P. N. Exon Smitha26cd9c2016-02-27 19:33:37 +0000554 if (&MI == CriticalPathMI) {
Dan Gohman66db3a02010-04-19 23:11:58 +0000555 if (const SDep *Edge = CriticalPathStep(CriticalPathSU)) {
556 const SUnit *NextSU = Edge->getSUnit();
David Goodwin2e7be612009-10-26 16:59:04 +0000557
558 // Only consider anti-dependence edges.
559 if (Edge->getKind() == SDep::Anti) {
560 AntiDepReg = Edge->getReg();
561 assert(AntiDepReg != 0 && "Anti-dependence on reg0?");
Jakob Stoklund Olesen14d1dd92012-10-15 22:41:03 +0000562 if (!MRI.isAllocatable(AntiDepReg))
David Goodwin2e7be612009-10-26 16:59:04 +0000563 // Don't break anti-dependencies on non-allocatable registers.
564 AntiDepReg = 0;
Benjamin Kramercff4ad72012-03-17 20:22:57 +0000565 else if (KeepRegs.test(AntiDepReg))
Sanjay Patel00295342014-06-24 21:11:51 +0000566 // Don't break anti-dependencies if a use down below requires
David Goodwin2e7be612009-10-26 16:59:04 +0000567 // this exact register.
568 AntiDepReg = 0;
569 else {
570 // If the SUnit has other dependencies on the SUnit that it
571 // anti-depends on, don't bother breaking the anti-dependency
572 // since those edges would prevent such units from being
573 // scheduled past each other regardless.
574 //
575 // Also, if there are dependencies on other SUnits with the
576 // same register as the anti-dependency, don't attempt to
577 // break it.
Dan Gohman66db3a02010-04-19 23:11:58 +0000578 for (SUnit::const_pred_iterator P = CriticalPathSU->Preds.begin(),
David Goodwin2e7be612009-10-26 16:59:04 +0000579 PE = CriticalPathSU->Preds.end(); P != PE; ++P)
580 if (P->getSUnit() == NextSU ?
581 (P->getKind() != SDep::Anti || P->getReg() != AntiDepReg) :
582 (P->getKind() == SDep::Data && P->getReg() == AntiDepReg)) {
583 AntiDepReg = 0;
584 break;
585 }
586 }
587 }
588 CriticalPathSU = NextSU;
589 CriticalPathMI = CriticalPathSU->getInstr();
590 } else {
591 // We've reached the end of the critical path.
Craig Topper4ba84432014-04-14 00:51:57 +0000592 CriticalPathSU = nullptr;
593 CriticalPathMI = nullptr;
David Goodwin2e7be612009-10-26 16:59:04 +0000594 }
595 }
596
597 PrescanInstruction(MI);
598
Bill Schmidt5ff776b2013-01-28 18:36:58 +0000599 SmallVector<unsigned, 2> ForbidRegs;
600
Evan Cheng46df4eb2010-06-16 07:35:02 +0000601 // If MI's defs have a special allocation requirement, don't allow
602 // any def registers to be changed. Also assume all registers
603 // defined in a call must not be changed (ABI).
Duncan P. N. Exon Smitha26cd9c2016-02-27 19:33:37 +0000604 if (MI.isCall() || MI.hasExtraDefRegAllocReq() || TII->isPredicated(MI))
David Goodwin2e7be612009-10-26 16:59:04 +0000605 // If this instruction's defs have special allocation requirement, don't
606 // break this anti-dependency.
607 AntiDepReg = 0;
608 else if (AntiDepReg) {
609 // If this instruction has a use of AntiDepReg, breaking it
Bill Schmidt5ff776b2013-01-28 18:36:58 +0000610 // is invalid. If the instruction defines other registers,
611 // save a list of them so that we don't pick a new register
612 // that overlaps any of them.
Duncan P. N. Exon Smitha26cd9c2016-02-27 19:33:37 +0000613 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
614 MachineOperand &MO = MI.getOperand(i);
David Goodwin2e7be612009-10-26 16:59:04 +0000615 if (!MO.isReg()) continue;
616 unsigned Reg = MO.getReg();
617 if (Reg == 0) continue;
Evan Cheng46df4eb2010-06-16 07:35:02 +0000618 if (MO.isUse() && TRI->regsOverlap(AntiDepReg, Reg)) {
David Goodwin2e7be612009-10-26 16:59:04 +0000619 AntiDepReg = 0;
620 break;
621 }
Bill Schmidt5ff776b2013-01-28 18:36:58 +0000622 if (MO.isDef() && Reg != AntiDepReg)
623 ForbidRegs.push_back(Reg);
David Goodwin2e7be612009-10-26 16:59:04 +0000624 }
625 }
626
627 // Determine AntiDepReg's register class, if it is live and is
628 // consistently used within a single class.
Craig Topper4ba84432014-04-14 00:51:57 +0000629 const TargetRegisterClass *RC = AntiDepReg != 0 ? Classes[AntiDepReg]
630 : nullptr;
631 assert((AntiDepReg == 0 || RC != nullptr) &&
David Goodwin2e7be612009-10-26 16:59:04 +0000632 "Register should be live if it's causing an anti-dependence!");
633 if (RC == reinterpret_cast<TargetRegisterClass *>(-1))
634 AntiDepReg = 0;
635
Alp Tokerae43cab62014-01-24 17:20:08 +0000636 // Look for a suitable register to use to break the anti-dependence.
David Goodwin2e7be612009-10-26 16:59:04 +0000637 //
638 // TODO: Instead of picking the first free register, consider which might
639 // be the best.
640 if (AntiDepReg != 0) {
Andrew Trick46388522010-11-02 18:16:45 +0000641 std::pair<std::multimap<unsigned, MachineOperand *>::iterator,
642 std::multimap<unsigned, MachineOperand *>::iterator>
643 Range = RegRefs.equal_range(AntiDepReg);
644 if (unsigned NewReg = findSuitableFreeRegister(Range.first, Range.second,
645 AntiDepReg,
David Goodwin2e7be612009-10-26 16:59:04 +0000646 LastNewReg[AntiDepReg],
Bill Schmidt5ff776b2013-01-28 18:36:58 +0000647 RC, ForbidRegs)) {
Nicola Zaghen0818e782018-05-14 12:53:11 +0000648 LLVM_DEBUG(dbgs() << "Breaking anti-dependence edge on "
649 << printReg(AntiDepReg, TRI) << " with "
650 << RegRefs.count(AntiDepReg) << " references"
651 << " using " << printReg(NewReg, TRI) << "!\n");
David Goodwin2e7be612009-10-26 16:59:04 +0000652
653 // Update the references to the old register to refer to the new
654 // register.
David Goodwin2e7be612009-10-26 16:59:04 +0000655 for (std::multimap<unsigned, MachineOperand *>::iterator
Jim Grosbach533934e2010-06-01 23:48:44 +0000656 Q = Range.first, QE = Range.second; Q != QE; ++Q) {
David Goodwin2e7be612009-10-26 16:59:04 +0000657 Q->second->setReg(NewReg);
Jim Grosbach533934e2010-06-01 23:48:44 +0000658 // If the SU for the instruction being updated has debug information
659 // related to the anti-dependency register, make sure to update that
660 // as well.
661 const SUnit *SU = MISUnitMap[Q->second->getParent()];
Jim Grosbach086723d2010-06-02 15:29:36 +0000662 if (!SU) continue;
Andrew Ngd8be4bf2017-04-25 15:39:57 +0000663 UpdateDbgValues(DbgValues, Q->second->getParent(),
664 AntiDepReg, NewReg);
Jim Grosbach533934e2010-06-01 23:48:44 +0000665 }
David Goodwin2e7be612009-10-26 16:59:04 +0000666
667 // We just went back in time and modified history; the
Bob Wilsonf70007e2010-10-02 01:49:29 +0000668 // liveness information for the anti-dependence reg is now
David Goodwin2e7be612009-10-26 16:59:04 +0000669 // inconsistent. Set the state as if it were dead.
670 Classes[NewReg] = Classes[AntiDepReg];
671 DefIndices[NewReg] = DefIndices[AntiDepReg];
672 KillIndices[NewReg] = KillIndices[AntiDepReg];
673 assert(((KillIndices[NewReg] == ~0u) !=
674 (DefIndices[NewReg] == ~0u)) &&
675 "Kill and Def maps aren't consistent for NewReg!");
676
Craig Topper4ba84432014-04-14 00:51:57 +0000677 Classes[AntiDepReg] = nullptr;
David Goodwin2e7be612009-10-26 16:59:04 +0000678 DefIndices[AntiDepReg] = KillIndices[AntiDepReg];
679 KillIndices[AntiDepReg] = ~0u;
680 assert(((KillIndices[AntiDepReg] == ~0u) !=
681 (DefIndices[AntiDepReg] == ~0u)) &&
682 "Kill and Def maps aren't consistent for AntiDepReg!");
683
684 RegRefs.erase(AntiDepReg);
685 LastNewReg[AntiDepReg] = NewReg;
686 ++Broken;
687 }
688 }
689
690 ScanInstruction(MI, Count);
691 }
692
693 return Broken;
694}