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