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