LLVM 24.0.0git
MachineCopyPropagation.cpp
Go to the documentation of this file.
1//===- MachineCopyPropagation.cpp - Machine Copy Propagation 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 is an extremely simple MachineInstr-level copy propagation pass.
10//
11// This pass forwards the source of COPYs to the users of their destinations
12// when doing so is legal. For example:
13//
14// %reg1 = COPY %reg0
15// ...
16// ... = OP %reg1
17//
18// If
19// - %reg0 has not been clobbered by the time of the use of %reg1
20// - the register class constraints are satisfied
21// - the COPY def is the only value that reaches OP
22// then this pass replaces the above with:
23//
24// %reg1 = COPY %reg0
25// ...
26// ... = OP %reg0
27//
28// This pass also removes some redundant COPYs. For example:
29//
30// %R1 = COPY %R0
31// ... // No clobber of %R1
32// %R0 = COPY %R1 <<< Removed
33//
34// or
35//
36// %R1 = COPY %R0
37// ... // No clobber of %R0
38// %R1 = COPY %R0 <<< Removed
39//
40// or
41//
42// $R0 = OP ...
43// ... // No read/clobber of $R0 and $R1
44// $R1 = COPY $R0 // $R0 is killed
45// Replace $R0 with $R1 and remove the COPY
46// $R1 = OP ...
47// ...
48//
49//===----------------------------------------------------------------------===//
50
52#include "llvm/ADT/DenseMap.h"
53#include "llvm/ADT/STLExtras.h"
54#include "llvm/ADT/SetVector.h"
55#include "llvm/ADT/SmallSet.h"
57#include "llvm/ADT/Statistic.h"
70#include "llvm/MC/MCRegister.h"
72#include "llvm/Pass.h"
73#include "llvm/Support/Debug.h"
76#include <cassert>
77#include <iterator>
78
79using namespace llvm;
80
81#define DEBUG_TYPE "machine-cp"
82
83STATISTIC(NumDeletes, "Number of dead copies deleted");
84STATISTIC(NumCopyForwards, "Number of copy uses forwarded");
85STATISTIC(NumCopyBackwardPropagated, "Number of copy defs backward propagated");
86STATISTIC(SpillageChainsLength, "Length of spillage chains");
87STATISTIC(NumSpillageChains, "Number of spillage chains");
88DEBUG_COUNTER(FwdCounter, "machine-cp-fwd",
89 "Controls which register COPYs are forwarded");
90
91static cl::opt<bool> MCPUseCopyInstr("mcp-use-is-copy-instr", cl::init(false),
94 EnableSpillageCopyElimination("enable-spill-copy-elim", cl::Hidden);
95
96namespace {
97
98MCRegister asPhysMCReg(const MachineOperand *Operand) {
99 Register Reg = Operand->getReg();
100 assert(Reg.isPhysical() &&
101 "MachineCopyPropagation should be run after register allocation!");
102 return Reg;
103}
104
105MCRegister getDstMCReg(const DestSourcePair &DSP) {
106 return asPhysMCReg(DSP.Destination);
107}
108MCRegister getSrcMCReg(const DestSourcePair &DSP) {
109 return asPhysMCReg(DSP.Source);
110}
111std::pair<MCRegister, MCRegister> getDstSrcMCRegs(const DestSourcePair &DSP) {
112 return {getDstMCReg(DSP), getSrcMCReg(DSP)};
113}
114
115std::optional<DestSourcePair> isCopyInstr(const MachineInstr &MI,
116 const TargetInstrInfo &TII,
117 bool UseCopyInstr) {
118 if (UseCopyInstr)
119 return TII.isCopyInstr(MI);
120
121 if (MI.isCopy())
122 return DestSourcePair{MI.getOperand(0), MI.getOperand(1)};
123
124 return std::nullopt;
125}
126
127class CopyTracker {
128 struct CopyInfo {
129 MachineInstr *MI = nullptr;
130 MachineInstr *LastSeenUseInCopy = nullptr;
131 SmallPtrSet<MachineInstr *, 4> SrcUsers;
133 bool Avail = false;
134 };
135
136 DenseMap<MCRegUnit, CopyInfo> Copies;
137
138 // Memoised sets of register units which are preserved by each register mask,
139 // needed to efficiently remove copies which are invalidated by call
140 // instructions.
141 DenseMap<const uint32_t *, BitVector> RegMaskToPreservedRegUnits;
142
143public:
144 /// Get the set of register units which are preserved by RegMaskOp.
145 BitVector &getPreservedRegUnits(const MachineOperand &RegMaskOp,
146 const TargetRegisterInfo &TRI) {
147 const uint32_t *RegMask = RegMaskOp.getRegMask();
148 auto [It, Inserted] = RegMaskToPreservedRegUnits.try_emplace(RegMask);
149 if (!Inserted)
150 return It->second;
151 BitVector &PreservedRegUnits = It->second;
152
153 PreservedRegUnits.resize(TRI.getNumRegUnits());
154 for (unsigned SafeReg = 0, E = TRI.getNumRegs(); SafeReg < E; ++SafeReg)
155 if (!RegMaskOp.clobbersPhysReg(SafeReg))
156 for (MCRegUnit SafeUnit : TRI.regunits(SafeReg))
157 PreservedRegUnits.set(static_cast<unsigned>(SafeUnit));
158
159 return PreservedRegUnits;
160 }
161
162 /// Mark all of the given registers and their subregisters as unavailable for
163 /// copying.
164 void markRegsUnavailable(ArrayRef<MCRegister> Regs,
165 const TargetRegisterInfo &TRI) {
166 for (MCRegister Reg : Regs) {
167 // Source of copy is no longer available for propagation.
168 for (MCRegUnit Unit : TRI.regunits(Reg)) {
169 auto CI = Copies.find(Unit);
170 if (CI != Copies.end())
171 CI->second.Avail = false;
172 }
173 }
174 }
175
176 /// Remove register from copy maps.
177 void invalidateRegister(MCRegister Reg, const TargetRegisterInfo &TRI,
178 const TargetInstrInfo &TII, bool UseCopyInstr) {
179 // Early exit if there are no copies, as the function wouldn't do anything
180 // in that case.
181 if (Copies.empty())
182 return;
183
184 // Since Reg might be a subreg of some registers, only invalidate Reg is not
185 // enough. We have to find the COPY defines Reg or registers defined by Reg
186 // and invalidate all of them. Similarly, we must invalidate all of the
187 // the subregisters used in the source of the COPY.
188 SmallSet<MCRegUnit, 8> RegUnitsToInvalidate;
189 auto InvalidateCopy = [&](MachineInstr *MI) {
190 DestSourcePair CopyOperands = *isCopyInstr(*MI, TII, UseCopyInstr);
191 auto [Dst, Src] = getDstSrcMCRegs(CopyOperands);
192 auto DstUnits = TRI.regunits(Dst);
193 auto SrcUnits = TRI.regunits(Src);
194 RegUnitsToInvalidate.insert_range(DstUnits);
195 RegUnitsToInvalidate.insert_range(SrcUnits);
196 };
197
198 for (MCRegUnit Unit : TRI.regunits(Reg)) {
199 auto I = Copies.find(Unit);
200 if (I != Copies.end()) {
201 if (MachineInstr *MI = I->second.MI)
202 InvalidateCopy(MI);
203 if (MachineInstr *MI = I->second.LastSeenUseInCopy)
204 InvalidateCopy(MI);
205 }
206 }
207 for (MCRegUnit Unit : RegUnitsToInvalidate)
208 Copies.erase(Unit);
209 }
210
211 /// Clobber a single register unit, removing it from the tracker's copy maps.
212 void clobberRegUnit(MCRegUnit Unit, const TargetRegisterInfo &TRI,
213 const TargetInstrInfo &TII, bool UseCopyInstr) {
214 auto I = Copies.find(Unit);
215 if (I != Copies.end()) {
216 // When we clobber the source of a copy, we need to clobber everything
217 // it defined.
218 markRegsUnavailable(I->second.DefRegs, TRI);
219 // When we clobber the destination of a copy, we need to clobber the
220 // whole register it defined.
221 if (MachineInstr *MI = I->second.MI) {
222 DestSourcePair CopyOperands = *isCopyInstr(*MI, TII, UseCopyInstr);
223 auto [Dst, Src] = getDstSrcMCRegs(CopyOperands);
224
225 markRegsUnavailable(Dst, TRI);
226
227 // Since we clobber the destination of a copy, the semantic of Src's
228 // "DefRegs" to contain Def is no longer effectual. We will also need
229 // to remove the record from the copy maps that indicates Src defined
230 // Def. Failing to do so might cause the target to miss some
231 // opportunities to further eliminate redundant copy instructions.
232 // Consider the following sequence during the
233 // ForwardCopyPropagateBlock procedure:
234 // L1: r0 = COPY r9 <- TrackMI
235 // L2: r0 = COPY r8 <- TrackMI (Remove r9 defined r0 from tracker)
236 // L3: use r0 <- Remove L2 from MaybeDeadCopies
237 // L4: early-clobber r9 <- Clobber r9 (L2 is still valid in tracker)
238 // L5: r0 = COPY r8 <- Remove NopCopy
239 for (MCRegUnit SrcUnit : TRI.regunits(Src)) {
240 auto SrcCopy = Copies.find(SrcUnit);
241 if (SrcCopy != Copies.end() && SrcCopy->second.LastSeenUseInCopy) {
242 // If SrcCopy defines multiple values, we only need
243 // to erase the record for Def in DefRegs.
244 // NOLINTNEXTLINE(llvm-qualified-auto)
245 for (auto Itr = SrcCopy->second.DefRegs.begin();
246 Itr != SrcCopy->second.DefRegs.end(); Itr++) {
247 if (*Itr == Dst) {
248 SrcCopy->second.DefRegs.erase(Itr);
249 // If DefReg becomes empty after removal, we can remove the
250 // SrcCopy from the tracker's copy maps. We only remove those
251 // entries solely record the Def is defined by Src. If an
252 // entry also contains the definition record of other Def'
253 // registers, it cannot be cleared.
254 if (SrcCopy->second.DefRegs.empty() && !SrcCopy->second.MI) {
255 Copies.erase(SrcCopy);
256 }
257 break;
258 }
259 }
260 }
261 }
262 }
263 // Now we can erase the copy.
264 Copies.erase(Unit);
265 }
266 }
267
268 /// Clobber a single register, removing it from the tracker's copy maps.
269 void clobberRegister(MCRegister Reg, const TargetRegisterInfo &TRI,
270 const TargetInstrInfo &TII, bool UseCopyInstr) {
271 // Early exit if there are no copies, as the function wouldn't do anything
272 // in that case.
273 if (Copies.empty())
274 return;
275
276 for (MCRegUnit Unit : TRI.regunits(Reg)) {
277 clobberRegUnit(Unit, TRI, TII, UseCopyInstr);
278 }
279 }
280
281 /// Track copy's src users, and return false if that can't be done.
282 /// We can only track if we have a COPY instruction which source is
283 /// the same as the Reg.
284 bool trackSrcUsers(MCRegister Reg, MachineInstr &MI,
285 const TargetRegisterInfo &TRI, const TargetInstrInfo &TII,
286 bool UseCopyInstr) {
287 MCRegUnit RU = *TRI.regunits(Reg).begin();
288 MachineInstr *AvailCopy = findCopyDefViaUnit(RU, TRI);
289 if (!AvailCopy)
290 return false;
291
292 DestSourcePair CopyOperands = *isCopyInstr(*AvailCopy, TII, UseCopyInstr);
293 MCRegister Src = getSrcMCReg(CopyOperands);
294
295 // Bail out, if the source of the copy is not the same as the Reg.
296 if (Src != Reg)
297 return false;
298
299 auto I = Copies.find(RU);
300 if (I == Copies.end())
301 return false;
302
303 I->second.SrcUsers.insert(&MI);
304 return true;
305 }
306
307 /// Return the users for a given register.
308 SmallPtrSet<MachineInstr *, 4> getSrcUsers(MCRegister Reg,
309 const TargetRegisterInfo &TRI) {
310 MCRegUnit RU = *TRI.regunits(Reg).begin();
311 auto I = Copies.find(RU);
312 if (I == Copies.end())
313 return {};
314 return I->second.SrcUsers;
315 }
316
317 /// Add this copy's registers into the tracker's copy maps.
318 void trackCopy(MachineInstr *MI, const TargetRegisterInfo &TRI,
319 const TargetInstrInfo &TII, bool UseCopyInstr) {
320 DestSourcePair CopyOperands = *isCopyInstr(*MI, TII, UseCopyInstr);
321 auto [Dst, Src] = getDstSrcMCRegs(CopyOperands);
322
323 // Remember Dst is defined by the copy.
324 for (MCRegUnit Unit : TRI.regunits(Dst))
325 Copies[Unit] = {MI, nullptr, {}, {}, true};
326
327 // Remember source that's copied to Dst. Once it's clobbered, then
328 // it's no longer available for copy propagation.
329 for (MCRegUnit Unit : TRI.regunits(Src)) {
330 auto &Copy = Copies[Unit];
331 if (!is_contained(Copy.DefRegs, Dst))
332 Copy.DefRegs.push_back(Dst);
333 Copy.LastSeenUseInCopy = MI;
334 }
335 }
336
337 bool hasAnyCopies() {
338 return !Copies.empty();
339 }
340
341 MachineInstr *findCopyForUnit(MCRegUnit RegUnit,
342 const TargetRegisterInfo &TRI,
343 bool MustBeAvailable = false) {
344 auto CI = Copies.find(RegUnit);
345 if (CI == Copies.end())
346 return nullptr;
347 if (MustBeAvailable && !CI->second.Avail)
348 return nullptr;
349 return CI->second.MI;
350 }
351
352 MachineInstr *findCopyDefViaUnit(MCRegUnit RegUnit,
353 const TargetRegisterInfo &TRI) {
354 auto CI = Copies.find(RegUnit);
355 if (CI == Copies.end())
356 return nullptr;
357 if (CI->second.DefRegs.size() != 1)
358 return nullptr;
359 MCRegUnit RU = *TRI.regunits(CI->second.DefRegs[0]).begin();
360 return findCopyForUnit(RU, TRI, true);
361 }
362
363 MachineInstr *findAvailBackwardCopy(MachineInstr &I, MCRegister Reg,
364 const TargetRegisterInfo &TRI,
365 const TargetInstrInfo &TII,
366 bool UseCopyInstr) {
367 MCRegUnit RU = *TRI.regunits(Reg).begin();
368 MachineInstr *AvailCopy = findCopyDefViaUnit(RU, TRI);
369
370 if (!AvailCopy)
371 return nullptr;
372
373 DestSourcePair CopyOperands = *isCopyInstr(*AvailCopy, TII, UseCopyInstr);
374 auto [AvailDst, AvailSrc] = getDstSrcMCRegs(CopyOperands);
375 if (!TRI.isSubRegisterEq(AvailSrc, Reg))
376 return nullptr;
377
378 for (const MachineInstr &MI :
379 make_range(AvailCopy->getReverseIterator(), I.getReverseIterator()))
380 for (const MachineOperand &MO : MI.operands())
381 if (MO.isRegMask())
382 // FIXME: Shall we simultaneously invalidate AvailSrc or AvailDst?
383 if (MO.clobbersPhysReg(AvailSrc) || MO.clobbersPhysReg(AvailDst))
384 return nullptr;
385
386 return AvailCopy;
387 }
388
389 MachineInstr *findAvailCopy(MachineInstr &DestCopy, MCRegister Reg,
390 const TargetRegisterInfo &TRI,
391 const TargetInstrInfo &TII, bool UseCopyInstr) {
392 // We check the first RegUnit here, since we'll only be interested in the
393 // copy if it copies the entire register anyway.
394 MCRegUnit RU = *TRI.regunits(Reg).begin();
395 MachineInstr *AvailCopy =
396 findCopyForUnit(RU, TRI, /*MustBeAvailable=*/true);
397
398 if (!AvailCopy)
399 return nullptr;
400
401 DestSourcePair CopyOperands = *isCopyInstr(*AvailCopy, TII, UseCopyInstr);
402 auto [AvailDst, AvailSrc] = getDstSrcMCRegs(CopyOperands);
403 if (!TRI.isSubRegisterEq(AvailDst, Reg))
404 return nullptr;
405
406 // Check that the available copy isn't clobbered by any regmasks between
407 // itself and the destination.
408 for (const MachineInstr &MI :
409 make_range(AvailCopy->getIterator(), DestCopy.getIterator()))
410 for (const MachineOperand &MO : MI.operands())
411 if (MO.isRegMask())
412 if (MO.clobbersPhysReg(AvailSrc) || MO.clobbersPhysReg(AvailDst))
413 return nullptr;
414
415 return AvailCopy;
416 }
417
418 // Find last COPY that defines Reg before Current MachineInstr.
419 MachineInstr *findLastSeenDefInCopy(const MachineInstr &Current,
420 MCRegister Reg,
421 const TargetRegisterInfo &TRI,
422 const TargetInstrInfo &TII,
423 bool UseCopyInstr) {
424 MCRegUnit RU = *TRI.regunits(Reg).begin();
425 auto CI = Copies.find(RU);
426 if (CI == Copies.end() || !CI->second.Avail)
427 return nullptr;
428
429 MachineInstr *DefCopy = CI->second.MI;
430 DestSourcePair CopyOperands = *isCopyInstr(*DefCopy, TII, UseCopyInstr);
431 MCRegister Dst = getDstMCReg(CopyOperands);
432 if (!TRI.isSubRegisterEq(Dst, Reg))
433 return nullptr;
434
435 return DefCopy;
436 }
437
438 void clobberNonPreservedRegs(const BitVector &PreservedRegUnits,
439 const TargetRegisterInfo &TRI,
440 const TargetInstrInfo &TII) {
441 SmallVector<MCRegUnit, 8> UnitsToClobber;
442 for (auto &[Unit, _] : Copies)
443 if (!PreservedRegUnits.test(static_cast<unsigned>(Unit)))
444 UnitsToClobber.push_back(Unit);
445
446 for (MCRegUnit Unit : UnitsToClobber) {
447 // If we clobber the RegUnit, it will mark all the DefReg Units
448 // as unavailable, which leads to issues if the Destination Reg Unit is
449 // preserved, and used later. As such, only mark them as unavailable if
450 // they are not preserved.
451 auto RegUnitInfo = Copies.find(Unit);
452 if (RegUnitInfo == Copies.end())
453 continue;
454
455 for (MCRegister DstReg : RegUnitInfo->second.DefRegs) {
456 for (MCRegUnit DstUnit : TRI.regunits(DstReg)) {
457 if (!PreservedRegUnits.test(static_cast<unsigned>(DstUnit))) {
458 if (auto CI = Copies.find(DstUnit); CI != Copies.end()) {
459 CI->second.Avail = false;
460 }
461 }
462 }
463 }
464 Copies.erase(RegUnitInfo);
465 }
466 }
467
468 // Find last COPY that uses Reg.
469 MachineInstr *findLastSeenUseInCopy(MCRegister Reg,
470 const TargetRegisterInfo &TRI) {
471 MCRegUnit RU = *TRI.regunits(Reg).begin();
472 auto CI = Copies.find(RU);
473 if (CI == Copies.end())
474 return nullptr;
475 return CI->second.LastSeenUseInCopy;
476 }
477
478 void clear() {
479 Copies.clear();
480 }
481};
482
483class MachineCopyPropagation {
484 const TargetRegisterInfo *TRI = nullptr;
485 const TargetInstrInfo *TII = nullptr;
486 const MachineRegisterInfo *MRI = nullptr;
487
488 // Return true if this is a copy instruction and false otherwise.
489 bool UseCopyInstr;
490
491public:
492 MachineCopyPropagation(bool CopyInstr = false)
493 : UseCopyInstr(CopyInstr || MCPUseCopyInstr) {}
494
495 bool run(MachineFunction &MF);
496
497private:
498 typedef enum { DebugUse = false, RegularUse = true } DebugType;
499
500 void readRegister(MCRegister Reg, MachineInstr &Reader, DebugType DT);
501 void readSuccessorLiveIns(const MachineBasicBlock &MBB);
502 void forwardCopyPropagateBlock(MachineBasicBlock &MBB);
503 void backwardCopyPropagateBlock(MachineBasicBlock &MBB);
504 void eliminateSpillageCopies(MachineBasicBlock &MBB);
505 bool eraseIfRedundant(MachineInstr &Copy, MCRegister Dst, MCRegister Src);
506 void forwardUses(MachineInstr &MI);
507 void propagateDefs(MachineInstr &MI);
508 bool isForwardableRegClassCopy(const MachineInstr &Copy,
509 const MachineInstr &UseI, unsigned UseIdx);
510 bool isBackwardPropagatableRegClassCopy(const MachineInstr &Copy,
511 const MachineInstr &UseI,
512 unsigned UseIdx);
513 bool isBackwardPropagatableCopy(const MachineInstr &Copy,
514 const DestSourcePair &CopyOperands);
515 /// Returns true iff a copy instruction having operand @p CopyOperand must
516 /// never be eliminated as redundant.
517 bool isNeverRedundant(MCRegister CopyOperand) {
518 // Avoid eliminating a copy from/to a reserved registers as we cannot
519 // predict the value (Example: The sparc zero register is writable but stays
520 // zero).
521 return MRI->isReserved(CopyOperand);
522 }
523 /// Returns true iff the @p Copy instruction must never be eliminated as
524 /// redundant. This overload does not consider the operands of @p Copy.
525 bool isNeverRedundant(const MachineInstr &Copy) {
526 return Copy.getFlag(MachineInstr::FrameSetup) ||
528 }
529 bool hasImplicitOverlap(const MachineInstr &MI, const MachineOperand &Use);
530 bool hasOverlappingMultipleDef(const MachineInstr &MI,
531 const MachineOperand &MODef, MCRegister Def);
532 bool canUpdateSrcUsers(const MachineInstr &Copy,
533 const MachineOperand &CopySrc);
534
535 /// Candidates for deletion.
536 SmallSetVector<MachineInstr *, 8> MaybeDeadCopies;
537
538 /// Multimap tracking debug users in current BB
539 DenseMap<MachineInstr *, SmallPtrSet<MachineInstr *, 2>> CopyDbgUsers;
540
541 CopyTracker Tracker;
542
543 bool Changed = false;
544};
545
546class MachineCopyPropagationLegacy : public MachineFunctionPass {
547 bool UseCopyInstr;
548
549public:
550 static char ID; // pass identification
551
552 MachineCopyPropagationLegacy(bool UseCopyInstr = false)
553 : MachineFunctionPass(ID), UseCopyInstr(UseCopyInstr) {}
554
555 void getAnalysisUsage(AnalysisUsage &AU) const override {
556 AU.setPreservesCFG();
558 }
559
560 bool runOnMachineFunction(MachineFunction &MF) override;
561
562 MachineFunctionProperties getRequiredProperties() const override {
563 return MachineFunctionProperties().setNoVRegs();
564 }
565};
566
567} // end anonymous namespace
568
569char MachineCopyPropagationLegacy::ID = 0;
570
571char &llvm::MachineCopyPropagationID = MachineCopyPropagationLegacy::ID;
572
573INITIALIZE_PASS(MachineCopyPropagationLegacy, DEBUG_TYPE,
574 "Machine Copy Propagation Pass", false, false)
575
576void MachineCopyPropagation::readRegister(MCRegister Reg, MachineInstr &Reader,
577 DebugType DT) {
578 // If 'Reg' is defined by a copy, the copy is no longer a candidate
579 // for elimination. If a copy is "read" by a debug user, record the user
580 // for propagation.
581 for (MCRegUnit Unit : TRI->regunits(Reg)) {
582 if (MachineInstr *Copy = Tracker.findCopyForUnit(Unit, *TRI)) {
583 if (DT == RegularUse) {
584 LLVM_DEBUG(dbgs() << "MCP: Copy is used - not dead: "; Copy->dump());
585 MaybeDeadCopies.remove(Copy);
586 } else {
587 CopyDbgUsers[Copy].insert(&Reader);
588 }
589 }
590 }
591}
592
593void MachineCopyPropagation::readSuccessorLiveIns(
594 const MachineBasicBlock &MBB) {
595 if (MaybeDeadCopies.empty())
596 return;
597
598 // If a copy result is livein to a successor, it is not dead.
599 for (const MachineBasicBlock *Succ : MBB.successors()) {
600 for (const auto &LI : Succ->liveins()) {
601 for (MCRegUnitMaskIterator U(LI.PhysReg, TRI); U.isValid(); ++U) {
602 auto [Unit, Mask] = *U;
603 if ((Mask & LI.LaneMask).any()) {
604 if (MachineInstr *Copy = Tracker.findCopyForUnit(Unit, *TRI))
605 MaybeDeadCopies.remove(Copy);
606 }
607 }
608 }
609 }
610}
611
612/// Return true if \p PreviousCopy did copy register \p Src to register \p Dst.
613/// This fact may have been obscured by sub register usage or may not be true at
614/// all even though Src and Dst are subregisters of the registers used in
615/// PreviousCopy. e.g.
616/// isNopCopy("ecx = COPY eax", AX, CX) == true
617/// isNopCopy("ecx = COPY eax", AH, CL) == false
618static bool isNopCopy(const MachineInstr &PreviousCopy, MCRegister Src,
620 const TargetInstrInfo *TII, bool UseCopyInstr) {
621
622 DestSourcePair CopyOperands = *isCopyInstr(PreviousCopy, *TII, UseCopyInstr);
623 auto [PreviousDst, PreviousSrc] = getDstSrcMCRegs(CopyOperands);
624 if (Src == PreviousSrc && Dst == PreviousDst)
625 return true;
626 if (!TRI->isSubRegister(PreviousSrc, Src))
627 return false;
628 unsigned SubIdx = TRI->getSubRegIndex(PreviousSrc, Src);
629 return SubIdx == TRI->getSubRegIndex(PreviousDst, Dst);
630}
631
632/// Remove instruction \p Copy if there exists a previous copy that copies the
633/// register \p Src to the register \p Dst; This may happen indirectly by
634/// copying the super registers.
635bool MachineCopyPropagation::eraseIfRedundant(MachineInstr &Copy,
636 MCRegister Dst, MCRegister Src) {
637 if (isNeverRedundant(Copy) || isNeverRedundant(Src) || isNeverRedundant(Dst))
638 return false;
639
640 // Search for an existing copy.
641 MachineInstr *PrevCopy =
642 Tracker.findAvailCopy(Copy, Dst, *TRI, *TII, UseCopyInstr);
643 if (!PrevCopy)
644 return false;
645
646 DestSourcePair PrevCopyOperands = *isCopyInstr(*PrevCopy, *TII, UseCopyInstr);
647 // Check that the existing copy uses the correct sub registers.
648 if (PrevCopyOperands.Destination->isDead())
649 return false;
650 if (!isNopCopy(*PrevCopy, Src, Dst, TRI, TII, UseCopyInstr))
651 return false;
652
653 LLVM_DEBUG(dbgs() << "MCP: copy is a NOP, removing: "; Copy.dump());
654
655 // Copy was redundantly redefining either Src or Dst. Remove earlier kill
656 // flags between Copy and PrevCopy because the value will be reused now.
657 DestSourcePair CopyOperands = *isCopyInstr(Copy, *TII, UseCopyInstr);
658
659 MCRegister CopyDst = getDstMCReg(CopyOperands);
660 assert(CopyDst == Src || CopyDst == Dst);
661 for (MachineInstr &MI :
662 make_range(PrevCopy->getIterator(), Copy.getIterator()))
663 MI.clearRegisterKills(CopyDst, TRI);
664
665 // Clear undef flag from remaining copy if needed.
666 if (!CopyOperands.Source->isUndef()) {
667 PrevCopy->getOperand(PrevCopyOperands.Source->getOperandNo())
668 .setIsUndef(false);
669 }
670
671 Copy.eraseFromParent();
672 Changed = true;
673 ++NumDeletes;
674 return true;
675}
676
677bool MachineCopyPropagation::isBackwardPropagatableRegClassCopy(
678 const MachineInstr &Copy, const MachineInstr &UseI, unsigned UseIdx) {
679 DestSourcePair CopyOperands = *isCopyInstr(Copy, *TII, UseCopyInstr);
680 MCRegister Dst = getDstMCReg(CopyOperands);
681
682 if (const TargetRegisterClass *URC =
683 UseI.getRegClassConstraint(UseIdx, TII, TRI))
684 return URC->contains(Dst);
685
686 // We don't process further if UseI is a COPY, since forward copy propagation
687 // should handle that.
688 return false;
689}
690
691bool MachineCopyPropagation::isBackwardPropagatableCopy(
692 const MachineInstr &Copy, const DestSourcePair &CopyOperands) {
693 auto [Dst, Src] = getDstSrcMCRegs(CopyOperands);
694
695 if (!Dst || !Src)
696 return false;
697
698 if (isNeverRedundant(Copy) || isNeverRedundant(Dst) || isNeverRedundant(Src))
699 return false;
700
701 return CopyOperands.Source->isRenamable() && CopyOperands.Source->isKill();
702}
703
704/// Decide whether we should forward the source of \param Copy to its use in
705/// \param UseI based on the physical register class constraints of the opcode
706/// and avoiding introducing more cross-class COPYs.
707bool MachineCopyPropagation::isForwardableRegClassCopy(const MachineInstr &Copy,
708 const MachineInstr &UseI,
709 unsigned UseIdx) {
710 DestSourcePair CopyOperands = *isCopyInstr(Copy, *TII, UseCopyInstr);
711 MCRegister CopySrc = getSrcMCReg(CopyOperands);
712
713 // If the new register meets the opcode register constraints, then allow
714 // forwarding.
715 if (const TargetRegisterClass *URC =
716 UseI.getRegClassConstraint(UseIdx, TII, TRI))
717 return URC->contains(CopySrc);
718
719 std::optional<DestSourcePair> UseICopyOperands =
720 isCopyInstr(UseI, *TII, UseCopyInstr);
721 if (!UseICopyOperands)
722 return false;
723
724 /// COPYs don't have register class constraints, so if the user instruction
725 /// is a COPY, we just try to avoid introducing additional cross-class
726 /// COPYs. For example:
727 ///
728 /// RegClassA = COPY RegClassB // Copy parameter
729 /// ...
730 /// RegClassB = COPY RegClassA // UseI parameter
731 ///
732 /// which after forwarding becomes
733 ///
734 /// RegClassA = COPY RegClassB
735 /// ...
736 /// RegClassB = COPY RegClassB
737 ///
738 /// so we have reduced the number of cross-class COPYs and potentially
739 /// introduced a nop COPY that can be removed.
740
741 // Allow forwarding if src and dst belong to any common class, so long as they
742 // don't belong to any (possibly smaller) common class that requires copies to
743 // go via a different class.
744 MCRegister UseDst = getDstMCReg(*UseICopyOperands);
745 bool Found = false;
746 bool IsCrossClass = false;
747 for (const TargetRegisterClass &RC : TRI->regclasses()) {
748 if (RC.contains(CopySrc) && RC.contains(UseDst)) {
749 Found = true;
750 if (TRI->getCrossCopyRegClass(&RC) != &RC) {
751 IsCrossClass = true;
752 break;
753 }
754 }
755 }
756 if (!Found)
757 return false;
758 if (!IsCrossClass)
759 return true;
760 // The forwarded copy would be cross-class. Only do this if the original copy
761 // was also cross-class.
762 MCRegister CopyDst = getDstMCReg(CopyOperands);
763 for (const TargetRegisterClass &RC : TRI->regclasses()) {
764 if (RC.contains(CopySrc) && RC.contains(CopyDst) &&
765 TRI->getCrossCopyRegClass(&RC) != &RC)
766 return true;
767 }
768 return false;
769}
770
771/// Check that \p MI does not have implicit uses that overlap with it's \p Use
772/// operand (the register being replaced), since these can sometimes be
773/// implicitly tied to other operands. For example, on AMDGPU:
774///
775/// V_MOVRELS_B32_e32 %VGPR2, %M0<imp-use>, %EXEC<imp-use>, %VGPR2_VGPR3_VGPR4_VGPR5<imp-use>
776///
777/// the %VGPR2 is implicitly tied to the larger reg operand, but we have no
778/// way of knowing we need to update the latter when updating the former.
779bool MachineCopyPropagation::hasImplicitOverlap(const MachineInstr &MI,
780 const MachineOperand &Use) {
781 for (const MachineOperand &MIUse : MI.uses())
782 if (&MIUse != &Use && MIUse.isReg() && MIUse.isImplicit() &&
783 MIUse.isUse() && TRI->regsOverlap(Use.getReg(), MIUse.getReg()))
784 return true;
785
786 return false;
787}
788
789/// For an MI that has multiple definitions, check whether \p MI has
790/// a definition that overlaps with another of its definitions.
791/// For example, on ARM: umull r9, r9, lr, r0
792/// The umull instruction is unpredictable unless RdHi and RdLo are different.
793bool MachineCopyPropagation::hasOverlappingMultipleDef(
794 const MachineInstr &MI, const MachineOperand &MODef, MCRegister Def) {
795 for (const MachineOperand &MIDef : MI.all_defs()) {
796 if ((&MIDef != &MODef) && MIDef.isReg() &&
797 TRI->regsOverlap(Def, MIDef.getReg()))
798 return true;
799 }
800
801 return false;
802}
803
804/// Return true if it is safe to update all users of the \p CopySrc register
805/// in the given \p Copy instruction.
806bool MachineCopyPropagation::canUpdateSrcUsers(const MachineInstr &Copy,
807 const MachineOperand &CopySrc) {
808 assert(CopySrc.isReg() && "Expected a register operand");
809 for (auto *SrcUser : Tracker.getSrcUsers(CopySrc.getReg(), *TRI)) {
810 if (hasImplicitOverlap(*SrcUser, CopySrc))
811 return false;
812
813 for (MachineOperand &MO : SrcUser->uses()) {
814 if (!MO.isReg() || !MO.isUse() || MO.getReg() != CopySrc.getReg())
815 continue;
816 if (MO.isTied() || !MO.isRenamable() ||
817 !isBackwardPropagatableRegClassCopy(Copy, *SrcUser,
818 MO.getOperandNo()))
819 return false;
820 }
821 }
822 return true;
823}
824
825/// Look for available copies whose destination register is used by \p MI and
826/// replace the use in \p MI with the copy's source register.
827void MachineCopyPropagation::forwardUses(MachineInstr &MI) {
828 if (!Tracker.hasAnyCopies())
829 return;
830
831 // Look for non-tied explicit vreg uses that have an active COPY
832 // instruction that defines the physical register allocated to them.
833 // Replace the vreg with the source of the active COPY.
834 for (unsigned OpIdx = 0, OpEnd = MI.getNumOperands(); OpIdx < OpEnd;
835 ++OpIdx) {
836 MachineOperand &MOUse = MI.getOperand(OpIdx);
837 // Don't forward into undef use operands since doing so can cause problems
838 // with the machine verifier, since it doesn't treat undef reads as reads,
839 // so we can end up with a live range that ends on an undef read, leading to
840 // an error that the live range doesn't end on a read of the live range
841 // register.
842 if (!MOUse.isReg() || MOUse.isTied() || MOUse.isUndef() || MOUse.isDef() ||
843 MOUse.isImplicit())
844 continue;
845
846 if (!MOUse.getReg())
847 continue;
848
849 // Check that the register is marked 'renamable' so we know it is safe to
850 // rename it without violating any constraints that aren't expressed in the
851 // IR (e.g. ABI or opcode requirements).
852 if (!MOUse.isRenamable())
853 continue;
854
855 MachineInstr *Copy = Tracker.findAvailCopy(MI, MOUse.getReg().asMCReg(),
856 *TRI, *TII, UseCopyInstr);
857 if (!Copy)
858 continue;
859
860 DestSourcePair CopyOperands = *isCopyInstr(*Copy, *TII, UseCopyInstr);
861 auto [CopyDst, CopySrc] = getDstSrcMCRegs(CopyOperands);
862 const MachineOperand &CopySrcOperand = *CopyOperands.Source;
863
864 MCRegister ForwardedReg = CopySrc;
865 // MI might use a sub-register of the Copy destination, in which case the
866 // forwarded register is the matching sub-register of the Copy source.
867 if (MOUse.getReg() != CopyDst) {
868 unsigned SubRegIdx = TRI->getSubRegIndex(CopyDst, MOUse.getReg());
869 assert(SubRegIdx &&
870 "MI source is not a sub-register of Copy destination");
871 ForwardedReg = TRI->getSubReg(CopySrc, SubRegIdx);
872 if (!ForwardedReg || TRI->isArtificial(ForwardedReg)) {
873 LLVM_DEBUG(dbgs() << "MCP: Copy source does not have sub-register "
874 << TRI->getSubRegIndexName(SubRegIdx) << '\n');
875 continue;
876 }
877 }
878
879 // Don't forward COPYs of reserved regs unless they are constant.
880 if (MRI->isReserved(CopySrc) && !MRI->isConstantPhysReg(CopySrc))
881 continue;
882
883 if (!isForwardableRegClassCopy(*Copy, MI, OpIdx))
884 continue;
885
886 if (hasImplicitOverlap(MI, MOUse))
887 continue;
888
889 // Check that the instruction is not a copy that partially overwrites the
890 // original copy source that we are about to use. The tracker mechanism
891 // cannot cope with that.
892 if (isCopyInstr(MI, *TII, UseCopyInstr) &&
893 MI.modifiesRegister(CopySrc, TRI) &&
894 !MI.definesRegister(CopySrc, /*TRI=*/nullptr)) {
895 LLVM_DEBUG(dbgs() << "MCP: Copy source overlap with dest in " << MI);
896 continue;
897 }
898
899 if (!DebugCounter::shouldExecute(FwdCounter)) {
900 LLVM_DEBUG(dbgs() << "MCP: Skipping forwarding due to debug counter:\n "
901 << MI);
902 continue;
903 }
904
905 LLVM_DEBUG(dbgs() << "MCP: Replacing " << printReg(MOUse.getReg(), TRI)
906 << "\n with " << printReg(ForwardedReg, TRI)
907 << "\n in " << MI << " from " << *Copy);
908
909 MOUse.setReg(ForwardedReg);
910
911 if (!CopySrcOperand.isRenamable())
912 MOUse.setIsRenamable(false);
913 MOUse.setIsUndef(CopySrcOperand.isUndef());
914
915 LLVM_DEBUG(dbgs() << "MCP: After replacement: " << MI << "\n");
916
917 // Clear kill markers that may have been invalidated.
918 for (MachineInstr &KMI :
919 make_range(Copy->getIterator(), std::next(MI.getIterator())))
920 KMI.clearRegisterKills(CopySrc, TRI);
921
922 ++NumCopyForwards;
923 Changed = true;
924 }
925}
926
927void MachineCopyPropagation::forwardCopyPropagateBlock(MachineBasicBlock &MBB) {
928 LLVM_DEBUG(dbgs() << "MCP: ForwardCopyPropagateBlock " << MBB.getName()
929 << "\n");
930
931 for (MachineInstr &MI : llvm::make_early_inc_range(MBB)) {
932 // Analyze copies (which don't overlap themselves).
933 std::optional<DestSourcePair> CopyOperands =
934 isCopyInstr(MI, *TII, UseCopyInstr);
935 if (CopyOperands) {
936 auto [Dst, Src] = getDstSrcMCRegs(*CopyOperands);
937 if (!TRI->regsOverlap(Dst, Src)) {
938 // The two copies cancel out and the source of the first copy
939 // hasn't been overridden, eliminate the second one. e.g.
940 // %ecx = COPY %eax
941 // ... nothing clobbered eax.
942 // %eax = COPY %ecx
943 // =>
944 // %ecx = COPY %eax
945 //
946 // or
947 //
948 // %ecx = COPY %eax
949 // ... nothing clobbered eax.
950 // %ecx = COPY %eax
951 // =>
952 // %ecx = COPY %eax
953 if (eraseIfRedundant(MI, Dst, Src) || eraseIfRedundant(MI, Src, Dst))
954 continue;
955 }
956 }
957
958 // Clobber any earlyclobber regs first.
959 for (const MachineOperand &MO : MI.operands())
960 if (MO.isReg() && MO.isEarlyClobber()) {
961 MCRegister Reg = MO.getReg().asMCReg();
962 // If we have a tied earlyclobber, that means it is also read by this
963 // instruction, so we need to make sure we don't remove it as dead
964 // later.
965 if (MO.isTied())
966 readRegister(Reg, MI, RegularUse);
967 Tracker.clobberRegister(Reg, *TRI, *TII, UseCopyInstr);
968 }
969
970 forwardUses(MI);
971
972 // Attempt to canonicalize/optimize the instruction now its arguments have
973 // been mutated. This may convert MI from a non-copy to a copy instruction.
974 if (TII->simplifyInstruction(MI)) {
975 Changed = true;
976 LLVM_DEBUG(dbgs() << "MCP: After simplifyInstruction: " << MI);
977 }
978
979 CopyOperands = isCopyInstr(MI, *TII, UseCopyInstr);
980 if (CopyOperands) {
981 auto [Dst, Src] = getDstSrcMCRegs(*CopyOperands);
982 if (!TRI->regsOverlap(Dst, Src)) {
983 // FIXME: Document why this does not consider `RegSrc`, similar to how
984 // `backwardCopyPropagateBlock` does.
985 if (!isNeverRedundant(MI) && !isNeverRedundant(Dst))
986 MaybeDeadCopies.insert(&MI);
987 }
988 }
989
991 const MachineOperand *RegMask = nullptr;
992 for (const MachineOperand &MO : MI.operands()) {
993 if (MO.isRegMask())
994 RegMask = &MO;
995 if (!MO.isReg())
996 continue;
997 Register Reg = MO.getReg();
998 if (!Reg)
999 continue;
1000
1001 assert(Reg.isPhysical() &&
1002 "MachineCopyPropagation should be run after register allocation!");
1003
1004 if (MO.isDef() && !MO.isEarlyClobber()) {
1005 // Skip invalidating constant registers.
1006 if (!MRI->isConstantPhysReg(Reg)) {
1007 Defs.push_back(Reg.asMCReg());
1008 continue;
1009 }
1010 } else if (MO.readsReg()) {
1011 readRegister(Reg.asMCReg(), MI, MO.isDebug() ? DebugUse : RegularUse);
1012 }
1013 }
1014
1015 // The instruction has a register mask operand which means that it clobbers
1016 // a large set of registers. Treat clobbered registers the same way as
1017 // defined registers.
1018 if (RegMask) {
1019 BitVector &PreservedRegUnits =
1020 Tracker.getPreservedRegUnits(*RegMask, *TRI);
1021
1022 // Erase any MaybeDeadCopies whose destination register is clobbered.
1023 for (SmallSetVector<MachineInstr *, 8>::iterator DI =
1024 MaybeDeadCopies.begin();
1025 DI != MaybeDeadCopies.end();) {
1026 MachineInstr *MaybeDead = *DI;
1027 std::optional<DestSourcePair> CopyOperands =
1028 isCopyInstr(*MaybeDead, *TII, UseCopyInstr);
1029 MCRegister Reg = CopyOperands->Destination->getReg().asMCReg();
1030 assert(!isNeverRedundant(*MaybeDead) && !isNeverRedundant(Reg));
1031
1032 if (!RegMask->clobbersPhysReg(Reg)) {
1033 ++DI;
1034 continue;
1035 }
1036
1037 // Invalidate all entries in the copy map which are not preserved by
1038 // this register mask.
1039 bool MIRefedinCopyInfo = false;
1040 for (MCRegUnit RegUnit : TRI->regunits(Reg)) {
1041 if (!PreservedRegUnits.test(static_cast<unsigned>(RegUnit)))
1042 Tracker.clobberRegUnit(RegUnit, *TRI, *TII, UseCopyInstr);
1043 else {
1044 if (MaybeDead == Tracker.findCopyForUnit(RegUnit, *TRI)) {
1045 MIRefedinCopyInfo = true;
1046 }
1047 }
1048 }
1049
1050 // erase() will return the next valid iterator pointing to the next
1051 // element after the erased one.
1052 DI = MaybeDeadCopies.erase(DI);
1053
1054 // Preserved by RegMask, DO NOT remove copy
1055 if (MIRefedinCopyInfo)
1056 continue;
1057
1058 LLVM_DEBUG(dbgs() << "MCP: Removing copy due to regmask clobbering: "
1059 << *MaybeDead);
1060
1061 MaybeDead->eraseFromParent();
1062 Changed = true;
1063 ++NumDeletes;
1064 }
1065 }
1066
1067 // Any previous copy definition or reading the Defs is no longer available.
1068 for (MCRegister Reg : Defs)
1069 Tracker.clobberRegister(Reg, *TRI, *TII, UseCopyInstr);
1070
1071 if (CopyOperands) {
1072 auto [Dst, Src] = getDstSrcMCRegs(*CopyOperands);
1073 if (!TRI->regsOverlap(Dst, Src)) {
1074 Tracker.trackCopy(&MI, *TRI, *TII, UseCopyInstr);
1075 }
1076 }
1077 }
1078
1079 bool TracksLiveness = MRI->tracksLiveness();
1080
1081 // If liveness is tracked, we can use the live-in lists to know which
1082 // copies aren't dead.
1083 if (TracksLiveness)
1084 readSuccessorLiveIns(MBB);
1085
1086 // If MBB doesn't have succesor, delete copies whose defs are not used.
1087 // If MBB does have successors, we can only delete copies if we are able to
1088 // use liveness information from successors to confirm they are really dead.
1089 if (MBB.succ_empty() || TracksLiveness) {
1090 for (MachineInstr *MaybeDead : MaybeDeadCopies) {
1091 LLVM_DEBUG(dbgs() << "MCP: Removing copy due to no live-out succ: ";
1092 MaybeDead->dump());
1093
1094 DestSourcePair CopyOperands =
1095 *isCopyInstr(*MaybeDead, *TII, UseCopyInstr);
1096
1097 auto [Dst, Src] = getDstSrcMCRegs(CopyOperands);
1098 assert(!isNeverRedundant(*MaybeDead) && !isNeverRedundant(Dst));
1099
1100 // Update matching debug values, if any.
1101 const auto &DbgUsers = CopyDbgUsers[MaybeDead];
1102 SmallVector<MachineInstr *> MaybeDeadDbgUsers(DbgUsers.begin(),
1103 DbgUsers.end());
1104 MRI->updateDbgUsersToReg(Dst, Src, MaybeDeadDbgUsers);
1105
1106 MaybeDead->eraseFromParent();
1107 Changed = true;
1108 ++NumDeletes;
1109 }
1110 }
1111
1112 MaybeDeadCopies.clear();
1113 CopyDbgUsers.clear();
1114 Tracker.clear();
1115}
1116
1117void MachineCopyPropagation::propagateDefs(MachineInstr &MI) {
1118 if (!Tracker.hasAnyCopies())
1119 return;
1120
1121 for (unsigned OpIdx = 0, OpEnd = MI.getNumOperands(); OpIdx != OpEnd;
1122 ++OpIdx) {
1123 MachineOperand &MODef = MI.getOperand(OpIdx);
1124
1125 if (!MODef.isReg() || MODef.isUse())
1126 continue;
1127
1128 // Ignore non-trivial cases.
1129 if (MODef.isTied() || MODef.isUndef() || MODef.isImplicit())
1130 continue;
1131
1132 if (!MODef.getReg())
1133 continue;
1134
1135 // We only handle if the register comes from a vreg.
1136 if (!MODef.isRenamable())
1137 continue;
1138
1139 MachineInstr *Copy = Tracker.findAvailBackwardCopy(
1140 MI, MODef.getReg().asMCReg(), *TRI, *TII, UseCopyInstr);
1141 if (!Copy)
1142 continue;
1143
1144 DestSourcePair CopyOperands = *isCopyInstr(*Copy, *TII, UseCopyInstr);
1145 auto [Dst, Src] = getDstSrcMCRegs(CopyOperands);
1146
1147 if (MODef.getReg() != Src)
1148 continue;
1149
1150 if (!isBackwardPropagatableRegClassCopy(*Copy, MI, OpIdx))
1151 continue;
1152
1153 if (hasImplicitOverlap(MI, MODef))
1154 continue;
1155
1156 if (hasOverlappingMultipleDef(MI, MODef, Dst))
1157 continue;
1158
1159 if (!canUpdateSrcUsers(*Copy, *CopyOperands.Source))
1160 continue;
1161
1162 LLVM_DEBUG(dbgs() << "MCP: Replacing " << printReg(MODef.getReg(), TRI)
1163 << "\n with " << printReg(Dst, TRI) << "\n in "
1164 << MI << " from " << *Copy);
1165
1166 MODef.setReg(Dst);
1167 MODef.setIsRenamable(CopyOperands.Destination->isRenamable());
1168
1169 for (auto *SrcUser : Tracker.getSrcUsers(Src, *TRI)) {
1170 for (MachineOperand &MO : SrcUser->uses()) {
1171 if (!MO.isReg() || !MO.isUse() || MO.getReg() != Src)
1172 continue;
1173 MO.setReg(Dst);
1174 MO.setIsRenamable(CopyOperands.Destination->isRenamable());
1175 }
1176 }
1177
1178 LLVM_DEBUG(dbgs() << "MCP: After replacement: " << MI << "\n");
1179 MaybeDeadCopies.insert(Copy);
1180 Changed = true;
1181 ++NumCopyBackwardPropagated;
1182 }
1183}
1184
1185void MachineCopyPropagation::backwardCopyPropagateBlock(
1186 MachineBasicBlock &MBB) {
1187 LLVM_DEBUG(dbgs() << "MCP: BackwardCopyPropagateBlock " << MBB.getName()
1188 << "\n");
1189
1190 for (MachineInstr &MI : llvm::make_early_inc_range(llvm::reverse(MBB))) {
1191 // Ignore non-trivial COPYs.
1192 std::optional<DestSourcePair> CopyOperands =
1193 isCopyInstr(MI, *TII, UseCopyInstr);
1194 if (CopyOperands && MI.getNumImplicitOperands() == 0) {
1195 auto [Dst, Src] = getDstSrcMCRegs(*CopyOperands);
1196
1197 if (!TRI->regsOverlap(Dst, Src)) {
1198 // Unlike forward cp, we don't invoke propagateDefs here,
1199 // just let forward cp do COPY-to-COPY propagation.
1200 if (isBackwardPropagatableCopy(MI, *CopyOperands)) {
1201 Tracker.invalidateRegister(Src, *TRI, *TII, UseCopyInstr);
1202 Tracker.invalidateRegister(Dst, *TRI, *TII, UseCopyInstr);
1203 Tracker.trackCopy(&MI, *TRI, *TII, UseCopyInstr);
1204 continue;
1205 }
1206 }
1207 }
1208
1209 // Invalidate any earlyclobber regs first.
1210 for (const MachineOperand &MO : MI.operands())
1211 if (MO.isReg() && MO.isEarlyClobber()) {
1212 MCRegister Reg = MO.getReg().asMCReg();
1213 if (!Reg)
1214 continue;
1215 Tracker.invalidateRegister(Reg, *TRI, *TII, UseCopyInstr);
1216 }
1217
1218 propagateDefs(MI);
1219 for (const MachineOperand &MO : MI.operands()) {
1220 if (!MO.isReg())
1221 continue;
1222
1223 if (!MO.getReg())
1224 continue;
1225
1226 if (MO.isDef())
1227 Tracker.invalidateRegister(MO.getReg().asMCReg(), *TRI, *TII,
1228 UseCopyInstr);
1229
1230 if (MO.readsReg()) {
1231 if (MO.isDebug()) {
1232 // Check if the register in the debug instruction is utilized
1233 // in a copy instruction, so we can update the debug info if the
1234 // register is changed.
1235 for (MCRegUnit Unit : TRI->regunits(MO.getReg().asMCReg())) {
1236 if (auto *Copy = Tracker.findCopyDefViaUnit(Unit, *TRI)) {
1237 CopyDbgUsers[Copy].insert(&MI);
1238 }
1239 }
1240 } else if (!Tracker.trackSrcUsers(MO.getReg().asMCReg(), MI, *TRI, *TII,
1241 UseCopyInstr)) {
1242 // If we can't track the source users, invalidate the register.
1243 Tracker.invalidateRegister(MO.getReg().asMCReg(), *TRI, *TII,
1244 UseCopyInstr);
1245 }
1246 }
1247 }
1248 }
1249
1250 for (auto *Copy : MaybeDeadCopies) {
1251 DestSourcePair CopyOperands = *isCopyInstr(*Copy, *TII, UseCopyInstr);
1252 auto [Dst, Src] = getDstSrcMCRegs(CopyOperands);
1253 const auto &DbgUsers = CopyDbgUsers[Copy];
1254 SmallVector<MachineInstr *> MaybeDeadDbgUsers(DbgUsers.begin(),
1255 DbgUsers.end());
1256
1257 MRI->updateDbgUsersToReg(Src, Dst, MaybeDeadDbgUsers);
1258 Copy->eraseFromParent();
1259 ++NumDeletes;
1260 }
1261
1262 MaybeDeadCopies.clear();
1263 CopyDbgUsers.clear();
1264 Tracker.clear();
1265}
1266
1267[[maybe_unused]] static void printSpillReloadChain(
1270 MachineInstr *Leader) {
1271 auto &SC = SpillChain[Leader];
1272 auto &RC = ReloadChain[Leader];
1273 for (auto I = SC.rbegin(), E = SC.rend(); I != E; ++I)
1274 (*I)->dump();
1275 for (MachineInstr *MI : RC)
1276 MI->dump();
1277}
1278
1279// Remove spill-reload like copy chains. For example
1280// r0 = COPY r1
1281// r1 = COPY r2
1282// r2 = COPY r3
1283// r3 = COPY r4
1284// <def-use r4>
1285// r4 = COPY r3
1286// r3 = COPY r2
1287// r2 = COPY r1
1288// r1 = COPY r0
1289// will be folded into
1290// r0 = COPY r1
1291// r1 = COPY r4
1292// <def-use r4>
1293// r4 = COPY r1
1294// r1 = COPY r0
1295// TODO: Currently we don't track usage of r0 outside the chain, so we
1296// conservatively keep its value as it was before the rewrite.
1297//
1298// The algorithm is trying to keep
1299// property#1: No Dst of spill COPY in the chain is used or defined until the
1300// paired reload COPY in the chain uses the Dst.
1301//
1302// property#2: NO Source of COPY in the chain is used or defined until the next
1303// COPY in the chain defines the Source, except the innermost spill-reload
1304// pair.
1305//
1306// The algorithm is conducted by checking every COPY inside the MBB, assuming
1307// the COPY is a reload COPY, then try to find paired spill COPY by searching
1308// the COPY defines the Src of the reload COPY backward. If such pair is found,
1309// it either belongs to an existing chain or a new chain depends on
1310// last available COPY uses the Dst of the reload COPY.
1311// Implementation notes, we use CopyTracker::findLastDefCopy(Reg, ...) to find
1312// out last COPY that defines Reg; we use CopyTracker::findLastUseCopy(Reg, ...)
1313// to find out last COPY that uses Reg. When we are encountered with a Non-COPY
1314// instruction, we check registers in the operands of this instruction. If this
1315// Reg is defined by a COPY, we untrack this Reg via
1316// CopyTracker::clobberRegister(Reg, ...).
1317void MachineCopyPropagation::eliminateSpillageCopies(MachineBasicBlock &MBB) {
1318
1319 // Perform some cost modelling to ensure that only MBB's with more
1320 // than 6 copies are checked. To create a chain that can be optimised,
1321 // 6 copies are needed.
1322 unsigned CopyCount = 0;
1323 for (const MachineInstr &MI : MBB) {
1324 if (isCopyInstr(MI, *TII, UseCopyInstr) && ++CopyCount > 6)
1325 break;
1326 }
1327 if (CopyCount < 6)
1328 return;
1329
1330 // ChainLeader maps MI inside a spill-reload chain to its innermost reload COPY.
1331 // Thus we can track if a MI belongs to an existing spill-reload chain.
1332 DenseMap<MachineInstr *, MachineInstr *> ChainLeader;
1333 // SpillChain maps innermost reload COPY of a spill-reload chain to a sequence
1334 // of COPYs that forms spills of a spill-reload chain.
1335 // ReloadChain maps innermost reload COPY of a spill-reload chain to a
1336 // sequence of COPYs that forms reloads of a spill-reload chain.
1337 DenseMap<MachineInstr *, SmallVector<MachineInstr *>> SpillChain, ReloadChain;
1338 // If a COPY's Source has use or def until next COPY defines the Source,
1339 // we put the COPY in this set to keep property#2.
1340 DenseSet<const MachineInstr *> CopySourceInvalid;
1341
1342 auto TryFoldSpillageCopies =
1343 [&, this](const SmallVectorImpl<MachineInstr *> &SC,
1344 const SmallVectorImpl<MachineInstr *> &RC) {
1345 assert(SC.size() == RC.size() && "Spill-reload should be paired");
1346
1347 // We need at least 3 pairs of copies for the transformation to apply,
1348 // because the first outermost pair cannot be removed since we don't
1349 // recolor outside of the chain and that we need at least one temporary
1350 // spill slot to shorten the chain. If we only have a chain of two
1351 // pairs, we already have the shortest sequence this code can handle:
1352 // the outermost pair for the temporary spill slot, and the pair that
1353 // use that temporary spill slot for the other end of the chain.
1354 // TODO: We might be able to simplify to one spill-reload pair if collecting
1355 // more infomation about the outermost COPY.
1356 if (SC.size() <= 2)
1357 return;
1358
1359 // If violate property#2, we don't fold the chain.
1360 for (const MachineInstr *Spill : drop_begin(SC))
1361 if (CopySourceInvalid.count(Spill))
1362 return;
1363
1364 for (const MachineInstr *Reload : drop_end(RC))
1365 if (CopySourceInvalid.count(Reload))
1366 return;
1367
1368 auto CheckCopyConstraint = [this](Register Dst, Register Src) {
1369 return TRI->getCommonMinimalPhysRegClass(Dst, Src);
1370 };
1371
1372 auto UpdateReg = [](MachineInstr *MI, const MachineOperand *Old,
1373 const MachineOperand *New) {
1374 for (MachineOperand &MO : MI->operands()) {
1375 if (&MO == Old)
1376 MO.setReg(New->getReg());
1377 }
1378 };
1379
1380 DestSourcePair InnerMostSpillCopy =
1381 *isCopyInstr(*SC[0], *TII, UseCopyInstr);
1382 DestSourcePair OuterMostSpillCopy =
1383 *isCopyInstr(*SC.back(), *TII, UseCopyInstr);
1384 DestSourcePair InnerMostReloadCopy =
1385 *isCopyInstr(*RC[0], *TII, UseCopyInstr);
1386 DestSourcePair OuterMostReloadCopy =
1387 *isCopyInstr(*RC.back(), *TII, UseCopyInstr);
1388 if (!CheckCopyConstraint(getSrcMCReg(OuterMostSpillCopy),
1389 getSrcMCReg(InnerMostSpillCopy)) ||
1390 !CheckCopyConstraint(getDstMCReg(InnerMostReloadCopy),
1391 getDstMCReg(OuterMostReloadCopy)))
1392 return;
1393
1394 SpillageChainsLength += SC.size() + RC.size();
1395 NumSpillageChains += 1;
1396 UpdateReg(SC[0], InnerMostSpillCopy.Destination,
1397 OuterMostSpillCopy.Source);
1398 UpdateReg(RC[0], InnerMostReloadCopy.Source,
1399 OuterMostReloadCopy.Destination);
1400
1401 for (size_t I = 1; I < SC.size() - 1; ++I) {
1402 SC[I]->eraseFromParent();
1403 RC[I]->eraseFromParent();
1404 NumDeletes += 2;
1405 }
1406 };
1407
1408 auto GetFoldableCopy =
1409 [this](const MachineInstr &MaybeCopy) -> std::optional<DestSourcePair> {
1410 if (MaybeCopy.getNumImplicitOperands() > 0)
1411 return std::nullopt;
1412 std::optional<DestSourcePair> CopyOperands =
1413 isCopyInstr(MaybeCopy, *TII, UseCopyInstr);
1414 if (!CopyOperands)
1415 return std::nullopt;
1416 auto [Dst, Src] = getDstSrcMCRegs(*CopyOperands);
1417 if (Src && Dst && !TRI->regsOverlap(Src, Dst) &&
1418 CopyOperands->Source->isRenamable() &&
1419 CopyOperands->Destination->isRenamable())
1420 return CopyOperands;
1421
1422 return std::nullopt;
1423 };
1424
1425 auto IsSpillReloadPair = [&](const MachineInstr &Spill,
1426 const MachineInstr &Reload) {
1427 std::optional<DestSourcePair> FoldableSpillCopy = GetFoldableCopy(Spill);
1428 if (!FoldableSpillCopy)
1429 return false;
1430 std::optional<DestSourcePair> FoldableReloadCopy = GetFoldableCopy(Reload);
1431 if (!FoldableReloadCopy)
1432 return false;
1433 return FoldableSpillCopy->Source->getReg() ==
1434 FoldableReloadCopy->Destination->getReg() &&
1435 FoldableSpillCopy->Destination->getReg() ==
1436 FoldableReloadCopy->Source->getReg();
1437 };
1438
1439 auto IsChainedCopy = [&](const MachineInstr &Prev,
1440 const MachineInstr &Current) {
1441 std::optional<DestSourcePair> FoldablePrevCopy = GetFoldableCopy(Prev);
1442 if (!FoldablePrevCopy)
1443 return false;
1444 std::optional<DestSourcePair> FoldableCurrentCopy =
1445 GetFoldableCopy(Current);
1446 if (!FoldableCurrentCopy)
1447 return false;
1448 return FoldablePrevCopy->Source->getReg() ==
1449 FoldableCurrentCopy->Destination->getReg();
1450 };
1451
1452 for (MachineInstr &MI : llvm::make_early_inc_range(MBB)) {
1453 std::optional<DestSourcePair> CopyOperands =
1454 isCopyInstr(MI, *TII, UseCopyInstr);
1455
1456 // Update track information via non-copy instruction.
1457 SmallSet<Register, 8> RegsToClobber;
1458 if (!CopyOperands) {
1459 for (const MachineOperand &MO : MI.operands()) {
1460 if (MO.isRegMask()) {
1461 BitVector &PreservedRegUnits = Tracker.getPreservedRegUnits(MO, *TRI);
1462 Tracker.clobberNonPreservedRegs(PreservedRegUnits, *TRI, *TII);
1463 continue;
1464 }
1465 if (!MO.isReg())
1466 continue;
1467 Register Reg = MO.getReg();
1468 if (!Reg)
1469 continue;
1470 MachineInstr *LastUseCopy =
1471 Tracker.findLastSeenUseInCopy(Reg.asMCReg(), *TRI);
1472 if (LastUseCopy) {
1473 LLVM_DEBUG(dbgs() << "MCP: Copy source of\n");
1474 LLVM_DEBUG(LastUseCopy->dump());
1475 LLVM_DEBUG(dbgs() << "might be invalidated by\n");
1476 LLVM_DEBUG(MI.dump());
1477 CopySourceInvalid.insert(LastUseCopy);
1478 }
1479 // Must be noted Tracker.clobberRegister(Reg, ...) removes tracking of
1480 // Reg, i.e, COPY that defines Reg is removed from the mapping as well
1481 // as marking COPYs that uses Reg unavailable.
1482 // We don't invoke CopyTracker::clobberRegister(Reg, ...) if Reg is not
1483 // defined by a previous COPY, since we don't want to make COPYs uses
1484 // Reg unavailable.
1485 if (Tracker.findLastSeenDefInCopy(MI, Reg.asMCReg(), *TRI, *TII,
1486 UseCopyInstr))
1487 // Thus we can keep the property#1.
1488 RegsToClobber.insert(Reg);
1489 }
1490 for (Register Reg : RegsToClobber) {
1491 Tracker.clobberRegister(Reg, *TRI, *TII, UseCopyInstr);
1492 LLVM_DEBUG(dbgs() << "MCP: Removed tracking of " << printReg(Reg, TRI)
1493 << "\n");
1494 }
1495 continue;
1496 }
1497
1498 auto [Dst, Src] = getDstSrcMCRegs(*CopyOperands);
1499 // Check if we can find a pair spill-reload copy.
1500 LLVM_DEBUG(dbgs() << "MCP: Searching paired spill for reload: ");
1501 LLVM_DEBUG(MI.dump());
1502 MachineInstr *MaybeSpill =
1503 Tracker.findAvailCopy(MI, Src, *TRI, *TII, UseCopyInstr);
1504 bool MaybeSpillIsChained = ChainLeader.count(MaybeSpill);
1505 if (!MaybeSpillIsChained && MaybeSpill &&
1506 IsSpillReloadPair(*MaybeSpill, MI)) {
1507 // Check if we already have an existing chain. Now we have a
1508 // spill-reload pair.
1509 // L2: r2 = COPY r3
1510 // L5: r3 = COPY r2
1511 // Looking for a valid COPY before L5 which uses r3.
1512 // This can be serverial cases.
1513 // Case #1:
1514 // No COPY is found, which can be r3 is def-use between (L2, L5), we
1515 // create a new chain for L2 and L5.
1516 // Case #2:
1517 // L2: r2 = COPY r3
1518 // L5: r3 = COPY r2
1519 // Such COPY is found and is L2, we create a new chain for L2 and L5.
1520 // Case #3:
1521 // L2: r2 = COPY r3
1522 // L3: r1 = COPY r3
1523 // L5: r3 = COPY r2
1524 // we create a new chain for L2 and L5.
1525 // Case #4:
1526 // L2: r2 = COPY r3
1527 // L3: r1 = COPY r3
1528 // L4: r3 = COPY r1
1529 // L5: r3 = COPY r2
1530 // Such COPY won't be found since L4 defines r3. we create a new chain
1531 // for L2 and L5.
1532 // Case #5:
1533 // L2: r2 = COPY r3
1534 // L3: r3 = COPY r1
1535 // L4: r1 = COPY r3
1536 // L5: r3 = COPY r2
1537 // COPY is found and is L4 which belongs to an existing chain, we add
1538 // L2 and L5 to this chain.
1539 LLVM_DEBUG(dbgs() << "MCP: Found spill: ");
1540 LLVM_DEBUG(MaybeSpill->dump());
1541 MachineInstr *MaybePrevReload = Tracker.findLastSeenUseInCopy(Dst, *TRI);
1542 auto Leader = ChainLeader.find(MaybePrevReload);
1543 MachineInstr *L = nullptr;
1544 if (Leader == ChainLeader.end() ||
1545 (MaybePrevReload && !IsChainedCopy(*MaybePrevReload, MI))) {
1546 L = &MI;
1547 assert(!SpillChain.count(L) &&
1548 "SpillChain should not have contained newly found chain");
1549 } else {
1550 assert(MaybePrevReload &&
1551 "Found a valid leader through nullptr should not happend");
1552 L = Leader->second;
1553 assert(SpillChain[L].size() > 0 &&
1554 "Existing chain's length should be larger than zero");
1555 }
1556 assert(!ChainLeader.count(&MI) && !ChainLeader.count(MaybeSpill) &&
1557 "Newly found paired spill-reload should not belong to any chain "
1558 "at this point");
1559 ChainLeader.insert({MaybeSpill, L});
1560 ChainLeader.insert({&MI, L});
1561 SpillChain[L].push_back(MaybeSpill);
1562 ReloadChain[L].push_back(&MI);
1563 LLVM_DEBUG(dbgs() << "MCP: Chain " << L << " now is:\n");
1564 LLVM_DEBUG(printSpillReloadChain(SpillChain, ReloadChain, L));
1565 } else if (MaybeSpill && !MaybeSpillIsChained) {
1566 // MaybeSpill is unable to pair with MI. That's to say adding MI makes
1567 // the chain invalid.
1568 // The COPY defines Src is no longer considered as a candidate of a
1569 // valid chain. Since we expect the Dst of a spill copy isn't used by
1570 // any COPY instruction until a reload copy. For example:
1571 // L1: r1 = COPY r2
1572 // L2: r3 = COPY r1
1573 // If we later have
1574 // L1: r1 = COPY r2
1575 // L2: r3 = COPY r1
1576 // L3: r2 = COPY r1
1577 // L1 and L3 can't be a valid spill-reload pair.
1578 // Thus we keep the property#1.
1579 LLVM_DEBUG(dbgs() << "MCP: Not paired spill-reload:\n");
1580 LLVM_DEBUG(MaybeSpill->dump());
1581 LLVM_DEBUG(MI.dump());
1582 Tracker.clobberRegister(Src, *TRI, *TII, UseCopyInstr);
1583 LLVM_DEBUG(dbgs() << "MCP: Removed tracking of " << printReg(Src, TRI)
1584 << "\n");
1585 }
1586 Tracker.trackCopy(&MI, *TRI, *TII, UseCopyInstr);
1587 }
1588
1589 for (auto I = SpillChain.begin(), E = SpillChain.end(); I != E; ++I) {
1590 auto &SC = I->second;
1591 assert(ReloadChain.count(I->first) &&
1592 "Reload chain of the same leader should exist");
1593 auto &RC = ReloadChain[I->first];
1594 TryFoldSpillageCopies(SC, RC);
1595 }
1596
1597 MaybeDeadCopies.clear();
1598 CopyDbgUsers.clear();
1599 Tracker.clear();
1600}
1601
1602bool MachineCopyPropagationLegacy::runOnMachineFunction(MachineFunction &MF) {
1603 if (skipFunction(MF.getFunction()))
1604 return false;
1605
1606 return MachineCopyPropagation(UseCopyInstr).run(MF);
1607}
1608
1609PreservedAnalyses
1612 MFPropsModifier _(*this, MF);
1613 if (!MachineCopyPropagation(UseCopyInstr).run(MF))
1614 return PreservedAnalyses::all();
1616 PA.preserveSet<CFGAnalyses>();
1617 return PA;
1618}
1619
1620bool MachineCopyPropagation::run(MachineFunction &MF) {
1621 bool IsSpillageCopyElimEnabled = false;
1624 IsSpillageCopyElimEnabled =
1626 break;
1628 IsSpillageCopyElimEnabled = true;
1629 break;
1631 IsSpillageCopyElimEnabled = false;
1632 break;
1633 }
1634
1635 Changed = false;
1636
1638 TII = MF.getSubtarget().getInstrInfo();
1639 MRI = &MF.getRegInfo();
1640
1641 for (MachineBasicBlock &MBB : MF) {
1642 if (IsSpillageCopyElimEnabled)
1643 eliminateSpillageCopies(MBB);
1644 backwardCopyPropagateBlock(MBB);
1645 forwardCopyPropagateBlock(MBB);
1646 }
1647
1648 return Changed;
1649}
1650
1651MachineFunctionPass *
1652llvm::createMachineCopyPropagationPass(bool UseCopyInstr = false) {
1653 return new MachineCopyPropagationLegacy(UseCopyInstr);
1654}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file provides an implementation of debug counters.
#define DEBUG_COUNTER(VARNAME, COUNTERNAME, DESC)
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 cl::opt< cl::boolOrDefault > EnableSpillageCopyElimination("enable-spill-copy-elim", cl::Hidden)
static void printSpillReloadChain(DenseMap< MachineInstr *, SmallVector< MachineInstr * > > &SpillChain, DenseMap< MachineInstr *, SmallVector< MachineInstr * > > &ReloadChain, MachineInstr *Leader)
static bool isNopCopy(const MachineInstr &PreviousCopy, MCRegister Src, MCRegister Dst, const TargetRegisterInfo *TRI, const TargetInstrInfo *TII, bool UseCopyInstr)
Return true if PreviousCopy did copy register Src to register Dst.
static cl::opt< bool > MCPUseCopyInstr("mcp-use-is-copy-instr", cl::init(false), cl::Hidden)
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
MachineInstr unsigned OpIdx
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
This file contains some templates that are useful if you are working with the STL at all.
This file implements a set that has insertion order iteration characteristics.
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
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:275
bool test(unsigned Idx) const
Returns true if bit Idx is set.
Definition BitVector.h:482
void resize(unsigned N, bool t=false)
Grow or shrink the bitvector.
Definition BitVector.h:355
BitVector & set()
Set all bits in the bitvector.
Definition BitVector.h:366
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
static bool shouldExecute(CounterInfo &Counter)
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:223
iterator begin()
Definition DenseMap.h:137
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition DenseMap.h:219
iterator end()
Definition DenseMap.h:141
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:284
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.
iterator_range< succ_iterator > successors()
LLVM_ABI StringRef getName() const
Return the name of the corresponding LLVM basic block, or an empty string.
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
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.
LLVM_ABI void dump() const
const MachineOperand & getOperand(unsigned i) const
LLVM_ABI MachineInstrBundleIterator< MachineInstr > eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
LLVM_ABI const TargetRegisterClass * getRegClassConstraint(unsigned OpIdx, const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const
Compute the static register class constraint for operand OpIdx.
MachineOperand class - Representation of each machine instruction operand.
LLVM_ABI unsigned getOperandNo() const
Returns the index of this operand in the instruction that it belongs to.
LLVM_ABI void setIsRenamable(bool Val=true)
bool isReg() const
isReg - Tests if this is a MO_Register operand.
LLVM_ABI void setReg(Register Reg)
Change the register this operand corresponds to.
LLVM_ABI bool isRenamable() const
isRenamable - Returns true if this register may be renamed, i.e.
void setIsUndef(bool Val=true)
Register getReg() const
getReg - Returns the register number.
static bool clobbersPhysReg(const uint32_t *RegMask, MCRegister PhysReg)
clobbersPhysReg - Returns true if this RegMask clobbers PhysReg.
const uint32_t * getRegMask() const
getRegMask - Returns a bit mask of registers preserved by this RegMask operand.
bool tracksLiveness() const
tracksLiveness - Returns true when tracking register liveness accurately.
bool isReserved(MCRegister PhysReg) const
isReserved - Returns true when PhysReg is a reserved register.
LLVM_ABI void updateDbgUsersToReg(MCRegister OldReg, MCRegister NewReg, ArrayRef< MachineInstr * > Users) const
updateDbgUsersToReg - Update a collection of debug instructions to refer to the designated register.
LLVM_ABI bool isConstantPhysReg(MCRegister PhysReg) const
Returns true if PhysReg is unallocatable and constant throughout the function.
void dump() const
Definition Pass.cpp:146
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
Wrapper class representing virtual and physical registers.
Definition Register.h:20
MCRegister asMCReg() const
Utility to check-convert this value to a MCRegister.
Definition Register.h:107
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition Register.h:83
void insert_range(Range &&R)
Definition SmallSet.h:196
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
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
TargetInstrInfo - Interface to description of machine instruction set.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual bool enableSpillageCopyElimination() const
Enable spillage copy elimination in MachineCopyPropagation pass.
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:209
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition DenseSet.h:187
reverse_self_iterator getReverseIterator()
Definition ilist_node.h:126
self_iterator getIterator()
Definition ilist_node.h:123
Changed
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
initializer< Ty > init(const Ty &Val)
DXILDebugInfoMap run(Module &M)
LLVM_ABI Value * readRegister(IRBuilder<> &IRB, StringRef Name)
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:315
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1669
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
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.
auto reverse(ContainerTy &&C)
Definition STLExtras.h:407
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...
auto drop_end(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the last N elements excluded.
Definition STLExtras.h:322
ArrayRef(const T &OneElt) -> ArrayRef< T >
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1947
LLVM_ABI MachineFunctionPass * createMachineCopyPropagationPass(bool UseCopyInstr)
LLVM_ABI Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
LLVM_ABI char & MachineCopyPropagationID
MachineCopyPropagation - This pass performs copy propagation on machine instructions.
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
const MachineOperand * Source
const MachineOperand * Destination