LiveVariables.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690
  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/Target/TargetRegisterInfo.h"
  33. #include "llvm/Target/TargetInstrInfo.h"
  34. #include "llvm/Target/TargetMachine.h"
  35. #include "llvm/ADT/DepthFirstIterator.h"
  36. #include "llvm/ADT/SmallPtrSet.h"
  37. #include "llvm/ADT/SmallSet.h"
  38. #include "llvm/ADT/STLExtras.h"
  39. #include "llvm/Config/alloca.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. void LiveVariables::VarInfo::dump() const {
  50. cerr << " Alive in blocks: ";
  51. for (SparseBitVector<>::iterator I = AliveBlocks.begin(),
  52. E = AliveBlocks.end(); I != E; ++I)
  53. cerr << *I << ", ";
  54. cerr << "\n Killed by:";
  55. if (Kills.empty())
  56. cerr << " No instructions.\n";
  57. else {
  58. for (unsigned i = 0, e = Kills.size(); i != e; ++i)
  59. cerr << "\n #" << i << ": " << *Kills[i];
  60. cerr << "\n";
  61. }
  62. }
  63. /// getVarInfo - Get (possibly creating) a VarInfo object for the given vreg.
  64. LiveVariables::VarInfo &LiveVariables::getVarInfo(unsigned RegIdx) {
  65. assert(TargetRegisterInfo::isVirtualRegister(RegIdx) &&
  66. "getVarInfo: not a virtual register!");
  67. RegIdx -= TargetRegisterInfo::FirstVirtualRegister;
  68. if (RegIdx >= VirtRegInfo.size()) {
  69. if (RegIdx >= 2*VirtRegInfo.size())
  70. VirtRegInfo.resize(RegIdx*2);
  71. else
  72. VirtRegInfo.resize(2*VirtRegInfo.size());
  73. }
  74. return VirtRegInfo[RegIdx];
  75. }
  76. void LiveVariables::MarkVirtRegAliveInBlock(VarInfo& VRInfo,
  77. MachineBasicBlock *DefBlock,
  78. MachineBasicBlock *MBB,
  79. std::vector<MachineBasicBlock*> &WorkList) {
  80. unsigned BBNum = MBB->getNumber();
  81. // Check to see if this basic block is one of the killing blocks. If so,
  82. // remove it.
  83. for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i)
  84. if (VRInfo.Kills[i]->getParent() == MBB) {
  85. VRInfo.Kills.erase(VRInfo.Kills.begin()+i); // Erase entry
  86. break;
  87. }
  88. if (MBB == DefBlock) return; // Terminate recursion
  89. if (VRInfo.AliveBlocks.test(BBNum))
  90. return; // We already know the block is live
  91. // Mark the variable known alive in this bb
  92. VRInfo.AliveBlocks.set(BBNum);
  93. for (MachineBasicBlock::const_pred_reverse_iterator PI = MBB->pred_rbegin(),
  94. E = MBB->pred_rend(); PI != E; ++PI)
  95. WorkList.push_back(*PI);
  96. }
  97. void LiveVariables::MarkVirtRegAliveInBlock(VarInfo &VRInfo,
  98. MachineBasicBlock *DefBlock,
  99. MachineBasicBlock *MBB) {
  100. std::vector<MachineBasicBlock*> WorkList;
  101. MarkVirtRegAliveInBlock(VRInfo, DefBlock, MBB, WorkList);
  102. while (!WorkList.empty()) {
  103. MachineBasicBlock *Pred = WorkList.back();
  104. WorkList.pop_back();
  105. MarkVirtRegAliveInBlock(VRInfo, DefBlock, Pred, WorkList);
  106. }
  107. }
  108. void LiveVariables::HandleVirtRegUse(unsigned reg, MachineBasicBlock *MBB,
  109. MachineInstr *MI) {
  110. assert(MRI->getVRegDef(reg) && "Register use before def!");
  111. unsigned BBNum = MBB->getNumber();
  112. VarInfo& VRInfo = getVarInfo(reg);
  113. VRInfo.NumUses++;
  114. // Check to see if this basic block is already a kill block.
  115. if (!VRInfo.Kills.empty() && VRInfo.Kills.back()->getParent() == MBB) {
  116. // Yes, this register is killed in this basic block already. Increase the
  117. // live range by updating the kill instruction.
  118. VRInfo.Kills.back() = MI;
  119. return;
  120. }
  121. #ifndef NDEBUG
  122. for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i)
  123. assert(VRInfo.Kills[i]->getParent() != MBB && "entry should be at end!");
  124. #endif
  125. // This situation can occur:
  126. //
  127. // ,------.
  128. // | |
  129. // | v
  130. // | t2 = phi ... t1 ...
  131. // | |
  132. // | v
  133. // | t1 = ...
  134. // | ... = ... t1 ...
  135. // | |
  136. // `------'
  137. //
  138. // where there is a use in a PHI node that's a predecessor to the defining
  139. // block. We don't want to mark all predecessors as having the value "alive"
  140. // in this case.
  141. if (MBB == MRI->getVRegDef(reg)->getParent()) return;
  142. // Add a new kill entry for this basic block. If this virtual register is
  143. // already marked as alive in this basic block, that means it is alive in at
  144. // least one of the successor blocks, it's not a kill.
  145. if (!VRInfo.AliveBlocks.test(BBNum))
  146. VRInfo.Kills.push_back(MI);
  147. // Update all dominating blocks to mark them as "known live".
  148. for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
  149. E = MBB->pred_end(); PI != E; ++PI)
  150. MarkVirtRegAliveInBlock(VRInfo, MRI->getVRegDef(reg)->getParent(), *PI);
  151. }
  152. void LiveVariables::HandleVirtRegDef(unsigned Reg, MachineInstr *MI) {
  153. VarInfo &VRInfo = getVarInfo(Reg);
  154. if (VRInfo.AliveBlocks.empty())
  155. // If vr is not alive in any block, then defaults to dead.
  156. VRInfo.Kills.push_back(MI);
  157. }
  158. /// FindLastPartialDef - Return the last partial def of the specified register.
  159. /// Also returns the sub-register that's defined.
  160. MachineInstr *LiveVariables::FindLastPartialDef(unsigned Reg,
  161. unsigned &PartDefReg) {
  162. unsigned LastDefReg = 0;
  163. unsigned LastDefDist = 0;
  164. MachineInstr *LastDef = NULL;
  165. for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
  166. unsigned SubReg = *SubRegs; ++SubRegs) {
  167. MachineInstr *Def = PhysRegDef[SubReg];
  168. if (!Def)
  169. continue;
  170. unsigned Dist = DistanceMap[Def];
  171. if (Dist > LastDefDist) {
  172. LastDefReg = SubReg;
  173. LastDef = Def;
  174. LastDefDist = Dist;
  175. }
  176. }
  177. PartDefReg = LastDefReg;
  178. return LastDef;
  179. }
  180. /// HandlePhysRegUse - Turn previous partial def's into read/mod/writes. Add
  181. /// implicit defs to a machine instruction if there was an earlier def of its
  182. /// super-register.
  183. void LiveVariables::HandlePhysRegUse(unsigned Reg, MachineInstr *MI) {
  184. // If there was a previous use or a "full" def all is well.
  185. if (!PhysRegDef[Reg] && !PhysRegUse[Reg]) {
  186. // Otherwise, the last sub-register def implicitly defines this register.
  187. // e.g.
  188. // AH =
  189. // AL = ... <imp-def EAX>, <imp-kill AH>
  190. // = AH
  191. // ...
  192. // = EAX
  193. // All of the sub-registers must have been defined before the use of Reg!
  194. unsigned PartDefReg = 0;
  195. MachineInstr *LastPartialDef = FindLastPartialDef(Reg, PartDefReg);
  196. // If LastPartialDef is NULL, it must be using a livein register.
  197. if (LastPartialDef) {
  198. LastPartialDef->addOperand(MachineOperand::CreateReg(Reg, true/*IsDef*/,
  199. true/*IsImp*/));
  200. PhysRegDef[Reg] = LastPartialDef;
  201. SmallSet<unsigned, 8> Processed;
  202. for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
  203. unsigned SubReg = *SubRegs; ++SubRegs) {
  204. if (Processed.count(SubReg))
  205. continue;
  206. if (SubReg == PartDefReg || TRI->isSubRegister(PartDefReg, SubReg))
  207. continue;
  208. // This part of Reg was defined before the last partial def. It's killed
  209. // here.
  210. LastPartialDef->addOperand(MachineOperand::CreateReg(SubReg,
  211. false/*IsDef*/,
  212. true/*IsImp*/));
  213. PhysRegDef[SubReg] = LastPartialDef;
  214. for (const unsigned *SS = TRI->getSubRegisters(SubReg); *SS; ++SS)
  215. Processed.insert(*SS);
  216. }
  217. }
  218. }
  219. // Remember this use.
  220. PhysRegUse[Reg] = MI;
  221. for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
  222. unsigned SubReg = *SubRegs; ++SubRegs)
  223. PhysRegUse[SubReg] = MI;
  224. }
  225. /// hasRegisterUseBelow - Return true if the specified register is used after
  226. /// the current instruction and before it's next definition.
  227. bool LiveVariables::hasRegisterUseBelow(unsigned Reg,
  228. MachineBasicBlock::iterator I,
  229. MachineBasicBlock *MBB) {
  230. if (I == MBB->end())
  231. return false;
  232. // First find out if there are any uses / defs below.
  233. bool hasDistInfo = true;
  234. unsigned CurDist = DistanceMap[I];
  235. SmallVector<MachineInstr*, 4> Uses;
  236. SmallVector<MachineInstr*, 4> Defs;
  237. for (MachineRegisterInfo::reg_iterator RI = MRI->reg_begin(Reg),
  238. RE = MRI->reg_end(); RI != RE; ++RI) {
  239. MachineOperand &UDO = RI.getOperand();
  240. MachineInstr *UDMI = &*RI;
  241. if (UDMI->getParent() != MBB)
  242. continue;
  243. DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UDMI);
  244. bool isBelow = false;
  245. if (DI == DistanceMap.end()) {
  246. // Must be below if it hasn't been assigned a distance yet.
  247. isBelow = true;
  248. hasDistInfo = false;
  249. } else if (DI->second > CurDist)
  250. isBelow = true;
  251. if (isBelow) {
  252. if (UDO.isUse())
  253. Uses.push_back(UDMI);
  254. if (UDO.isDef())
  255. Defs.push_back(UDMI);
  256. }
  257. }
  258. if (Uses.empty())
  259. // No uses below.
  260. return false;
  261. else if (!Uses.empty() && Defs.empty())
  262. // There are uses below but no defs below.
  263. return true;
  264. // There are both uses and defs below. We need to know which comes first.
  265. if (!hasDistInfo) {
  266. // Complete DistanceMap for this MBB. This information is computed only
  267. // once per MBB.
  268. ++I;
  269. ++CurDist;
  270. for (MachineBasicBlock::iterator E = MBB->end(); I != E; ++I, ++CurDist)
  271. DistanceMap.insert(std::make_pair(I, CurDist));
  272. }
  273. unsigned EarliestUse = DistanceMap[Uses[0]];
  274. for (unsigned i = 1, e = Uses.size(); i != e; ++i) {
  275. unsigned Dist = DistanceMap[Uses[i]];
  276. if (Dist < EarliestUse)
  277. EarliestUse = Dist;
  278. }
  279. for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
  280. unsigned Dist = DistanceMap[Defs[i]];
  281. if (Dist < EarliestUse)
  282. // The register is defined before its first use below.
  283. return false;
  284. }
  285. return true;
  286. }
  287. bool LiveVariables::HandlePhysRegKill(unsigned Reg, MachineInstr *MI) {
  288. if (!PhysRegUse[Reg] && !PhysRegDef[Reg])
  289. return false;
  290. MachineInstr *LastRefOrPartRef = PhysRegUse[Reg]
  291. ? PhysRegUse[Reg] : PhysRegDef[Reg];
  292. unsigned LastRefOrPartRefDist = DistanceMap[LastRefOrPartRef];
  293. // The whole register is used.
  294. // AL =
  295. // AH =
  296. //
  297. // = AX
  298. // = AL, AX<imp-use, kill>
  299. // AX =
  300. //
  301. // Or whole register is defined, but not used at all.
  302. // AX<dead> =
  303. // ...
  304. // AX =
  305. //
  306. // Or whole register is defined, but only partly used.
  307. // AX<dead> = AL<imp-def>
  308. // = AL<kill>
  309. // AX =
  310. SmallSet<unsigned, 8> PartUses;
  311. for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
  312. unsigned SubReg = *SubRegs; ++SubRegs) {
  313. if (MachineInstr *Use = PhysRegUse[SubReg]) {
  314. PartUses.insert(SubReg);
  315. for (const unsigned *SS = TRI->getSubRegisters(SubReg); *SS; ++SS)
  316. PartUses.insert(*SS);
  317. unsigned Dist = DistanceMap[Use];
  318. if (Dist > LastRefOrPartRefDist) {
  319. LastRefOrPartRefDist = Dist;
  320. LastRefOrPartRef = Use;
  321. }
  322. }
  323. }
  324. if (LastRefOrPartRef == PhysRegDef[Reg] && LastRefOrPartRef != MI)
  325. // If the last reference is the last def, then it's not used at all.
  326. // That is, unless we are currently processing the last reference itself.
  327. LastRefOrPartRef->addRegisterDead(Reg, TRI, true);
  328. // Partial uses. Mark register def dead and add implicit def of
  329. // sub-registers which are used.
  330. // EAX<dead> = op AL<imp-def>
  331. // That is, EAX def is dead but AL def extends pass it.
  332. // Enable this after live interval analysis is fixed to improve codegen!
  333. else if (!PhysRegUse[Reg]) {
  334. PhysRegDef[Reg]->addRegisterDead(Reg, TRI, true);
  335. for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
  336. unsigned SubReg = *SubRegs; ++SubRegs) {
  337. if (PartUses.count(SubReg)) {
  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, true));
  349. LastRefOrPartRef->addRegisterKilled(SubReg, TRI, true);
  350. for (const unsigned *SS = TRI->getSubRegisters(SubReg); *SS; ++SS)
  351. PartUses.erase(*SS);
  352. }
  353. }
  354. }
  355. else
  356. LastRefOrPartRef->addRegisterKilled(Reg, TRI, true);
  357. return true;
  358. }
  359. void LiveVariables::HandlePhysRegDef(unsigned Reg, MachineInstr *MI) {
  360. // What parts of the register are previously defined?
  361. SmallSet<unsigned, 32> Live;
  362. if (PhysRegDef[Reg] || PhysRegUse[Reg]) {
  363. Live.insert(Reg);
  364. for (const unsigned *SS = TRI->getSubRegisters(Reg); *SS; ++SS)
  365. Live.insert(*SS);
  366. } else {
  367. for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
  368. unsigned SubReg = *SubRegs; ++SubRegs) {
  369. // If a register isn't itself defined, but all parts that make up of it
  370. // are defined, then consider it also defined.
  371. // e.g.
  372. // AL =
  373. // AH =
  374. // = AX
  375. if (PhysRegDef[SubReg] || PhysRegUse[SubReg]) {
  376. Live.insert(SubReg);
  377. for (const unsigned *SS = TRI->getSubRegisters(SubReg); *SS; ++SS)
  378. Live.insert(*SS);
  379. }
  380. }
  381. }
  382. // Start from the largest piece, find the last time any part of the register
  383. // is referenced.
  384. if (!HandlePhysRegKill(Reg, MI)) {
  385. // Only some of the sub-registers are used.
  386. for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
  387. unsigned SubReg = *SubRegs; ++SubRegs) {
  388. if (!Live.count(SubReg))
  389. // Skip if this sub-register isn't defined.
  390. continue;
  391. if (HandlePhysRegKill(SubReg, MI)) {
  392. Live.erase(SubReg);
  393. for (const unsigned *SS = TRI->getSubRegisters(SubReg); *SS; ++SS)
  394. Live.erase(*SS);
  395. }
  396. }
  397. assert(Live.empty() && "Not all defined registers are killed / dead?");
  398. }
  399. if (MI) {
  400. // Does this extend the live range of a super-register?
  401. SmallSet<unsigned, 8> Processed;
  402. for (const unsigned *SuperRegs = TRI->getSuperRegisters(Reg);
  403. unsigned SuperReg = *SuperRegs; ++SuperRegs) {
  404. if (Processed.count(SuperReg))
  405. continue;
  406. MachineInstr *LastRef = PhysRegUse[SuperReg]
  407. ? PhysRegUse[SuperReg] : PhysRegDef[SuperReg];
  408. if (LastRef && LastRef != MI) {
  409. // The larger register is previously defined. Now a smaller part is
  410. // being re-defined. Treat it as read/mod/write if there are uses
  411. // below.
  412. // EAX =
  413. // AX = EAX<imp-use,kill>, EAX<imp-def>
  414. // ...
  415. /// = EAX
  416. if (hasRegisterUseBelow(SuperReg, MI, MI->getParent())) {
  417. MI->addOperand(MachineOperand::CreateReg(SuperReg, false/*IsDef*/,
  418. true/*IsImp*/,true/*IsKill*/));
  419. MI->addOperand(MachineOperand::CreateReg(SuperReg, true/*IsDef*/,
  420. true/*IsImp*/));
  421. PhysRegDef[SuperReg] = MI;
  422. PhysRegUse[SuperReg] = NULL;
  423. Processed.insert(SuperReg);
  424. for (const unsigned *SS = TRI->getSubRegisters(SuperReg); *SS; ++SS) {
  425. PhysRegDef[*SS] = MI;
  426. PhysRegUse[*SS] = NULL;
  427. Processed.insert(*SS);
  428. }
  429. } else {
  430. // Otherwise, the super register is killed.
  431. if (HandlePhysRegKill(SuperReg, MI)) {
  432. PhysRegDef[SuperReg] = NULL;
  433. PhysRegUse[SuperReg] = NULL;
  434. for (const unsigned *SS = TRI->getSubRegisters(SuperReg); *SS; ++SS) {
  435. PhysRegDef[*SS] = NULL;
  436. PhysRegUse[*SS] = NULL;
  437. Processed.insert(*SS);
  438. }
  439. }
  440. }
  441. }
  442. }
  443. // Remember this def.
  444. PhysRegDef[Reg] = MI;
  445. PhysRegUse[Reg] = NULL;
  446. for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
  447. unsigned SubReg = *SubRegs; ++SubRegs) {
  448. PhysRegDef[SubReg] = MI;
  449. PhysRegUse[SubReg] = NULL;
  450. }
  451. }
  452. }
  453. bool LiveVariables::runOnMachineFunction(MachineFunction &mf) {
  454. MF = &mf;
  455. MRI = &mf.getRegInfo();
  456. TRI = MF->getTarget().getRegisterInfo();
  457. ReservedRegisters = TRI->getReservedRegs(mf);
  458. unsigned NumRegs = TRI->getNumRegs();
  459. PhysRegDef = new MachineInstr*[NumRegs];
  460. PhysRegUse = new MachineInstr*[NumRegs];
  461. PHIVarInfo = new SmallVector<unsigned, 4>[MF->getNumBlockIDs()];
  462. std::fill(PhysRegDef, PhysRegDef + NumRegs, (MachineInstr*)0);
  463. std::fill(PhysRegUse, PhysRegUse + NumRegs, (MachineInstr*)0);
  464. /// Get some space for a respectable number of registers.
  465. VirtRegInfo.resize(64);
  466. analyzePHINodes(mf);
  467. // Calculate live variable information in depth first order on the CFG of the
  468. // function. This guarantees that we will see the definition of a virtual
  469. // register before its uses due to dominance properties of SSA (except for PHI
  470. // nodes, which are treated as a special case).
  471. MachineBasicBlock *Entry = MF->begin();
  472. SmallPtrSet<MachineBasicBlock*,16> Visited;
  473. for (df_ext_iterator<MachineBasicBlock*, SmallPtrSet<MachineBasicBlock*,16> >
  474. DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
  475. DFI != E; ++DFI) {
  476. MachineBasicBlock *MBB = *DFI;
  477. // Mark live-in registers as live-in.
  478. for (MachineBasicBlock::const_livein_iterator II = MBB->livein_begin(),
  479. EE = MBB->livein_end(); II != EE; ++II) {
  480. assert(TargetRegisterInfo::isPhysicalRegister(*II) &&
  481. "Cannot have a live-in virtual register!");
  482. HandlePhysRegDef(*II, 0);
  483. }
  484. // Loop over all of the instructions, processing them.
  485. DistanceMap.clear();
  486. unsigned Dist = 0;
  487. for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
  488. I != E; ++I) {
  489. MachineInstr *MI = I;
  490. DistanceMap.insert(std::make_pair(MI, Dist++));
  491. // Process all of the operands of the instruction...
  492. unsigned NumOperandsToProcess = MI->getNumOperands();
  493. // Unless it is a PHI node. In this case, ONLY process the DEF, not any
  494. // of the uses. They will be handled in other basic blocks.
  495. if (MI->getOpcode() == TargetInstrInfo::PHI)
  496. NumOperandsToProcess = 1;
  497. SmallVector<unsigned, 4> UseRegs;
  498. SmallVector<unsigned, 4> DefRegs;
  499. for (unsigned i = 0; i != NumOperandsToProcess; ++i) {
  500. const MachineOperand &MO = MI->getOperand(i);
  501. if (!MO.isReg() || MO.getReg() == 0)
  502. continue;
  503. unsigned MOReg = MO.getReg();
  504. if (MO.isUse())
  505. UseRegs.push_back(MOReg);
  506. if (MO.isDef())
  507. DefRegs.push_back(MOReg);
  508. }
  509. // Process all uses.
  510. for (unsigned i = 0, e = UseRegs.size(); i != e; ++i) {
  511. unsigned MOReg = UseRegs[i];
  512. if (TargetRegisterInfo::isVirtualRegister(MOReg))
  513. HandleVirtRegUse(MOReg, MBB, MI);
  514. else if (!ReservedRegisters[MOReg])
  515. HandlePhysRegUse(MOReg, MI);
  516. }
  517. // Process all defs.
  518. for (unsigned i = 0, e = DefRegs.size(); i != e; ++i) {
  519. unsigned MOReg = DefRegs[i];
  520. if (TargetRegisterInfo::isVirtualRegister(MOReg))
  521. HandleVirtRegDef(MOReg, MI);
  522. else if (!ReservedRegisters[MOReg])
  523. HandlePhysRegDef(MOReg, MI);
  524. }
  525. }
  526. // Handle any virtual assignments from PHI nodes which might be at the
  527. // bottom of this basic block. We check all of our successor blocks to see
  528. // if they have PHI nodes, and if so, we simulate an assignment at the end
  529. // of the current block.
  530. if (!PHIVarInfo[MBB->getNumber()].empty()) {
  531. SmallVector<unsigned, 4>& VarInfoVec = PHIVarInfo[MBB->getNumber()];
  532. for (SmallVector<unsigned, 4>::iterator I = VarInfoVec.begin(),
  533. E = VarInfoVec.end(); I != E; ++I)
  534. // Mark it alive only in the block we are representing.
  535. MarkVirtRegAliveInBlock(getVarInfo(*I),MRI->getVRegDef(*I)->getParent(),
  536. MBB);
  537. }
  538. // Finally, if the last instruction in the block is a return, make sure to
  539. // mark it as using all of the live-out values in the function.
  540. if (!MBB->empty() && MBB->back().getDesc().isReturn()) {
  541. MachineInstr *Ret = &MBB->back();
  542. for (MachineRegisterInfo::liveout_iterator
  543. I = MF->getRegInfo().liveout_begin(),
  544. E = MF->getRegInfo().liveout_end(); I != E; ++I) {
  545. assert(TargetRegisterInfo::isPhysicalRegister(*I) &&
  546. "Cannot have a live-out virtual register!");
  547. HandlePhysRegUse(*I, Ret);
  548. // Add live-out registers as implicit uses.
  549. if (!Ret->readsRegister(*I))
  550. Ret->addOperand(MachineOperand::CreateReg(*I, false, true));
  551. }
  552. }
  553. // Loop over PhysRegDef / PhysRegUse, killing any registers that are
  554. // available at the end of the basic block.
  555. for (unsigned i = 0; i != NumRegs; ++i)
  556. if (PhysRegDef[i] || PhysRegUse[i])
  557. HandlePhysRegDef(i, 0);
  558. std::fill(PhysRegDef, PhysRegDef + NumRegs, (MachineInstr*)0);
  559. std::fill(PhysRegUse, PhysRegUse + NumRegs, (MachineInstr*)0);
  560. }
  561. // Convert and transfer the dead / killed information we have gathered into
  562. // VirtRegInfo onto MI's.
  563. for (unsigned i = 0, e1 = VirtRegInfo.size(); i != e1; ++i)
  564. for (unsigned j = 0, e2 = VirtRegInfo[i].Kills.size(); j != e2; ++j)
  565. if (VirtRegInfo[i].Kills[j] ==
  566. MRI->getVRegDef(i + TargetRegisterInfo::FirstVirtualRegister))
  567. VirtRegInfo[i]
  568. .Kills[j]->addRegisterDead(i +
  569. TargetRegisterInfo::FirstVirtualRegister,
  570. TRI);
  571. else
  572. VirtRegInfo[i]
  573. .Kills[j]->addRegisterKilled(i +
  574. TargetRegisterInfo::FirstVirtualRegister,
  575. TRI);
  576. // Check to make sure there are no unreachable blocks in the MC CFG for the
  577. // function. If so, it is due to a bug in the instruction selector or some
  578. // other part of the code generator if this happens.
  579. #ifndef NDEBUG
  580. for(MachineFunction::iterator i = MF->begin(), e = MF->end(); i != e; ++i)
  581. assert(Visited.count(&*i) != 0 && "unreachable basic block found");
  582. #endif
  583. delete[] PhysRegDef;
  584. delete[] PhysRegUse;
  585. delete[] PHIVarInfo;
  586. return false;
  587. }
  588. /// replaceKillInstruction - Update register kill info by replacing a kill
  589. /// instruction with a new one.
  590. void LiveVariables::replaceKillInstruction(unsigned Reg, MachineInstr *OldMI,
  591. MachineInstr *NewMI) {
  592. VarInfo &VI = getVarInfo(Reg);
  593. std::replace(VI.Kills.begin(), VI.Kills.end(), OldMI, NewMI);
  594. }
  595. /// removeVirtualRegistersKilled - Remove all killed info for the specified
  596. /// instruction.
  597. void LiveVariables::removeVirtualRegistersKilled(MachineInstr *MI) {
  598. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  599. MachineOperand &MO = MI->getOperand(i);
  600. if (MO.isReg() && MO.isKill()) {
  601. MO.setIsKill(false);
  602. unsigned Reg = MO.getReg();
  603. if (TargetRegisterInfo::isVirtualRegister(Reg)) {
  604. bool removed = getVarInfo(Reg).removeKill(MI);
  605. assert(removed && "kill not in register's VarInfo?");
  606. removed = true;
  607. }
  608. }
  609. }
  610. }
  611. /// analyzePHINodes - Gather information about the PHI nodes in here. In
  612. /// particular, we want to map the variable information of a virtual register
  613. /// which is used in a PHI node. We map that to the BB the vreg is coming from.
  614. ///
  615. void LiveVariables::analyzePHINodes(const MachineFunction& Fn) {
  616. for (MachineFunction::const_iterator I = Fn.begin(), E = Fn.end();
  617. I != E; ++I)
  618. for (MachineBasicBlock::const_iterator BBI = I->begin(), BBE = I->end();
  619. BBI != BBE && BBI->getOpcode() == TargetInstrInfo::PHI; ++BBI)
  620. for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2)
  621. PHIVarInfo[BBI->getOperand(i + 1).getMBB()->getNumber()]
  622. .push_back(BBI->getOperand(i).getReg());
  623. }