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