MachineCSE.cpp 22 KB

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