MachineCSE.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  1. //===-- MachineCSE.cpp - Machine Common Subexpression Elimination Pass ----===//
  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 pass performs global common subexpression elimination on machine
  11. // instructions using a scoped hash table based value numbering scheme. It
  12. // must be run while the machine function is still in SSA form.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #define DEBUG_TYPE "machine-cse"
  16. #include "llvm/CodeGen/Passes.h"
  17. #include "llvm/CodeGen/MachineDominators.h"
  18. #include "llvm/CodeGen/MachineInstr.h"
  19. #include "llvm/CodeGen/MachineRegisterInfo.h"
  20. #include "llvm/Analysis/AliasAnalysis.h"
  21. #include "llvm/Target/TargetInstrInfo.h"
  22. #include "llvm/ADT/DenseMap.h"
  23. #include "llvm/ADT/ScopedHashTable.h"
  24. #include "llvm/ADT/SmallSet.h"
  25. #include "llvm/ADT/Statistic.h"
  26. #include "llvm/Support/Debug.h"
  27. #include "llvm/Support/RecyclingAllocator.h"
  28. using namespace llvm;
  29. STATISTIC(NumCoalesces, "Number of copies coalesced");
  30. STATISTIC(NumCSEs, "Number of common subexpression eliminated");
  31. STATISTIC(NumPhysCSEs,
  32. "Number of physreg referencing common subexpr eliminated");
  33. STATISTIC(NumCrossBBCSEs,
  34. "Number of cross-MBB physreg referencing CS eliminated");
  35. STATISTIC(NumCommutes, "Number of copies coalesced after commuting");
  36. namespace {
  37. class MachineCSE : public MachineFunctionPass {
  38. const TargetInstrInfo *TII;
  39. const TargetRegisterInfo *TRI;
  40. AliasAnalysis *AA;
  41. MachineDominatorTree *DT;
  42. MachineRegisterInfo *MRI;
  43. public:
  44. static char ID; // Pass identification
  45. MachineCSE() : MachineFunctionPass(ID), LookAheadLimit(5), CurrVN(0) {
  46. initializeMachineCSEPass(*PassRegistry::getPassRegistry());
  47. }
  48. virtual bool runOnMachineFunction(MachineFunction &MF);
  49. virtual void getAnalysisUsage(AnalysisUsage &AU) const {
  50. AU.setPreservesCFG();
  51. MachineFunctionPass::getAnalysisUsage(AU);
  52. AU.addRequired<AliasAnalysis>();
  53. AU.addPreservedID(MachineLoopInfoID);
  54. AU.addRequired<MachineDominatorTree>();
  55. AU.addPreserved<MachineDominatorTree>();
  56. }
  57. virtual void releaseMemory() {
  58. ScopeMap.clear();
  59. Exps.clear();
  60. AllocatableRegs.clear();
  61. ReservedRegs.clear();
  62. }
  63. private:
  64. const unsigned LookAheadLimit;
  65. typedef RecyclingAllocator<BumpPtrAllocator,
  66. ScopedHashTableVal<MachineInstr*, unsigned> > AllocatorTy;
  67. typedef ScopedHashTable<MachineInstr*, unsigned,
  68. MachineInstrExpressionTrait, AllocatorTy> ScopedHTType;
  69. typedef ScopedHTType::ScopeTy ScopeType;
  70. DenseMap<MachineBasicBlock*, ScopeType*> ScopeMap;
  71. ScopedHTType VNT;
  72. SmallVector<MachineInstr*, 64> Exps;
  73. unsigned CurrVN;
  74. BitVector AllocatableRegs;
  75. BitVector ReservedRegs;
  76. bool PerformTrivialCoalescing(MachineInstr *MI, MachineBasicBlock *MBB);
  77. bool isPhysDefTriviallyDead(unsigned Reg,
  78. MachineBasicBlock::const_iterator I,
  79. MachineBasicBlock::const_iterator E) const;
  80. bool hasLivePhysRegDefUses(const MachineInstr *MI,
  81. const MachineBasicBlock *MBB,
  82. SmallSet<unsigned,8> &PhysRefs,
  83. SmallVector<unsigned,2> &PhysDefs) const;
  84. bool PhysRegDefsReach(MachineInstr *CSMI, MachineInstr *MI,
  85. SmallSet<unsigned,8> &PhysRefs,
  86. SmallVector<unsigned,2> &PhysDefs,
  87. bool &NonLocal) const;
  88. bool isCSECandidate(MachineInstr *MI);
  89. bool isProfitableToCSE(unsigned CSReg, unsigned Reg,
  90. MachineInstr *CSMI, MachineInstr *MI);
  91. void EnterScope(MachineBasicBlock *MBB);
  92. void ExitScope(MachineBasicBlock *MBB);
  93. bool ProcessBlock(MachineBasicBlock *MBB);
  94. void ExitScopeIfDone(MachineDomTreeNode *Node,
  95. DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren);
  96. bool PerformCSE(MachineDomTreeNode *Node);
  97. };
  98. } // end anonymous namespace
  99. char MachineCSE::ID = 0;
  100. char &llvm::MachineCSEID = MachineCSE::ID;
  101. INITIALIZE_PASS_BEGIN(MachineCSE, "machine-cse",
  102. "Machine Common Subexpression Elimination", false, false)
  103. INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
  104. INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
  105. INITIALIZE_PASS_END(MachineCSE, "machine-cse",
  106. "Machine Common Subexpression Elimination", false, false)
  107. bool MachineCSE::PerformTrivialCoalescing(MachineInstr *MI,
  108. MachineBasicBlock *MBB) {
  109. bool Changed = false;
  110. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  111. MachineOperand &MO = MI->getOperand(i);
  112. if (!MO.isReg() || !MO.isUse())
  113. continue;
  114. unsigned Reg = MO.getReg();
  115. if (!TargetRegisterInfo::isVirtualRegister(Reg))
  116. continue;
  117. if (!MRI->hasOneNonDBGUse(Reg))
  118. // Only coalesce single use copies. This ensure the copy will be
  119. // deleted.
  120. continue;
  121. MachineInstr *DefMI = MRI->getVRegDef(Reg);
  122. if (DefMI->getParent() != MBB)
  123. continue;
  124. if (!DefMI->isCopy())
  125. continue;
  126. unsigned SrcReg = DefMI->getOperand(1).getReg();
  127. if (!TargetRegisterInfo::isVirtualRegister(SrcReg))
  128. continue;
  129. if (DefMI->getOperand(0).getSubReg() || DefMI->getOperand(1).getSubReg())
  130. continue;
  131. if (!MRI->constrainRegClass(SrcReg, MRI->getRegClass(Reg)))
  132. continue;
  133. DEBUG(dbgs() << "Coalescing: " << *DefMI);
  134. DEBUG(dbgs() << "*** to: " << *MI);
  135. MO.setReg(SrcReg);
  136. MRI->clearKillFlags(SrcReg);
  137. DefMI->eraseFromParent();
  138. ++NumCoalesces;
  139. Changed = true;
  140. }
  141. return Changed;
  142. }
  143. bool
  144. MachineCSE::isPhysDefTriviallyDead(unsigned Reg,
  145. MachineBasicBlock::const_iterator I,
  146. MachineBasicBlock::const_iterator E) const {
  147. unsigned LookAheadLeft = LookAheadLimit;
  148. while (LookAheadLeft) {
  149. // Skip over dbg_value's.
  150. while (I != E && I->isDebugValue())
  151. ++I;
  152. if (I == E)
  153. // Reached end of block, register is obviously dead.
  154. return true;
  155. bool SeenDef = false;
  156. for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
  157. const MachineOperand &MO = I->getOperand(i);
  158. if (MO.isRegMask() && MO.clobbersPhysReg(Reg))
  159. SeenDef = true;
  160. if (!MO.isReg() || !MO.getReg())
  161. continue;
  162. if (!TRI->regsOverlap(MO.getReg(), Reg))
  163. continue;
  164. if (MO.isUse())
  165. // Found a use!
  166. return false;
  167. SeenDef = true;
  168. }
  169. if (SeenDef)
  170. // See a def of Reg (or an alias) before encountering any use, it's
  171. // trivially dead.
  172. return true;
  173. --LookAheadLeft;
  174. ++I;
  175. }
  176. return false;
  177. }
  178. /// hasLivePhysRegDefUses - Return true if the specified instruction read/write
  179. /// physical registers (except for dead defs of physical registers). It also
  180. /// returns the physical register def by reference if it's the only one and the
  181. /// instruction does not uses a physical register.
  182. bool MachineCSE::hasLivePhysRegDefUses(const MachineInstr *MI,
  183. const MachineBasicBlock *MBB,
  184. SmallSet<unsigned,8> &PhysRefs,
  185. SmallVector<unsigned,2> &PhysDefs) const{
  186. MachineBasicBlock::const_iterator I = MI; I = llvm::next(I);
  187. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  188. const MachineOperand &MO = MI->getOperand(i);
  189. if (!MO.isReg())
  190. continue;
  191. unsigned Reg = MO.getReg();
  192. if (!Reg)
  193. continue;
  194. if (TargetRegisterInfo::isVirtualRegister(Reg))
  195. continue;
  196. // If the def is dead, it's ok. But the def may not marked "dead". That's
  197. // common since this pass is run before livevariables. We can scan
  198. // forward a few instructions and check if it is obviously dead.
  199. if (MO.isDef() &&
  200. (MO.isDead() || isPhysDefTriviallyDead(Reg, I, MBB->end())))
  201. continue;
  202. for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
  203. PhysRefs.insert(*AI);
  204. if (MO.isDef())
  205. PhysDefs.push_back(Reg);
  206. }
  207. return !PhysRefs.empty();
  208. }
  209. bool MachineCSE::PhysRegDefsReach(MachineInstr *CSMI, MachineInstr *MI,
  210. SmallSet<unsigned,8> &PhysRefs,
  211. SmallVector<unsigned,2> &PhysDefs,
  212. bool &NonLocal) const {
  213. // For now conservatively returns false if the common subexpression is
  214. // not in the same basic block as the given instruction. The only exception
  215. // is if the common subexpression is in the sole predecessor block.
  216. const MachineBasicBlock *MBB = MI->getParent();
  217. const MachineBasicBlock *CSMBB = CSMI->getParent();
  218. bool CrossMBB = false;
  219. if (CSMBB != MBB) {
  220. if (MBB->pred_size() != 1 || *MBB->pred_begin() != CSMBB)
  221. return false;
  222. for (unsigned i = 0, e = PhysDefs.size(); i != e; ++i) {
  223. if (AllocatableRegs.test(PhysDefs[i]) || ReservedRegs.test(PhysDefs[i]))
  224. // Avoid extending live range of physical registers if they are
  225. //allocatable or reserved.
  226. return false;
  227. }
  228. CrossMBB = true;
  229. }
  230. MachineBasicBlock::const_iterator I = CSMI; I = llvm::next(I);
  231. MachineBasicBlock::const_iterator E = MI;
  232. MachineBasicBlock::const_iterator EE = CSMBB->end();
  233. unsigned LookAheadLeft = LookAheadLimit;
  234. while (LookAheadLeft) {
  235. // Skip over dbg_value's.
  236. while (I != E && I != EE && I->isDebugValue())
  237. ++I;
  238. if (I == EE) {
  239. assert(CrossMBB && "Reaching end-of-MBB without finding MI?");
  240. (void)CrossMBB;
  241. CrossMBB = false;
  242. NonLocal = true;
  243. I = MBB->begin();
  244. EE = MBB->end();
  245. continue;
  246. }
  247. if (I == E)
  248. return true;
  249. for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
  250. const MachineOperand &MO = I->getOperand(i);
  251. // RegMasks go on instructions like calls that clobber lots of physregs.
  252. // Don't attempt to CSE across such an instruction.
  253. if (MO.isRegMask())
  254. return false;
  255. if (!MO.isReg() || !MO.isDef())
  256. continue;
  257. unsigned MOReg = MO.getReg();
  258. if (TargetRegisterInfo::isVirtualRegister(MOReg))
  259. continue;
  260. if (PhysRefs.count(MOReg))
  261. return false;
  262. }
  263. --LookAheadLeft;
  264. ++I;
  265. }
  266. return false;
  267. }
  268. bool MachineCSE::isCSECandidate(MachineInstr *MI) {
  269. if (MI->isLabel() || MI->isPHI() || MI->isImplicitDef() ||
  270. MI->isKill() || MI->isInlineAsm() || MI->isDebugValue())
  271. return false;
  272. // Ignore copies.
  273. if (MI->isCopyLike())
  274. return false;
  275. // Ignore stuff that we obviously can't move.
  276. if (MI->mayStore() || MI->isCall() || MI->isTerminator() ||
  277. MI->hasUnmodeledSideEffects())
  278. return false;
  279. if (MI->mayLoad()) {
  280. // Okay, this instruction does a load. As a refinement, we allow the target
  281. // to decide whether the loaded value is actually a constant. If so, we can
  282. // actually use it as a load.
  283. if (!MI->isInvariantLoad(AA))
  284. // FIXME: we should be able to hoist loads with no other side effects if
  285. // there are no other instructions which can change memory in this loop.
  286. // This is a trivial form of alias analysis.
  287. return false;
  288. }
  289. return true;
  290. }
  291. /// isProfitableToCSE - Return true if it's profitable to eliminate MI with a
  292. /// common expression that defines Reg.
  293. bool MachineCSE::isProfitableToCSE(unsigned CSReg, unsigned Reg,
  294. MachineInstr *CSMI, MachineInstr *MI) {
  295. // FIXME: Heuristics that works around the lack the live range splitting.
  296. // If CSReg is used at all uses of Reg, CSE should not increase register
  297. // pressure of CSReg.
  298. bool MayIncreasePressure = true;
  299. if (TargetRegisterInfo::isVirtualRegister(CSReg) &&
  300. TargetRegisterInfo::isVirtualRegister(Reg)) {
  301. MayIncreasePressure = false;
  302. SmallPtrSet<MachineInstr*, 8> CSUses;
  303. for (MachineRegisterInfo::use_nodbg_iterator I =MRI->use_nodbg_begin(CSReg),
  304. E = MRI->use_nodbg_end(); I != E; ++I) {
  305. MachineInstr *Use = &*I;
  306. CSUses.insert(Use);
  307. }
  308. for (MachineRegisterInfo::use_nodbg_iterator I = MRI->use_nodbg_begin(Reg),
  309. E = MRI->use_nodbg_end(); I != E; ++I) {
  310. MachineInstr *Use = &*I;
  311. if (!CSUses.count(Use)) {
  312. MayIncreasePressure = true;
  313. break;
  314. }
  315. }
  316. }
  317. if (!MayIncreasePressure) return true;
  318. // Heuristics #1: Don't CSE "cheap" computation if the def is not local or in
  319. // an immediate predecessor. We don't want to increase register pressure and
  320. // end up causing other computation to be spilled.
  321. if (MI->isAsCheapAsAMove()) {
  322. MachineBasicBlock *CSBB = CSMI->getParent();
  323. MachineBasicBlock *BB = MI->getParent();
  324. if (CSBB != BB && !CSBB->isSuccessor(BB))
  325. return false;
  326. }
  327. // Heuristics #2: If the expression doesn't not use a vr and the only use
  328. // of the redundant computation are copies, do not cse.
  329. bool HasVRegUse = false;
  330. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  331. const MachineOperand &MO = MI->getOperand(i);
  332. if (MO.isReg() && MO.isUse() &&
  333. TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
  334. HasVRegUse = true;
  335. break;
  336. }
  337. }
  338. if (!HasVRegUse) {
  339. bool HasNonCopyUse = false;
  340. for (MachineRegisterInfo::use_nodbg_iterator I = MRI->use_nodbg_begin(Reg),
  341. E = MRI->use_nodbg_end(); I != E; ++I) {
  342. MachineInstr *Use = &*I;
  343. // Ignore copies.
  344. if (!Use->isCopyLike()) {
  345. HasNonCopyUse = true;
  346. break;
  347. }
  348. }
  349. if (!HasNonCopyUse)
  350. return false;
  351. }
  352. // Heuristics #3: If the common subexpression is used by PHIs, do not reuse
  353. // it unless the defined value is already used in the BB of the new use.
  354. bool HasPHI = false;
  355. SmallPtrSet<MachineBasicBlock*, 4> CSBBs;
  356. for (MachineRegisterInfo::use_nodbg_iterator I = MRI->use_nodbg_begin(CSReg),
  357. E = MRI->use_nodbg_end(); I != E; ++I) {
  358. MachineInstr *Use = &*I;
  359. HasPHI |= Use->isPHI();
  360. CSBBs.insert(Use->getParent());
  361. }
  362. if (!HasPHI)
  363. return true;
  364. return CSBBs.count(MI->getParent());
  365. }
  366. void MachineCSE::EnterScope(MachineBasicBlock *MBB) {
  367. DEBUG(dbgs() << "Entering: " << MBB->getName() << '\n');
  368. ScopeType *Scope = new ScopeType(VNT);
  369. ScopeMap[MBB] = Scope;
  370. }
  371. void MachineCSE::ExitScope(MachineBasicBlock *MBB) {
  372. DEBUG(dbgs() << "Exiting: " << MBB->getName() << '\n');
  373. DenseMap<MachineBasicBlock*, ScopeType*>::iterator SI = ScopeMap.find(MBB);
  374. assert(SI != ScopeMap.end());
  375. ScopeMap.erase(SI);
  376. delete SI->second;
  377. }
  378. bool MachineCSE::ProcessBlock(MachineBasicBlock *MBB) {
  379. bool Changed = false;
  380. SmallVector<std::pair<unsigned, unsigned>, 8> CSEPairs;
  381. for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E; ) {
  382. MachineInstr *MI = &*I;
  383. ++I;
  384. if (!isCSECandidate(MI))
  385. continue;
  386. bool FoundCSE = VNT.count(MI);
  387. if (!FoundCSE) {
  388. // Look for trivial copy coalescing opportunities.
  389. if (PerformTrivialCoalescing(MI, MBB)) {
  390. Changed = true;
  391. // After coalescing MI itself may become a copy.
  392. if (MI->isCopyLike())
  393. continue;
  394. FoundCSE = VNT.count(MI);
  395. }
  396. }
  397. // Commute commutable instructions.
  398. bool Commuted = false;
  399. if (!FoundCSE && MI->isCommutable()) {
  400. MachineInstr *NewMI = TII->commuteInstruction(MI);
  401. if (NewMI) {
  402. Commuted = true;
  403. FoundCSE = VNT.count(NewMI);
  404. if (NewMI != MI) {
  405. // New instruction. It doesn't need to be kept.
  406. NewMI->eraseFromParent();
  407. Changed = true;
  408. } else if (!FoundCSE)
  409. // MI was changed but it didn't help, commute it back!
  410. (void)TII->commuteInstruction(MI);
  411. }
  412. }
  413. // If the instruction defines physical registers and the values *may* be
  414. // used, then it's not safe to replace it with a common subexpression.
  415. // It's also not safe if the instruction uses physical registers.
  416. bool CrossMBBPhysDef = false;
  417. SmallSet<unsigned, 8> PhysRefs;
  418. SmallVector<unsigned, 2> PhysDefs;
  419. if (FoundCSE && hasLivePhysRegDefUses(MI, MBB, PhysRefs, PhysDefs)) {
  420. FoundCSE = false;
  421. // ... Unless the CS is local or is in the sole predecessor block
  422. // and it also defines the physical register which is not clobbered
  423. // in between and the physical register uses were not clobbered.
  424. unsigned CSVN = VNT.lookup(MI);
  425. MachineInstr *CSMI = Exps[CSVN];
  426. if (PhysRegDefsReach(CSMI, MI, PhysRefs, PhysDefs, CrossMBBPhysDef))
  427. FoundCSE = true;
  428. }
  429. if (!FoundCSE) {
  430. VNT.insert(MI, CurrVN++);
  431. Exps.push_back(MI);
  432. continue;
  433. }
  434. // Found a common subexpression, eliminate it.
  435. unsigned CSVN = VNT.lookup(MI);
  436. MachineInstr *CSMI = Exps[CSVN];
  437. DEBUG(dbgs() << "Examining: " << *MI);
  438. DEBUG(dbgs() << "*** Found a common subexpression: " << *CSMI);
  439. // Check if it's profitable to perform this CSE.
  440. bool DoCSE = true;
  441. unsigned NumDefs = MI->getDesc().getNumDefs();
  442. for (unsigned i = 0, e = MI->getNumOperands(); NumDefs && i != e; ++i) {
  443. MachineOperand &MO = MI->getOperand(i);
  444. if (!MO.isReg() || !MO.isDef())
  445. continue;
  446. unsigned OldReg = MO.getReg();
  447. unsigned NewReg = CSMI->getOperand(i).getReg();
  448. if (OldReg == NewReg)
  449. continue;
  450. assert(TargetRegisterInfo::isVirtualRegister(OldReg) &&
  451. TargetRegisterInfo::isVirtualRegister(NewReg) &&
  452. "Do not CSE physical register defs!");
  453. if (!isProfitableToCSE(NewReg, OldReg, CSMI, MI)) {
  454. DEBUG(dbgs() << "*** Not profitable, avoid CSE!\n");
  455. DoCSE = false;
  456. break;
  457. }
  458. // Don't perform CSE if the result of the old instruction cannot exist
  459. // within the register class of the new instruction.
  460. const TargetRegisterClass *OldRC = MRI->getRegClass(OldReg);
  461. if (!MRI->constrainRegClass(NewReg, OldRC)) {
  462. DEBUG(dbgs() << "*** Not the same register class, avoid CSE!\n");
  463. DoCSE = false;
  464. break;
  465. }
  466. CSEPairs.push_back(std::make_pair(OldReg, NewReg));
  467. --NumDefs;
  468. }
  469. // Actually perform the elimination.
  470. if (DoCSE) {
  471. for (unsigned i = 0, e = CSEPairs.size(); i != e; ++i) {
  472. MRI->replaceRegWith(CSEPairs[i].first, CSEPairs[i].second);
  473. MRI->clearKillFlags(CSEPairs[i].second);
  474. }
  475. if (CrossMBBPhysDef) {
  476. // Add physical register defs now coming in from a predecessor to MBB
  477. // livein list.
  478. while (!PhysDefs.empty()) {
  479. unsigned LiveIn = PhysDefs.pop_back_val();
  480. if (!MBB->isLiveIn(LiveIn))
  481. MBB->addLiveIn(LiveIn);
  482. }
  483. ++NumCrossBBCSEs;
  484. }
  485. MI->eraseFromParent();
  486. ++NumCSEs;
  487. if (!PhysRefs.empty())
  488. ++NumPhysCSEs;
  489. if (Commuted)
  490. ++NumCommutes;
  491. Changed = true;
  492. } else {
  493. VNT.insert(MI, CurrVN++);
  494. Exps.push_back(MI);
  495. }
  496. CSEPairs.clear();
  497. }
  498. return Changed;
  499. }
  500. /// ExitScopeIfDone - Destroy scope for the MBB that corresponds to the given
  501. /// dominator tree node if its a leaf or all of its children are done. Walk
  502. /// up the dominator tree to destroy ancestors which are now done.
  503. void
  504. MachineCSE::ExitScopeIfDone(MachineDomTreeNode *Node,
  505. DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren) {
  506. if (OpenChildren[Node])
  507. return;
  508. // Pop scope.
  509. ExitScope(Node->getBlock());
  510. // Now traverse upwards to pop ancestors whose offsprings are all done.
  511. while (MachineDomTreeNode *Parent = Node->getIDom()) {
  512. unsigned Left = --OpenChildren[Parent];
  513. if (Left != 0)
  514. break;
  515. ExitScope(Parent->getBlock());
  516. Node = Parent;
  517. }
  518. }
  519. bool MachineCSE::PerformCSE(MachineDomTreeNode *Node) {
  520. SmallVector<MachineDomTreeNode*, 32> Scopes;
  521. SmallVector<MachineDomTreeNode*, 8> WorkList;
  522. DenseMap<MachineDomTreeNode*, unsigned> OpenChildren;
  523. CurrVN = 0;
  524. // Perform a DFS walk to determine the order of visit.
  525. WorkList.push_back(Node);
  526. do {
  527. Node = WorkList.pop_back_val();
  528. Scopes.push_back(Node);
  529. const std::vector<MachineDomTreeNode*> &Children = Node->getChildren();
  530. unsigned NumChildren = Children.size();
  531. OpenChildren[Node] = NumChildren;
  532. for (unsigned i = 0; i != NumChildren; ++i) {
  533. MachineDomTreeNode *Child = Children[i];
  534. WorkList.push_back(Child);
  535. }
  536. } while (!WorkList.empty());
  537. // Now perform CSE.
  538. bool Changed = false;
  539. for (unsigned i = 0, e = Scopes.size(); i != e; ++i) {
  540. MachineDomTreeNode *Node = Scopes[i];
  541. MachineBasicBlock *MBB = Node->getBlock();
  542. EnterScope(MBB);
  543. Changed |= ProcessBlock(MBB);
  544. // If it's a leaf node, it's done. Traverse upwards to pop ancestors.
  545. ExitScopeIfDone(Node, OpenChildren);
  546. }
  547. return Changed;
  548. }
  549. bool MachineCSE::runOnMachineFunction(MachineFunction &MF) {
  550. TII = MF.getTarget().getInstrInfo();
  551. TRI = MF.getTarget().getRegisterInfo();
  552. MRI = &MF.getRegInfo();
  553. AA = &getAnalysis<AliasAnalysis>();
  554. DT = &getAnalysis<MachineDominatorTree>();
  555. AllocatableRegs = TRI->getAllocatableSet(MF);
  556. ReservedRegs = TRI->getReservedRegs(MF);
  557. return PerformCSE(DT->getRootNode());
  558. }