LLVM  9.0.0svn
MachineCSE.cpp
Go to the documentation of this file.
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"
17 #include "llvm/ADT/SmallPtrSet.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/Statistic.h"
29 #include "llvm/CodeGen/Passes.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"
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;
66 
67  public:
68  static char ID; // Pass identification
69 
70  MachineCSE() : MachineFunctionPass(ID) {
72  }
73 
74  bool runOnMachineFunction(MachineFunction &MF) override;
75 
76  void getAnalysisUsage(AnalysisUsage &AU) const override {
77  AU.setPreservesCFG();
83  }
84 
85  void releaseMemory() override {
86  ScopeMap.clear();
87  Exps.clear();
88  }
89 
90  private:
91  using AllocatorTy = RecyclingAllocator<BumpPtrAllocator,
93  using ScopedHTType =
95  AllocatorTy>;
96  using ScopeType = ScopedHTType::ScopeTy;
97  using PhysDefVector = SmallVector<std::pair<unsigned, unsigned>, 2>;
98 
99  unsigned LookAheadLimit = 0;
101  ScopedHTType VNT;
103  unsigned CurrVN = 0;
104 
105  bool PerformTrivialCopyPropagation(MachineInstr *MI,
106  MachineBasicBlock *MBB);
107  bool isPhysDefTriviallyDead(unsigned Reg,
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,
125  bool PerformCSE(MachineDomTreeNode *Node);
126  };
127 
128 } // end anonymous namespace
129 
130 char MachineCSE::ID = 0;
131 
133 
135  "Machine Common Subexpression Elimination", false, false)
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();
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();
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,
203  unsigned LookAheadLeft = LookAheadLimit;
204  while (LookAheadLeft) {
205  // Skip over dbg_value's.
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;
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;
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);
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();
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() ||
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;
418  MayIncreasePressure = false;
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() &&
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');
486  assert(SI != ScopeMap.end());
487  delete SI->second;
488  ScopeMap.erase(SI);
489 }
490 
492  bool Changed = false;
493 
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 
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,
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) {
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 }
Machine Common Subexpression Elimination
Definition: MachineCSE.cpp:138
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
bool isCall(QueryType Type=AnyInBundle) const
Definition: MachineInstr.h:632
bool isAllocatable(unsigned PhysReg) const
isAllocatable - Returns true when PhysReg belongs to an allocatable register class and it hasn&#39;t been...
const MachineFunction * getMF() const
Return the function that contains the basic block that this instruction belongs to.
This class represents lattice values for constants.
Definition: AllocatorList.h:23
INITIALIZE_PASS_BEGIN(MachineCSE, DEBUG_TYPE, "Machine Common Subexpression Elimination", false, false) INITIALIZE_PASS_END(MachineCSE
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
void push_back(const T &Elt)
Definition: SmallVector.h:211
void initializeMachineCSEPass(PassRegistry &)
unsigned getReg() const
getReg - Returns the register number.
static bool isVirtualRegister(unsigned Reg)
Return true if the specified register number is in the virtual register namespace.
#define DEBUG_TYPE
Definition: MachineCSE.cpp:48
unsigned Reg
MachineInstr * commuteInstruction(MachineInstr &MI, bool NewMI=false, unsigned OpIdx1=CommuteAnyOperandIndex, unsigned OpIdx2=CommuteAnyOperandIndex) const
This method commutes the operands of the given machine instruction MI.
unsigned getSubReg() const
bool isInlineAsm() const
bool constrainRegAttrs(unsigned Reg, unsigned ConstrainingReg, unsigned MinNumRegs=0)
Constrain the register class or the register bank of the virtual register Reg (and low-level type) to...
unsigned second
STATISTIC(NumFunctions, "Total number of functions")
unsigned const TargetRegisterInfo * TRI
void setIsDead(bool Val=true)
bool reservedRegsFrozen() const
reservedRegsFrozen - Returns true after freezeReservedRegs() was called to ensure the set of reserved...
iterator_range< mop_iterator > operands()
Definition: MachineInstr.h:458
bool isCopyLike() const
Return true if the instruction behaves like a copy.
bool isPHI() const
Special DenseMapInfo traits to compare MachineInstr* by value of the instruction rather than by point...
This file defines the MallocAllocator and BumpPtrAllocator interfaces.
virtual unsigned getMachineCSELookAheadLimit() const
Return the value to use for the MachineCSE&#39;s LookAheadLimit, which is a heuristic used for CSE&#39;ing ph...
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:50
LLVM_NODISCARD bool empty() const
Definition: SmallSet.h:155
char & MachineLoopInfoID
MachineLoopInfo - This pass is a loop analysis pass.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
const HexagonInstrInfo * TII
unsigned getNumOperands() const
Retuns the total number of operands.
Definition: MachineInstr.h:411
void eraseFromParent()
Unlink &#39;this&#39; from the containing basic block and delete it.
bool isTerminator(QueryType Type=AnyInBundle) const
Returns true if this instruction part of the terminator for a basic block.
Definition: MachineInstr.h:648
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
Definition: MachineInstr.h:408
RecyclingAllocator - This class wraps an Allocator, adding the functionality of recycling deleted obj...
MachineInstr * getVRegDef(unsigned Reg) const
getVRegDef - Return the machine instr that defines the specified virtual register or null if none is ...
char & MachineCSEID
MachineCSE - This pass performs global CSE on machine instructions.
Definition: MachineCSE.cpp:132
void clearKillFlags(unsigned Reg) const
clearKillFlags - Iterate over all the uses of the given register and clear the kill flag from the Mac...
void changeDebugValuesDefReg(unsigned Reg)
Find all DBG_VALUEs immediately following this instruction that point to a register def in this instr...
Base class for the actual dominator tree node.
const std::vector< DomTreeNodeBase * > & getChildren() const
AnalysisUsage & addPreservedID(const void *ID)
COFF::MachineTypes Machine
Definition: COFFYAML.cpp:365
virtual const TargetInstrInfo * getInstrInfo() const
static bool ProcessBlock(BasicBlock &BB, DominatorTree &DT, LoopInfo &LI, AAResults &AA)
Definition: Sink.cpp:198
bool isDereferenceableInvariantLoad(AliasAnalysis *AA) const
Return true if this load instruction never traps and points to a memory location whose value doesn&#39;t ...
TargetInstrInfo - Interface to description of machine instruction set.
BumpPtrAllocatorImpl BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition: Allocator.h:434
NodeT * getBlock() const
bool mayStore(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly modify memory.
Definition: MachineInstr.h:819
void addLiveIn(MCPhysReg PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
unsigned const MachineRegisterInfo * MRI
StringRef getName() const
Return the name of the corresponding LLVM basic block, or an empty string.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
void clearRegisterDeads(unsigned Reg)
Clear all dead flags on operands defining register Reg.
MachineInstrBuilder & UseMI
DomTreeNodeBase * getIDom() const
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:370
MCRegAliasIterator enumerates all registers aliasing Reg.
Represent the analysis usage information of a pass.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Definition: SmallPtrSet.h:381
std::pair< NoneType, bool > insert(const T &V)
insert - Insert an element into the set if it isn&#39;t already there.
Definition: SmallSet.h:180
bool isCopy() const
bool isImplicitDef() const
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
bool isDebugInstr() const
Definition: MachineInstr.h:998
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
bool isConstantPhysReg(unsigned PhysReg) const
Returns true if PhysReg is unallocatable and constant throughout the function.
virtual bool isAsCheapAsAMove(const MachineInstr &MI) const
Return true if the instruction is as cheap as a move instruction.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:417
bool regsOverlap(unsigned regA, unsigned regB) const
Returns true if the two registers are equal or alias each other.
MachineDomTreeNode * getRootNode() const
MachineOperand class - Representation of each machine instruction operand.
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:841
MachineInstrBuilder MachineInstrBuilder & DefMI
LLVM_NODISCARD T pop_back_val()
Definition: SmallVector.h:374
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition: Pass.cpp:301
unsigned pred_size() const
MachineInstr * getUniqueVRegDef(unsigned Reg) const
getUniqueVRegDef - Return the unique machine instr that defines the specified virtual register or nul...
const Function & getFunction() const
Return the LLVM function that this machine code represents.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
bool isLiveIn(MCPhysReg Reg, LaneBitmask LaneMask=LaneBitmask::getAll()) const
Return true if the specified register is in the live in set.
void replaceRegWith(unsigned FromReg, unsigned ToReg)
replaceRegWith - Replace all instances of FromReg with ToReg in the machine function.
IterT skipDebugInstructionsForward(IterT It, IterT End)
Increment It until it points to a non-debug instruction or to End and return the resulting iterator...
const MachineBasicBlock * getParent() const
Definition: MachineInstr.h:253
MachineRegisterInfo - Keep track of information for virtual and physical registers, including vreg register classes, use/def chains for registers, etc.
Representation of each machine instruction.
Definition: MachineInstr.h:63
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:55
#define I(x, y, z)
Definition: MD5.cpp:58
unsigned getNumDefs() const
Returns the total number of definitions.
Definition: MachineInstr.h:423
virtual bool isCallerPreservedPhysReg(unsigned PhysReg, const MachineFunction &MF) const
Physical registers that may be modified within a function but are guaranteed to be restored before an...
bool isSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB is a successor of this block.
bool hasOneNonDBGUse(unsigned RegNo) const
hasOneNonDBGUse - Return true if there is exactly one non-Debug instruction using the specified regis...
bool isKill() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
static bool isCallerPreservedOrConstPhysReg(unsigned Reg, const MachineFunction &MF, const TargetRegisterInfo &TRI)
Definition: MachineCSE.cpp:236
bool mayLoad(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read memory.
Definition: MachineInstr.h:806
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
bool isPosition() const
Definition: MachineInstr.h:994
bool hasUnmodeledSideEffects() const
Return true if this instruction has side effects that are not modeled by mayLoad / mayStore...
IRTranslator LLVM IR MI
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object...
#define LLVM_DEBUG(X)
Definition: Debug.h:122
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:413
iterator_range< use_instr_nodbg_iterator > use_nodbg_instructions(unsigned Reg) const
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
bool isCommutable(QueryType Type=IgnoreBundle) const
Return true if this may be a 2- or 3-address instruction (of the form "X = op Y, Z, ..."), which produces the same result if Y and Z are exchanged.
Definition: MachineInstr.h:847
bool isReserved(unsigned PhysReg) const
isReserved - Returns true when PhysReg is a reserved register.
detail::enumerator< R > enumerate(R &&TheRange)
Given an input range, returns a new range whose values are are pair (A,B) such that A is the 0-based ...
Definition: STLExtras.h:1571
bool isImplicit() const
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
Definition: SmallSet.h:164