LiveVariables.cpp 29 KB

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