MachineRegisterInfo.cpp 17 KB

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