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