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