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