blob: 3d62d48876025c1dfa95c5b44a368c7b96b127e8 [file] [log] [blame]
David Goodwin83704852009-10-26 16:59:04 +00001//===----- CriticalAntiDepBreaker.cpp - Anti-dep breaker -------- ---------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
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 Goodwin83704852009-10-26 16:59:04 +000016#include "CriticalAntiDepBreaker.h"
17#include "llvm/CodeGen/MachineBasicBlock.h"
18#include "llvm/CodeGen/MachineFrameInfo.h"
David Goodwin83704852009-10-26 16:59:04 +000019#include "llvm/Support/Debug.h"
20#include "llvm/Support/ErrorHandling.h"
21#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000022#include "llvm/Target/TargetInstrInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000023#include "llvm/Target/TargetRegisterInfo.h"
Eric Christopherd9134482014-08-04 21:25:23 +000024#include "llvm/Target/TargetSubtargetInfo.h"
David Goodwin83704852009-10-26 16:59:04 +000025
26using namespace llvm;
27
Chandler Carruth1b9dde02014-04-22 02:02:50 +000028#define DEBUG_TYPE "post-RA-sched"
29
Eric Christopherd9134482014-08-04 21:25:23 +000030CriticalAntiDepBreaker::CriticalAntiDepBreaker(MachineFunction &MFi,
31 const RegisterClassInfo &RCI)
32 : AntiDepBreaker(), MF(MFi), MRI(MF.getRegInfo()),
Eric Christopherfc6de422014-08-05 02:39:49 +000033 TII(MF.getSubtarget().getInstrInfo()),
34 TRI(MF.getSubtarget().getRegisterInfo()), RegClassInfo(RCI),
35 Classes(TRI->getNumRegs(), nullptr), KillIndices(TRI->getNumRegs(), 0),
36 DefIndices(TRI->getNumRegs(), 0), KeepRegs(TRI->getNumRegs(), false) {}
David Goodwin83704852009-10-26 16:59:04 +000037
38CriticalAntiDepBreaker::~CriticalAntiDepBreaker() {
39}
40
41void CriticalAntiDepBreaker::StartBlock(MachineBasicBlock *BB) {
David Goodwina45fe672009-12-09 17:18:22 +000042 const unsigned BBSize = BB->size();
Bill Wendling51a9c0a2010-07-15 19:58:14 +000043 for (unsigned i = 0, e = TRI->getNumRegs(); i != e; ++i) {
44 // Clear out the register class data.
Craig Topperc0196b12014-04-14 00:51:57 +000045 Classes[i] = nullptr;
Bill Wendling51a9c0a2010-07-15 19:58:14 +000046
47 // Initialize the indices to indicate that no registers are live.
David Goodwina45fe672009-12-09 17:18:22 +000048 KillIndices[i] = ~0u;
49 DefIndices[i] = BBSize;
50 }
David Goodwin83704852009-10-26 16:59:04 +000051
52 // Clear "do not change" set.
Benjamin Kramer5d1bca82012-03-17 20:22:57 +000053 KeepRegs.reset();
David Goodwin83704852009-10-26 16:59:04 +000054
Benjamin Kramer8e5af372012-03-16 15:46:47 +000055 bool IsReturnBlock = (BBSize != 0 && BB->back().isReturn());
David Goodwin83704852009-10-26 16:59:04 +000056
Jakob Stoklund Olesenc3386792013-02-05 18:21:52 +000057 // Examine the live-in regs of all successors.
Evan Chengf128bdc2010-06-16 07:35:02 +000058 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
59 SE = BB->succ_end(); SI != SE; ++SI)
60 for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
61 E = (*SI)->livein_end(); I != E; ++I) {
Jakob Stoklund Olesen92a00832012-06-01 20:36:54 +000062 for (MCRegAliasIterator AI(*I, TRI, true); AI.isValid(); ++AI) {
63 unsigned Reg = *AI;
64 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
65 KillIndices[Reg] = BBSize;
66 DefIndices[Reg] = ~0u;
Evan Chengf128bdc2010-06-16 07:35:02 +000067 }
68 }
69
David Goodwin83704852009-10-26 16:59:04 +000070 // Mark live-out callee-saved registers. In a return block this is
71 // all callee-saved registers. In non-return this is any
72 // callee-saved register that is not saved in the prolog.
73 const MachineFrameInfo *MFI = MF.getFrameInfo();
74 BitVector Pristine = MFI->getPristineRegs(BB);
Craig Topper840beec2014-04-04 05:16:06 +000075 for (const MCPhysReg *I = TRI->getCalleeSavedRegs(&MF); *I; ++I) {
Jakob Stoklund Olesen92a00832012-06-01 20:36:54 +000076 if (!IsReturnBlock && !Pristine.test(*I)) continue;
77 for (MCRegAliasIterator AI(*I, TRI, true); AI.isValid(); ++AI) {
78 unsigned Reg = *AI;
79 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
80 KillIndices[Reg] = BBSize;
81 DefIndices[Reg] = ~0u;
David Goodwin83704852009-10-26 16:59:04 +000082 }
83 }
84}
85
86void CriticalAntiDepBreaker::FinishBlock() {
87 RegRefs.clear();
Benjamin Kramer5d1bca82012-03-17 20:22:57 +000088 KeepRegs.reset();
David Goodwin83704852009-10-26 16:59:04 +000089}
90
91void CriticalAntiDepBreaker::Observe(MachineInstr *MI, unsigned Count,
92 unsigned InsertPosIndex) {
Sanjay Patelf3cfeef2014-08-20 18:03:00 +000093 // Kill instructions can define registers but are really nops, and there might
94 // be a real definition earlier that needs to be paired with uses dominated by
95 // this kill.
96
97 // FIXME: It may be possible to remove the isKill() restriction once PR18663
98 // has been properly fixed. There can be value in processing kills as seen in
99 // the AggressiveAntiDepBreaker class.
100 if (MI->isDebugValue() || MI->isKill())
Dale Johannesen2061c842010-03-05 00:02:59 +0000101 return;
David Goodwin83704852009-10-26 16:59:04 +0000102 assert(Count < InsertPosIndex && "Instruction index out of expected range!");
103
Bob Wilsonc57c2202010-10-02 01:49:29 +0000104 for (unsigned Reg = 0; Reg != TRI->getNumRegs(); ++Reg) {
105 if (KillIndices[Reg] != ~0u) {
106 // If Reg is currently live, then mark that it can't be renamed as
107 // we don't know the extent of its live-range anymore (now that it
108 // has been scheduled).
109 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
110 KillIndices[Reg] = Count;
111 } else if (DefIndices[Reg] < InsertPosIndex && DefIndices[Reg] >= Count) {
112 // Any register which was defined within the previous scheduling region
113 // may have been rescheduled and its lifetime may overlap with registers
114 // in ways not reflected in our current liveness state. For each such
115 // register, adjust the liveness state to be conservatively correct.
David Goodwin83704852009-10-26 16:59:04 +0000116 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
Bill Wendling51a9c0a2010-07-15 19:58:14 +0000117
David Goodwin83704852009-10-26 16:59:04 +0000118 // Move the def index to the end of the previous region, to reflect
119 // that the def could theoretically have been scheduled at the end.
120 DefIndices[Reg] = InsertPosIndex;
121 }
Bob Wilsonc57c2202010-10-02 01:49:29 +0000122 }
David Goodwin83704852009-10-26 16:59:04 +0000123
124 PrescanInstruction(MI);
125 ScanInstruction(MI, Count);
126}
127
128/// CriticalPathStep - Return the next SUnit after SU on the bottom-up
129/// critical path.
Dan Gohman35bc4d42010-04-19 23:11:58 +0000130static const SDep *CriticalPathStep(const SUnit *SU) {
Craig Topperc0196b12014-04-14 00:51:57 +0000131 const SDep *Next = nullptr;
David Goodwin83704852009-10-26 16:59:04 +0000132 unsigned NextDepth = 0;
133 // Find the predecessor edge with the greatest depth.
Dan Gohman35bc4d42010-04-19 23:11:58 +0000134 for (SUnit::const_pred_iterator P = SU->Preds.begin(), PE = SU->Preds.end();
David Goodwin83704852009-10-26 16:59:04 +0000135 P != PE; ++P) {
Dan Gohman35bc4d42010-04-19 23:11:58 +0000136 const SUnit *PredSU = P->getSUnit();
David Goodwin83704852009-10-26 16:59:04 +0000137 unsigned PredLatency = P->getLatency();
138 unsigned PredTotalLatency = PredSU->getDepth() + PredLatency;
139 // In the case of a latency tie, prefer an anti-dependency edge over
140 // other types of edges.
141 if (NextDepth < PredTotalLatency ||
142 (NextDepth == PredTotalLatency && P->getKind() == SDep::Anti)) {
143 NextDepth = PredTotalLatency;
144 Next = &*P;
145 }
146 }
147 return Next;
148}
149
150void CriticalAntiDepBreaker::PrescanInstruction(MachineInstr *MI) {
Evan Chengf128bdc2010-06-16 07:35:02 +0000151 // It's not safe to change register allocation for source operands of
Sanjay Patel99475192014-06-24 21:11:51 +0000152 // instructions that have special allocation requirements. Also assume all
153 // registers used in a call must not be changed (ABI).
Evan Chengf128bdc2010-06-16 07:35:02 +0000154 // FIXME: The issue with predicated instruction is more complex. We are being
Bob Wilsonf3ecfd02010-09-10 22:42:21 +0000155 // conservative here because the kill markers cannot be trusted after
Evan Chengf128bdc2010-06-16 07:35:02 +0000156 // if-conversion:
157 // %R6<def> = LDR %SP, %reg0, 92, pred:14, pred:%reg0; mem:LD4[FixedStack14]
158 // ...
159 // STR %R0, %R6<kill>, %reg0, 0, pred:0, pred:%CPSR; mem:ST4[%395]
160 // %R6<def> = LDR %SP, %reg0, 100, pred:0, pred:%CPSR; mem:LD4[FixedStack12]
161 // STR %R0, %R6<kill>, %reg0, 0, pred:14, pred:%reg0; mem:ST4[%396](align=8)
162 //
163 // The first R6 kill is not really a kill since it's killed by a predicated
164 // instruction which may not be executed. The second R6 def may or may not
165 // re-define R6 so it's not safe to change it since the last R6 use cannot be
166 // changed.
Evan Cheng7f8e5632011-12-07 07:15:52 +0000167 bool Special = MI->isCall() ||
168 MI->hasExtraSrcRegAllocReq() ||
Evan Chengf128bdc2010-06-16 07:35:02 +0000169 TII->isPredicated(MI);
170
David Goodwin83704852009-10-26 16:59:04 +0000171 // Scan the register operands for this instruction and update
172 // Classes and RegRefs.
173 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
174 MachineOperand &MO = MI->getOperand(i);
175 if (!MO.isReg()) continue;
176 unsigned Reg = MO.getReg();
177 if (Reg == 0) continue;
Craig Topperc0196b12014-04-14 00:51:57 +0000178 const TargetRegisterClass *NewRC = nullptr;
Jim Grosbach866b74b2010-05-14 21:20:46 +0000179
David Goodwin83704852009-10-26 16:59:04 +0000180 if (i < MI->getDesc().getNumOperands())
Jakob Stoklund Olesen3c52f022012-05-07 22:10:26 +0000181 NewRC = TII->getRegClass(MI->getDesc(), i, TRI, MF);
David Goodwin83704852009-10-26 16:59:04 +0000182
183 // For now, only allow the register to be changed if its register
184 // class is consistent across all uses.
185 if (!Classes[Reg] && NewRC)
186 Classes[Reg] = NewRC;
187 else if (!NewRC || Classes[Reg] != NewRC)
188 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
189
190 // Now check for aliases.
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000191 for (MCRegAliasIterator AI(Reg, TRI, false); AI.isValid(); ++AI) {
David Goodwin83704852009-10-26 16:59:04 +0000192 // If an alias of the reg is used during the live range, give up.
193 // Note that this allows us to skip checking if AntiDepReg
194 // overlaps with any of the aliases, among other things.
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000195 unsigned AliasReg = *AI;
David Goodwin83704852009-10-26 16:59:04 +0000196 if (Classes[AliasReg]) {
197 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
198 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
199 }
200 }
201
202 // If we're still willing to consider this register, note the reference.
203 if (Classes[Reg] != reinterpret_cast<TargetRegisterClass *>(-1))
204 RegRefs.insert(std::make_pair(Reg, &MO));
205
Sanjay Pateldc574ab2014-07-03 15:19:40 +0000206 // If this reg is tied and live (Classes[Reg] is set to -1), we can't change
207 // it or any of its sub or super regs. We need to use KeepRegs to mark the
208 // reg because not all uses of the same reg within an instruction are
209 // necessarily tagged as tied.
210 // Example: an x86 "xor %eax, %eax" will have one source operand tied to the
211 // def register but not the second (see PR20020 for details).
212 // FIXME: can this check be relaxed to account for undef uses
213 // of a register? In the above 'xor' example, the uses of %eax are undef, so
214 // earlier instructions could still replace %eax even though the 'xor'
215 // itself can't be changed.
216 if (MI->isRegTiedToUseOperand(i) &&
217 Classes[Reg] == reinterpret_cast<TargetRegisterClass *>(-1)) {
218 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
219 SubRegs.isValid(); ++SubRegs) {
220 KeepRegs.set(*SubRegs);
221 }
222 for (MCSuperRegIterator SuperRegs(Reg, TRI);
223 SuperRegs.isValid(); ++SuperRegs) {
224 KeepRegs.set(*SuperRegs);
225 }
226 }
227
Evan Chengf128bdc2010-06-16 07:35:02 +0000228 if (MO.isUse() && Special) {
Benjamin Kramer5d1bca82012-03-17 20:22:57 +0000229 if (!KeepRegs.test(Reg)) {
Chad Rosierabdb1d62013-05-22 23:17:36 +0000230 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
231 SubRegs.isValid(); ++SubRegs)
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000232 KeepRegs.set(*SubRegs);
David Goodwin83704852009-10-26 16:59:04 +0000233 }
234 }
235 }
236}
237
238void CriticalAntiDepBreaker::ScanInstruction(MachineInstr *MI,
239 unsigned Count) {
240 // Update liveness.
Benjamin Kramerbde91762012-06-02 10:20:22 +0000241 // Proceeding upwards, registers that are defed but not used in this
David Goodwin83704852009-10-26 16:59:04 +0000242 // instruction are now dead.
Sanjay Patelf3cfeef2014-08-20 18:03:00 +0000243 assert(!MI->isKill() && "Attempting to scan a kill instruction");
David Goodwin83704852009-10-26 16:59:04 +0000244
Evan Chengf128bdc2010-06-16 07:35:02 +0000245 if (!TII->isPredicated(MI)) {
246 // Predicated defs are modeled as read + write, i.e. similar to two
247 // address updates.
248 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
249 MachineOperand &MO = MI->getOperand(i);
Jakob Stoklund Olesen38ce8892012-02-23 01:15:26 +0000250
251 if (MO.isRegMask())
252 for (unsigned i = 0, e = TRI->getNumRegs(); i != e; ++i)
253 if (MO.clobbersPhysReg(i)) {
254 DefIndices[i] = Count;
255 KillIndices[i] = ~0u;
Benjamin Kramer5d1bca82012-03-17 20:22:57 +0000256 KeepRegs.reset(i);
Craig Topperc0196b12014-04-14 00:51:57 +0000257 Classes[i] = nullptr;
Jakob Stoklund Olesen38ce8892012-02-23 01:15:26 +0000258 RegRefs.erase(i);
259 }
260
Evan Chengf128bdc2010-06-16 07:35:02 +0000261 if (!MO.isReg()) continue;
262 unsigned Reg = MO.getReg();
263 if (Reg == 0) continue;
264 if (!MO.isDef()) continue;
Sanjay Pateldc574ab2014-07-03 15:19:40 +0000265
266 // If we've already marked this reg as unchangeable, carry on.
267 if (KeepRegs.test(Reg)) continue;
268
Evan Chengf128bdc2010-06-16 07:35:02 +0000269 // Ignore two-addr defs.
270 if (MI->isRegTiedToUseOperand(i)) continue;
271
Sanjay Pateld26358e2014-08-06 15:58:15 +0000272 // For the reg itself and all subregs: update the def to current;
273 // reset the kill state, any restrictions, and references.
274 for (MCSubRegIterator SRI(Reg, TRI, true); SRI.isValid(); ++SRI) {
275 unsigned SubregReg = *SRI;
Evan Chengf128bdc2010-06-16 07:35:02 +0000276 DefIndices[SubregReg] = Count;
277 KillIndices[SubregReg] = ~0u;
Benjamin Kramer5d1bca82012-03-17 20:22:57 +0000278 KeepRegs.reset(SubregReg);
Craig Topperc0196b12014-04-14 00:51:57 +0000279 Classes[SubregReg] = nullptr;
Evan Chengf128bdc2010-06-16 07:35:02 +0000280 RegRefs.erase(SubregReg);
281 }
282 // Conservatively mark super-registers as unusable.
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000283 for (MCSuperRegIterator SR(Reg, TRI); SR.isValid(); ++SR)
284 Classes[*SR] = reinterpret_cast<TargetRegisterClass *>(-1);
David Goodwin83704852009-10-26 16:59:04 +0000285 }
286 }
287 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
288 MachineOperand &MO = MI->getOperand(i);
289 if (!MO.isReg()) continue;
290 unsigned Reg = MO.getReg();
291 if (Reg == 0) continue;
292 if (!MO.isUse()) continue;
293
Craig Topperc0196b12014-04-14 00:51:57 +0000294 const TargetRegisterClass *NewRC = nullptr;
David Goodwin83704852009-10-26 16:59:04 +0000295 if (i < MI->getDesc().getNumOperands())
Jakob Stoklund Olesen3c52f022012-05-07 22:10:26 +0000296 NewRC = TII->getRegClass(MI->getDesc(), i, TRI, MF);
David Goodwin83704852009-10-26 16:59:04 +0000297
298 // For now, only allow the register to be changed if its register
299 // class is consistent across all uses.
300 if (!Classes[Reg] && NewRC)
301 Classes[Reg] = NewRC;
302 else if (!NewRC || Classes[Reg] != NewRC)
303 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
304
305 RegRefs.insert(std::make_pair(Reg, &MO));
306
307 // It wasn't previously live but now it is, this is a kill.
Sanjay Pateld26358e2014-08-06 15:58:15 +0000308 // Repeat for all aliases.
309 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) {
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000310 unsigned AliasReg = *AI;
David Goodwin83704852009-10-26 16:59:04 +0000311 if (KillIndices[AliasReg] == ~0u) {
312 KillIndices[AliasReg] = Count;
313 DefIndices[AliasReg] = ~0u;
314 }
315 }
316 }
317}
318
Andrew Trick4b491872011-02-08 17:39:46 +0000319// Check all machine operands that reference the antidependent register and must
320// be replaced by NewReg. Return true if any of their parent instructions may
321// clobber the new register.
322//
323// Note: AntiDepReg may be referenced by a two-address instruction such that
324// it's use operand is tied to a def operand. We guard against the case in which
325// the two-address instruction also defines NewReg, as may happen with
326// pre/postincrement loads. In this case, both the use and def operands are in
327// RegRefs because the def is inserted by PrescanInstruction and not erased
Sanjay Patel99475192014-06-24 21:11:51 +0000328// during ScanInstruction. So checking for an instruction with definitions of
Andrew Trick4b491872011-02-08 17:39:46 +0000329// both NewReg and AntiDepReg covers it.
Andrew Trick82ae9a92010-11-02 18:16:45 +0000330bool
Andrew Trick4b491872011-02-08 17:39:46 +0000331CriticalAntiDepBreaker::isNewRegClobberedByRefs(RegRefIter RegRefBegin,
332 RegRefIter RegRefEnd,
333 unsigned NewReg)
Andrew Trick82ae9a92010-11-02 18:16:45 +0000334{
335 for (RegRefIter I = RegRefBegin; I != RegRefEnd; ++I ) {
Andrew Trick4b491872011-02-08 17:39:46 +0000336 MachineOperand *RefOper = I->second;
337
338 // Don't allow the instruction defining AntiDepReg to earlyclobber its
339 // operands, in case they may be assigned to NewReg. In this case antidep
340 // breaking must fail, but it's too rare to bother optimizing.
341 if (RefOper->isDef() && RefOper->isEarlyClobber())
Andrew Trick82ae9a92010-11-02 18:16:45 +0000342 return true;
Andrew Trick4b491872011-02-08 17:39:46 +0000343
Sanjay Patel99475192014-06-24 21:11:51 +0000344 // Handle cases in which this instruction defines NewReg.
Andrew Trick4b491872011-02-08 17:39:46 +0000345 MachineInstr *MI = RefOper->getParent();
346 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
347 const MachineOperand &CheckOper = MI->getOperand(i);
348
Jakob Stoklund Olesen38ce8892012-02-23 01:15:26 +0000349 if (CheckOper.isRegMask() && CheckOper.clobbersPhysReg(NewReg))
350 return true;
351
Andrew Trick4b491872011-02-08 17:39:46 +0000352 if (!CheckOper.isReg() || !CheckOper.isDef() ||
353 CheckOper.getReg() != NewReg)
354 continue;
355
356 // Don't allow the instruction to define NewReg and AntiDepReg.
357 // When AntiDepReg is renamed it will be an illegal op.
358 if (RefOper->isDef())
359 return true;
360
361 // Don't allow an instruction using AntiDepReg to be earlyclobbered by
Sanjay Patel99475192014-06-24 21:11:51 +0000362 // NewReg.
Andrew Trick4b491872011-02-08 17:39:46 +0000363 if (CheckOper.isEarlyClobber())
364 return true;
365
Sanjay Patel99475192014-06-24 21:11:51 +0000366 // Don't allow inline asm to define NewReg at all. Who knows what it's
Andrew Trick4b491872011-02-08 17:39:46 +0000367 // doing with it.
368 if (MI->isInlineAsm())
369 return true;
370 }
Andrew Trick82ae9a92010-11-02 18:16:45 +0000371 }
372 return false;
373}
374
Bill Schmidt2e4ae4e2013-01-28 18:36:58 +0000375unsigned CriticalAntiDepBreaker::
376findSuitableFreeRegister(RegRefIter RegRefBegin,
377 RegRefIter RegRefEnd,
378 unsigned AntiDepReg,
379 unsigned LastNewReg,
380 const TargetRegisterClass *RC,
Craig Topper72cde632013-07-03 05:16:59 +0000381 SmallVectorImpl<unsigned> &Forbid)
Jim Grosbacheb431da2010-01-06 16:48:02 +0000382{
Jakob Stoklund Olesenbdb55e02012-11-29 03:34:17 +0000383 ArrayRef<MCPhysReg> Order = RegClassInfo.getOrder(RC);
Jakob Stoklund Olesen4f5f84c2011-06-16 21:56:21 +0000384 for (unsigned i = 0; i != Order.size(); ++i) {
385 unsigned NewReg = Order[i];
David Goodwin83704852009-10-26 16:59:04 +0000386 // Don't replace a register with itself.
387 if (NewReg == AntiDepReg) continue;
388 // Don't replace a register with one that was recently used to repair
389 // an anti-dependence with this AntiDepReg, because that would
390 // re-introduce that anti-dependence.
391 if (NewReg == LastNewReg) continue;
Andrew Trick82ae9a92010-11-02 18:16:45 +0000392 // If any instructions that define AntiDepReg also define the NewReg, it's
393 // not suitable. For example, Instruction with multiple definitions can
394 // result in this condition.
Andrew Trick4b491872011-02-08 17:39:46 +0000395 if (isNewRegClobberedByRefs(RegRefBegin, RegRefEnd, NewReg)) continue;
David Goodwin83704852009-10-26 16:59:04 +0000396 // If NewReg is dead and NewReg's most recent def is not before
397 // AntiDepReg's kill, it's safe to replace AntiDepReg with NewReg.
Jim Grosbacheb431da2010-01-06 16:48:02 +0000398 assert(((KillIndices[AntiDepReg] == ~0u) != (DefIndices[AntiDepReg] == ~0u))
399 && "Kill and Def maps aren't consistent for AntiDepReg!");
400 assert(((KillIndices[NewReg] == ~0u) != (DefIndices[NewReg] == ~0u))
401 && "Kill and Def maps aren't consistent for NewReg!");
David Goodwin83704852009-10-26 16:59:04 +0000402 if (KillIndices[NewReg] != ~0u ||
403 Classes[NewReg] == reinterpret_cast<TargetRegisterClass *>(-1) ||
404 KillIndices[AntiDepReg] > DefIndices[NewReg])
405 continue;
Bill Schmidt2e4ae4e2013-01-28 18:36:58 +0000406 // If NewReg overlaps any of the forbidden registers, we can't use it.
407 bool Forbidden = false;
Craig Toppere1c1d362013-07-03 05:11:49 +0000408 for (SmallVectorImpl<unsigned>::iterator it = Forbid.begin(),
Bill Schmidt2e4ae4e2013-01-28 18:36:58 +0000409 ite = Forbid.end(); it != ite; ++it)
410 if (TRI->regsOverlap(NewReg, *it)) {
411 Forbidden = true;
412 break;
413 }
414 if (Forbidden) continue;
David Goodwin83704852009-10-26 16:59:04 +0000415 return NewReg;
416 }
417
418 // No registers are free and available!
419 return 0;
420}
421
422unsigned CriticalAntiDepBreaker::
Dan Gohman35bc4d42010-04-19 23:11:58 +0000423BreakAntiDependencies(const std::vector<SUnit>& SUnits,
424 MachineBasicBlock::iterator Begin,
425 MachineBasicBlock::iterator End,
Devang Patelf02a3762011-06-02 21:26:52 +0000426 unsigned InsertPosIndex,
427 DbgValueVector &DbgValues) {
David Goodwin83704852009-10-26 16:59:04 +0000428 // The code below assumes that there is at least one instruction,
429 // so just duck out immediately if the block is empty.
430 if (SUnits.empty()) return 0;
431
Jim Grosbach12ac8f02010-06-01 23:48:44 +0000432 // Keep a map of the MachineInstr*'s back to the SUnit representing them.
433 // This is used for updating debug information.
Andrew Trick46cc9a42012-02-22 06:08:11 +0000434 //
435 // FIXME: Replace this with the existing map in ScheduleDAGInstrs::MISUnitMap
Jim Grosbach12ac8f02010-06-01 23:48:44 +0000436 DenseMap<MachineInstr*,const SUnit*> MISUnitMap;
437
David Goodwin83704852009-10-26 16:59:04 +0000438 // Find the node at the bottom of the critical path.
Craig Topperc0196b12014-04-14 00:51:57 +0000439 const SUnit *Max = nullptr;
David Goodwin83704852009-10-26 16:59:04 +0000440 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
Dan Gohman35bc4d42010-04-19 23:11:58 +0000441 const SUnit *SU = &SUnits[i];
Jim Grosbach12ac8f02010-06-01 23:48:44 +0000442 MISUnitMap[SU->getInstr()] = SU;
David Goodwin83704852009-10-26 16:59:04 +0000443 if (!Max || SU->getDepth() + SU->Latency > Max->getDepth() + Max->Latency)
444 Max = SU;
445 }
446
447#ifndef NDEBUG
448 {
David Greene96b90532010-01-04 17:47:05 +0000449 DEBUG(dbgs() << "Critical path has total latency "
David Goodwin83704852009-10-26 16:59:04 +0000450 << (Max->getDepth() + Max->Latency) << "\n");
David Greene96b90532010-01-04 17:47:05 +0000451 DEBUG(dbgs() << "Available regs:");
David Goodwin83704852009-10-26 16:59:04 +0000452 for (unsigned Reg = 0; Reg < TRI->getNumRegs(); ++Reg) {
453 if (KillIndices[Reg] == ~0u)
David Greene96b90532010-01-04 17:47:05 +0000454 DEBUG(dbgs() << " " << TRI->getName(Reg));
David Goodwin83704852009-10-26 16:59:04 +0000455 }
David Greene96b90532010-01-04 17:47:05 +0000456 DEBUG(dbgs() << '\n');
David Goodwin83704852009-10-26 16:59:04 +0000457 }
458#endif
459
460 // Track progress along the critical path through the SUnit graph as we walk
461 // the instructions.
Dan Gohman35bc4d42010-04-19 23:11:58 +0000462 const SUnit *CriticalPathSU = Max;
David Goodwin83704852009-10-26 16:59:04 +0000463 MachineInstr *CriticalPathMI = CriticalPathSU->getInstr();
464
465 // Consider this pattern:
466 // A = ...
467 // ... = A
468 // A = ...
469 // ... = A
470 // A = ...
471 // ... = A
472 // A = ...
473 // ... = A
474 // There are three anti-dependencies here, and without special care,
475 // we'd break all of them using the same register:
476 // A = ...
477 // ... = A
478 // B = ...
479 // ... = B
480 // B = ...
481 // ... = B
482 // B = ...
483 // ... = B
484 // because at each anti-dependence, B is the first register that
485 // isn't A which is free. This re-introduces anti-dependencies
486 // at all but one of the original anti-dependencies that we were
487 // trying to break. To avoid this, keep track of the most recent
488 // register that each register was replaced with, avoid
489 // using it to repair an anti-dependence on the same register.
490 // This lets us produce this:
491 // A = ...
492 // ... = A
493 // B = ...
494 // ... = B
495 // C = ...
496 // ... = C
497 // B = ...
498 // ... = B
499 // This still has an anti-dependence on B, but at least it isn't on the
500 // original critical path.
501 //
502 // TODO: If we tracked more than one register here, we could potentially
503 // fix that remaining critical edge too. This is a little more involved,
504 // because unlike the most recent register, less recent registers should
505 // still be considered, though only if no other registers are available.
Bill Wendling51a9c0a2010-07-15 19:58:14 +0000506 std::vector<unsigned> LastNewReg(TRI->getNumRegs(), 0);
David Goodwin83704852009-10-26 16:59:04 +0000507
508 // Attempt to break anti-dependence edges on the critical path. Walk the
509 // instructions from the bottom up, tracking information about liveness
510 // as we go to help determine which registers are available.
511 unsigned Broken = 0;
512 unsigned Count = InsertPosIndex - 1;
Sanjay Patel99475192014-06-24 21:11:51 +0000513 for (MachineBasicBlock::iterator I = End, E = Begin; I != E; --Count) {
David Goodwin83704852009-10-26 16:59:04 +0000514 MachineInstr *MI = --I;
Sanjay Patelf3cfeef2014-08-20 18:03:00 +0000515 // Kill instructions can define registers but are really nops, and there
516 // might be a real definition earlier that needs to be paired with uses
517 // dominated by this kill.
518
519 // FIXME: It may be possible to remove the isKill() restriction once PR18663
520 // has been properly fixed. There can be value in processing kills as seen
521 // in the AggressiveAntiDepBreaker class.
522 if (MI->isDebugValue() || MI->isKill())
Dale Johannesen2061c842010-03-05 00:02:59 +0000523 continue;
David Goodwin83704852009-10-26 16:59:04 +0000524
525 // Check if this instruction has a dependence on the critical path that
526 // is an anti-dependence that we may be able to break. If it is, set
527 // AntiDepReg to the non-zero register associated with the anti-dependence.
528 //
529 // We limit our attention to the critical path as a heuristic to avoid
530 // breaking anti-dependence edges that aren't going to significantly
531 // impact the overall schedule. There are a limited number of registers
532 // and we want to save them for the important edges.
Jim Grosbach866b74b2010-05-14 21:20:46 +0000533 //
David Goodwin83704852009-10-26 16:59:04 +0000534 // TODO: Instructions with multiple defs could have multiple
535 // anti-dependencies. The current code here only knows how to break one
536 // edge per instruction. Note that we'd have to be able to break all of
537 // the anti-dependencies in an instruction in order to be effective.
538 unsigned AntiDepReg = 0;
539 if (MI == CriticalPathMI) {
Dan Gohman35bc4d42010-04-19 23:11:58 +0000540 if (const SDep *Edge = CriticalPathStep(CriticalPathSU)) {
541 const SUnit *NextSU = Edge->getSUnit();
David Goodwin83704852009-10-26 16:59:04 +0000542
543 // Only consider anti-dependence edges.
544 if (Edge->getKind() == SDep::Anti) {
545 AntiDepReg = Edge->getReg();
546 assert(AntiDepReg != 0 && "Anti-dependence on reg0?");
Jakob Stoklund Olesenf67bf3e2012-10-15 22:41:03 +0000547 if (!MRI.isAllocatable(AntiDepReg))
David Goodwin83704852009-10-26 16:59:04 +0000548 // Don't break anti-dependencies on non-allocatable registers.
549 AntiDepReg = 0;
Benjamin Kramer5d1bca82012-03-17 20:22:57 +0000550 else if (KeepRegs.test(AntiDepReg))
Sanjay Patel99475192014-06-24 21:11:51 +0000551 // Don't break anti-dependencies if a use down below requires
David Goodwin83704852009-10-26 16:59:04 +0000552 // this exact register.
553 AntiDepReg = 0;
554 else {
555 // If the SUnit has other dependencies on the SUnit that it
556 // anti-depends on, don't bother breaking the anti-dependency
557 // since those edges would prevent such units from being
558 // scheduled past each other regardless.
559 //
560 // Also, if there are dependencies on other SUnits with the
561 // same register as the anti-dependency, don't attempt to
562 // break it.
Dan Gohman35bc4d42010-04-19 23:11:58 +0000563 for (SUnit::const_pred_iterator P = CriticalPathSU->Preds.begin(),
David Goodwin83704852009-10-26 16:59:04 +0000564 PE = CriticalPathSU->Preds.end(); P != PE; ++P)
565 if (P->getSUnit() == NextSU ?
566 (P->getKind() != SDep::Anti || P->getReg() != AntiDepReg) :
567 (P->getKind() == SDep::Data && P->getReg() == AntiDepReg)) {
568 AntiDepReg = 0;
569 break;
570 }
571 }
572 }
573 CriticalPathSU = NextSU;
574 CriticalPathMI = CriticalPathSU->getInstr();
575 } else {
576 // We've reached the end of the critical path.
Craig Topperc0196b12014-04-14 00:51:57 +0000577 CriticalPathSU = nullptr;
578 CriticalPathMI = nullptr;
David Goodwin83704852009-10-26 16:59:04 +0000579 }
580 }
581
582 PrescanInstruction(MI);
583
Bill Schmidt2e4ae4e2013-01-28 18:36:58 +0000584 SmallVector<unsigned, 2> ForbidRegs;
585
Evan Chengf128bdc2010-06-16 07:35:02 +0000586 // If MI's defs have a special allocation requirement, don't allow
587 // any def registers to be changed. Also assume all registers
588 // defined in a call must not be changed (ABI).
Sanjay Patel99475192014-06-24 21:11:51 +0000589 if (MI->isCall() || MI->hasExtraDefRegAllocReq() || TII->isPredicated(MI))
David Goodwin83704852009-10-26 16:59:04 +0000590 // If this instruction's defs have special allocation requirement, don't
591 // break this anti-dependency.
592 AntiDepReg = 0;
593 else if (AntiDepReg) {
594 // If this instruction has a use of AntiDepReg, breaking it
Bill Schmidt2e4ae4e2013-01-28 18:36:58 +0000595 // is invalid. If the instruction defines other registers,
596 // save a list of them so that we don't pick a new register
597 // that overlaps any of them.
David Goodwin83704852009-10-26 16:59:04 +0000598 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
599 MachineOperand &MO = MI->getOperand(i);
600 if (!MO.isReg()) continue;
601 unsigned Reg = MO.getReg();
602 if (Reg == 0) continue;
Evan Chengf128bdc2010-06-16 07:35:02 +0000603 if (MO.isUse() && TRI->regsOverlap(AntiDepReg, Reg)) {
David Goodwin83704852009-10-26 16:59:04 +0000604 AntiDepReg = 0;
605 break;
606 }
Bill Schmidt2e4ae4e2013-01-28 18:36:58 +0000607 if (MO.isDef() && Reg != AntiDepReg)
608 ForbidRegs.push_back(Reg);
David Goodwin83704852009-10-26 16:59:04 +0000609 }
610 }
611
612 // Determine AntiDepReg's register class, if it is live and is
613 // consistently used within a single class.
Craig Topperc0196b12014-04-14 00:51:57 +0000614 const TargetRegisterClass *RC = AntiDepReg != 0 ? Classes[AntiDepReg]
615 : nullptr;
616 assert((AntiDepReg == 0 || RC != nullptr) &&
David Goodwin83704852009-10-26 16:59:04 +0000617 "Register should be live if it's causing an anti-dependence!");
618 if (RC == reinterpret_cast<TargetRegisterClass *>(-1))
619 AntiDepReg = 0;
620
Alp Tokercb402912014-01-24 17:20:08 +0000621 // Look for a suitable register to use to break the anti-dependence.
David Goodwin83704852009-10-26 16:59:04 +0000622 //
623 // TODO: Instead of picking the first free register, consider which might
624 // be the best.
625 if (AntiDepReg != 0) {
Andrew Trick82ae9a92010-11-02 18:16:45 +0000626 std::pair<std::multimap<unsigned, MachineOperand *>::iterator,
627 std::multimap<unsigned, MachineOperand *>::iterator>
628 Range = RegRefs.equal_range(AntiDepReg);
629 if (unsigned NewReg = findSuitableFreeRegister(Range.first, Range.second,
630 AntiDepReg,
David Goodwin83704852009-10-26 16:59:04 +0000631 LastNewReg[AntiDepReg],
Bill Schmidt2e4ae4e2013-01-28 18:36:58 +0000632 RC, ForbidRegs)) {
David Greene96b90532010-01-04 17:47:05 +0000633 DEBUG(dbgs() << "Breaking anti-dependence edge on "
David Goodwin83704852009-10-26 16:59:04 +0000634 << TRI->getName(AntiDepReg)
635 << " with " << RegRefs.count(AntiDepReg) << " references"
636 << " using " << TRI->getName(NewReg) << "!\n");
637
638 // Update the references to the old register to refer to the new
639 // register.
David Goodwin83704852009-10-26 16:59:04 +0000640 for (std::multimap<unsigned, MachineOperand *>::iterator
Jim Grosbach12ac8f02010-06-01 23:48:44 +0000641 Q = Range.first, QE = Range.second; Q != QE; ++Q) {
David Goodwin83704852009-10-26 16:59:04 +0000642 Q->second->setReg(NewReg);
Jim Grosbach12ac8f02010-06-01 23:48:44 +0000643 // If the SU for the instruction being updated has debug information
644 // related to the anti-dependency register, make sure to update that
645 // as well.
646 const SUnit *SU = MISUnitMap[Q->second->getParent()];
Jim Grosbach84854832010-06-02 15:29:36 +0000647 if (!SU) continue;
Devang Patelf02a3762011-06-02 21:26:52 +0000648 for (DbgValueVector::iterator DVI = DbgValues.begin(),
649 DVE = DbgValues.end(); DVI != DVE; ++DVI)
650 if (DVI->second == Q->second->getParent())
651 UpdateDbgValue(DVI->first, AntiDepReg, NewReg);
Jim Grosbach12ac8f02010-06-01 23:48:44 +0000652 }
David Goodwin83704852009-10-26 16:59:04 +0000653
654 // We just went back in time and modified history; the
Bob Wilsonc57c2202010-10-02 01:49:29 +0000655 // liveness information for the anti-dependence reg is now
David Goodwin83704852009-10-26 16:59:04 +0000656 // inconsistent. Set the state as if it were dead.
657 Classes[NewReg] = Classes[AntiDepReg];
658 DefIndices[NewReg] = DefIndices[AntiDepReg];
659 KillIndices[NewReg] = KillIndices[AntiDepReg];
660 assert(((KillIndices[NewReg] == ~0u) !=
661 (DefIndices[NewReg] == ~0u)) &&
662 "Kill and Def maps aren't consistent for NewReg!");
663
Craig Topperc0196b12014-04-14 00:51:57 +0000664 Classes[AntiDepReg] = nullptr;
David Goodwin83704852009-10-26 16:59:04 +0000665 DefIndices[AntiDepReg] = KillIndices[AntiDepReg];
666 KillIndices[AntiDepReg] = ~0u;
667 assert(((KillIndices[AntiDepReg] == ~0u) !=
668 (DefIndices[AntiDepReg] == ~0u)) &&
669 "Kill and Def maps aren't consistent for AntiDepReg!");
670
671 RegRefs.erase(AntiDepReg);
672 LastNewReg[AntiDepReg] = NewReg;
673 ++Broken;
674 }
675 }
676
677 ScanInstruction(MI, Count);
678 }
679
680 return Broken;
681}