LLVM 24.0.0git
AggressiveAntiDepBreaker.cpp
Go to the documentation of this file.
1//===- AggressiveAntiDepBreaker.cpp - Anti-dep breaker --------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the AggressiveAntiDepBreaker class, which
10// implements register anti-dependence breaking during post-RA
11// scheduling. It attempts to break all anti-dependencies within a
12// block.
13//
14//===----------------------------------------------------------------------===//
15
17#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/SmallSet.h"
31#include "llvm/MC/MCInstrDesc.h"
34#include "llvm/Support/Debug.h"
36#include <cassert>
37
38using namespace llvm;
39
40#define DEBUG_TYPE "post-RA-sched"
41
42// If DebugDiv > 0 then only break antidep with (ID % DebugDiv) == DebugMod
43static cl::opt<int>
44DebugDiv("agg-antidep-debugdiv",
45 cl::desc("Debug control for aggressive anti-dep breaker"),
47
48static cl::opt<int>
49DebugMod("agg-antidep-debugmod",
50 cl::desc("Debug control for aggressive anti-dep breaker"),
52
55 : NumTargetRegs(TargetRegs), GroupNodes(TargetRegs, 0),
56 GroupNodeIndices(TargetRegs, 0), KillIndices(TargetRegs, 0),
57 DefIndices(TargetRegs, 0) {
58 const unsigned BBSize = BB->size();
59 for (unsigned i = 0; i < NumTargetRegs; ++i) {
60 // Initialize all registers to be in their own group. Initially we
61 // assign the register to the same-indexed GroupNode.
62 GroupNodeIndices[i] = i;
63 // Initialize the indices to indicate that no registers are live.
64 KillIndices[i] = ~0u;
65 DefIndices[i] = BBSize;
66 }
67}
68
70 unsigned Node = GroupNodeIndices[Reg.id()];
71 while (GroupNodes[Node] != Node)
72 Node = GroupNodes[Node];
73
74 return Node;
75}
76
78 unsigned Group, std::vector<MCRegister> &Regs,
79 std::multimap<MCRegister, AggressiveAntiDepState::RegisterReference>
80 *RegRefs) {
81 for (unsigned Reg = 0; Reg != NumTargetRegs; ++Reg) {
82 if ((GetGroup(Reg) == Group) && (RegRefs->count(Reg) > 0))
83 Regs.push_back(Reg);
84 }
85}
86
88 assert(GroupNodes[0] == 0 && "GroupNode 0 not parent!");
89 assert(GroupNodeIndices[0] == 0 && "Reg 0 not in Group 0!");
90
91 // find group for each register
92 unsigned Group1 = GetGroup(Reg1);
93 unsigned Group2 = GetGroup(Reg2);
94
95 // if either group is 0, then that must become the parent
96 unsigned Parent = (Group1 == 0) ? Group1 : Group2;
97 unsigned Other = (Parent == Group1) ? Group2 : Group1;
98 GroupNodes.at(Other) = Parent;
99 return Parent;
100}
101
103 // Create a new GroupNode for Reg. Reg's existing GroupNode must
104 // stay as is because there could be other GroupNodes referring to
105 // it.
106 unsigned idx = GroupNodes.size();
107 GroupNodes.push_back(idx);
108 GroupNodeIndices[Reg.id()] = idx;
109 return idx;
110}
111
113 // KillIndex must be defined and DefIndex not defined for a register
114 // to be live.
115 return ((KillIndices[Reg.id()] != ~0u) && (DefIndices[Reg.id()] == ~0u));
116}
117
119 MachineFunction &MFi, const RegisterClassInfo &RCI,
121 : MF(MFi), MRI(MF.getRegInfo()), TII(MF.getSubtarget().getInstrInfo()),
122 TRI(MF.getSubtarget().getRegisterInfo()), RegClassInfo(RCI) {
123 /* Collect a bitset of all registers that are only broken if they
124 are on the critical path. */
125 for (const TargetRegisterClass *RC : CriticalPathRCs) {
126 BitVector CPSet = TRI->getAllocatableSet(MF, RC);
127 if (CriticalPathSet.none())
128 CriticalPathSet = CPSet;
129 else
130 CriticalPathSet |= CPSet;
131 }
132
133 LLVM_DEBUG(dbgs() << "AntiDep Critical-Path Registers:");
134 LLVM_DEBUG(for (unsigned r
135 : CriticalPathSet.set_bits()) dbgs()
136 << " " << printReg(r, TRI));
137 LLVM_DEBUG(dbgs() << '\n');
138}
139
143
145 assert(!State);
146 State = new AggressiveAntiDepState(TRI->getNumRegs(), BB);
147
148 std::vector<unsigned> &KillIndices = State->GetKillIndices();
149 std::vector<unsigned> &DefIndices = State->GetDefIndices();
150
151 // Compute the register units live out of the block: the live-ins of all
152 // successors, the pristine registers and, in a return block, the
153 // callee-saved registers.
154 LiveRegUnits LiveOuts(*TRI);
155 LiveOuts.addLiveOuts(*BB);
156 const BitVector &LiveOutUnits = LiveOuts.getBitVector();
157
158 // Mark the registers fully covered by live-out units as live, and don't
159 // allow renaming them. A super-register that merely overlaps a live-out
160 // register (e.g. a register tuple) is not live, and treating it as such would
161 // wrongly prevent its other sub-registers from being renamed.
162 for (unsigned R = 1, E = TRI->getNumRegs(); R != E; ++R) {
163 MCRegister Reg(R);
164 if (!all_of(TRI->regunits(Reg), [&](MCRegUnit Unit) {
165 return LiveOutUnits.test(static_cast<unsigned>(Unit));
166 }))
167 continue;
168 State->UnionGroups(Reg, 0);
169 KillIndices[Reg.id()] = BB->size();
170 DefIndices[Reg.id()] = ~0u;
171 }
172}
173
175 delete State;
176 State = nullptr;
177}
178
180 unsigned InsertPosIndex) {
181 assert(Count < InsertPosIndex && "Instruction index out of expected range!");
182
183 std::set<MCRegister> PassthruRegs;
184 GetPassthruRegs(MI, PassthruRegs);
185 PrescanInstruction(MI, Count, PassthruRegs);
186 ScanInstruction(MI, Count);
187
188 LLVM_DEBUG(dbgs() << "Observe: ");
189 LLVM_DEBUG(MI.dump());
190 LLVM_DEBUG(dbgs() << "\tRegs:");
191
192 std::vector<unsigned> &DefIndices = State->GetDefIndices();
193 for (unsigned Reg = 1; Reg != TRI->getNumRegs(); ++Reg) {
194 // If Reg is current live, then mark that it can't be renamed as
195 // we don't know the extent of its live-range anymore (now that it
196 // has been scheduled). If it is not live but was defined in the
197 // previous schedule region, then set its def index to the most
198 // conservative location (i.e. the beginning of the previous
199 // schedule region).
200 if (State->IsLive(Reg)) {
201 LLVM_DEBUG(if (State->GetGroup(Reg) != 0) dbgs()
202 << " " << printReg(Reg, TRI) << "=g" << State->GetGroup(Reg)
203 << "->g0(region live-out)");
204 State->UnionGroups(Reg, 0);
205 } else if ((DefIndices[Reg] < InsertPosIndex)
206 && (DefIndices[Reg] >= Count)) {
207 DefIndices[Reg] = Count;
208 }
209 }
210 LLVM_DEBUG(dbgs() << '\n');
211}
212
213bool AggressiveAntiDepBreaker::IsImplicitDefUse(MachineInstr &MI,
214 MachineOperand &MO) {
215 if (!MO.isReg() || !MO.isImplicit())
216 return false;
217
218 Register Reg = MO.getReg();
219 if (Reg == 0)
220 return false;
221
222 MachineOperand *Op = nullptr;
223 if (MO.isDef())
224 Op = MI.findRegisterUseOperand(Reg, /*TRI=*/nullptr, true);
225 else
226 Op = MI.findRegisterDefOperand(Reg, /*TRI=*/nullptr);
227
228 return(Op && Op->isImplicit());
229}
230
231void AggressiveAntiDepBreaker::GetPassthruRegs(
232 MachineInstr &MI, std::set<MCRegister> &PassthruRegs) {
233 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
234 MachineOperand &MO = MI.getOperand(i);
235 if (!MO.isReg()) continue;
236 if ((MO.isDef() && MI.isRegTiedToUseOperand(i)) ||
237 IsImplicitDefUse(MI, MO)) {
238 const Register Reg = MO.getReg();
239 for (MCPhysReg SubReg : TRI->subregs_inclusive(Reg))
240 PassthruRegs.insert(SubReg);
241 }
242 }
243}
244
245/// AntiDepEdges - Return in Edges the anti- and output- dependencies
246/// in SU that we want to consider for breaking.
247static void AntiDepEdges(const SUnit *SU, std::vector<const SDep *> &Edges) {
249 for (const SDep &Pred : SU->Preds) {
250 if ((Pred.getKind() == SDep::Anti) || (Pred.getKind() == SDep::Output)) {
251 if (RegSet.insert(Pred.getReg()).second)
252 Edges.push_back(&Pred);
253 }
254 }
255}
256
257/// CriticalPathStep - Return the next SUnit after SU on the bottom-up
258/// critical path.
259static const SUnit *CriticalPathStep(const SUnit *SU) {
260 const SDep *Next = nullptr;
261 unsigned NextDepth = 0;
262 // Find the predecessor edge with the greatest depth.
263 if (SU) {
264 for (const SDep &Pred : SU->Preds) {
265 const SUnit *PredSU = Pred.getSUnit();
266 unsigned PredLatency = Pred.getLatency();
267 unsigned PredTotalLatency = PredSU->getDepth() + PredLatency;
268 // In the case of a latency tie, prefer an anti-dependency edge over
269 // other types of edges.
270 if (NextDepth < PredTotalLatency ||
271 (NextDepth == PredTotalLatency && Pred.getKind() == SDep::Anti)) {
272 NextDepth = PredTotalLatency;
273 Next = &Pred;
274 }
275 }
276 }
277
278 return (Next) ? Next->getSUnit() : nullptr;
279}
280
281void AggressiveAntiDepBreaker::HandleLastUse(MCRegister Reg, unsigned KillIdx,
282 const char *tag,
283 const char *header,
284 const char *footer) {
285 std::vector<unsigned> &KillIndices = State->GetKillIndices();
286 std::vector<unsigned> &DefIndices = State->GetDefIndices();
287 std::multimap<MCRegister, AggressiveAntiDepState::RegisterReference>
288 &RegRefs = State->GetRegRefs();
289
290 // FIXME: We must leave subregisters of live super registers as live, so that
291 // we don't clear out the register tracking information for subregisters of
292 // super registers we're still tracking (and with which we're unioning
293 // subregister definitions).
294 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
295 if (TRI->isSuperRegister(Reg, *AI) && State->IsLive(*AI)) {
296 LLVM_DEBUG(if (!header && footer) dbgs() << footer);
297 return;
298 }
299
300 if (!State->IsLive(Reg)) {
301 KillIndices[Reg.id()] = KillIdx;
302 DefIndices[Reg.id()] = ~0u;
303 RegRefs.erase(Reg);
304 State->LeaveGroup(Reg);
305 LLVM_DEBUG(if (header) {
306 dbgs() << header << printReg(Reg, TRI);
307 header = nullptr;
308 });
309 LLVM_DEBUG(dbgs() << "->g" << State->GetGroup(Reg) << tag);
310 // Repeat for subregisters. Note that we only do this if the superregister
311 // was not live because otherwise, regardless whether we have an explicit
312 // use of the subregister, the subregister's contents are needed for the
313 // uses of the superregister.
314 for (MCPhysReg SubregReg : TRI->subregs(Reg)) {
315 if (!State->IsLive(SubregReg)) {
316 KillIndices[SubregReg] = KillIdx;
317 DefIndices[SubregReg] = ~0u;
318 RegRefs.erase(SubregReg);
319 State->LeaveGroup(SubregReg);
320 LLVM_DEBUG(if (header) {
321 dbgs() << header << printReg(Reg, TRI);
322 header = nullptr;
323 });
324 LLVM_DEBUG(dbgs() << " " << printReg(SubregReg, TRI) << "->g"
325 << State->GetGroup(SubregReg) << tag);
326 }
327 }
328 }
329
330 LLVM_DEBUG(if (!header && footer) dbgs() << footer);
331}
332
333void AggressiveAntiDepBreaker::PrescanInstruction(
334 MachineInstr &MI, unsigned Count,
335 const std::set<MCRegister> &PassthruRegs) {
336 std::vector<unsigned> &DefIndices = State->GetDefIndices();
337 std::multimap<MCRegister, AggressiveAntiDepState::RegisterReference>
338 &RegRefs = State->GetRegRefs();
339
340 // Handle dead defs by simulating a last-use of the register just
341 // after the def. A dead def can occur because the def is truly
342 // dead, or because only a subregister is live at the def. If we
343 // don't do this the dead def will be incorrectly merged into the
344 // previous def.
345 for (const MachineOperand &MO : MI.all_defs()) {
346 Register Reg = MO.getReg();
347 if (!Reg)
348 continue;
349
350 HandleLastUse(Reg.asMCReg(), Count + 1, "", "\tDead Def: ", "\n");
351 }
352
353 LLVM_DEBUG(dbgs() << "\tDef Groups:");
354 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
355 MachineOperand &MO = MI.getOperand(i);
356 if (!MO.isReg() || !MO.isDef()) continue;
357 Register Reg = MO.getReg();
358 if (!Reg)
359 continue;
360
361 LLVM_DEBUG(dbgs() << " " << printReg(Reg, TRI) << "=g"
362 << State->GetGroup(Reg));
363
364 // If MI's defs have a special allocation requirement, don't allow
365 // any def registers to be changed. Also assume all registers
366 // defined in a call must not be changed (ABI). Inline assembly may
367 // reference either system calls or the register directly. Skip it until we
368 // can tell user specified registers from compiler-specified.
369 if (MI.isCall() || MI.hasExtraDefRegAllocReq() || TII->isPredicated(MI) ||
370 MI.isInlineAsm()) {
371 LLVM_DEBUG(if (State->GetGroup(Reg) != 0) dbgs() << "->g0(alloc-req)");
372 State->UnionGroups(Reg, 0);
373 }
374
375 // Any aliased that are live at this point are completely or
376 // partially defined here, so group those aliases with Reg.
377 for (MCRegAliasIterator AI(Reg, TRI, false); AI.isValid(); ++AI) {
378 MCRegister AliasReg = *AI;
379 if (State->IsLive(AliasReg)) {
380 State->UnionGroups(Reg, AliasReg);
381 LLVM_DEBUG(dbgs() << "->g" << State->GetGroup(Reg) << "(via "
382 << printReg(AliasReg, TRI) << ")");
383 }
384 }
385
386 // Note register reference...
387 const TargetRegisterClass *RC = nullptr;
388 if (i < MI.getDesc().getNumOperands())
389 RC = TII->getRegClass(MI.getDesc(), i);
390 AggressiveAntiDepState::RegisterReference RR = { &MO, RC };
391 RegRefs.emplace(Reg.asMCReg(), RR);
392 }
393
394 LLVM_DEBUG(dbgs() << '\n');
395
396 // Scan the register defs for this instruction and update
397 // live-ranges.
398 for (const MachineOperand &MO : MI.all_defs()) {
399 Register Reg = MO.getReg();
400 if (!Reg)
401 continue;
402 // Ignore KILLs and passthru registers for liveness...
403 if (MI.isKill() || (PassthruRegs.count(Reg) != 0))
404 continue;
405
406 // Update def for Reg and aliases.
407 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) {
408 // We need to be careful here not to define already-live super registers.
409 // If the super register is already live, then this definition is not
410 // a definition of the whole super register (just a partial insertion
411 // into it). Earlier subregister definitions (which we've not yet visited
412 // because we're iterating bottom-up) need to be linked to the same group
413 // as this definition.
414 if (TRI->isSuperRegister(Reg, *AI) && State->IsLive(*AI))
415 continue;
416
417 DefIndices[(*AI).id()] = Count;
418 }
419 }
420}
421
422void AggressiveAntiDepBreaker::ScanInstruction(MachineInstr &MI,
423 unsigned Count) {
424 LLVM_DEBUG(dbgs() << "\tUse Groups:");
425 std::multimap<MCRegister, AggressiveAntiDepState::RegisterReference>
426 &RegRefs = State->GetRegRefs();
427
428 // If MI's uses have special allocation requirement, don't allow
429 // any use registers to be changed. Also assume all registers
430 // used in a call must not be changed (ABI).
431 // Inline Assembly register uses also cannot be safely changed.
432 // FIXME: The issue with predicated instruction is more complex. We are being
433 // conservatively here because the kill markers cannot be trusted after
434 // if-conversion:
435 // %r6 = LDR %sp, %reg0, 92, 14, %reg0; mem:LD4[FixedStack14]
436 // ...
437 // STR %r0, killed %r6, %reg0, 0, 0, %cpsr; mem:ST4[%395]
438 // %r6 = LDR %sp, %reg0, 100, 0, %cpsr; mem:LD4[FixedStack12]
439 // STR %r0, killed %r6, %reg0, 0, 14, %reg0; mem:ST4[%396](align=8)
440 //
441 // The first R6 kill is not really a kill since it's killed by a predicated
442 // instruction which may not be executed. The second R6 def may or may not
443 // re-define R6 so it's not safe to change it since the last R6 use cannot be
444 // changed.
445 bool Special = MI.isCall() || MI.hasExtraSrcRegAllocReq() ||
446 TII->isPredicated(MI) || MI.isInlineAsm();
447
448 // Scan the register uses for this instruction and update
449 // live-ranges, groups and RegRefs.
450 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
451 MachineOperand &MO = MI.getOperand(i);
452 if (!MO.isReg() || !MO.isUse()) continue;
453 Register Reg = MO.getReg();
454 if (!Reg)
455 continue;
456
457 LLVM_DEBUG(dbgs() << " " << printReg(Reg, TRI) << "=g"
458 << State->GetGroup(Reg));
459
460 // It wasn't previously live but now it is, this is a kill. Forget
461 // the previous live-range information and start a new live-range
462 // for the register.
463 HandleLastUse(Reg.asMCReg(), Count, "(last-use)");
464
465 if (Special) {
466 LLVM_DEBUG(if (State->GetGroup(Reg) != 0) dbgs() << "->g0(alloc-req)");
467 State->UnionGroups(Reg, 0);
468 }
469
470 // Note register reference...
471 const TargetRegisterClass *RC = nullptr;
472 if (i < MI.getDesc().getNumOperands())
473 RC = TII->getRegClass(MI.getDesc(), i);
474 AggressiveAntiDepState::RegisterReference RR = { &MO, RC };
475 RegRefs.emplace(Reg.asMCReg(), RR);
476 }
477
478 LLVM_DEBUG(dbgs() << '\n');
479
480 // Form a group of all defs and uses of a KILL instruction to ensure
481 // that all registers are renamed as a group.
482 if (MI.isKill()) {
483 LLVM_DEBUG(dbgs() << "\tKill Group:");
484
485 Register FirstReg;
486 for (const MachineOperand &MO : MI.operands()) {
487 if (!MO.isReg()) continue;
488 Register Reg = MO.getReg();
489 if (!Reg)
490 continue;
491
492 if (FirstReg) {
493 LLVM_DEBUG(dbgs() << "=" << printReg(Reg, TRI));
494 State->UnionGroups(FirstReg, Reg);
495 } else {
496 LLVM_DEBUG(dbgs() << " " << printReg(Reg, TRI));
497 FirstReg = Reg;
498 }
499 }
500
501 LLVM_DEBUG(dbgs() << "->g" << State->GetGroup(FirstReg) << '\n');
502 }
503}
504
505BitVector AggressiveAntiDepBreaker::GetRenameRegisters(MCRegister Reg) {
506 BitVector BV(TRI->getNumRegs(), false);
507 bool first = true;
508
509 // Check all references that need rewriting for Reg. For each, use
510 // the corresponding register class to narrow the set of registers
511 // that are appropriate for renaming.
512 for (const auto &Q : make_range(State->GetRegRefs().equal_range(Reg))) {
513 const TargetRegisterClass *RC = Q.second.RC;
514 if (!RC) continue;
515
516 BitVector RCBV = TRI->getAllocatableSet(MF, RC);
517 if (first) {
518 BV |= RCBV;
519 first = false;
520 } else {
521 BV &= RCBV;
522 }
523
524 LLVM_DEBUG(dbgs() << " " << TRI->getRegClassName(RC));
525 }
526
527 return BV;
528}
529
530bool AggressiveAntiDepBreaker::FindSuitableFreeRegisters(
531 MCRegister SuperReg, unsigned AntiDepGroupIndex,
532 RenameOrderType &RenameOrder, std::map<MCRegister, MCRegister> &RenameMap) {
533 std::vector<unsigned> &KillIndices = State->GetKillIndices();
534 std::vector<unsigned> &DefIndices = State->GetDefIndices();
535 std::multimap<MCRegister, AggressiveAntiDepState::RegisterReference>
536 &RegRefs = State->GetRegRefs();
537
538 // Collect all referenced registers in the same group as
539 // AntiDepReg. These all need to be renamed together if we are to
540 // break the anti-dependence.
541 std::vector<MCRegister> Regs;
542 State->GetGroupRegs(AntiDepGroupIndex, Regs, &RegRefs);
543 assert(!Regs.empty() && "Empty register group!");
544 if (Regs.empty())
545 return false;
546
547 // Collect the BitVector of registers that can be used to rename
548 // each register.
549 LLVM_DEBUG(dbgs() << "\tRename Candidates for Group g" << AntiDepGroupIndex
550 << ":\n");
551 std::map<MCRegister, BitVector> RenameRegisterMap;
552 for (MCRegister Reg : Regs) {
553 // If Reg has any references, then collect possible rename regs
554 if (RegRefs.count(Reg) > 0) {
555 LLVM_DEBUG(dbgs() << "\t\t" << printReg(Reg, TRI) << ":");
556
557 BitVector &BV = RenameRegisterMap[Reg];
558 assert(BV.empty());
559 BV = GetRenameRegisters(Reg);
560
561 LLVM_DEBUG({
562 dbgs() << " ::";
563 for (unsigned r : BV.set_bits())
564 dbgs() << " " << printReg(r, TRI);
565 dbgs() << "\n";
566 });
567 }
568 }
569
570 // All group registers should be a subreg of SuperReg.
571 for (MCRegister Reg : Regs) {
572 if (Reg == SuperReg) continue;
573 bool IsSub = TRI->isSubRegister(SuperReg, Reg);
574 // FIXME: remove this once PR18663 has been properly fixed. For now,
575 // return a conservative answer:
576 // assert(IsSub && "Expecting group subregister");
577 if (!IsSub)
578 return false;
579 }
580
581#ifndef NDEBUG
582 // If DebugDiv > 0 then only rename (renamecnt % DebugDiv) == DebugMod
583 if (DebugDiv > 0) {
584 static int renamecnt = 0;
585 if (renamecnt++ % DebugDiv != DebugMod)
586 return false;
587
588 dbgs() << "*** Performing rename " << printReg(SuperReg, TRI)
589 << " for debug ***\n";
590 }
591#endif
592
593 // Check each possible rename register for SuperReg in round-robin
594 // order. If that register is available, and the corresponding
595 // registers are available for the other group subregisters, then we
596 // can use those registers to rename.
597
598 // FIXME: Using getMinimalPhysRegClass is very conservative. We should
599 // check every use of the register and find the largest register class
600 // that can be used in all of them.
601 const TargetRegisterClass *SuperRC = TRI->getMinimalPhysRegClass(SuperReg);
602
603 ArrayRef<MCPhysReg> Order = RegClassInfo.getOrder(SuperRC);
604 if (Order.empty()) {
605 LLVM_DEBUG(dbgs() << "\tEmpty Super Regclass!!\n");
606 return false;
607 }
608
609 LLVM_DEBUG(dbgs() << "\tFind Registers:");
610
611 RenameOrder.insert(RenameOrderType::value_type(SuperRC, Order.size()));
612
613 unsigned OrigR = RenameOrder[SuperRC];
614 unsigned EndR = ((OrigR == Order.size()) ? 0 : OrigR);
615 unsigned R = OrigR;
616 do {
617 if (R == 0) R = Order.size();
618 --R;
619 const MCRegister NewSuperReg = Order[R];
620 // Don't consider non-allocatable registers
621 if (!MRI.isAllocatable(NewSuperReg)) continue;
622 // Don't replace a register with itself.
623 if (NewSuperReg == SuperReg) continue;
624
625 LLVM_DEBUG(dbgs() << " [" << printReg(NewSuperReg, TRI) << ':');
626 RenameMap.clear();
627
628 // For each referenced group register (which must be a SuperReg or
629 // a subregister of SuperReg), find the corresponding subregister
630 // of NewSuperReg and make sure it is free to be renamed.
631 for (MCRegister Reg : Regs) {
632 MCRegister NewReg;
633 if (Reg == SuperReg) {
634 NewReg = NewSuperReg;
635 } else {
636 unsigned NewSubRegIdx = TRI->getSubRegIndex(SuperReg, Reg);
637 if (NewSubRegIdx != 0)
638 NewReg = TRI->getSubReg(NewSuperReg, NewSubRegIdx);
639 }
640
641 LLVM_DEBUG(dbgs() << " " << printReg(NewReg, TRI));
642
643 // Check if Reg can be renamed to NewReg.
644 if (!RenameRegisterMap[Reg].test(NewReg.id())) {
645 LLVM_DEBUG(dbgs() << "(no rename)");
646 goto next_super_reg;
647 }
648
649 // If NewReg is dead and NewReg's most recent def is not before
650 // Regs's kill, it's safe to replace Reg with NewReg. We
651 // must also check all aliases of NewReg, because we can't define a
652 // register when any sub or super is already live.
653 if (State->IsLive(NewReg) ||
654 (KillIndices[Reg.id()] > DefIndices[NewReg.id()])) {
655 LLVM_DEBUG(dbgs() << "(live)");
656 goto next_super_reg;
657 } else {
658 bool found = false;
659 for (MCRegAliasIterator AI(NewReg, TRI, false); AI.isValid(); ++AI) {
660 MCRegister AliasReg = *AI;
661 if (State->IsLive(AliasReg) ||
662 (KillIndices[Reg.id()] > DefIndices[AliasReg.id()])) {
664 << "(alias " << printReg(AliasReg, TRI) << " live)");
665 found = true;
666 break;
667 }
668 }
669 if (found)
670 goto next_super_reg;
671 }
672
673 // We cannot rename 'Reg' to 'NewReg' if one of the uses of 'Reg' also
674 // defines 'NewReg' via an early-clobber operand.
675 for (const auto &Q : make_range(RegRefs.equal_range(Reg))) {
676 MachineInstr *UseMI = Q.second.Operand->getParent();
677 int Idx = UseMI->findRegisterDefOperandIdx(NewReg, TRI, false, true);
678 if (Idx == -1)
679 continue;
680
681 if (UseMI->getOperand(Idx).isEarlyClobber()) {
682 LLVM_DEBUG(dbgs() << "(ec)");
683 goto next_super_reg;
684 }
685 }
686
687 // Also, we cannot rename 'Reg' to 'NewReg' if the instruction defining
688 // 'Reg' is an early-clobber define and that instruction also uses
689 // 'NewReg'.
690 for (const auto &Q : make_range(RegRefs.equal_range(Reg))) {
691 if (!Q.second.Operand->isDef() || !Q.second.Operand->isEarlyClobber())
692 continue;
693
694 MachineInstr *DefMI = Q.second.Operand->getParent();
695 if (DefMI->readsRegister(NewReg, TRI)) {
696 LLVM_DEBUG(dbgs() << "(ec)");
697 goto next_super_reg;
698 }
699 }
700
701 // Record that 'Reg' can be renamed to 'NewReg'.
702 RenameMap.insert(std::make_pair(Reg, NewReg));
703 }
704
705 // If we fall-out here, then every register in the group can be
706 // renamed, as recorded in RenameMap.
707 RenameOrder.erase(SuperRC);
708 RenameOrder.insert(RenameOrderType::value_type(SuperRC, R));
709 LLVM_DEBUG(dbgs() << "]\n");
710 return true;
711
712 next_super_reg:
713 LLVM_DEBUG(dbgs() << ']');
714 } while (R != EndR);
715
716 LLVM_DEBUG(dbgs() << '\n');
717
718 // No registers are free and available!
719 return false;
720}
721
722/// BreakAntiDependencies - Identifiy anti-dependencies within the
723/// ScheduleDAG and break them by renaming registers.
725 const std::vector<SUnit> &SUnits,
728 unsigned InsertPosIndex,
729 DbgValueVector &DbgValues) {
730 std::vector<unsigned> &KillIndices = State->GetKillIndices();
731 std::vector<unsigned> &DefIndices = State->GetDefIndices();
732 std::multimap<MCRegister, AggressiveAntiDepState::RegisterReference>
733 &RegRefs = State->GetRegRefs();
734
735 // The code below assumes that there is at least one instruction,
736 // so just duck out immediately if the block is empty.
737 if (SUnits.empty()) return 0;
738
739 // For each regclass the next register to use for renaming.
740 RenameOrderType RenameOrder;
741
742 // ...need a map from MI to SUnit.
743 std::map<MachineInstr *, const SUnit *> MISUnitMap;
744 for (const SUnit &SU : SUnits)
745 MISUnitMap.insert(std::make_pair(SU.getInstr(), &SU));
746
747 // Track progress along the critical path through the SUnit graph as
748 // we walk the instructions. This is needed for regclasses that only
749 // break critical-path anti-dependencies.
750 const SUnit *CriticalPathSU = nullptr;
751 MachineInstr *CriticalPathMI = nullptr;
752 if (CriticalPathSet.any()) {
753 for (const SUnit &SU : SUnits) {
754 if (!CriticalPathSU ||
755 ((SU.getDepth() + SU.Latency) >
756 (CriticalPathSU->getDepth() + CriticalPathSU->Latency))) {
757 CriticalPathSU = &SU;
758 }
759 }
760 assert(CriticalPathSU && "Failed to find SUnit critical path");
761 CriticalPathMI = CriticalPathSU->getInstr();
762 }
763
764#ifndef NDEBUG
765 LLVM_DEBUG(dbgs() << "\n===== Aggressive anti-dependency breaking\n");
766 LLVM_DEBUG(dbgs() << "Available regs:");
767 for (unsigned Reg = 1; Reg < TRI->getNumRegs(); ++Reg) {
768 if (!State->IsLive(Reg))
769 LLVM_DEBUG(dbgs() << " " << printReg(Reg, TRI));
770 }
771 LLVM_DEBUG(dbgs() << '\n');
772#endif
773
774 // Attempt to break anti-dependence edges. Walk the instructions
775 // from the bottom up, tracking information about liveness as we go
776 // to help determine which registers are available.
777 unsigned Broken = 0;
778 unsigned Count = InsertPosIndex - 1;
779 for (MachineBasicBlock::iterator I = End, E = Begin;
780 I != E; --Count) {
781 MachineInstr &MI = *--I;
782
783 if (MI.isDebugOrPseudoInstr())
784 continue;
785
786 LLVM_DEBUG(dbgs() << "Anti: ");
787 LLVM_DEBUG(MI.dump());
788
789 std::set<MCRegister> PassthruRegs;
790 GetPassthruRegs(MI, PassthruRegs);
791
792 // Process the defs in MI...
793 PrescanInstruction(MI, Count, PassthruRegs);
794
795 // The dependence edges that represent anti- and output-
796 // dependencies that are candidates for breaking.
797 std::vector<const SDep *> Edges;
798 const SUnit *PathSU = MISUnitMap[&MI];
799 AntiDepEdges(PathSU, Edges);
800
801 // If MI is not on the critical path, then we don't rename
802 // registers in the CriticalPathSet.
803 BitVector *ExcludeRegs = nullptr;
804 if (&MI == CriticalPathMI) {
805 CriticalPathSU = CriticalPathStep(CriticalPathSU);
806 CriticalPathMI = (CriticalPathSU) ? CriticalPathSU->getInstr() : nullptr;
807 } else if (CriticalPathSet.any()) {
808 ExcludeRegs = &CriticalPathSet;
809 }
810
811 // Ignore KILL instructions (they form a group in ScanInstruction
812 // but don't cause any anti-dependence breaking themselves)
813 if (!MI.isKill()) {
814 // Attempt to break each anti-dependency...
815 for (const SDep *Edge : Edges) {
816 SUnit *NextSU = Edge->getSUnit();
817
818 if ((Edge->getKind() != SDep::Anti) &&
819 (Edge->getKind() != SDep::Output)) continue;
820
821 MCRegister AntiDepReg = Edge->getReg().asMCReg();
822 LLVM_DEBUG(dbgs() << "\tAntidep reg: " << printReg(AntiDepReg, TRI));
823 assert(AntiDepReg && "Anti-dependence on reg0?");
824
825 if (!MRI.isAllocatable(AntiDepReg)) {
826 // Don't break anti-dependencies on non-allocatable registers.
827 LLVM_DEBUG(dbgs() << " (non-allocatable)\n");
828 continue;
829 } else if (ExcludeRegs && ExcludeRegs->test(AntiDepReg.id())) {
830 // Don't break anti-dependencies for critical path registers
831 // if not on the critical path
832 LLVM_DEBUG(dbgs() << " (not critical-path)\n");
833 continue;
834 } else if (PassthruRegs.count(AntiDepReg) != 0) {
835 // If the anti-dep register liveness "passes-thru", then
836 // don't try to change it. It will be changed along with
837 // the use if required to break an earlier antidep.
838 LLVM_DEBUG(dbgs() << " (passthru)\n");
839 continue;
840 } else {
841 // No anti-dep breaking for implicit deps
842 MachineOperand *AntiDepOp =
843 MI.findRegisterDefOperand(AntiDepReg, /*TRI=*/nullptr);
844 assert(AntiDepOp && "Can't find index for defined register operand");
845 if (!AntiDepOp || AntiDepOp->isImplicit()) {
846 LLVM_DEBUG(dbgs() << " (implicit)\n");
847 continue;
848 }
849
850 // If the SUnit has other dependencies on the SUnit that
851 // it anti-depends on, don't bother breaking the
852 // anti-dependency since those edges would prevent such
853 // units from being scheduled past each other
854 // regardless.
855 //
856 // Also, if there are dependencies on other SUnits with the
857 // same register as the anti-dependency, don't attempt to
858 // break it.
859 for (const SDep &Pred : PathSU->Preds) {
860 if (Pred.getSUnit() == NextSU ? (Pred.getKind() != SDep::Anti ||
861 Pred.getReg() != AntiDepReg)
862 : (Pred.getKind() == SDep::Data &&
863 Pred.getReg() == AntiDepReg)) {
864 AntiDepReg = MCRegister();
865 break;
866 }
867 }
868 for (const SDep &Pred : PathSU->Preds) {
869 if ((Pred.getSUnit() == NextSU) && (Pred.getKind() != SDep::Anti) &&
870 (Pred.getKind() != SDep::Output)) {
871 LLVM_DEBUG(dbgs() << " (real dependency)\n");
872 AntiDepReg = MCRegister();
873 break;
874 } else if ((Pred.getSUnit() != NextSU) &&
875 (Pred.getKind() == SDep::Data) &&
876 (Pred.getReg() == AntiDepReg)) {
877 LLVM_DEBUG(dbgs() << " (other dependency)\n");
878 AntiDepReg = MCRegister();
879 break;
880 }
881 }
882
883 if (!AntiDepReg)
884 continue;
885 }
886
887 assert(AntiDepReg);
888
889 // Determine AntiDepReg's register group.
890 const unsigned GroupIndex = State->GetGroup(AntiDepReg);
891 if (GroupIndex == 0) {
892 LLVM_DEBUG(dbgs() << " (zero group)\n");
893 continue;
894 }
895
896 LLVM_DEBUG(dbgs() << '\n');
897
898 // Look for a suitable register to use to break the anti-dependence.
899 std::map<MCRegister, MCRegister> RenameMap;
900 if (FindSuitableFreeRegisters(AntiDepReg, GroupIndex, RenameOrder,
901 RenameMap)) {
902 LLVM_DEBUG(dbgs() << "\tBreaking anti-dependence edge on "
903 << printReg(AntiDepReg, TRI) << ":");
904
905 // Handle each group register...
906 for (const auto &P : RenameMap) {
907 MCRegister CurrReg = P.first;
908 MCRegister NewReg = P.second;
909
910 LLVM_DEBUG(dbgs() << " " << printReg(CurrReg, TRI) << "->"
911 << printReg(NewReg, TRI) << "("
912 << RegRefs.count(CurrReg) << " refs)");
913
914 // Update the references to the old register CurrReg to
915 // refer to the new register NewReg.
916 for (const auto &Q : make_range(RegRefs.equal_range(CurrReg))) {
917 Q.second.Operand->setReg(NewReg);
918 // If the SU for the instruction being updated has debug
919 // information related to the anti-dependency register, make
920 // sure to update that as well.
921 const SUnit *SU = MISUnitMap[Q.second.Operand->getParent()];
922 if (!SU) continue;
923 UpdateDbgValues(DbgValues, Q.second.Operand->getParent(),
924 AntiDepReg, NewReg);
925 }
926
927 // We just went back in time and modified history; the
928 // liveness information for CurrReg is now inconsistent. Set
929 // the state as if it were dead.
930 State->UnionGroups(NewReg, 0);
931 RegRefs.erase(NewReg);
932 DefIndices[NewReg.id()] = DefIndices[CurrReg.id()];
933 KillIndices[NewReg.id()] = KillIndices[CurrReg.id()];
934
935 State->UnionGroups(CurrReg, 0);
936 RegRefs.erase(CurrReg);
937 DefIndices[CurrReg.id()] = KillIndices[CurrReg.id()];
938 KillIndices[CurrReg.id()] = ~0u;
939 assert(((KillIndices[CurrReg.id()] == ~0u) !=
940 (DefIndices[CurrReg.id()] == ~0u)) &&
941 "Kill and Def maps aren't consistent for AntiDepReg!");
942 }
943
944 ++Broken;
945 LLVM_DEBUG(dbgs() << '\n');
946 }
947 }
948 }
949
950 ScanInstruction(MI, Count);
951 }
952
953 return Broken;
954}
955
957 MachineFunction &MFi, const RegisterClassInfo &RCI,
958 TargetSubtargetInfo::RegClassVector &CriticalPathRCs) {
959 return new AggressiveAntiDepBreaker(MFi, RCI, CriticalPathRCs);
960}
MachineInstrBuilder & UseMI
MachineInstrBuilder MachineInstrBuilder & DefMI
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static void AntiDepEdges(const SUnit *SU, std::vector< const SDep * > &Edges)
AntiDepEdges - Return in Edges the anti- and output- dependencies in SU that we want to consider for ...
static const SUnit * CriticalPathStep(const SUnit *SU)
CriticalPathStep - Return the next SUnit after SU on the bottom-up critical path.
static cl::opt< int > DebugDiv("agg-antidep-debugdiv", cl::desc("Debug control for aggressive anti-dep breaker"), cl::init(0), cl::Hidden)
static cl::opt< int > DebugMod("agg-antidep-debugmod", cl::desc("Debug control for aggressive anti-dep breaker"), cl::init(0), cl::Hidden)
IRTranslator LLVM IR MI
A set of register units.
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
modulo schedule test
#define P(N)
This file defines the SmallSet class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
void Observe(MachineInstr &MI, unsigned Count, unsigned InsertPosIndex) override
Update liveness information to account for the current instruction, which will not be scheduled.
void FinishBlock() override
Finish anti-dep breaking for a basic block.
unsigned BreakAntiDependencies(const std::vector< SUnit > &SUnits, MachineBasicBlock::iterator Begin, MachineBasicBlock::iterator End, unsigned InsertPosIndex, DbgValueVector &DbgValues) override
Identifiy anti-dependencies along the critical path of the ScheduleDAG and break them by renaming reg...
void StartBlock(MachineBasicBlock *BB) override
Initialize anti-dep breaking for a new basic block.
AggressiveAntiDepBreaker(MachineFunction &MFi, const RegisterClassInfo &RCI, TargetSubtargetInfo::RegClassVector &CriticalPathRCs)
Contains all the state necessary for anti-dep breaking.
AggressiveAntiDepState(const unsigned TargetRegs, MachineBasicBlock *BB)
void GetGroupRegs(unsigned Group, std::vector< MCRegister > &Regs, std::multimap< MCRegister, AggressiveAntiDepState::RegisterReference > *RegRefs)
bool IsLive(MCRegister Reg)
Return true if Reg is live.
unsigned UnionGroups(MCRegister Reg1, MCRegister Reg2)
This class works in conjunction with the post-RA scheduler to rename registers to break register anti...
void UpdateDbgValues(const DbgValueVector &DbgValues, MachineInstr *ParentMI, MCRegister OldReg, MCRegister NewReg)
Update all DBG_VALUE instructions that may be affected by the dependency breaker's update of ParentMI...
std::vector< std::pair< MachineInstr *, MachineInstr * > > DbgValueVector
size_t size() const
Get the array size.
Definition ArrayRef.h:141
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
bool test(unsigned Idx) const
Returns true if bit Idx is set.
Definition BitVector.h:483
iterator_range< const_set_bits_iterator > set_bits() const
Definition BitVector.h:160
bool empty() const
Returns whether there are no bits in this bitvector.
Definition BitVector.h:176
A set of register units used to track register liveness.
const BitVector & getBitVector() const
Return the internal bitvector representation of the set.
LLVM_ABI void addLiveOuts(const MachineBasicBlock &MBB)
Adds registers living out of block MBB.
Wrapper class representing physical registers. Should be passed by value.
Definition MCRegister.h:41
constexpr unsigned id() const
Definition MCRegister.h:82
MachineInstrBundleIterator< MachineInstr > iterator
Representation of each machine instruction.
const MachineBasicBlock * getParent() const
bool readsRegister(Register Reg, const TargetRegisterInfo *TRI) const
Return true if the MachineInstr reads the specified register.
const MachineOperand & getOperand(unsigned i) const
LLVM_ABI int findRegisterDefOperandIdx(Register Reg, const TargetRegisterInfo *TRI, bool isDead=false, bool Overlap=false) const
Returns the operand index that is a def of the specified register or -1 if it is not found.
MachineOperand class - Representation of each machine instruction operand.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
bool isEarlyClobber() const
Register getReg() const
getReg - Returns the register number.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
MCRegister asMCReg() const
Utility to check-convert this value to a MCRegister.
Definition Register.h:107
constexpr unsigned id() const
Definition Register.h:100
Scheduling dependency.
Definition ScheduleDAG.h:54
@ Output
A register output-dependence (aka WAW).
Definition ScheduleDAG.h:60
@ Anti
A register anti-dependence (aka WAR).
Definition ScheduleDAG.h:59
@ Data
Regular data dependence (aka true-dependence).
Definition ScheduleDAG.h:58
Scheduling unit. This is a node in the scheduling DAG.
unsigned short Latency
Node latency.
unsigned getDepth() const
Returns the depth of this node, which is the length of the maximum path up to any node which has no p...
SmallVector< SDep, 4 > Preds
All sunit predecessors.
MachineInstr * getInstr() const
Returns the representative MachineInstr for this SUnit.
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition SmallSet.h:134
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
SmallVectorImpl< const TargetRegisterClass * > RegClassVector
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
LLVM_ABI AntiDepBreaker * createAggressiveAntiDepBreaker(MachineFunction &MFi, const RegisterClassInfo &RCI, TargetSubtargetInfo::RegClassVector &CriticalPathRCs)
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
@ Other
Any other memory.
Definition ModRef.h:68
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Definition MCRegister.h:21
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
LLVM_ABI Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58