MachineCSE.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717
  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. #include "llvm/CodeGen/Passes.h"
  16. #include "llvm/ADT/DenseMap.h"
  17. #include "llvm/ADT/ScopedHashTable.h"
  18. #include "llvm/ADT/SmallSet.h"
  19. #include "llvm/ADT/Statistic.h"
  20. #include "llvm/Analysis/AliasAnalysis.h"
  21. #include "llvm/CodeGen/MachineDominators.h"
  22. #include "llvm/CodeGen/MachineInstr.h"
  23. #include "llvm/CodeGen/MachineRegisterInfo.h"
  24. #include "llvm/Support/Debug.h"
  25. #include "llvm/Support/RecyclingAllocator.h"
  26. #include "llvm/Support/raw_ostream.h"
  27. #include "llvm/Target/TargetInstrInfo.h"
  28. #include "llvm/Target/TargetSubtargetInfo.h"
  29. using namespace llvm;
  30. #define DEBUG_TYPE "machine-cse"
  31. STATISTIC(NumCoalesces, "Number of copies coalesced");
  32. STATISTIC(NumCSEs, "Number of common subexpression eliminated");
  33. STATISTIC(NumPhysCSEs,
  34. "Number of physreg referencing common subexpr eliminated");
  35. STATISTIC(NumCrossBBCSEs,
  36. "Number of cross-MBB physreg referencing CS eliminated");
  37. STATISTIC(NumCommutes, "Number of copies coalesced after commuting");
  38. namespace {
  39. class MachineCSE : public MachineFunctionPass {
  40. const TargetInstrInfo *TII;
  41. const TargetRegisterInfo *TRI;
  42. AliasAnalysis *AA;
  43. MachineDominatorTree *DT;
  44. MachineRegisterInfo *MRI;
  45. public:
  46. static char ID; // Pass identification
  47. MachineCSE() : MachineFunctionPass(ID), LookAheadLimit(0), CurrVN(0) {
  48. initializeMachineCSEPass(*PassRegistry::getPassRegistry());
  49. }
  50. bool runOnMachineFunction(MachineFunction &MF) override;
  51. void getAnalysisUsage(AnalysisUsage &AU) const override {
  52. AU.setPreservesCFG();
  53. MachineFunctionPass::getAnalysisUsage(AU);
  54. AU.addRequired<AAResultsWrapperPass>();
  55. AU.addPreservedID(MachineLoopInfoID);
  56. AU.addRequired<MachineDominatorTree>();
  57. AU.addPreserved<MachineDominatorTree>();
  58. }
  59. void releaseMemory() override {
  60. ScopeMap.clear();
  61. Exps.clear();
  62. }
  63. private:
  64. 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. bool PerformTrivialCopyPropagation(MachineInstr *MI,
  75. MachineBasicBlock *MBB);
  76. bool isPhysDefTriviallyDead(unsigned Reg,
  77. MachineBasicBlock::const_iterator I,
  78. MachineBasicBlock::const_iterator E) const;
  79. bool hasLivePhysRegDefUses(const MachineInstr *MI,
  80. const MachineBasicBlock *MBB,
  81. SmallSet<unsigned,8> &PhysRefs,
  82. SmallVectorImpl<unsigned> &PhysDefs,
  83. bool &PhysUseDef) const;
  84. bool PhysRegDefsReach(MachineInstr *CSMI, MachineInstr *MI,
  85. SmallSet<unsigned,8> &PhysRefs,
  86. SmallVectorImpl<unsigned> &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_PASS_DEPENDENCY(AAResultsWrapperPass)
  105. INITIALIZE_PASS_END(MachineCSE, "machine-cse",
  106. "Machine Common Subexpression Elimination", false, false)
  107. /// The source register of a COPY machine instruction can be propagated to all
  108. /// its users, and this propagation could increase the probability of finding
  109. /// common subexpressions. If the COPY has only one user, the COPY itself can
  110. /// be removed.
  111. bool MachineCSE::PerformTrivialCopyPropagation(MachineInstr *MI,
  112. MachineBasicBlock *MBB) {
  113. bool Changed = false;
  114. for (MachineOperand &MO : MI->operands()) {
  115. if (!MO.isReg() || !MO.isUse())
  116. continue;
  117. unsigned Reg = MO.getReg();
  118. if (!TargetRegisterInfo::isVirtualRegister(Reg))
  119. continue;
  120. bool OnlyOneUse = MRI->hasOneNonDBGUse(Reg);
  121. MachineInstr *DefMI = MRI->getVRegDef(Reg);
  122. if (!DefMI->isCopy())
  123. continue;
  124. unsigned SrcReg = DefMI->getOperand(1).getReg();
  125. if (!TargetRegisterInfo::isVirtualRegister(SrcReg))
  126. continue;
  127. if (DefMI->getOperand(0).getSubReg())
  128. continue;
  129. // FIXME: We should trivially coalesce subregister copies to expose CSE
  130. // opportunities on instructions with truncated operands (see
  131. // cse-add-with-overflow.ll). This can be done here as follows:
  132. // if (SrcSubReg)
  133. // RC = TRI->getMatchingSuperRegClass(MRI->getRegClass(SrcReg), RC,
  134. // SrcSubReg);
  135. // MO.substVirtReg(SrcReg, SrcSubReg, *TRI);
  136. //
  137. // The 2-addr pass has been updated to handle coalesced subregs. However,
  138. // some machine-specific code still can't handle it.
  139. // To handle it properly we also need a way find a constrained subregister
  140. // class given a super-reg class and subreg index.
  141. if (DefMI->getOperand(1).getSubReg())
  142. continue;
  143. const TargetRegisterClass *RC = MRI->getRegClass(Reg);
  144. if (!MRI->constrainRegClass(SrcReg, RC))
  145. continue;
  146. DEBUG(dbgs() << "Coalescing: " << *DefMI);
  147. DEBUG(dbgs() << "*** to: " << *MI);
  148. // Propagate SrcReg of copies to MI.
  149. MO.setReg(SrcReg);
  150. MRI->clearKillFlags(SrcReg);
  151. // Coalesce single use copies.
  152. if (OnlyOneUse) {
  153. DefMI->eraseFromParent();
  154. ++NumCoalesces;
  155. }
  156. Changed = true;
  157. }
  158. return Changed;
  159. }
  160. bool
  161. MachineCSE::isPhysDefTriviallyDead(unsigned Reg,
  162. MachineBasicBlock::const_iterator I,
  163. MachineBasicBlock::const_iterator E) const {
  164. unsigned LookAheadLeft = LookAheadLimit;
  165. while (LookAheadLeft) {
  166. // Skip over dbg_value's.
  167. while (I != E && I->isDebugValue())
  168. ++I;
  169. if (I == E)
  170. // Reached end of block, register is obviously dead.
  171. return true;
  172. bool SeenDef = false;
  173. for (const MachineOperand &MO : I->operands()) {
  174. if (MO.isRegMask() && MO.clobbersPhysReg(Reg))
  175. SeenDef = true;
  176. if (!MO.isReg() || !MO.getReg())
  177. continue;
  178. if (!TRI->regsOverlap(MO.getReg(), Reg))
  179. continue;
  180. if (MO.isUse())
  181. // Found a use!
  182. return false;
  183. SeenDef = true;
  184. }
  185. if (SeenDef)
  186. // See a def of Reg (or an alias) before encountering any use, it's
  187. // trivially dead.
  188. return true;
  189. --LookAheadLeft;
  190. ++I;
  191. }
  192. return false;
  193. }
  194. /// hasLivePhysRegDefUses - Return true if the specified instruction read/write
  195. /// physical registers (except for dead defs of physical registers). It also
  196. /// returns the physical register def by reference if it's the only one and the
  197. /// instruction does not uses a physical register.
  198. bool MachineCSE::hasLivePhysRegDefUses(const MachineInstr *MI,
  199. const MachineBasicBlock *MBB,
  200. SmallSet<unsigned,8> &PhysRefs,
  201. SmallVectorImpl<unsigned> &PhysDefs,
  202. bool &PhysUseDef) const{
  203. // First, add all uses to PhysRefs.
  204. for (const MachineOperand &MO : MI->operands()) {
  205. if (!MO.isReg() || MO.isDef())
  206. continue;
  207. unsigned Reg = MO.getReg();
  208. if (!Reg)
  209. continue;
  210. if (TargetRegisterInfo::isVirtualRegister(Reg))
  211. continue;
  212. // Reading constant physregs is ok.
  213. if (!MRI->isConstantPhysReg(Reg, *MBB->getParent()))
  214. for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
  215. PhysRefs.insert(*AI);
  216. }
  217. // Next, collect all defs into PhysDefs. If any is already in PhysRefs
  218. // (which currently contains only uses), set the PhysUseDef flag.
  219. PhysUseDef = false;
  220. MachineBasicBlock::const_iterator I = MI; I = std::next(I);
  221. for (const MachineOperand &MO : MI->operands()) {
  222. if (!MO.isReg() || !MO.isDef())
  223. continue;
  224. unsigned Reg = MO.getReg();
  225. if (!Reg)
  226. continue;
  227. if (TargetRegisterInfo::isVirtualRegister(Reg))
  228. continue;
  229. // Check against PhysRefs even if the def is "dead".
  230. if (PhysRefs.count(Reg))
  231. PhysUseDef = true;
  232. // If the def is dead, it's ok. But the def may not marked "dead". That's
  233. // common since this pass is run before livevariables. We can scan
  234. // forward a few instructions and check if it is obviously dead.
  235. if (!MO.isDead() && !isPhysDefTriviallyDead(Reg, I, MBB->end()))
  236. PhysDefs.push_back(Reg);
  237. }
  238. // Finally, add all defs to PhysRefs as well.
  239. for (unsigned i = 0, e = PhysDefs.size(); i != e; ++i)
  240. for (MCRegAliasIterator AI(PhysDefs[i], TRI, true); AI.isValid(); ++AI)
  241. PhysRefs.insert(*AI);
  242. return !PhysRefs.empty();
  243. }
  244. bool MachineCSE::PhysRegDefsReach(MachineInstr *CSMI, MachineInstr *MI,
  245. SmallSet<unsigned,8> &PhysRefs,
  246. SmallVectorImpl<unsigned> &PhysDefs,
  247. bool &NonLocal) const {
  248. // For now conservatively returns false if the common subexpression is
  249. // not in the same basic block as the given instruction. The only exception
  250. // is if the common subexpression is in the sole predecessor block.
  251. const MachineBasicBlock *MBB = MI->getParent();
  252. const MachineBasicBlock *CSMBB = CSMI->getParent();
  253. bool CrossMBB = false;
  254. if (CSMBB != MBB) {
  255. if (MBB->pred_size() != 1 || *MBB->pred_begin() != CSMBB)
  256. return false;
  257. for (unsigned i = 0, e = PhysDefs.size(); i != e; ++i) {
  258. if (MRI->isAllocatable(PhysDefs[i]) || MRI->isReserved(PhysDefs[i]))
  259. // Avoid extending live range of physical registers if they are
  260. //allocatable or reserved.
  261. return false;
  262. }
  263. CrossMBB = true;
  264. }
  265. MachineBasicBlock::const_iterator I = CSMI; I = std::next(I);
  266. MachineBasicBlock::const_iterator E = MI;
  267. MachineBasicBlock::const_iterator EE = CSMBB->end();
  268. unsigned LookAheadLeft = LookAheadLimit;
  269. while (LookAheadLeft) {
  270. // Skip over dbg_value's.
  271. while (I != E && I != EE && I->isDebugValue())
  272. ++I;
  273. if (I == EE) {
  274. assert(CrossMBB && "Reaching end-of-MBB without finding MI?");
  275. (void)CrossMBB;
  276. CrossMBB = false;
  277. NonLocal = true;
  278. I = MBB->begin();
  279. EE = MBB->end();
  280. continue;
  281. }
  282. if (I == E)
  283. return true;
  284. for (const MachineOperand &MO : I->operands()) {
  285. // RegMasks go on instructions like calls that clobber lots of physregs.
  286. // Don't attempt to CSE across such an instruction.
  287. if (MO.isRegMask())
  288. return false;
  289. if (!MO.isReg() || !MO.isDef())
  290. continue;
  291. unsigned MOReg = MO.getReg();
  292. if (TargetRegisterInfo::isVirtualRegister(MOReg))
  293. continue;
  294. if (PhysRefs.count(MOReg))
  295. return false;
  296. }
  297. --LookAheadLeft;
  298. ++I;
  299. }
  300. return false;
  301. }
  302. bool MachineCSE::isCSECandidate(MachineInstr *MI) {
  303. if (MI->isPosition() || MI->isPHI() || MI->isImplicitDef() || MI->isKill() ||
  304. MI->isInlineAsm() || MI->isDebugValue())
  305. return false;
  306. // Ignore copies.
  307. if (MI->isCopyLike())
  308. return false;
  309. // Ignore stuff that we obviously can't move.
  310. if (MI->mayStore() || MI->isCall() || MI->isTerminator() ||
  311. MI->hasUnmodeledSideEffects())
  312. return false;
  313. if (MI->mayLoad()) {
  314. // Okay, this instruction does a load. As a refinement, we allow the target
  315. // to decide whether the loaded value is actually a constant. If so, we can
  316. // actually use it as a load.
  317. if (!MI->isInvariantLoad(AA))
  318. // FIXME: we should be able to hoist loads with no other side effects if
  319. // there are no other instructions which can change memory in this loop.
  320. // This is a trivial form of alias analysis.
  321. return false;
  322. }
  323. // Ignore stack guard loads, otherwise the register that holds CSEed value may
  324. // be spilled and get loaded back with corrupted data.
  325. if (MI->getOpcode() == TargetOpcode::LOAD_STACK_GUARD)
  326. return false;
  327. return true;
  328. }
  329. /// isProfitableToCSE - Return true if it's profitable to eliminate MI with a
  330. /// common expression that defines Reg.
  331. bool MachineCSE::isProfitableToCSE(unsigned CSReg, unsigned Reg,
  332. MachineInstr *CSMI, MachineInstr *MI) {
  333. // FIXME: Heuristics that works around the lack the live range splitting.
  334. // If CSReg is used at all uses of Reg, CSE should not increase register
  335. // pressure of CSReg.
  336. bool MayIncreasePressure = true;
  337. if (TargetRegisterInfo::isVirtualRegister(CSReg) &&
  338. TargetRegisterInfo::isVirtualRegister(Reg)) {
  339. MayIncreasePressure = false;
  340. SmallPtrSet<MachineInstr*, 8> CSUses;
  341. for (MachineInstr &MI : MRI->use_nodbg_instructions(CSReg)) {
  342. CSUses.insert(&MI);
  343. }
  344. for (MachineInstr &MI : MRI->use_nodbg_instructions(Reg)) {
  345. if (!CSUses.count(&MI)) {
  346. MayIncreasePressure = true;
  347. break;
  348. }
  349. }
  350. }
  351. if (!MayIncreasePressure) return true;
  352. // Heuristics #1: Don't CSE "cheap" computation if the def is not local or in
  353. // an immediate predecessor. We don't want to increase register pressure and
  354. // end up causing other computation to be spilled.
  355. if (TII->isAsCheapAsAMove(MI)) {
  356. MachineBasicBlock *CSBB = CSMI->getParent();
  357. MachineBasicBlock *BB = MI->getParent();
  358. if (CSBB != BB && !CSBB->isSuccessor(BB))
  359. return false;
  360. }
  361. // Heuristics #2: If the expression doesn't not use a vr and the only use
  362. // of the redundant computation are copies, do not cse.
  363. bool HasVRegUse = false;
  364. for (const MachineOperand &MO : MI->operands()) {
  365. if (MO.isReg() && MO.isUse() &&
  366. TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
  367. HasVRegUse = true;
  368. break;
  369. }
  370. }
  371. if (!HasVRegUse) {
  372. bool HasNonCopyUse = false;
  373. for (MachineInstr &MI : MRI->use_nodbg_instructions(Reg)) {
  374. // Ignore copies.
  375. if (!MI.isCopyLike()) {
  376. HasNonCopyUse = true;
  377. break;
  378. }
  379. }
  380. if (!HasNonCopyUse)
  381. return false;
  382. }
  383. // Heuristics #3: If the common subexpression is used by PHIs, do not reuse
  384. // it unless the defined value is already used in the BB of the new use.
  385. bool HasPHI = false;
  386. SmallPtrSet<MachineBasicBlock*, 4> CSBBs;
  387. for (MachineInstr &MI : MRI->use_nodbg_instructions(CSReg)) {
  388. HasPHI |= MI.isPHI();
  389. CSBBs.insert(MI.getParent());
  390. }
  391. if (!HasPHI)
  392. return true;
  393. return CSBBs.count(MI->getParent());
  394. }
  395. void MachineCSE::EnterScope(MachineBasicBlock *MBB) {
  396. DEBUG(dbgs() << "Entering: " << MBB->getName() << '\n');
  397. ScopeType *Scope = new ScopeType(VNT);
  398. ScopeMap[MBB] = Scope;
  399. }
  400. void MachineCSE::ExitScope(MachineBasicBlock *MBB) {
  401. DEBUG(dbgs() << "Exiting: " << MBB->getName() << '\n');
  402. DenseMap<MachineBasicBlock*, ScopeType*>::iterator SI = ScopeMap.find(MBB);
  403. assert(SI != ScopeMap.end());
  404. delete SI->second;
  405. ScopeMap.erase(SI);
  406. }
  407. bool MachineCSE::ProcessBlock(MachineBasicBlock *MBB) {
  408. bool Changed = false;
  409. SmallVector<std::pair<unsigned, unsigned>, 8> CSEPairs;
  410. SmallVector<unsigned, 2> ImplicitDefsToUpdate;
  411. SmallVector<unsigned, 2> ImplicitDefs;
  412. for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E; ) {
  413. MachineInstr *MI = &*I;
  414. ++I;
  415. if (!isCSECandidate(MI))
  416. continue;
  417. bool FoundCSE = VNT.count(MI);
  418. if (!FoundCSE) {
  419. // Using trivial copy propagation to find more CSE opportunities.
  420. if (PerformTrivialCopyPropagation(MI, MBB)) {
  421. Changed = true;
  422. // After coalescing MI itself may become a copy.
  423. if (MI->isCopyLike())
  424. continue;
  425. // Try again to see if CSE is possible.
  426. FoundCSE = VNT.count(MI);
  427. }
  428. }
  429. // Commute commutable instructions.
  430. bool Commuted = false;
  431. if (!FoundCSE && MI->isCommutable()) {
  432. MachineInstr *NewMI = TII->commuteInstruction(MI);
  433. if (NewMI) {
  434. Commuted = true;
  435. FoundCSE = VNT.count(NewMI);
  436. if (NewMI != MI) {
  437. // New instruction. It doesn't need to be kept.
  438. NewMI->eraseFromParent();
  439. Changed = true;
  440. } else if (!FoundCSE)
  441. // MI was changed but it didn't help, commute it back!
  442. (void)TII->commuteInstruction(MI);
  443. }
  444. }
  445. // If the instruction defines physical registers and the values *may* be
  446. // used, then it's not safe to replace it with a common subexpression.
  447. // It's also not safe if the instruction uses physical registers.
  448. bool CrossMBBPhysDef = false;
  449. SmallSet<unsigned, 8> PhysRefs;
  450. SmallVector<unsigned, 2> PhysDefs;
  451. bool PhysUseDef = false;
  452. if (FoundCSE && hasLivePhysRegDefUses(MI, MBB, PhysRefs,
  453. PhysDefs, PhysUseDef)) {
  454. FoundCSE = false;
  455. // ... Unless the CS is local or is in the sole predecessor block
  456. // and it also defines the physical register which is not clobbered
  457. // in between and the physical register uses were not clobbered.
  458. // This can never be the case if the instruction both uses and
  459. // defines the same physical register, which was detected above.
  460. if (!PhysUseDef) {
  461. unsigned CSVN = VNT.lookup(MI);
  462. MachineInstr *CSMI = Exps[CSVN];
  463. if (PhysRegDefsReach(CSMI, MI, PhysRefs, PhysDefs, CrossMBBPhysDef))
  464. FoundCSE = true;
  465. }
  466. }
  467. if (!FoundCSE) {
  468. VNT.insert(MI, CurrVN++);
  469. Exps.push_back(MI);
  470. continue;
  471. }
  472. // Found a common subexpression, eliminate it.
  473. unsigned CSVN = VNT.lookup(MI);
  474. MachineInstr *CSMI = Exps[CSVN];
  475. DEBUG(dbgs() << "Examining: " << *MI);
  476. DEBUG(dbgs() << "*** Found a common subexpression: " << *CSMI);
  477. // Check if it's profitable to perform this CSE.
  478. bool DoCSE = true;
  479. unsigned NumDefs = MI->getDesc().getNumDefs() +
  480. MI->getDesc().getNumImplicitDefs();
  481. for (unsigned i = 0, e = MI->getNumOperands(); NumDefs && i != e; ++i) {
  482. MachineOperand &MO = MI->getOperand(i);
  483. if (!MO.isReg() || !MO.isDef())
  484. continue;
  485. unsigned OldReg = MO.getReg();
  486. unsigned NewReg = CSMI->getOperand(i).getReg();
  487. // Go through implicit defs of CSMI and MI, if a def is not dead at MI,
  488. // we should make sure it is not dead at CSMI.
  489. if (MO.isImplicit() && !MO.isDead() && CSMI->getOperand(i).isDead())
  490. ImplicitDefsToUpdate.push_back(i);
  491. // Keep track of implicit defs of CSMI and MI, to clear possibly
  492. // made-redundant kill flags.
  493. if (MO.isImplicit() && !MO.isDead() && OldReg == NewReg)
  494. ImplicitDefs.push_back(OldReg);
  495. if (OldReg == NewReg) {
  496. --NumDefs;
  497. continue;
  498. }
  499. assert(TargetRegisterInfo::isVirtualRegister(OldReg) &&
  500. TargetRegisterInfo::isVirtualRegister(NewReg) &&
  501. "Do not CSE physical register defs!");
  502. if (!isProfitableToCSE(NewReg, OldReg, CSMI, MI)) {
  503. DEBUG(dbgs() << "*** Not profitable, avoid CSE!\n");
  504. DoCSE = false;
  505. break;
  506. }
  507. // Don't perform CSE if the result of the old instruction cannot exist
  508. // within the register class of the new instruction.
  509. const TargetRegisterClass *OldRC = MRI->getRegClass(OldReg);
  510. if (!MRI->constrainRegClass(NewReg, OldRC)) {
  511. DEBUG(dbgs() << "*** Not the same register class, avoid CSE!\n");
  512. DoCSE = false;
  513. break;
  514. }
  515. CSEPairs.push_back(std::make_pair(OldReg, NewReg));
  516. --NumDefs;
  517. }
  518. // Actually perform the elimination.
  519. if (DoCSE) {
  520. for (std::pair<unsigned, unsigned> &CSEPair : CSEPairs) {
  521. unsigned OldReg = CSEPair.first;
  522. unsigned NewReg = CSEPair.second;
  523. // OldReg may have been unused but is used now, clear the Dead flag
  524. MachineInstr *Def = MRI->getUniqueVRegDef(NewReg);
  525. assert(Def != nullptr && "CSEd register has no unique definition?");
  526. Def->clearRegisterDeads(NewReg);
  527. // Replace with NewReg and clear kill flags which may be wrong now.
  528. MRI->replaceRegWith(OldReg, NewReg);
  529. MRI->clearKillFlags(NewReg);
  530. }
  531. // Go through implicit defs of CSMI and MI, if a def is not dead at MI,
  532. // we should make sure it is not dead at CSMI.
  533. for (unsigned ImplicitDefToUpdate : ImplicitDefsToUpdate)
  534. CSMI->getOperand(ImplicitDefToUpdate).setIsDead(false);
  535. // Go through implicit defs of CSMI and MI, and clear the kill flags on
  536. // their uses in all the instructions between CSMI and MI.
  537. // We might have made some of the kill flags redundant, consider:
  538. // subs ... %NZCV<imp-def> <- CSMI
  539. // csinc ... %NZCV<imp-use,kill> <- this kill flag isn't valid anymore
  540. // subs ... %NZCV<imp-def> <- MI, to be eliminated
  541. // csinc ... %NZCV<imp-use,kill>
  542. // Since we eliminated MI, and reused a register imp-def'd by CSMI
  543. // (here %NZCV), that register, if it was killed before MI, should have
  544. // that kill flag removed, because it's lifetime was extended.
  545. if (CSMI->getParent() == MI->getParent()) {
  546. for (MachineBasicBlock::iterator II = CSMI, IE = MI; II != IE; ++II)
  547. for (auto ImplicitDef : ImplicitDefs)
  548. if (MachineOperand *MO = II->findRegisterUseOperand(
  549. ImplicitDef, /*isKill=*/true, TRI))
  550. MO->setIsKill(false);
  551. } else {
  552. // If the instructions aren't in the same BB, bail out and clear the
  553. // kill flag on all uses of the imp-def'd register.
  554. for (auto ImplicitDef : ImplicitDefs)
  555. MRI->clearKillFlags(ImplicitDef);
  556. }
  557. if (CrossMBBPhysDef) {
  558. // Add physical register defs now coming in from a predecessor to MBB
  559. // livein list.
  560. while (!PhysDefs.empty()) {
  561. unsigned LiveIn = PhysDefs.pop_back_val();
  562. if (!MBB->isLiveIn(LiveIn))
  563. MBB->addLiveIn(LiveIn);
  564. }
  565. ++NumCrossBBCSEs;
  566. }
  567. MI->eraseFromParent();
  568. ++NumCSEs;
  569. if (!PhysRefs.empty())
  570. ++NumPhysCSEs;
  571. if (Commuted)
  572. ++NumCommutes;
  573. Changed = true;
  574. } else {
  575. VNT.insert(MI, CurrVN++);
  576. Exps.push_back(MI);
  577. }
  578. CSEPairs.clear();
  579. ImplicitDefsToUpdate.clear();
  580. ImplicitDefs.clear();
  581. }
  582. return Changed;
  583. }
  584. /// ExitScopeIfDone - Destroy scope for the MBB that corresponds to the given
  585. /// dominator tree node if its a leaf or all of its children are done. Walk
  586. /// up the dominator tree to destroy ancestors which are now done.
  587. void
  588. MachineCSE::ExitScopeIfDone(MachineDomTreeNode *Node,
  589. DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren) {
  590. if (OpenChildren[Node])
  591. return;
  592. // Pop scope.
  593. ExitScope(Node->getBlock());
  594. // Now traverse upwards to pop ancestors whose offsprings are all done.
  595. while (MachineDomTreeNode *Parent = Node->getIDom()) {
  596. unsigned Left = --OpenChildren[Parent];
  597. if (Left != 0)
  598. break;
  599. ExitScope(Parent->getBlock());
  600. Node = Parent;
  601. }
  602. }
  603. bool MachineCSE::PerformCSE(MachineDomTreeNode *Node) {
  604. SmallVector<MachineDomTreeNode*, 32> Scopes;
  605. SmallVector<MachineDomTreeNode*, 8> WorkList;
  606. DenseMap<MachineDomTreeNode*, unsigned> OpenChildren;
  607. CurrVN = 0;
  608. // Perform a DFS walk to determine the order of visit.
  609. WorkList.push_back(Node);
  610. do {
  611. Node = WorkList.pop_back_val();
  612. Scopes.push_back(Node);
  613. const std::vector<MachineDomTreeNode*> &Children = Node->getChildren();
  614. OpenChildren[Node] = Children.size();
  615. for (MachineDomTreeNode *Child : Children)
  616. WorkList.push_back(Child);
  617. } while (!WorkList.empty());
  618. // Now perform CSE.
  619. bool Changed = false;
  620. for (MachineDomTreeNode *Node : Scopes) {
  621. MachineBasicBlock *MBB = Node->getBlock();
  622. EnterScope(MBB);
  623. Changed |= ProcessBlock(MBB);
  624. // If it's a leaf node, it's done. Traverse upwards to pop ancestors.
  625. ExitScopeIfDone(Node, OpenChildren);
  626. }
  627. return Changed;
  628. }
  629. bool MachineCSE::runOnMachineFunction(MachineFunction &MF) {
  630. if (skipFunction(*MF.getFunction()))
  631. return false;
  632. TII = MF.getSubtarget().getInstrInfo();
  633. TRI = MF.getSubtarget().getRegisterInfo();
  634. MRI = &MF.getRegInfo();
  635. AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
  636. DT = &getAnalysis<MachineDominatorTree>();
  637. LookAheadLimit = TII->getMachineCSELookAheadLimit();
  638. return PerformCSE(DT->getRootNode());
  639. }