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