blob: 984e0135b8c647103af49e29e22ddcbf0bfcd2fd [file] [log] [blame]
David Goodwin2e7be612009-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 Goodwin4de099d2009-11-03 20:57:50 +000016#define DEBUG_TYPE "post-RA-sched"
David Goodwin2e7be612009-10-26 16:59:04 +000017#include "CriticalAntiDepBreaker.h"
18#include "llvm/CodeGen/MachineBasicBlock.h"
19#include "llvm/CodeGen/MachineFrameInfo.h"
20#include "llvm/Target/TargetMachine.h"
21#include "llvm/Target/TargetRegisterInfo.h"
22#include "llvm/Support/Debug.h"
23#include "llvm/Support/ErrorHandling.h"
24#include "llvm/Support/raw_ostream.h"
25
26using namespace llvm;
27
28CriticalAntiDepBreaker::
29CriticalAntiDepBreaker(MachineFunction& MFi) :
30 AntiDepBreaker(), MF(MFi),
31 MRI(MF.getRegInfo()),
32 TRI(MF.getTarget().getRegisterInfo()),
33 AllocatableSet(TRI->getAllocatableSet(MF))
34{
35}
36
37CriticalAntiDepBreaker::~CriticalAntiDepBreaker() {
38}
39
40void CriticalAntiDepBreaker::StartBlock(MachineBasicBlock *BB) {
41 // Clear out the register class data.
42 std::fill(Classes, array_endof(Classes),
43 static_cast<const TargetRegisterClass *>(0));
44
45 // Initialize the indices to indicate that no registers are live.
46 std::fill(KillIndices, array_endof(KillIndices), ~0u);
47 std::fill(DefIndices, array_endof(DefIndices), BB->size());
48
49 // Clear "do not change" set.
50 KeepRegs.clear();
51
52 bool IsReturnBlock = (!BB->empty() && BB->back().getDesc().isReturn());
53
54 // Determine the live-out physregs for this block.
55 if (IsReturnBlock) {
56 // In a return block, examine the function live-out regs.
57 for (MachineRegisterInfo::liveout_iterator I = MRI.liveout_begin(),
58 E = MRI.liveout_end(); I != E; ++I) {
59 unsigned Reg = *I;
60 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
61 KillIndices[Reg] = BB->size();
62 DefIndices[Reg] = ~0u;
63 // Repeat, for all aliases.
64 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
65 unsigned AliasReg = *Alias;
66 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
67 KillIndices[AliasReg] = BB->size();
68 DefIndices[AliasReg] = ~0u;
69 }
70 }
71 } else {
72 // In a non-return block, examine the live-in regs of all successors.
73 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
74 SE = BB->succ_end(); SI != SE; ++SI)
75 for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
76 E = (*SI)->livein_end(); I != E; ++I) {
77 unsigned Reg = *I;
78 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
79 KillIndices[Reg] = BB->size();
80 DefIndices[Reg] = ~0u;
81 // Repeat, for all aliases.
82 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
83 unsigned AliasReg = *Alias;
84 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
85 KillIndices[AliasReg] = BB->size();
86 DefIndices[AliasReg] = ~0u;
87 }
88 }
89 }
90
91 // Mark live-out callee-saved registers. In a return block this is
92 // all callee-saved registers. In non-return this is any
93 // callee-saved register that is not saved in the prolog.
94 const MachineFrameInfo *MFI = MF.getFrameInfo();
95 BitVector Pristine = MFI->getPristineRegs(BB);
96 for (const unsigned *I = TRI->getCalleeSavedRegs(); *I; ++I) {
97 unsigned Reg = *I;
98 if (!IsReturnBlock && !Pristine.test(Reg)) continue;
99 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
100 KillIndices[Reg] = BB->size();
101 DefIndices[Reg] = ~0u;
102 // Repeat, for all aliases.
103 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
104 unsigned AliasReg = *Alias;
105 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
106 KillIndices[AliasReg] = BB->size();
107 DefIndices[AliasReg] = ~0u;
108 }
109 }
110}
111
112void CriticalAntiDepBreaker::FinishBlock() {
113 RegRefs.clear();
114 KeepRegs.clear();
115}
116
117void CriticalAntiDepBreaker::Observe(MachineInstr *MI, unsigned Count,
118 unsigned InsertPosIndex) {
119 assert(Count < InsertPosIndex && "Instruction index out of expected range!");
120
121 // Any register which was defined within the previous scheduling region
122 // may have been rescheduled and its lifetime may overlap with registers
123 // in ways not reflected in our current liveness state. For each such
124 // register, adjust the liveness state to be conservatively correct.
125 for (unsigned Reg = 0; Reg != TargetRegisterInfo::FirstVirtualRegister; ++Reg)
126 if (DefIndices[Reg] < InsertPosIndex && DefIndices[Reg] >= Count) {
127 assert(KillIndices[Reg] == ~0u && "Clobbered register is live!");
128 // Mark this register to be non-renamable.
129 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
130 // Move the def index to the end of the previous region, to reflect
131 // that the def could theoretically have been scheduled at the end.
132 DefIndices[Reg] = InsertPosIndex;
133 }
134
135 PrescanInstruction(MI);
136 ScanInstruction(MI, Count);
137}
138
139/// CriticalPathStep - Return the next SUnit after SU on the bottom-up
140/// critical path.
141static SDep *CriticalPathStep(SUnit *SU) {
142 SDep *Next = 0;
143 unsigned NextDepth = 0;
144 // Find the predecessor edge with the greatest depth.
145 for (SUnit::pred_iterator P = SU->Preds.begin(), PE = SU->Preds.end();
146 P != PE; ++P) {
147 SUnit *PredSU = P->getSUnit();
148 unsigned PredLatency = P->getLatency();
149 unsigned PredTotalLatency = PredSU->getDepth() + PredLatency;
150 // In the case of a latency tie, prefer an anti-dependency edge over
151 // other types of edges.
152 if (NextDepth < PredTotalLatency ||
153 (NextDepth == PredTotalLatency && P->getKind() == SDep::Anti)) {
154 NextDepth = PredTotalLatency;
155 Next = &*P;
156 }
157 }
158 return Next;
159}
160
161void CriticalAntiDepBreaker::PrescanInstruction(MachineInstr *MI) {
162 // Scan the register operands for this instruction and update
163 // Classes and RegRefs.
164 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
165 MachineOperand &MO = MI->getOperand(i);
166 if (!MO.isReg()) continue;
167 unsigned Reg = MO.getReg();
168 if (Reg == 0) continue;
169 const TargetRegisterClass *NewRC = 0;
170
171 if (i < MI->getDesc().getNumOperands())
172 NewRC = MI->getDesc().OpInfo[i].getRegClass(TRI);
173
174 // For now, only allow the register to be changed if its register
175 // class is consistent across all uses.
176 if (!Classes[Reg] && NewRC)
177 Classes[Reg] = NewRC;
178 else if (!NewRC || Classes[Reg] != NewRC)
179 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
180
181 // Now check for aliases.
182 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
183 // If an alias of the reg is used during the live range, give up.
184 // Note that this allows us to skip checking if AntiDepReg
185 // overlaps with any of the aliases, among other things.
186 unsigned AliasReg = *Alias;
187 if (Classes[AliasReg]) {
188 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
189 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
190 }
191 }
192
193 // If we're still willing to consider this register, note the reference.
194 if (Classes[Reg] != reinterpret_cast<TargetRegisterClass *>(-1))
195 RegRefs.insert(std::make_pair(Reg, &MO));
196
197 // It's not safe to change register allocation for source operands of
198 // that have special allocation requirements.
199 if (MO.isUse() && MI->getDesc().hasExtraSrcRegAllocReq()) {
200 if (KeepRegs.insert(Reg)) {
201 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
202 *Subreg; ++Subreg)
203 KeepRegs.insert(*Subreg);
204 }
205 }
206 }
207}
208
209void CriticalAntiDepBreaker::ScanInstruction(MachineInstr *MI,
210 unsigned Count) {
211 // Update liveness.
212 // Proceding upwards, registers that are defed but not used in this
213 // instruction are now dead.
214 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
215 MachineOperand &MO = MI->getOperand(i);
216 if (!MO.isReg()) continue;
217 unsigned Reg = MO.getReg();
218 if (Reg == 0) continue;
219 if (!MO.isDef()) continue;
220 // Ignore two-addr defs.
221 if (MI->isRegTiedToUseOperand(i)) continue;
222
223 DefIndices[Reg] = Count;
224 KillIndices[Reg] = ~0u;
225 assert(((KillIndices[Reg] == ~0u) !=
226 (DefIndices[Reg] == ~0u)) &&
227 "Kill and Def maps aren't consistent for Reg!");
228 KeepRegs.erase(Reg);
229 Classes[Reg] = 0;
230 RegRefs.erase(Reg);
231 // Repeat, for all subregs.
232 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
233 *Subreg; ++Subreg) {
234 unsigned SubregReg = *Subreg;
235 DefIndices[SubregReg] = Count;
236 KillIndices[SubregReg] = ~0u;
237 KeepRegs.erase(SubregReg);
238 Classes[SubregReg] = 0;
239 RegRefs.erase(SubregReg);
240 }
241 // Conservatively mark super-registers as unusable.
242 for (const unsigned *Super = TRI->getSuperRegisters(Reg);
243 *Super; ++Super) {
244 unsigned SuperReg = *Super;
245 Classes[SuperReg] = reinterpret_cast<TargetRegisterClass *>(-1);
246 }
247 }
248 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
249 MachineOperand &MO = MI->getOperand(i);
250 if (!MO.isReg()) continue;
251 unsigned Reg = MO.getReg();
252 if (Reg == 0) continue;
253 if (!MO.isUse()) continue;
254
255 const TargetRegisterClass *NewRC = 0;
256 if (i < MI->getDesc().getNumOperands())
257 NewRC = MI->getDesc().OpInfo[i].getRegClass(TRI);
258
259 // For now, only allow the register to be changed if its register
260 // class is consistent across all uses.
261 if (!Classes[Reg] && NewRC)
262 Classes[Reg] = NewRC;
263 else if (!NewRC || Classes[Reg] != NewRC)
264 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
265
266 RegRefs.insert(std::make_pair(Reg, &MO));
267
268 // It wasn't previously live but now it is, this is a kill.
269 if (KillIndices[Reg] == ~0u) {
270 KillIndices[Reg] = Count;
271 DefIndices[Reg] = ~0u;
272 assert(((KillIndices[Reg] == ~0u) !=
273 (DefIndices[Reg] == ~0u)) &&
274 "Kill and Def maps aren't consistent for Reg!");
275 }
276 // Repeat, for all aliases.
277 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
278 unsigned AliasReg = *Alias;
279 if (KillIndices[AliasReg] == ~0u) {
280 KillIndices[AliasReg] = Count;
281 DefIndices[AliasReg] = ~0u;
282 }
283 }
284 }
285}
286
287unsigned
288CriticalAntiDepBreaker::findSuitableFreeRegister(unsigned AntiDepReg,
289 unsigned LastNewReg,
290 const TargetRegisterClass *RC) {
291 for (TargetRegisterClass::iterator R = RC->allocation_order_begin(MF),
292 RE = RC->allocation_order_end(MF); R != RE; ++R) {
293 unsigned NewReg = *R;
294 // Don't replace a register with itself.
295 if (NewReg == AntiDepReg) continue;
296 // Don't replace a register with one that was recently used to repair
297 // an anti-dependence with this AntiDepReg, because that would
298 // re-introduce that anti-dependence.
299 if (NewReg == LastNewReg) continue;
300 // If NewReg is dead and NewReg's most recent def is not before
301 // AntiDepReg's kill, it's safe to replace AntiDepReg with NewReg.
302 assert(((KillIndices[AntiDepReg] == ~0u) != (DefIndices[AntiDepReg] == ~0u)) &&
303 "Kill and Def maps aren't consistent for AntiDepReg!");
304 assert(((KillIndices[NewReg] == ~0u) != (DefIndices[NewReg] == ~0u)) &&
305 "Kill and Def maps aren't consistent for NewReg!");
306 if (KillIndices[NewReg] != ~0u ||
307 Classes[NewReg] == reinterpret_cast<TargetRegisterClass *>(-1) ||
308 KillIndices[AntiDepReg] > DefIndices[NewReg])
309 continue;
310 return NewReg;
311 }
312
313 // No registers are free and available!
314 return 0;
315}
316
317unsigned CriticalAntiDepBreaker::
318BreakAntiDependencies(std::vector<SUnit>& SUnits,
David Goodwin4de099d2009-11-03 20:57:50 +0000319 CandidateMap& Candidates,
David Goodwin2e7be612009-10-26 16:59:04 +0000320 MachineBasicBlock::iterator& Begin,
321 MachineBasicBlock::iterator& End,
322 unsigned InsertPosIndex) {
323 // The code below assumes that there is at least one instruction,
324 // so just duck out immediately if the block is empty.
325 if (SUnits.empty()) return 0;
326
327 // Find the node at the bottom of the critical path.
328 SUnit *Max = 0;
329 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
330 SUnit *SU = &SUnits[i];
331 if (!Max || SU->getDepth() + SU->Latency > Max->getDepth() + Max->Latency)
332 Max = SU;
333 }
334
335#ifndef NDEBUG
336 {
337 DEBUG(errs() << "Critical path has total latency "
338 << (Max->getDepth() + Max->Latency) << "\n");
339 DEBUG(errs() << "Available regs:");
340 for (unsigned Reg = 0; Reg < TRI->getNumRegs(); ++Reg) {
341 if (KillIndices[Reg] == ~0u)
342 DEBUG(errs() << " " << TRI->getName(Reg));
343 }
344 DEBUG(errs() << '\n');
345 }
346#endif
347
348 // Track progress along the critical path through the SUnit graph as we walk
349 // the instructions.
350 SUnit *CriticalPathSU = Max;
351 MachineInstr *CriticalPathMI = CriticalPathSU->getInstr();
352
353 // Consider this pattern:
354 // A = ...
355 // ... = A
356 // A = ...
357 // ... = A
358 // A = ...
359 // ... = A
360 // A = ...
361 // ... = A
362 // There are three anti-dependencies here, and without special care,
363 // we'd break all of them using the same register:
364 // A = ...
365 // ... = A
366 // B = ...
367 // ... = B
368 // B = ...
369 // ... = B
370 // B = ...
371 // ... = B
372 // because at each anti-dependence, B is the first register that
373 // isn't A which is free. This re-introduces anti-dependencies
374 // at all but one of the original anti-dependencies that we were
375 // trying to break. To avoid this, keep track of the most recent
376 // register that each register was replaced with, avoid
377 // using it to repair an anti-dependence on the same register.
378 // This lets us produce this:
379 // A = ...
380 // ... = A
381 // B = ...
382 // ... = B
383 // C = ...
384 // ... = C
385 // B = ...
386 // ... = B
387 // This still has an anti-dependence on B, but at least it isn't on the
388 // original critical path.
389 //
390 // TODO: If we tracked more than one register here, we could potentially
391 // fix that remaining critical edge too. This is a little more involved,
392 // because unlike the most recent register, less recent registers should
393 // still be considered, though only if no other registers are available.
394 unsigned LastNewReg[TargetRegisterInfo::FirstVirtualRegister] = {};
395
396 // Attempt to break anti-dependence edges on the critical path. Walk the
397 // instructions from the bottom up, tracking information about liveness
398 // as we go to help determine which registers are available.
399 unsigned Broken = 0;
400 unsigned Count = InsertPosIndex - 1;
401 for (MachineBasicBlock::iterator I = End, E = Begin;
402 I != E; --Count) {
403 MachineInstr *MI = --I;
404
405 // Check if this instruction has a dependence on the critical path that
406 // is an anti-dependence that we may be able to break. If it is, set
407 // AntiDepReg to the non-zero register associated with the anti-dependence.
408 //
409 // We limit our attention to the critical path as a heuristic to avoid
410 // breaking anti-dependence edges that aren't going to significantly
411 // impact the overall schedule. There are a limited number of registers
412 // and we want to save them for the important edges.
413 //
414 // TODO: Instructions with multiple defs could have multiple
415 // anti-dependencies. The current code here only knows how to break one
416 // edge per instruction. Note that we'd have to be able to break all of
417 // the anti-dependencies in an instruction in order to be effective.
418 unsigned AntiDepReg = 0;
419 if (MI == CriticalPathMI) {
420 if (SDep *Edge = CriticalPathStep(CriticalPathSU)) {
421 SUnit *NextSU = Edge->getSUnit();
422
423 // Only consider anti-dependence edges.
424 if (Edge->getKind() == SDep::Anti) {
425 AntiDepReg = Edge->getReg();
426 assert(AntiDepReg != 0 && "Anti-dependence on reg0?");
427 if (!AllocatableSet.test(AntiDepReg))
428 // Don't break anti-dependencies on non-allocatable registers.
429 AntiDepReg = 0;
430 else if (KeepRegs.count(AntiDepReg))
431 // Don't break anti-dependencies if an use down below requires
432 // this exact register.
433 AntiDepReg = 0;
434 else {
435 // If the SUnit has other dependencies on the SUnit that it
436 // anti-depends on, don't bother breaking the anti-dependency
437 // since those edges would prevent such units from being
438 // scheduled past each other regardless.
439 //
440 // Also, if there are dependencies on other SUnits with the
441 // same register as the anti-dependency, don't attempt to
442 // break it.
443 for (SUnit::pred_iterator P = CriticalPathSU->Preds.begin(),
444 PE = CriticalPathSU->Preds.end(); P != PE; ++P)
445 if (P->getSUnit() == NextSU ?
446 (P->getKind() != SDep::Anti || P->getReg() != AntiDepReg) :
447 (P->getKind() == SDep::Data && P->getReg() == AntiDepReg)) {
448 AntiDepReg = 0;
449 break;
450 }
451 }
452 }
453 CriticalPathSU = NextSU;
454 CriticalPathMI = CriticalPathSU->getInstr();
455 } else {
456 // We've reached the end of the critical path.
457 CriticalPathSU = 0;
458 CriticalPathMI = 0;
459 }
460 }
461
462 PrescanInstruction(MI);
463
464 if (MI->getDesc().hasExtraDefRegAllocReq())
465 // If this instruction's defs have special allocation requirement, don't
466 // break this anti-dependency.
467 AntiDepReg = 0;
468 else if (AntiDepReg) {
469 // If this instruction has a use of AntiDepReg, breaking it
470 // is invalid.
471 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
472 MachineOperand &MO = MI->getOperand(i);
473 if (!MO.isReg()) continue;
474 unsigned Reg = MO.getReg();
475 if (Reg == 0) continue;
476 if (MO.isUse() && AntiDepReg == Reg) {
477 AntiDepReg = 0;
478 break;
479 }
480 }
481 }
482
483 // Determine AntiDepReg's register class, if it is live and is
484 // consistently used within a single class.
485 const TargetRegisterClass *RC = AntiDepReg != 0 ? Classes[AntiDepReg] : 0;
486 assert((AntiDepReg == 0 || RC != NULL) &&
487 "Register should be live if it's causing an anti-dependence!");
488 if (RC == reinterpret_cast<TargetRegisterClass *>(-1))
489 AntiDepReg = 0;
490
491 // Look for a suitable register to use to break the anti-depenence.
492 //
493 // TODO: Instead of picking the first free register, consider which might
494 // be the best.
495 if (AntiDepReg != 0) {
496 if (unsigned NewReg = findSuitableFreeRegister(AntiDepReg,
497 LastNewReg[AntiDepReg],
498 RC)) {
499 DEBUG(errs() << "Breaking anti-dependence edge on "
500 << TRI->getName(AntiDepReg)
501 << " with " << RegRefs.count(AntiDepReg) << " references"
502 << " using " << TRI->getName(NewReg) << "!\n");
503
504 // Update the references to the old register to refer to the new
505 // register.
506 std::pair<std::multimap<unsigned, MachineOperand *>::iterator,
507 std::multimap<unsigned, MachineOperand *>::iterator>
508 Range = RegRefs.equal_range(AntiDepReg);
509 for (std::multimap<unsigned, MachineOperand *>::iterator
510 Q = Range.first, QE = Range.second; Q != QE; ++Q)
511 Q->second->setReg(NewReg);
512
513 // We just went back in time and modified history; the
514 // liveness information for the anti-depenence reg is now
515 // inconsistent. Set the state as if it were dead.
516 Classes[NewReg] = Classes[AntiDepReg];
517 DefIndices[NewReg] = DefIndices[AntiDepReg];
518 KillIndices[NewReg] = KillIndices[AntiDepReg];
519 assert(((KillIndices[NewReg] == ~0u) !=
520 (DefIndices[NewReg] == ~0u)) &&
521 "Kill and Def maps aren't consistent for NewReg!");
522
523 Classes[AntiDepReg] = 0;
524 DefIndices[AntiDepReg] = KillIndices[AntiDepReg];
525 KillIndices[AntiDepReg] = ~0u;
526 assert(((KillIndices[AntiDepReg] == ~0u) !=
527 (DefIndices[AntiDepReg] == ~0u)) &&
528 "Kill and Def maps aren't consistent for AntiDepReg!");
529
530 RegRefs.erase(AntiDepReg);
531 LastNewReg[AntiDepReg] = NewReg;
532 ++Broken;
533 }
534 }
535
536 ScanInstruction(MI, Count);
537 }
538
539 return Broken;
540}