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