1 //===-- lib/Codegen/MachineRegisterInfo.cpp -------------------------------===// 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 // Implementation of the MachineRegisterInfo class. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/CodeGen/MachineRegisterInfo.h" 15 #include "llvm/CodeGen/MachineInstrBuilder.h" 16 #include "llvm/IR/Function.h" 17 #include "llvm/Support/raw_os_ostream.h" 18 #include "llvm/Target/TargetInstrInfo.h" 19 #include "llvm/Target/TargetMachine.h" 20 #include "llvm/Target/TargetSubtargetInfo.h" 21 22 using namespace llvm; 23 24 static cl::opt<bool> EnableSubRegLiveness("enable-subreg-liveness", cl::Hidden, 25 cl::init(true), cl::desc("Enable subregister liveness tracking.")); 26 27 // Pin the vtable to this file. 28 void MachineRegisterInfo::Delegate::anchor() {} 29 30 MachineRegisterInfo::MachineRegisterInfo(MachineFunction *MF) 31 : MF(MF), TheDelegate(nullptr), 32 TracksSubRegLiveness(MF->getSubtarget().enableSubRegLiveness() && 33 EnableSubRegLiveness) { 34 unsigned NumRegs = getTargetRegisterInfo()->getNumRegs(); 35 VRegInfo.reserve(256); 36 RegAllocHints.reserve(256); 37 UsedPhysRegMask.resize(NumRegs); 38 PhysRegUseDefLists.reset(new MachineOperand*[NumRegs]()); 39 } 40 41 /// setRegClass - Set the register class of the specified virtual register. 42 /// 43 void 44 MachineRegisterInfo::setRegClass(unsigned Reg, const TargetRegisterClass *RC) { 45 assert(RC && RC->isAllocatable() && "Invalid RC for virtual register"); 46 VRegInfo[Reg].first = RC; 47 } 48 49 void MachineRegisterInfo::setRegBank(unsigned Reg, 50 const RegisterBank &RegBank) { 51 VRegInfo[Reg].first = &RegBank; 52 } 53 54 const TargetRegisterClass * 55 MachineRegisterInfo::constrainRegClass(unsigned Reg, 56 const TargetRegisterClass *RC, 57 unsigned MinNumRegs) { 58 const TargetRegisterClass *OldRC = getRegClass(Reg); 59 if (OldRC == RC) 60 return RC; 61 const TargetRegisterClass *NewRC = 62 getTargetRegisterInfo()->getCommonSubClass(OldRC, RC); 63 if (!NewRC || NewRC == OldRC) 64 return NewRC; 65 if (NewRC->getNumRegs() < MinNumRegs) 66 return nullptr; 67 setRegClass(Reg, NewRC); 68 return NewRC; 69 } 70 71 bool 72 MachineRegisterInfo::recomputeRegClass(unsigned Reg) { 73 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo(); 74 const TargetRegisterClass *OldRC = getRegClass(Reg); 75 const TargetRegisterClass *NewRC = 76 getTargetRegisterInfo()->getLargestLegalSuperClass(OldRC, *MF); 77 78 // Stop early if there is no room to grow. 79 if (NewRC == OldRC) 80 return false; 81 82 // Accumulate constraints from all uses. 83 for (MachineOperand &MO : reg_nodbg_operands(Reg)) { 84 // Apply the effect of the given operand to NewRC. 85 MachineInstr *MI = MO.getParent(); 86 unsigned OpNo = &MO - &MI->getOperand(0); 87 NewRC = MI->getRegClassConstraintEffect(OpNo, NewRC, TII, 88 getTargetRegisterInfo()); 89 if (!NewRC || NewRC == OldRC) 90 return false; 91 } 92 setRegClass(Reg, NewRC); 93 return true; 94 } 95 96 unsigned MachineRegisterInfo::createIncompleteVirtualRegister() { 97 unsigned Reg = TargetRegisterInfo::index2VirtReg(getNumVirtRegs()); 98 VRegInfo.grow(Reg); 99 RegAllocHints.grow(Reg); 100 return Reg; 101 } 102 103 /// createVirtualRegister - Create and return a new virtual register in the 104 /// function with the specified register class. 105 /// 106 unsigned 107 MachineRegisterInfo::createVirtualRegister(const TargetRegisterClass *RegClass){ 108 assert(RegClass && "Cannot create register without RegClass!"); 109 assert(RegClass->isAllocatable() && 110 "Virtual register RegClass must be allocatable."); 111 112 // New virtual register number. 113 unsigned Reg = createIncompleteVirtualRegister(); 114 VRegInfo[Reg].first = RegClass; 115 if (TheDelegate) 116 TheDelegate->MRI_NoteNewVirtualRegister(Reg); 117 return Reg; 118 } 119 120 LLT MachineRegisterInfo::getType(unsigned VReg) const { 121 VRegToTypeMap::const_iterator TypeIt = getVRegToType().find(VReg); 122 return TypeIt != getVRegToType().end() ? TypeIt->second : LLT{}; 123 } 124 125 void MachineRegisterInfo::setType(unsigned VReg, LLT Ty) { 126 // Check that VReg doesn't have a class. 127 assert((getRegClassOrRegBank(VReg).isNull() || 128 !getRegClassOrRegBank(VReg).is<const TargetRegisterClass *>()) && 129 "Can't set the size of a non-generic virtual register"); 130 getVRegToType()[VReg] = Ty; 131 } 132 133 unsigned 134 MachineRegisterInfo::createGenericVirtualRegister(LLT Ty) { 135 // New virtual register number. 136 unsigned Reg = createIncompleteVirtualRegister(); 137 // FIXME: Should we use a dummy register class? 138 VRegInfo[Reg].first = static_cast<RegisterBank *>(nullptr); 139 getVRegToType()[Reg] = Ty; 140 if (TheDelegate) 141 TheDelegate->MRI_NoteNewVirtualRegister(Reg); 142 return Reg; 143 } 144 145 void MachineRegisterInfo::clearVirtRegTypes() { 146 #ifndef NDEBUG 147 // Verify that the size of the now-constrained vreg is unchanged. 148 for (auto &VRegToType : getVRegToType()) { 149 auto *RC = getRegClass(VRegToType.first); 150 if (VRegToType.second.isValid() && 151 VRegToType.second.getSizeInBits() > (RC->getSize() * 8)) 152 llvm_unreachable( 153 "Virtual register has explicit size different from its class size"); 154 } 155 #endif 156 157 getVRegToType().clear(); 158 } 159 160 /// clearVirtRegs - Remove all virtual registers (after physreg assignment). 161 void MachineRegisterInfo::clearVirtRegs() { 162 #ifndef NDEBUG 163 for (unsigned i = 0, e = getNumVirtRegs(); i != e; ++i) { 164 unsigned Reg = TargetRegisterInfo::index2VirtReg(i); 165 if (!VRegInfo[Reg].second) 166 continue; 167 verifyUseList(Reg); 168 llvm_unreachable("Remaining virtual register operands"); 169 } 170 #endif 171 VRegInfo.clear(); 172 for (auto &I : LiveIns) 173 I.second = 0; 174 } 175 176 void MachineRegisterInfo::verifyUseList(unsigned Reg) const { 177 #ifndef NDEBUG 178 bool Valid = true; 179 for (MachineOperand &M : reg_operands(Reg)) { 180 MachineOperand *MO = &M; 181 MachineInstr *MI = MO->getParent(); 182 if (!MI) { 183 errs() << PrintReg(Reg, getTargetRegisterInfo()) 184 << " use list MachineOperand " << MO 185 << " has no parent instruction.\n"; 186 Valid = false; 187 continue; 188 } 189 MachineOperand *MO0 = &MI->getOperand(0); 190 unsigned NumOps = MI->getNumOperands(); 191 if (!(MO >= MO0 && MO < MO0+NumOps)) { 192 errs() << PrintReg(Reg, getTargetRegisterInfo()) 193 << " use list MachineOperand " << MO 194 << " doesn't belong to parent MI: " << *MI; 195 Valid = false; 196 } 197 if (!MO->isReg()) { 198 errs() << PrintReg(Reg, getTargetRegisterInfo()) 199 << " MachineOperand " << MO << ": " << *MO 200 << " is not a register\n"; 201 Valid = false; 202 } 203 if (MO->getReg() != Reg) { 204 errs() << PrintReg(Reg, getTargetRegisterInfo()) 205 << " use-list MachineOperand " << MO << ": " 206 << *MO << " is the wrong register\n"; 207 Valid = false; 208 } 209 } 210 assert(Valid && "Invalid use list"); 211 #endif 212 } 213 214 void MachineRegisterInfo::verifyUseLists() const { 215 #ifndef NDEBUG 216 for (unsigned i = 0, e = getNumVirtRegs(); i != e; ++i) 217 verifyUseList(TargetRegisterInfo::index2VirtReg(i)); 218 for (unsigned i = 1, e = getTargetRegisterInfo()->getNumRegs(); i != e; ++i) 219 verifyUseList(i); 220 #endif 221 } 222 223 /// Add MO to the linked list of operands for its register. 224 void MachineRegisterInfo::addRegOperandToUseList(MachineOperand *MO) { 225 assert(!MO->isOnRegUseList() && "Already on list"); 226 MachineOperand *&HeadRef = getRegUseDefListHead(MO->getReg()); 227 MachineOperand *const Head = HeadRef; 228 229 // Head points to the first list element. 230 // Next is NULL on the last list element. 231 // Prev pointers are circular, so Head->Prev == Last. 232 233 // Head is NULL for an empty list. 234 if (!Head) { 235 MO->Contents.Reg.Prev = MO; 236 MO->Contents.Reg.Next = nullptr; 237 HeadRef = MO; 238 return; 239 } 240 assert(MO->getReg() == Head->getReg() && "Different regs on the same list!"); 241 242 // Insert MO between Last and Head in the circular Prev chain. 243 MachineOperand *Last = Head->Contents.Reg.Prev; 244 assert(Last && "Inconsistent use list"); 245 assert(MO->getReg() == Last->getReg() && "Different regs on the same list!"); 246 Head->Contents.Reg.Prev = MO; 247 MO->Contents.Reg.Prev = Last; 248 249 // Def operands always precede uses. This allows def_iterator to stop early. 250 // Insert def operands at the front, and use operands at the back. 251 if (MO->isDef()) { 252 // Insert def at the front. 253 MO->Contents.Reg.Next = Head; 254 HeadRef = MO; 255 } else { 256 // Insert use at the end. 257 MO->Contents.Reg.Next = nullptr; 258 Last->Contents.Reg.Next = MO; 259 } 260 } 261 262 /// Remove MO from its use-def list. 263 void MachineRegisterInfo::removeRegOperandFromUseList(MachineOperand *MO) { 264 assert(MO->isOnRegUseList() && "Operand not on use list"); 265 MachineOperand *&HeadRef = getRegUseDefListHead(MO->getReg()); 266 MachineOperand *const Head = HeadRef; 267 assert(Head && "List already empty"); 268 269 // Unlink this from the doubly linked list of operands. 270 MachineOperand *Next = MO->Contents.Reg.Next; 271 MachineOperand *Prev = MO->Contents.Reg.Prev; 272 273 // Prev links are circular, next link is NULL instead of looping back to Head. 274 if (MO == Head) 275 HeadRef = Next; 276 else 277 Prev->Contents.Reg.Next = Next; 278 279 (Next ? Next : Head)->Contents.Reg.Prev = Prev; 280 281 MO->Contents.Reg.Prev = nullptr; 282 MO->Contents.Reg.Next = nullptr; 283 } 284 285 /// Move NumOps operands from Src to Dst, updating use-def lists as needed. 286 /// 287 /// The Dst range is assumed to be uninitialized memory. (Or it may contain 288 /// operands that won't be destroyed, which is OK because the MO destructor is 289 /// trivial anyway). 290 /// 291 /// The Src and Dst ranges may overlap. 292 void MachineRegisterInfo::moveOperands(MachineOperand *Dst, 293 MachineOperand *Src, 294 unsigned NumOps) { 295 assert(Src != Dst && NumOps && "Noop moveOperands"); 296 297 // Copy backwards if Dst is within the Src range. 298 int Stride = 1; 299 if (Dst >= Src && Dst < Src + NumOps) { 300 Stride = -1; 301 Dst += NumOps - 1; 302 Src += NumOps - 1; 303 } 304 305 // Copy one operand at a time. 306 do { 307 new (Dst) MachineOperand(*Src); 308 309 // Dst takes Src's place in the use-def chain. 310 if (Src->isReg()) { 311 MachineOperand *&Head = getRegUseDefListHead(Src->getReg()); 312 MachineOperand *Prev = Src->Contents.Reg.Prev; 313 MachineOperand *Next = Src->Contents.Reg.Next; 314 assert(Head && "List empty, but operand is chained"); 315 assert(Prev && "Operand was not on use-def list"); 316 317 // Prev links are circular, next link is NULL instead of looping back to 318 // Head. 319 if (Src == Head) 320 Head = Dst; 321 else 322 Prev->Contents.Reg.Next = Dst; 323 324 // Update Prev pointer. This also works when Src was pointing to itself 325 // in a 1-element list. In that case Head == Dst. 326 (Next ? Next : Head)->Contents.Reg.Prev = Dst; 327 } 328 329 Dst += Stride; 330 Src += Stride; 331 } while (--NumOps); 332 } 333 334 /// replaceRegWith - Replace all instances of FromReg with ToReg in the 335 /// machine function. This is like llvm-level X->replaceAllUsesWith(Y), 336 /// except that it also changes any definitions of the register as well. 337 /// If ToReg is a physical register we apply the sub register to obtain the 338 /// final/proper physical register. 339 void MachineRegisterInfo::replaceRegWith(unsigned FromReg, unsigned ToReg) { 340 assert(FromReg != ToReg && "Cannot replace a reg with itself"); 341 342 const TargetRegisterInfo *TRI = getTargetRegisterInfo(); 343 344 // TODO: This could be more efficient by bulk changing the operands. 345 for (reg_iterator I = reg_begin(FromReg), E = reg_end(); I != E; ) { 346 MachineOperand &O = *I; 347 ++I; 348 if (TargetRegisterInfo::isPhysicalRegister(ToReg)) { 349 O.substPhysReg(ToReg, *TRI); 350 } else { 351 O.setReg(ToReg); 352 } 353 } 354 } 355 356 /// getVRegDef - Return the machine instr that defines the specified virtual 357 /// register or null if none is found. This assumes that the code is in SSA 358 /// form, so there should only be one definition. 359 MachineInstr *MachineRegisterInfo::getVRegDef(unsigned Reg) const { 360 // Since we are in SSA form, we can use the first definition. 361 def_instr_iterator I = def_instr_begin(Reg); 362 assert((I.atEnd() || std::next(I) == def_instr_end()) && 363 "getVRegDef assumes a single definition or no definition"); 364 return !I.atEnd() ? &*I : nullptr; 365 } 366 367 /// getUniqueVRegDef - Return the unique machine instr that defines the 368 /// specified virtual register or null if none is found. If there are 369 /// multiple definitions or no definition, return null. 370 MachineInstr *MachineRegisterInfo::getUniqueVRegDef(unsigned Reg) const { 371 if (def_empty(Reg)) return nullptr; 372 def_instr_iterator I = def_instr_begin(Reg); 373 if (std::next(I) != def_instr_end()) 374 return nullptr; 375 return &*I; 376 } 377 378 bool MachineRegisterInfo::hasOneNonDBGUse(unsigned RegNo) const { 379 use_nodbg_iterator UI = use_nodbg_begin(RegNo); 380 if (UI == use_nodbg_end()) 381 return false; 382 return ++UI == use_nodbg_end(); 383 } 384 385 /// clearKillFlags - Iterate over all the uses of the given register and 386 /// clear the kill flag from the MachineOperand. This function is used by 387 /// optimization passes which extend register lifetimes and need only 388 /// preserve conservative kill flag information. 389 void MachineRegisterInfo::clearKillFlags(unsigned Reg) const { 390 for (MachineOperand &MO : use_operands(Reg)) 391 MO.setIsKill(false); 392 } 393 394 bool MachineRegisterInfo::isLiveIn(unsigned Reg) const { 395 for (livein_iterator I = livein_begin(), E = livein_end(); I != E; ++I) 396 if (I->first == Reg || I->second == Reg) 397 return true; 398 return false; 399 } 400 401 /// getLiveInPhysReg - If VReg is a live-in virtual register, return the 402 /// corresponding live-in physical register. 403 unsigned MachineRegisterInfo::getLiveInPhysReg(unsigned VReg) const { 404 for (livein_iterator I = livein_begin(), E = livein_end(); I != E; ++I) 405 if (I->second == VReg) 406 return I->first; 407 return 0; 408 } 409 410 /// getLiveInVirtReg - If PReg is a live-in physical register, return the 411 /// corresponding live-in physical register. 412 unsigned MachineRegisterInfo::getLiveInVirtReg(unsigned PReg) const { 413 for (livein_iterator I = livein_begin(), E = livein_end(); I != E; ++I) 414 if (I->first == PReg) 415 return I->second; 416 return 0; 417 } 418 419 /// EmitLiveInCopies - Emit copies to initialize livein virtual registers 420 /// into the given entry block. 421 void 422 MachineRegisterInfo::EmitLiveInCopies(MachineBasicBlock *EntryMBB, 423 const TargetRegisterInfo &TRI, 424 const TargetInstrInfo &TII) { 425 // Emit the copies into the top of the block. 426 for (unsigned i = 0, e = LiveIns.size(); i != e; ++i) 427 if (LiveIns[i].second) { 428 if (use_empty(LiveIns[i].second)) { 429 // The livein has no uses. Drop it. 430 // 431 // It would be preferable to have isel avoid creating live-in 432 // records for unused arguments in the first place, but it's 433 // complicated by the debug info code for arguments. 434 LiveIns.erase(LiveIns.begin() + i); 435 --i; --e; 436 } else { 437 // Emit a copy. 438 BuildMI(*EntryMBB, EntryMBB->begin(), DebugLoc(), 439 TII.get(TargetOpcode::COPY), LiveIns[i].second) 440 .addReg(LiveIns[i].first); 441 442 // Add the register to the entry block live-in set. 443 EntryMBB->addLiveIn(LiveIns[i].first); 444 } 445 } else { 446 // Add the register to the entry block live-in set. 447 EntryMBB->addLiveIn(LiveIns[i].first); 448 } 449 } 450 451 LaneBitmask MachineRegisterInfo::getMaxLaneMaskForVReg(unsigned Reg) const { 452 // Lane masks are only defined for vregs. 453 assert(TargetRegisterInfo::isVirtualRegister(Reg)); 454 const TargetRegisterClass &TRC = *getRegClass(Reg); 455 return TRC.getLaneMask(); 456 } 457 458 #ifndef NDEBUG 459 void MachineRegisterInfo::dumpUses(unsigned Reg) const { 460 for (MachineInstr &I : use_instructions(Reg)) 461 I.dump(); 462 } 463 #endif 464 465 void MachineRegisterInfo::freezeReservedRegs(const MachineFunction &MF) { 466 ReservedRegs = getTargetRegisterInfo()->getReservedRegs(MF); 467 assert(ReservedRegs.size() == getTargetRegisterInfo()->getNumRegs() && 468 "Invalid ReservedRegs vector from target"); 469 } 470 471 bool MachineRegisterInfo::isConstantPhysReg(unsigned PhysReg, 472 const MachineFunction &MF) const { 473 assert(TargetRegisterInfo::isPhysicalRegister(PhysReg)); 474 475 const TargetRegisterInfo *TRI = getTargetRegisterInfo(); 476 if (TRI->isConstantPhysReg(PhysReg)) 477 return true; 478 479 // Check if any overlapping register is modified, or allocatable so it may be 480 // used later. 481 for (MCRegAliasIterator AI(PhysReg, TRI, true); 482 AI.isValid(); ++AI) 483 if (!def_empty(*AI) || isAllocatable(*AI)) 484 return false; 485 return true; 486 } 487 488 /// markUsesInDebugValueAsUndef - Mark every DBG_VALUE referencing the 489 /// specified register as undefined which causes the DBG_VALUE to be 490 /// deleted during LiveDebugVariables analysis. 491 void MachineRegisterInfo::markUsesInDebugValueAsUndef(unsigned Reg) const { 492 // Mark any DBG_VALUE that uses Reg as undef (but don't delete it.) 493 MachineRegisterInfo::use_instr_iterator nextI; 494 for (use_instr_iterator I = use_instr_begin(Reg), E = use_instr_end(); 495 I != E; I = nextI) { 496 nextI = std::next(I); // I is invalidated by the setReg 497 MachineInstr *UseMI = &*I; 498 if (UseMI->isDebugValue()) 499 UseMI->getOperand(0).setReg(0U); 500 } 501 } 502 503 static const Function *getCalledFunction(const MachineInstr &MI) { 504 for (const MachineOperand &MO : MI.operands()) { 505 if (!MO.isGlobal()) 506 continue; 507 const Function *Func = dyn_cast<Function>(MO.getGlobal()); 508 if (Func != nullptr) 509 return Func; 510 } 511 return nullptr; 512 } 513 514 static bool isNoReturnDef(const MachineOperand &MO) { 515 // Anything which is not a noreturn function is a real def. 516 const MachineInstr &MI = *MO.getParent(); 517 if (!MI.isCall()) 518 return false; 519 const MachineBasicBlock &MBB = *MI.getParent(); 520 if (!MBB.succ_empty()) 521 return false; 522 const MachineFunction &MF = *MBB.getParent(); 523 // We need to keep correct unwind information even if the function will 524 // not return, since the runtime may need it. 525 if (MF.getFunction()->hasFnAttribute(Attribute::UWTable)) 526 return false; 527 const Function *Called = getCalledFunction(MI); 528 return !(Called == nullptr || !Called->hasFnAttribute(Attribute::NoReturn) || 529 !Called->hasFnAttribute(Attribute::NoUnwind)); 530 } 531 532 bool MachineRegisterInfo::isPhysRegModified(unsigned PhysReg, 533 bool SkipNoReturnDef) const { 534 if (UsedPhysRegMask.test(PhysReg)) 535 return true; 536 const TargetRegisterInfo *TRI = getTargetRegisterInfo(); 537 for (MCRegAliasIterator AI(PhysReg, TRI, true); AI.isValid(); ++AI) { 538 for (const MachineOperand &MO : make_range(def_begin(*AI), def_end())) { 539 if (!SkipNoReturnDef && isNoReturnDef(MO)) 540 continue; 541 return true; 542 } 543 } 544 return false; 545 } 546 547 bool MachineRegisterInfo::isPhysRegUsed(unsigned PhysReg) const { 548 if (UsedPhysRegMask.test(PhysReg)) 549 return true; 550 const TargetRegisterInfo *TRI = getTargetRegisterInfo(); 551 for (MCRegAliasIterator AliasReg(PhysReg, TRI, true); AliasReg.isValid(); 552 ++AliasReg) { 553 if (!reg_nodbg_empty(*AliasReg)) 554 return true; 555 } 556 return false; 557 } 558