2
0

VirtRegMap.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. //===-- llvm/CodeGen/VirtRegMap.cpp - Virtual Register Map ----------------===//
  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. // This file implements the VirtRegMap class.
  11. //
  12. // It also contains implementations of the Spiller interface, which, given a
  13. // virtual register map and a machine function, eliminates all virtual
  14. // references by replacing them with physical register references - adding spill
  15. // code as necessary.
  16. //
  17. //===----------------------------------------------------------------------===//
  18. #include "llvm/CodeGen/VirtRegMap.h"
  19. #include "LiveDebugVariables.h"
  20. #include "llvm/ADT/STLExtras.h"
  21. #include "llvm/ADT/SparseSet.h"
  22. #include "llvm/ADT/Statistic.h"
  23. #include "llvm/CodeGen/LiveIntervalAnalysis.h"
  24. #include "llvm/CodeGen/LiveStackAnalysis.h"
  25. #include "llvm/CodeGen/MachineFrameInfo.h"
  26. #include "llvm/CodeGen/MachineFunction.h"
  27. #include "llvm/CodeGen/MachineInstrBuilder.h"
  28. #include "llvm/CodeGen/MachineRegisterInfo.h"
  29. #include "llvm/CodeGen/Passes.h"
  30. #include "llvm/IR/Function.h"
  31. #include "llvm/Support/CommandLine.h"
  32. #include "llvm/Support/Compiler.h"
  33. #include "llvm/Support/Debug.h"
  34. #include "llvm/Support/raw_ostream.h"
  35. #include "llvm/Target/TargetInstrInfo.h"
  36. #include "llvm/Target/TargetMachine.h"
  37. #include "llvm/Target/TargetRegisterInfo.h"
  38. #include "llvm/Target/TargetSubtargetInfo.h"
  39. #include <algorithm>
  40. using namespace llvm;
  41. #define DEBUG_TYPE "regalloc"
  42. STATISTIC(NumSpillSlots, "Number of spill slots allocated");
  43. STATISTIC(NumIdCopies, "Number of identity moves eliminated after rewriting");
  44. //===----------------------------------------------------------------------===//
  45. // VirtRegMap implementation
  46. //===----------------------------------------------------------------------===//
  47. char VirtRegMap::ID = 0;
  48. INITIALIZE_PASS(VirtRegMap, "virtregmap", "Virtual Register Map", false, false)
  49. bool VirtRegMap::runOnMachineFunction(MachineFunction &mf) {
  50. MRI = &mf.getRegInfo();
  51. TII = mf.getSubtarget().getInstrInfo();
  52. TRI = mf.getSubtarget().getRegisterInfo();
  53. MF = &mf;
  54. Virt2PhysMap.clear();
  55. Virt2StackSlotMap.clear();
  56. Virt2SplitMap.clear();
  57. grow();
  58. return false;
  59. }
  60. void VirtRegMap::grow() {
  61. unsigned NumRegs = MF->getRegInfo().getNumVirtRegs();
  62. Virt2PhysMap.resize(NumRegs);
  63. Virt2StackSlotMap.resize(NumRegs);
  64. Virt2SplitMap.resize(NumRegs);
  65. }
  66. unsigned VirtRegMap::createSpillSlot(const TargetRegisterClass *RC) {
  67. int SS = MF->getFrameInfo()->CreateSpillStackObject(RC->getSize(),
  68. RC->getAlignment());
  69. ++NumSpillSlots;
  70. return SS;
  71. }
  72. bool VirtRegMap::hasPreferredPhys(unsigned VirtReg) {
  73. unsigned Hint = MRI->getSimpleHint(VirtReg);
  74. if (!Hint)
  75. return 0;
  76. if (TargetRegisterInfo::isVirtualRegister(Hint))
  77. Hint = getPhys(Hint);
  78. return getPhys(VirtReg) == Hint;
  79. }
  80. bool VirtRegMap::hasKnownPreference(unsigned VirtReg) {
  81. std::pair<unsigned, unsigned> Hint = MRI->getRegAllocationHint(VirtReg);
  82. if (TargetRegisterInfo::isPhysicalRegister(Hint.second))
  83. return true;
  84. if (TargetRegisterInfo::isVirtualRegister(Hint.second))
  85. return hasPhys(Hint.second);
  86. return false;
  87. }
  88. int VirtRegMap::assignVirt2StackSlot(unsigned virtReg) {
  89. assert(TargetRegisterInfo::isVirtualRegister(virtReg));
  90. assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT &&
  91. "attempt to assign stack slot to already spilled register");
  92. const TargetRegisterClass* RC = MF->getRegInfo().getRegClass(virtReg);
  93. return Virt2StackSlotMap[virtReg] = createSpillSlot(RC);
  94. }
  95. void VirtRegMap::assignVirt2StackSlot(unsigned virtReg, int SS) {
  96. assert(TargetRegisterInfo::isVirtualRegister(virtReg));
  97. assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT &&
  98. "attempt to assign stack slot to already spilled register");
  99. assert((SS >= 0 ||
  100. (SS >= MF->getFrameInfo()->getObjectIndexBegin())) &&
  101. "illegal fixed frame index");
  102. Virt2StackSlotMap[virtReg] = SS;
  103. }
  104. void VirtRegMap::print(raw_ostream &OS, const Module*) const {
  105. OS << "********** REGISTER MAP **********\n";
  106. for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
  107. unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
  108. if (Virt2PhysMap[Reg] != (unsigned)VirtRegMap::NO_PHYS_REG) {
  109. OS << '[' << PrintReg(Reg, TRI) << " -> "
  110. << PrintReg(Virt2PhysMap[Reg], TRI) << "] "
  111. << TRI->getRegClassName(MRI->getRegClass(Reg)) << "\n";
  112. }
  113. }
  114. for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
  115. unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
  116. if (Virt2StackSlotMap[Reg] != VirtRegMap::NO_STACK_SLOT) {
  117. OS << '[' << PrintReg(Reg, TRI) << " -> fi#" << Virt2StackSlotMap[Reg]
  118. << "] " << TRI->getRegClassName(MRI->getRegClass(Reg)) << "\n";
  119. }
  120. }
  121. OS << '\n';
  122. }
  123. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  124. void VirtRegMap::dump() const {
  125. print(dbgs());
  126. }
  127. #endif
  128. //===----------------------------------------------------------------------===//
  129. // VirtRegRewriter
  130. //===----------------------------------------------------------------------===//
  131. //
  132. // The VirtRegRewriter is the last of the register allocator passes.
  133. // It rewrites virtual registers to physical registers as specified in the
  134. // VirtRegMap analysis. It also updates live-in information on basic blocks
  135. // according to LiveIntervals.
  136. //
  137. namespace {
  138. class VirtRegRewriter : public MachineFunctionPass {
  139. MachineFunction *MF;
  140. const TargetMachine *TM;
  141. const TargetRegisterInfo *TRI;
  142. const TargetInstrInfo *TII;
  143. MachineRegisterInfo *MRI;
  144. SlotIndexes *Indexes;
  145. LiveIntervals *LIS;
  146. VirtRegMap *VRM;
  147. SparseSet<unsigned> PhysRegs;
  148. void rewrite();
  149. void addMBBLiveIns();
  150. bool readsUndefSubreg(const MachineOperand &MO) const;
  151. public:
  152. static char ID;
  153. VirtRegRewriter() : MachineFunctionPass(ID) {}
  154. void getAnalysisUsage(AnalysisUsage &AU) const override;
  155. bool runOnMachineFunction(MachineFunction&) override;
  156. };
  157. } // end anonymous namespace
  158. char &llvm::VirtRegRewriterID = VirtRegRewriter::ID;
  159. INITIALIZE_PASS_BEGIN(VirtRegRewriter, "virtregrewriter",
  160. "Virtual Register Rewriter", false, false)
  161. INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
  162. INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
  163. INITIALIZE_PASS_DEPENDENCY(LiveDebugVariables)
  164. INITIALIZE_PASS_DEPENDENCY(LiveStacks)
  165. INITIALIZE_PASS_DEPENDENCY(VirtRegMap)
  166. INITIALIZE_PASS_END(VirtRegRewriter, "virtregrewriter",
  167. "Virtual Register Rewriter", false, false)
  168. char VirtRegRewriter::ID = 0;
  169. void VirtRegRewriter::getAnalysisUsage(AnalysisUsage &AU) const {
  170. AU.setPreservesCFG();
  171. AU.addRequired<LiveIntervals>();
  172. AU.addRequired<SlotIndexes>();
  173. AU.addPreserved<SlotIndexes>();
  174. AU.addRequired<LiveDebugVariables>();
  175. AU.addRequired<LiveStacks>();
  176. AU.addPreserved<LiveStacks>();
  177. AU.addRequired<VirtRegMap>();
  178. MachineFunctionPass::getAnalysisUsage(AU);
  179. }
  180. bool VirtRegRewriter::runOnMachineFunction(MachineFunction &fn) {
  181. MF = &fn;
  182. TM = &MF->getTarget();
  183. TRI = MF->getSubtarget().getRegisterInfo();
  184. TII = MF->getSubtarget().getInstrInfo();
  185. MRI = &MF->getRegInfo();
  186. Indexes = &getAnalysis<SlotIndexes>();
  187. LIS = &getAnalysis<LiveIntervals>();
  188. VRM = &getAnalysis<VirtRegMap>();
  189. DEBUG(dbgs() << "********** REWRITE VIRTUAL REGISTERS **********\n"
  190. << "********** Function: "
  191. << MF->getName() << '\n');
  192. DEBUG(VRM->dump());
  193. // Add kill flags while we still have virtual registers.
  194. LIS->addKillFlags(VRM);
  195. // Live-in lists on basic blocks are required for physregs.
  196. addMBBLiveIns();
  197. // Rewrite virtual registers.
  198. rewrite();
  199. // Write out new DBG_VALUE instructions.
  200. getAnalysis<LiveDebugVariables>().emitDebugValues(VRM);
  201. // All machine operands and other references to virtual registers have been
  202. // replaced. Remove the virtual registers and release all the transient data.
  203. VRM->clearAllVirt();
  204. MRI->clearVirtRegs();
  205. return true;
  206. }
  207. // Compute MBB live-in lists from virtual register live ranges and their
  208. // assignments.
  209. void VirtRegRewriter::addMBBLiveIns() {
  210. SmallVector<MachineBasicBlock*, 16> LiveIn;
  211. for (unsigned Idx = 0, IdxE = MRI->getNumVirtRegs(); Idx != IdxE; ++Idx) {
  212. unsigned VirtReg = TargetRegisterInfo::index2VirtReg(Idx);
  213. if (MRI->reg_nodbg_empty(VirtReg))
  214. continue;
  215. LiveInterval &LI = LIS->getInterval(VirtReg);
  216. if (LI.empty() || LIS->intervalIsInOneMBB(LI))
  217. continue;
  218. // This is a virtual register that is live across basic blocks. Its
  219. // assigned PhysReg must be marked as live-in to those blocks.
  220. unsigned PhysReg = VRM->getPhys(VirtReg);
  221. assert(PhysReg != VirtRegMap::NO_PHYS_REG && "Unmapped virtual register.");
  222. if (LI.hasSubRanges()) {
  223. for (LiveInterval::SubRange &S : LI.subranges()) {
  224. for (const auto &Seg : S.segments) {
  225. if (!Indexes->findLiveInMBBs(Seg.start, Seg.end, LiveIn))
  226. continue;
  227. for (MCSubRegIndexIterator SR(PhysReg, TRI); SR.isValid(); ++SR) {
  228. unsigned SubReg = SR.getSubReg();
  229. unsigned SubRegIndex = SR.getSubRegIndex();
  230. unsigned SubRegLaneMask = TRI->getSubRegIndexLaneMask(SubRegIndex);
  231. if ((SubRegLaneMask & S.LaneMask) == 0)
  232. continue;
  233. for (unsigned i = 0, e = LiveIn.size(); i != e; ++i) {
  234. LiveIn[i]->addLiveIn(SubReg);
  235. }
  236. }
  237. LiveIn.clear();
  238. }
  239. }
  240. } else {
  241. // Scan the segments of LI.
  242. for (const auto &Seg : LI.segments) {
  243. if (!Indexes->findLiveInMBBs(Seg.start, Seg.end, LiveIn))
  244. continue;
  245. for (unsigned i = 0, e = LiveIn.size(); i != e; ++i)
  246. LiveIn[i]->addLiveIn(PhysReg);
  247. LiveIn.clear();
  248. }
  249. }
  250. }
  251. // Sort and unique MBB LiveIns as we've not checked if SubReg/PhysReg were in
  252. // each MBB's LiveIns set before calling addLiveIn on them.
  253. for (MachineBasicBlock &MBB : *MF)
  254. MBB.sortUniqueLiveIns();
  255. }
  256. /// Returns true if the given machine operand \p MO only reads undefined lanes.
  257. /// The function only works for use operands with a subregister set.
  258. bool VirtRegRewriter::readsUndefSubreg(const MachineOperand &MO) const {
  259. // Shortcut if the operand is already marked undef.
  260. if (MO.isUndef())
  261. return true;
  262. unsigned Reg = MO.getReg();
  263. const LiveInterval &LI = LIS->getInterval(Reg);
  264. const MachineInstr &MI = *MO.getParent();
  265. SlotIndex BaseIndex = LIS->getInstructionIndex(&MI);
  266. // This code is only meant to handle reading undefined subregisters which
  267. // we couldn't properly detect before.
  268. assert(LI.liveAt(BaseIndex) &&
  269. "Reads of completely dead register should be marked undef already");
  270. unsigned SubRegIdx = MO.getSubReg();
  271. unsigned UseMask = TRI->getSubRegIndexLaneMask(SubRegIdx);
  272. // See if any of the relevant subregister liveranges is defined at this point.
  273. for (const LiveInterval::SubRange &SR : LI.subranges()) {
  274. if ((SR.LaneMask & UseMask) != 0 && SR.liveAt(BaseIndex))
  275. return false;
  276. }
  277. return true;
  278. }
  279. void VirtRegRewriter::rewrite() {
  280. bool NoSubRegLiveness = !MRI->subRegLivenessEnabled();
  281. SmallVector<unsigned, 8> SuperDeads;
  282. SmallVector<unsigned, 8> SuperDefs;
  283. SmallVector<unsigned, 8> SuperKills;
  284. SmallPtrSet<const MachineInstr *, 4> NoReturnInsts;
  285. // Here we have a SparseSet to hold which PhysRegs are actually encountered
  286. // in the MF we are about to iterate over so that later when we call
  287. // setPhysRegUsed, we are only doing it for physRegs that were actually found
  288. // in the program and not for all of the possible physRegs for the given
  289. // target architecture. If the target has a lot of physRegs, then for a small
  290. // program there will be a significant compile time reduction here.
  291. PhysRegs.clear();
  292. PhysRegs.setUniverse(TRI->getNumRegs());
  293. // The function with uwtable should guarantee that the stack unwinder
  294. // can unwind the stack to the previous frame. Thus, we can't apply the
  295. // noreturn optimization if the caller function has uwtable attribute.
  296. bool HasUWTable = MF->getFunction()->hasFnAttribute(Attribute::UWTable);
  297. for (MachineFunction::iterator MBBI = MF->begin(), MBBE = MF->end();
  298. MBBI != MBBE; ++MBBI) {
  299. DEBUG(MBBI->print(dbgs(), Indexes));
  300. bool IsExitBB = MBBI->succ_empty();
  301. for (MachineBasicBlock::instr_iterator
  302. MII = MBBI->instr_begin(), MIE = MBBI->instr_end(); MII != MIE;) {
  303. MachineInstr *MI = MII;
  304. ++MII;
  305. // Check if this instruction is a call to a noreturn function. If this
  306. // is a call to noreturn function and we don't need the stack unwinding
  307. // functionality (i.e. this function does not have uwtable attribute and
  308. // the callee function has the nounwind attribute), then we can ignore
  309. // the definitions set by this instruction.
  310. if (!HasUWTable && IsExitBB && MI->isCall()) {
  311. for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
  312. MOE = MI->operands_end(); MOI != MOE; ++MOI) {
  313. MachineOperand &MO = *MOI;
  314. if (!MO.isGlobal())
  315. continue;
  316. const Function *Func = dyn_cast<Function>(MO.getGlobal());
  317. if (!Func || !Func->hasFnAttribute(Attribute::NoReturn) ||
  318. // We need to keep correct unwind information
  319. // even if the function will not return, since the
  320. // runtime may need it.
  321. !Func->hasFnAttribute(Attribute::NoUnwind))
  322. continue;
  323. NoReturnInsts.insert(MI);
  324. break;
  325. }
  326. }
  327. for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
  328. MOE = MI->operands_end(); MOI != MOE; ++MOI) {
  329. MachineOperand &MO = *MOI;
  330. // Make sure MRI knows about registers clobbered by regmasks.
  331. if (MO.isRegMask())
  332. MRI->addPhysRegsUsedFromRegMask(MO.getRegMask());
  333. // If we encounter a VirtReg or PhysReg then get at the PhysReg and add
  334. // it to the physreg bitset. Later we use only the PhysRegs that were
  335. // actually encountered in the MF to populate the MRI's used physregs.
  336. if (MO.isReg() && MO.getReg())
  337. PhysRegs.insert(
  338. TargetRegisterInfo::isVirtualRegister(MO.getReg()) ?
  339. VRM->getPhys(MO.getReg()) :
  340. MO.getReg());
  341. if (!MO.isReg() || !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
  342. continue;
  343. unsigned VirtReg = MO.getReg();
  344. unsigned PhysReg = VRM->getPhys(VirtReg);
  345. assert(PhysReg != VirtRegMap::NO_PHYS_REG &&
  346. "Instruction uses unmapped VirtReg");
  347. assert(!MRI->isReserved(PhysReg) && "Reserved register assignment");
  348. // Preserve semantics of sub-register operands.
  349. unsigned SubReg = MO.getSubReg();
  350. if (SubReg != 0) {
  351. if (NoSubRegLiveness) {
  352. // A virtual register kill refers to the whole register, so we may
  353. // have to add <imp-use,kill> operands for the super-register. A
  354. // partial redef always kills and redefines the super-register.
  355. if (MO.readsReg() && (MO.isDef() || MO.isKill()))
  356. SuperKills.push_back(PhysReg);
  357. if (MO.isDef()) {
  358. // Also add implicit defs for the super-register.
  359. if (MO.isDead())
  360. SuperDeads.push_back(PhysReg);
  361. else
  362. SuperDefs.push_back(PhysReg);
  363. }
  364. } else {
  365. if (MO.isUse()) {
  366. if (readsUndefSubreg(MO))
  367. // We need to add an <undef> flag if the subregister is
  368. // completely undefined (and we are not adding super-register
  369. // defs).
  370. MO.setIsUndef(true);
  371. } else if (!MO.isDead()) {
  372. assert(MO.isDef());
  373. // Things get tricky when we ran out of lane mask bits and
  374. // merged multiple lanes into the overflow bit: In this case
  375. // our subregister liveness tracking isn't precise and we can't
  376. // know what subregister parts are undefined, fall back to the
  377. // implicit super-register def then.
  378. unsigned LaneMask = TRI->getSubRegIndexLaneMask(SubReg);
  379. if (TargetRegisterInfo::isImpreciseLaneMask(LaneMask))
  380. SuperDefs.push_back(PhysReg);
  381. }
  382. }
  383. // The <def,undef> flag only makes sense for sub-register defs, and
  384. // we are substituting a full physreg. An <imp-use,kill> operand
  385. // from the SuperKills list will represent the partial read of the
  386. // super-register.
  387. if (MO.isDef())
  388. MO.setIsUndef(false);
  389. // PhysReg operands cannot have subregister indexes.
  390. PhysReg = TRI->getSubReg(PhysReg, SubReg);
  391. assert(PhysReg && "Invalid SubReg for physical register");
  392. MO.setSubReg(0);
  393. }
  394. // Rewrite. Note we could have used MachineOperand::substPhysReg(), but
  395. // we need the inlining here.
  396. MO.setReg(PhysReg);
  397. }
  398. // Add any missing super-register kills after rewriting the whole
  399. // instruction.
  400. while (!SuperKills.empty())
  401. MI->addRegisterKilled(SuperKills.pop_back_val(), TRI, true);
  402. while (!SuperDeads.empty())
  403. MI->addRegisterDead(SuperDeads.pop_back_val(), TRI, true);
  404. while (!SuperDefs.empty())
  405. MI->addRegisterDefined(SuperDefs.pop_back_val(), TRI);
  406. DEBUG(dbgs() << "> " << *MI);
  407. // Finally, remove any identity copies.
  408. if (MI->isIdentityCopy()) {
  409. ++NumIdCopies;
  410. DEBUG(dbgs() << "Deleting identity copy.\n");
  411. if (Indexes)
  412. Indexes->removeMachineInstrFromMaps(MI);
  413. // It's safe to erase MI because MII has already been incremented.
  414. MI->eraseFromParent();
  415. }
  416. }
  417. }
  418. // Tell MRI about physical registers in use.
  419. if (NoReturnInsts.empty()) {
  420. for (SparseSet<unsigned>::iterator
  421. RegI = PhysRegs.begin(), E = PhysRegs.end(); RegI != E; ++RegI)
  422. if (!MRI->reg_nodbg_empty(*RegI))
  423. MRI->setPhysRegUsed(*RegI);
  424. } else {
  425. for (SparseSet<unsigned>::iterator
  426. I = PhysRegs.begin(), E = PhysRegs.end(); I != E; ++I) {
  427. unsigned Reg = *I;
  428. if (MRI->reg_nodbg_empty(Reg))
  429. continue;
  430. // Check if this register has a use that will impact the rest of the
  431. // code. Uses in debug and noreturn instructions do not impact the
  432. // generated code.
  433. for (MachineInstr &It : MRI->reg_nodbg_instructions(Reg)) {
  434. if (!NoReturnInsts.count(&It)) {
  435. MRI->setPhysRegUsed(Reg);
  436. break;
  437. }
  438. }
  439. }
  440. }
  441. }