LiveVariables.cpp 29 KB

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