LiveVariables.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810
  1. //===-- LiveVariables.cpp - Live Variable Analysis for Machine Code -------===//
  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 LiveVariable analysis pass. For each machine
  11. // instruction in the function, this pass calculates the set of registers that
  12. // are immediately dead after the instruction (i.e., the instruction calculates
  13. // the value, but it is never used) and the set of registers that are used by
  14. // the instruction, but are never used after the instruction (i.e., they are
  15. // killed).
  16. //
  17. // This class computes live variables using a sparse implementation based on
  18. // the machine code SSA form. This class computes live variable information for
  19. // each virtual and _register allocatable_ physical register in a function. It
  20. // uses the dominance properties of SSA form to efficiently compute live
  21. // variables for virtual registers, and assumes that physical registers are only
  22. // live within a single basic block (allowing it to do a single local analysis
  23. // to resolve physical register lifetimes in each basic block). If a physical
  24. // register is not register allocatable, it is not tracked. This is useful for
  25. // things like the stack pointer and condition codes.
  26. //
  27. //===----------------------------------------------------------------------===//
  28. #include "llvm/CodeGen/LiveVariables.h"
  29. #include "llvm/ADT/DepthFirstIterator.h"
  30. #include "llvm/ADT/STLExtras.h"
  31. #include "llvm/ADT/SmallPtrSet.h"
  32. #include "llvm/ADT/SmallSet.h"
  33. #include "llvm/CodeGen/MachineInstr.h"
  34. #include "llvm/CodeGen/MachineRegisterInfo.h"
  35. #include "llvm/CodeGen/Passes.h"
  36. #include "llvm/Config/llvm-config.h"
  37. #include "llvm/Support/Debug.h"
  38. #include "llvm/Support/ErrorHandling.h"
  39. #include "llvm/Support/raw_ostream.h"
  40. #include <algorithm>
  41. using namespace llvm;
  42. char LiveVariables::ID = 0;
  43. char &llvm::LiveVariablesID = LiveVariables::ID;
  44. INITIALIZE_PASS_BEGIN(LiveVariables, "livevars",
  45. "Live Variable Analysis", false, false)
  46. INITIALIZE_PASS_DEPENDENCY(UnreachableMachineBlockElim)
  47. INITIALIZE_PASS_END(LiveVariables, "livevars",
  48. "Live Variable Analysis", false, false)
  49. void LiveVariables::getAnalysisUsage(AnalysisUsage &AU) const {
  50. AU.addRequiredID(UnreachableMachineBlockElimID);
  51. AU.setPreservesAll();
  52. MachineFunctionPass::getAnalysisUsage(AU);
  53. }
  54. MachineInstr *
  55. LiveVariables::VarInfo::findKill(const MachineBasicBlock *MBB) const {
  56. for (unsigned i = 0, e = Kills.size(); i != e; ++i)
  57. if (Kills[i]->getParent() == MBB)
  58. return Kills[i];
  59. return nullptr;
  60. }
  61. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  62. LLVM_DUMP_METHOD void LiveVariables::VarInfo::dump() const {
  63. dbgs() << " Alive in blocks: ";
  64. for (SparseBitVector<>::iterator I = AliveBlocks.begin(),
  65. E = AliveBlocks.end(); I != E; ++I)
  66. dbgs() << *I << ", ";
  67. dbgs() << "\n Killed by:";
  68. if (Kills.empty())
  69. dbgs() << " No instructions.\n";
  70. else {
  71. for (unsigned i = 0, e = Kills.size(); i != e; ++i)
  72. dbgs() << "\n #" << i << ": " << *Kills[i];
  73. dbgs() << "\n";
  74. }
  75. }
  76. #endif
  77. /// getVarInfo - Get (possibly creating) a VarInfo object for the given vreg.
  78. LiveVariables::VarInfo &LiveVariables::getVarInfo(unsigned RegIdx) {
  79. assert(TargetRegisterInfo::isVirtualRegister(RegIdx) &&
  80. "getVarInfo: not a virtual register!");
  81. VirtRegInfo.grow(RegIdx);
  82. return VirtRegInfo[RegIdx];
  83. }
  84. void LiveVariables::MarkVirtRegAliveInBlock(VarInfo& VRInfo,
  85. MachineBasicBlock *DefBlock,
  86. MachineBasicBlock *MBB,
  87. std::vector<MachineBasicBlock*> &WorkList) {
  88. unsigned BBNum = MBB->getNumber();
  89. // Check to see if this basic block is one of the killing blocks. If so,
  90. // remove it.
  91. for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i)
  92. if (VRInfo.Kills[i]->getParent() == MBB) {
  93. VRInfo.Kills.erase(VRInfo.Kills.begin()+i); // Erase entry
  94. break;
  95. }
  96. if (MBB == DefBlock) return; // Terminate recursion
  97. if (VRInfo.AliveBlocks.test(BBNum))
  98. return; // We already know the block is live
  99. // Mark the variable known alive in this bb
  100. VRInfo.AliveBlocks.set(BBNum);
  101. assert(MBB != &MF->front() && "Can't find reaching def for virtreg");
  102. WorkList.insert(WorkList.end(), MBB->pred_rbegin(), MBB->pred_rend());
  103. }
  104. void LiveVariables::MarkVirtRegAliveInBlock(VarInfo &VRInfo,
  105. MachineBasicBlock *DefBlock,
  106. MachineBasicBlock *MBB) {
  107. std::vector<MachineBasicBlock*> WorkList;
  108. MarkVirtRegAliveInBlock(VRInfo, DefBlock, MBB, WorkList);
  109. while (!WorkList.empty()) {
  110. MachineBasicBlock *Pred = WorkList.back();
  111. WorkList.pop_back();
  112. MarkVirtRegAliveInBlock(VRInfo, DefBlock, Pred, WorkList);
  113. }
  114. }
  115. void LiveVariables::HandleVirtRegUse(unsigned reg, MachineBasicBlock *MBB,
  116. MachineInstr &MI) {
  117. assert(MRI->getVRegDef(reg) && "Register use before def!");
  118. unsigned BBNum = MBB->getNumber();
  119. VarInfo& VRInfo = getVarInfo(reg);
  120. // Check to see if this basic block is already a kill block.
  121. if (!VRInfo.Kills.empty() && VRInfo.Kills.back()->getParent() == MBB) {
  122. // Yes, this register is killed in this basic block already. Increase the
  123. // live range by updating the kill instruction.
  124. VRInfo.Kills.back() = &MI;
  125. return;
  126. }
  127. #ifndef NDEBUG
  128. for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i)
  129. assert(VRInfo.Kills[i]->getParent() != MBB && "entry should be at end!");
  130. #endif
  131. // This situation can occur:
  132. //
  133. // ,------.
  134. // | |
  135. // | v
  136. // | t2 = phi ... t1 ...
  137. // | |
  138. // | v
  139. // | t1 = ...
  140. // | ... = ... t1 ...
  141. // | |
  142. // `------'
  143. //
  144. // where there is a use in a PHI node that's a predecessor to the defining
  145. // block. We don't want to mark all predecessors as having the value "alive"
  146. // in this case.
  147. if (MBB == MRI->getVRegDef(reg)->getParent()) return;
  148. // Add a new kill entry for this basic block. If this virtual register is
  149. // already marked as alive in this basic block, that means it is alive in at
  150. // least one of the successor blocks, it's not a kill.
  151. if (!VRInfo.AliveBlocks.test(BBNum))
  152. VRInfo.Kills.push_back(&MI);
  153. // Update all dominating blocks to mark them as "known live".
  154. for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
  155. E = MBB->pred_end(); PI != E; ++PI)
  156. MarkVirtRegAliveInBlock(VRInfo, MRI->getVRegDef(reg)->getParent(), *PI);
  157. }
  158. void LiveVariables::HandleVirtRegDef(unsigned Reg, MachineInstr &MI) {
  159. VarInfo &VRInfo = getVarInfo(Reg);
  160. if (VRInfo.AliveBlocks.empty())
  161. // If vr is not alive in any block, then defaults to dead.
  162. VRInfo.Kills.push_back(&MI);
  163. }
  164. /// FindLastPartialDef - Return the last partial def of the specified register.
  165. /// Also returns the sub-registers that're defined by the instruction.
  166. MachineInstr *LiveVariables::FindLastPartialDef(unsigned Reg,
  167. SmallSet<unsigned,4> &PartDefRegs) {
  168. unsigned LastDefReg = 0;
  169. unsigned LastDefDist = 0;
  170. MachineInstr *LastDef = nullptr;
  171. for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
  172. unsigned SubReg = *SubRegs;
  173. MachineInstr *Def = PhysRegDef[SubReg];
  174. if (!Def)
  175. continue;
  176. unsigned Dist = DistanceMap[Def];
  177. if (Dist > LastDefDist) {
  178. LastDefReg = SubReg;
  179. LastDef = Def;
  180. LastDefDist = Dist;
  181. }
  182. }
  183. if (!LastDef)
  184. return nullptr;
  185. PartDefRegs.insert(LastDefReg);
  186. for (unsigned i = 0, e = LastDef->getNumOperands(); i != e; ++i) {
  187. MachineOperand &MO = LastDef->getOperand(i);
  188. if (!MO.isReg() || !MO.isDef() || MO.getReg() == 0)
  189. continue;
  190. unsigned DefReg = MO.getReg();
  191. if (TRI->isSubRegister(Reg, DefReg)) {
  192. for (MCSubRegIterator SubRegs(DefReg, TRI, /*IncludeSelf=*/true);
  193. SubRegs.isValid(); ++SubRegs)
  194. PartDefRegs.insert(*SubRegs);
  195. }
  196. }
  197. return LastDef;
  198. }
  199. /// HandlePhysRegUse - Turn previous partial def's into read/mod/writes. Add
  200. /// implicit defs to a machine instruction if there was an earlier def of its
  201. /// super-register.
  202. void LiveVariables::HandlePhysRegUse(unsigned Reg, MachineInstr &MI) {
  203. MachineInstr *LastDef = PhysRegDef[Reg];
  204. // If there was a previous use or a "full" def all is well.
  205. if (!LastDef && !PhysRegUse[Reg]) {
  206. // Otherwise, the last sub-register def implicitly defines this register.
  207. // e.g.
  208. // AH =
  209. // AL = ... implicit-def EAX, implicit killed AH
  210. // = AH
  211. // ...
  212. // = EAX
  213. // All of the sub-registers must have been defined before the use of Reg!
  214. SmallSet<unsigned, 4> PartDefRegs;
  215. MachineInstr *LastPartialDef = FindLastPartialDef(Reg, PartDefRegs);
  216. // If LastPartialDef is NULL, it must be using a livein register.
  217. if (LastPartialDef) {
  218. LastPartialDef->addOperand(MachineOperand::CreateReg(Reg, true/*IsDef*/,
  219. true/*IsImp*/));
  220. PhysRegDef[Reg] = LastPartialDef;
  221. SmallSet<unsigned, 8> Processed;
  222. for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
  223. unsigned SubReg = *SubRegs;
  224. if (Processed.count(SubReg))
  225. continue;
  226. if (PartDefRegs.count(SubReg))
  227. continue;
  228. // This part of Reg was defined before the last partial def. It's killed
  229. // here.
  230. LastPartialDef->addOperand(MachineOperand::CreateReg(SubReg,
  231. false/*IsDef*/,
  232. true/*IsImp*/));
  233. PhysRegDef[SubReg] = LastPartialDef;
  234. for (MCSubRegIterator SS(SubReg, TRI); SS.isValid(); ++SS)
  235. Processed.insert(*SS);
  236. }
  237. }
  238. } else if (LastDef && !PhysRegUse[Reg] &&
  239. !LastDef->findRegisterDefOperand(Reg))
  240. // Last def defines the super register, add an implicit def of reg.
  241. LastDef->addOperand(MachineOperand::CreateReg(Reg, true/*IsDef*/,
  242. true/*IsImp*/));
  243. // Remember this use.
  244. for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
  245. SubRegs.isValid(); ++SubRegs)
  246. PhysRegUse[*SubRegs] = &MI;
  247. }
  248. /// FindLastRefOrPartRef - Return the last reference or partial reference of
  249. /// the specified register.
  250. MachineInstr *LiveVariables::FindLastRefOrPartRef(unsigned Reg) {
  251. MachineInstr *LastDef = PhysRegDef[Reg];
  252. MachineInstr *LastUse = PhysRegUse[Reg];
  253. if (!LastDef && !LastUse)
  254. return nullptr;
  255. MachineInstr *LastRefOrPartRef = LastUse ? LastUse : LastDef;
  256. unsigned LastRefOrPartRefDist = DistanceMap[LastRefOrPartRef];
  257. unsigned LastPartDefDist = 0;
  258. for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
  259. unsigned SubReg = *SubRegs;
  260. MachineInstr *Def = PhysRegDef[SubReg];
  261. if (Def && Def != LastDef) {
  262. // There was a def of this sub-register in between. This is a partial
  263. // def, keep track of the last one.
  264. unsigned Dist = DistanceMap[Def];
  265. if (Dist > LastPartDefDist)
  266. LastPartDefDist = Dist;
  267. } else if (MachineInstr *Use = PhysRegUse[SubReg]) {
  268. unsigned Dist = DistanceMap[Use];
  269. if (Dist > LastRefOrPartRefDist) {
  270. LastRefOrPartRefDist = Dist;
  271. LastRefOrPartRef = Use;
  272. }
  273. }
  274. }
  275. return LastRefOrPartRef;
  276. }
  277. bool LiveVariables::HandlePhysRegKill(unsigned Reg, MachineInstr *MI) {
  278. MachineInstr *LastDef = PhysRegDef[Reg];
  279. MachineInstr *LastUse = PhysRegUse[Reg];
  280. if (!LastDef && !LastUse)
  281. return false;
  282. MachineInstr *LastRefOrPartRef = LastUse ? LastUse : LastDef;
  283. unsigned LastRefOrPartRefDist = DistanceMap[LastRefOrPartRef];
  284. // The whole register is used.
  285. // AL =
  286. // AH =
  287. //
  288. // = AX
  289. // = AL, implicit killed AX
  290. // AX =
  291. //
  292. // Or whole register is defined, but not used at all.
  293. // dead AX =
  294. // ...
  295. // AX =
  296. //
  297. // Or whole register is defined, but only partly used.
  298. // dead AX = implicit-def AL
  299. // = killed AL
  300. // AX =
  301. MachineInstr *LastPartDef = nullptr;
  302. unsigned LastPartDefDist = 0;
  303. SmallSet<unsigned, 8> PartUses;
  304. for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
  305. unsigned SubReg = *SubRegs;
  306. MachineInstr *Def = PhysRegDef[SubReg];
  307. if (Def && Def != LastDef) {
  308. // There was a def of this sub-register in between. This is a partial
  309. // def, keep track of the last one.
  310. unsigned Dist = DistanceMap[Def];
  311. if (Dist > LastPartDefDist) {
  312. LastPartDefDist = Dist;
  313. LastPartDef = Def;
  314. }
  315. continue;
  316. }
  317. if (MachineInstr *Use = PhysRegUse[SubReg]) {
  318. for (MCSubRegIterator SS(SubReg, TRI, /*IncludeSelf=*/true); SS.isValid();
  319. ++SS)
  320. PartUses.insert(*SS);
  321. unsigned Dist = DistanceMap[Use];
  322. if (Dist > LastRefOrPartRefDist) {
  323. LastRefOrPartRefDist = Dist;
  324. LastRefOrPartRef = Use;
  325. }
  326. }
  327. }
  328. if (!PhysRegUse[Reg]) {
  329. // Partial uses. Mark register def dead and add implicit def of
  330. // sub-registers which are used.
  331. // dead EAX = op implicit-def AL
  332. // That is, EAX def is dead but AL def extends pass it.
  333. PhysRegDef[Reg]->addRegisterDead(Reg, TRI, true);
  334. for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
  335. unsigned SubReg = *SubRegs;
  336. if (!PartUses.count(SubReg))
  337. continue;
  338. bool NeedDef = true;
  339. if (PhysRegDef[Reg] == PhysRegDef[SubReg]) {
  340. MachineOperand *MO = PhysRegDef[Reg]->findRegisterDefOperand(SubReg);
  341. if (MO) {
  342. NeedDef = false;
  343. assert(!MO->isDead());
  344. }
  345. }
  346. if (NeedDef)
  347. PhysRegDef[Reg]->addOperand(MachineOperand::CreateReg(SubReg,
  348. true/*IsDef*/, true/*IsImp*/));
  349. MachineInstr *LastSubRef = FindLastRefOrPartRef(SubReg);
  350. if (LastSubRef)
  351. LastSubRef->addRegisterKilled(SubReg, TRI, true);
  352. else {
  353. LastRefOrPartRef->addRegisterKilled(SubReg, TRI, true);
  354. for (MCSubRegIterator SS(SubReg, TRI, /*IncludeSelf=*/true);
  355. SS.isValid(); ++SS)
  356. PhysRegUse[*SS] = LastRefOrPartRef;
  357. }
  358. for (MCSubRegIterator SS(SubReg, TRI); SS.isValid(); ++SS)
  359. PartUses.erase(*SS);
  360. }
  361. } else if (LastRefOrPartRef == PhysRegDef[Reg] && LastRefOrPartRef != MI) {
  362. if (LastPartDef)
  363. // The last partial def kills the register.
  364. LastPartDef->addOperand(MachineOperand::CreateReg(Reg, false/*IsDef*/,
  365. true/*IsImp*/, true/*IsKill*/));
  366. else {
  367. MachineOperand *MO =
  368. LastRefOrPartRef->findRegisterDefOperand(Reg, false, TRI);
  369. bool NeedEC = MO->isEarlyClobber() && MO->getReg() != Reg;
  370. // If the last reference is the last def, then it's not used at all.
  371. // That is, unless we are currently processing the last reference itself.
  372. LastRefOrPartRef->addRegisterDead(Reg, TRI, true);
  373. if (NeedEC) {
  374. // If we are adding a subreg def and the superreg def is marked early
  375. // clobber, add an early clobber marker to the subreg def.
  376. MO = LastRefOrPartRef->findRegisterDefOperand(Reg);
  377. if (MO)
  378. MO->setIsEarlyClobber();
  379. }
  380. }
  381. } else
  382. LastRefOrPartRef->addRegisterKilled(Reg, TRI, true);
  383. return true;
  384. }
  385. void LiveVariables::HandleRegMask(const MachineOperand &MO) {
  386. // Call HandlePhysRegKill() for all live registers clobbered by Mask.
  387. // Clobbered registers are always dead, sp there is no need to use
  388. // HandlePhysRegDef().
  389. for (unsigned Reg = 1, NumRegs = TRI->getNumRegs(); Reg != NumRegs; ++Reg) {
  390. // Skip dead regs.
  391. if (!PhysRegDef[Reg] && !PhysRegUse[Reg])
  392. continue;
  393. // Skip mask-preserved regs.
  394. if (!MO.clobbersPhysReg(Reg))
  395. continue;
  396. // Kill the largest clobbered super-register.
  397. // This avoids needless implicit operands.
  398. unsigned Super = Reg;
  399. for (MCSuperRegIterator SR(Reg, TRI); SR.isValid(); ++SR)
  400. if ((PhysRegDef[*SR] || PhysRegUse[*SR]) && MO.clobbersPhysReg(*SR))
  401. Super = *SR;
  402. HandlePhysRegKill(Super, nullptr);
  403. }
  404. }
  405. void LiveVariables::HandlePhysRegDef(unsigned Reg, MachineInstr *MI,
  406. SmallVectorImpl<unsigned> &Defs) {
  407. // What parts of the register are previously defined?
  408. SmallSet<unsigned, 32> Live;
  409. if (PhysRegDef[Reg] || PhysRegUse[Reg]) {
  410. for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
  411. SubRegs.isValid(); ++SubRegs)
  412. Live.insert(*SubRegs);
  413. } else {
  414. for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
  415. unsigned SubReg = *SubRegs;
  416. // If a register isn't itself defined, but all parts that make up of it
  417. // are defined, then consider it also defined.
  418. // e.g.
  419. // AL =
  420. // AH =
  421. // = AX
  422. if (Live.count(SubReg))
  423. continue;
  424. if (PhysRegDef[SubReg] || PhysRegUse[SubReg]) {
  425. for (MCSubRegIterator SS(SubReg, TRI, /*IncludeSelf=*/true);
  426. SS.isValid(); ++SS)
  427. Live.insert(*SS);
  428. }
  429. }
  430. }
  431. // Start from the largest piece, find the last time any part of the register
  432. // is referenced.
  433. HandlePhysRegKill(Reg, MI);
  434. // Only some of the sub-registers are used.
  435. for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
  436. unsigned SubReg = *SubRegs;
  437. if (!Live.count(SubReg))
  438. // Skip if this sub-register isn't defined.
  439. continue;
  440. HandlePhysRegKill(SubReg, MI);
  441. }
  442. if (MI)
  443. Defs.push_back(Reg); // Remember this def.
  444. }
  445. void LiveVariables::UpdatePhysRegDefs(MachineInstr &MI,
  446. SmallVectorImpl<unsigned> &Defs) {
  447. while (!Defs.empty()) {
  448. unsigned Reg = Defs.back();
  449. Defs.pop_back();
  450. for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
  451. SubRegs.isValid(); ++SubRegs) {
  452. unsigned SubReg = *SubRegs;
  453. PhysRegDef[SubReg] = &MI;
  454. PhysRegUse[SubReg] = nullptr;
  455. }
  456. }
  457. }
  458. void LiveVariables::runOnInstr(MachineInstr &MI,
  459. SmallVectorImpl<unsigned> &Defs) {
  460. assert(!MI.isDebugInstr());
  461. // Process all of the operands of the instruction...
  462. unsigned NumOperandsToProcess = MI.getNumOperands();
  463. // Unless it is a PHI node. In this case, ONLY process the DEF, not any
  464. // of the uses. They will be handled in other basic blocks.
  465. if (MI.isPHI())
  466. NumOperandsToProcess = 1;
  467. // Clear kill and dead markers. LV will recompute them.
  468. SmallVector<unsigned, 4> UseRegs;
  469. SmallVector<unsigned, 4> DefRegs;
  470. SmallVector<unsigned, 1> RegMasks;
  471. for (unsigned i = 0; i != NumOperandsToProcess; ++i) {
  472. MachineOperand &MO = MI.getOperand(i);
  473. if (MO.isRegMask()) {
  474. RegMasks.push_back(i);
  475. continue;
  476. }
  477. if (!MO.isReg() || MO.getReg() == 0)
  478. continue;
  479. unsigned MOReg = MO.getReg();
  480. if (MO.isUse()) {
  481. if (!(TargetRegisterInfo::isPhysicalRegister(MOReg) &&
  482. MRI->isReserved(MOReg)))
  483. MO.setIsKill(false);
  484. if (MO.readsReg())
  485. UseRegs.push_back(MOReg);
  486. } else {
  487. assert(MO.isDef());
  488. // FIXME: We should not remove any dead flags. However the MIPS RDDSP
  489. // instruction needs it at the moment: http://llvm.org/PR27116.
  490. if (TargetRegisterInfo::isPhysicalRegister(MOReg) &&
  491. !MRI->isReserved(MOReg))
  492. MO.setIsDead(false);
  493. DefRegs.push_back(MOReg);
  494. }
  495. }
  496. MachineBasicBlock *MBB = MI.getParent();
  497. // Process all uses.
  498. for (unsigned i = 0, e = UseRegs.size(); i != e; ++i) {
  499. unsigned MOReg = UseRegs[i];
  500. if (TargetRegisterInfo::isVirtualRegister(MOReg))
  501. HandleVirtRegUse(MOReg, MBB, MI);
  502. else if (!MRI->isReserved(MOReg))
  503. HandlePhysRegUse(MOReg, MI);
  504. }
  505. // Process all masked registers. (Call clobbers).
  506. for (unsigned i = 0, e = RegMasks.size(); i != e; ++i)
  507. HandleRegMask(MI.getOperand(RegMasks[i]));
  508. // Process all defs.
  509. for (unsigned i = 0, e = DefRegs.size(); i != e; ++i) {
  510. unsigned MOReg = DefRegs[i];
  511. if (TargetRegisterInfo::isVirtualRegister(MOReg))
  512. HandleVirtRegDef(MOReg, MI);
  513. else if (!MRI->isReserved(MOReg))
  514. HandlePhysRegDef(MOReg, &MI, Defs);
  515. }
  516. UpdatePhysRegDefs(MI, Defs);
  517. }
  518. void LiveVariables::runOnBlock(MachineBasicBlock *MBB, const unsigned NumRegs) {
  519. // Mark live-in registers as live-in.
  520. SmallVector<unsigned, 4> Defs;
  521. for (const auto &LI : MBB->liveins()) {
  522. assert(TargetRegisterInfo::isPhysicalRegister(LI.PhysReg) &&
  523. "Cannot have a live-in virtual register!");
  524. HandlePhysRegDef(LI.PhysReg, nullptr, Defs);
  525. }
  526. // Loop over all of the instructions, processing them.
  527. DistanceMap.clear();
  528. unsigned Dist = 0;
  529. for (MachineInstr &MI : *MBB) {
  530. if (MI.isDebugInstr())
  531. continue;
  532. DistanceMap.insert(std::make_pair(&MI, Dist++));
  533. runOnInstr(MI, Defs);
  534. }
  535. // Handle any virtual assignments from PHI nodes which might be at the
  536. // bottom of this basic block. We check all of our successor blocks to see
  537. // if they have PHI nodes, and if so, we simulate an assignment at the end
  538. // of the current block.
  539. if (!PHIVarInfo[MBB->getNumber()].empty()) {
  540. SmallVectorImpl<unsigned> &VarInfoVec = PHIVarInfo[MBB->getNumber()];
  541. for (SmallVectorImpl<unsigned>::iterator I = VarInfoVec.begin(),
  542. E = VarInfoVec.end(); I != E; ++I)
  543. // Mark it alive only in the block we are representing.
  544. MarkVirtRegAliveInBlock(getVarInfo(*I),MRI->getVRegDef(*I)->getParent(),
  545. MBB);
  546. }
  547. // MachineCSE may CSE instructions which write to non-allocatable physical
  548. // registers across MBBs. Remember if any reserved register is liveout.
  549. SmallSet<unsigned, 4> LiveOuts;
  550. for (MachineBasicBlock::const_succ_iterator SI = MBB->succ_begin(),
  551. SE = MBB->succ_end(); SI != SE; ++SI) {
  552. MachineBasicBlock *SuccMBB = *SI;
  553. if (SuccMBB->isEHPad())
  554. continue;
  555. for (const auto &LI : SuccMBB->liveins()) {
  556. if (!TRI->isInAllocatableClass(LI.PhysReg))
  557. // Ignore other live-ins, e.g. those that are live into landing pads.
  558. LiveOuts.insert(LI.PhysReg);
  559. }
  560. }
  561. // Loop over PhysRegDef / PhysRegUse, killing any registers that are
  562. // available at the end of the basic block.
  563. for (unsigned i = 0; i != NumRegs; ++i)
  564. if ((PhysRegDef[i] || PhysRegUse[i]) && !LiveOuts.count(i))
  565. HandlePhysRegDef(i, nullptr, Defs);
  566. }
  567. bool LiveVariables::runOnMachineFunction(MachineFunction &mf) {
  568. MF = &mf;
  569. MRI = &mf.getRegInfo();
  570. TRI = MF->getSubtarget().getRegisterInfo();
  571. const unsigned NumRegs = TRI->getNumRegs();
  572. PhysRegDef.assign(NumRegs, nullptr);
  573. PhysRegUse.assign(NumRegs, nullptr);
  574. PHIVarInfo.resize(MF->getNumBlockIDs());
  575. PHIJoins.clear();
  576. // FIXME: LiveIntervals will be updated to remove its dependence on
  577. // LiveVariables to improve compilation time and eliminate bizarre pass
  578. // dependencies. Until then, we can't change much in -O0.
  579. if (!MRI->isSSA())
  580. report_fatal_error("regalloc=... not currently supported with -O0");
  581. analyzePHINodes(mf);
  582. // Calculate live variable information in depth first order on the CFG of the
  583. // function. This guarantees that we will see the definition of a virtual
  584. // register before its uses due to dominance properties of SSA (except for PHI
  585. // nodes, which are treated as a special case).
  586. MachineBasicBlock *Entry = &MF->front();
  587. df_iterator_default_set<MachineBasicBlock*,16> Visited;
  588. for (MachineBasicBlock *MBB : depth_first_ext(Entry, Visited)) {
  589. runOnBlock(MBB, NumRegs);
  590. PhysRegDef.assign(NumRegs, nullptr);
  591. PhysRegUse.assign(NumRegs, nullptr);
  592. }
  593. // Convert and transfer the dead / killed information we have gathered into
  594. // VirtRegInfo onto MI's.
  595. for (unsigned i = 0, e1 = VirtRegInfo.size(); i != e1; ++i) {
  596. const unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
  597. for (unsigned j = 0, e2 = VirtRegInfo[Reg].Kills.size(); j != e2; ++j)
  598. if (VirtRegInfo[Reg].Kills[j] == MRI->getVRegDef(Reg))
  599. VirtRegInfo[Reg].Kills[j]->addRegisterDead(Reg, TRI);
  600. else
  601. VirtRegInfo[Reg].Kills[j]->addRegisterKilled(Reg, TRI);
  602. }
  603. // Check to make sure there are no unreachable blocks in the MC CFG for the
  604. // function. If so, it is due to a bug in the instruction selector or some
  605. // other part of the code generator if this happens.
  606. #ifndef NDEBUG
  607. for(MachineFunction::iterator i = MF->begin(), e = MF->end(); i != e; ++i)
  608. assert(Visited.count(&*i) != 0 && "unreachable basic block found");
  609. #endif
  610. PhysRegDef.clear();
  611. PhysRegUse.clear();
  612. PHIVarInfo.clear();
  613. return false;
  614. }
  615. /// replaceKillInstruction - Update register kill info by replacing a kill
  616. /// instruction with a new one.
  617. void LiveVariables::replaceKillInstruction(unsigned Reg, MachineInstr &OldMI,
  618. MachineInstr &NewMI) {
  619. VarInfo &VI = getVarInfo(Reg);
  620. std::replace(VI.Kills.begin(), VI.Kills.end(), &OldMI, &NewMI);
  621. }
  622. /// removeVirtualRegistersKilled - Remove all killed info for the specified
  623. /// instruction.
  624. void LiveVariables::removeVirtualRegistersKilled(MachineInstr &MI) {
  625. for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
  626. MachineOperand &MO = MI.getOperand(i);
  627. if (MO.isReg() && MO.isKill()) {
  628. MO.setIsKill(false);
  629. unsigned Reg = MO.getReg();
  630. if (TargetRegisterInfo::isVirtualRegister(Reg)) {
  631. bool removed = getVarInfo(Reg).removeKill(MI);
  632. assert(removed && "kill not in register's VarInfo?");
  633. (void)removed;
  634. }
  635. }
  636. }
  637. }
  638. /// analyzePHINodes - Gather information about the PHI nodes in here. In
  639. /// particular, we want to map the variable information of a virtual register
  640. /// which is used in a PHI node. We map that to the BB the vreg is coming from.
  641. ///
  642. void LiveVariables::analyzePHINodes(const MachineFunction& Fn) {
  643. for (const auto &MBB : Fn)
  644. for (const auto &BBI : MBB) {
  645. if (!BBI.isPHI())
  646. break;
  647. for (unsigned i = 1, e = BBI.getNumOperands(); i != e; i += 2)
  648. if (BBI.getOperand(i).readsReg())
  649. PHIVarInfo[BBI.getOperand(i + 1).getMBB()->getNumber()]
  650. .push_back(BBI.getOperand(i).getReg());
  651. }
  652. }
  653. bool LiveVariables::VarInfo::isLiveIn(const MachineBasicBlock &MBB,
  654. unsigned Reg,
  655. MachineRegisterInfo &MRI) {
  656. unsigned Num = MBB.getNumber();
  657. // Reg is live-through.
  658. if (AliveBlocks.test(Num))
  659. return true;
  660. // Registers defined in MBB cannot be live in.
  661. const MachineInstr *Def = MRI.getVRegDef(Reg);
  662. if (Def && Def->getParent() == &MBB)
  663. return false;
  664. // Reg was not defined in MBB, was it killed here?
  665. return findKill(&MBB);
  666. }
  667. bool LiveVariables::isLiveOut(unsigned Reg, const MachineBasicBlock &MBB) {
  668. LiveVariables::VarInfo &VI = getVarInfo(Reg);
  669. SmallPtrSet<const MachineBasicBlock *, 8> Kills;
  670. for (unsigned i = 0, e = VI.Kills.size(); i != e; ++i)
  671. Kills.insert(VI.Kills[i]->getParent());
  672. // Loop over all of the successors of the basic block, checking to see if
  673. // the value is either live in the block, or if it is killed in the block.
  674. for (const MachineBasicBlock *SuccMBB : MBB.successors()) {
  675. // Is it alive in this successor?
  676. unsigned SuccIdx = SuccMBB->getNumber();
  677. if (VI.AliveBlocks.test(SuccIdx))
  678. return true;
  679. // Or is it live because there is a use in a successor that kills it?
  680. if (Kills.count(SuccMBB))
  681. return true;
  682. }
  683. return false;
  684. }
  685. /// addNewBlock - Add a new basic block BB as an empty succcessor to DomBB. All
  686. /// variables that are live out of DomBB will be marked as passing live through
  687. /// BB.
  688. void LiveVariables::addNewBlock(MachineBasicBlock *BB,
  689. MachineBasicBlock *DomBB,
  690. MachineBasicBlock *SuccBB) {
  691. const unsigned NumNew = BB->getNumber();
  692. DenseSet<unsigned> Defs, Kills;
  693. MachineBasicBlock::iterator BBI = SuccBB->begin(), BBE = SuccBB->end();
  694. for (; BBI != BBE && BBI->isPHI(); ++BBI) {
  695. // Record the def of the PHI node.
  696. Defs.insert(BBI->getOperand(0).getReg());
  697. // All registers used by PHI nodes in SuccBB must be live through BB.
  698. for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2)
  699. if (BBI->getOperand(i+1).getMBB() == BB)
  700. getVarInfo(BBI->getOperand(i).getReg()).AliveBlocks.set(NumNew);
  701. }
  702. // Record all vreg defs and kills of all instructions in SuccBB.
  703. for (; BBI != BBE; ++BBI) {
  704. for (MachineInstr::mop_iterator I = BBI->operands_begin(),
  705. E = BBI->operands_end(); I != E; ++I) {
  706. if (I->isReg() && TargetRegisterInfo::isVirtualRegister(I->getReg())) {
  707. if (I->isDef())
  708. Defs.insert(I->getReg());
  709. else if (I->isKill())
  710. Kills.insert(I->getReg());
  711. }
  712. }
  713. }
  714. // Update info for all live variables
  715. for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
  716. unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
  717. // If the Defs is defined in the successor it can't be live in BB.
  718. if (Defs.count(Reg))
  719. continue;
  720. // If the register is either killed in or live through SuccBB it's also live
  721. // through BB.
  722. VarInfo &VI = getVarInfo(Reg);
  723. if (Kills.count(Reg) || VI.AliveBlocks.test(SuccBB->getNumber()))
  724. VI.AliveBlocks.set(NumNew);
  725. }
  726. }