LLVM 23.0.0git
VirtRegMap.cpp
Go to the documentation of this file.
1//===- llvm/CodeGen/VirtRegMap.cpp - Virtual Register Map -----------------===//
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 file implements the VirtRegMap class.
10//
11// It also contains implementations of the Spiller interface, which, given a
12// virtual register map and a machine function, eliminates all virtual
13// references by replacing them with physical register references - adding spill
14// code as necessary.
15//
16//===----------------------------------------------------------------------===//
17
20#include "llvm/ADT/Statistic.h"
39#include "llvm/Config/llvm-config.h"
40#include "llvm/MC/LaneBitmask.h"
41#include "llvm/Pass.h"
43#include "llvm/Support/Debug.h"
45#include <cassert>
46#include <iterator>
47#include <utility>
48
49using namespace llvm;
50
51#define DEBUG_TYPE "regalloc"
52
53STATISTIC(NumSpillSlots, "Number of spill slots allocated");
54STATISTIC(NumIdCopies, "Number of identity moves eliminated after rewriting");
55
56//===----------------------------------------------------------------------===//
57// VirtRegMap implementation
58//===----------------------------------------------------------------------===//
59
61
62INITIALIZE_PASS(VirtRegMapWrapperLegacy, "virtregmap", "Virtual Register Map",
63 false, true)
64
65void VirtRegMap::init(MachineFunction &mf) {
66 MRI = &mf.getRegInfo();
67 TII = mf.getSubtarget().getInstrInfo();
68 TRI = mf.getSubtarget().getRegisterInfo();
69 MF = &mf;
70
71 Virt2PhysMap.clear();
72 Virt2StackSlotMap.clear();
73 Virt2SplitMap.clear();
74 Virt2ShapeMap.clear();
75
76 grow();
77}
78
80 unsigned NumRegs = MF->getRegInfo().getNumVirtRegs();
81 Virt2PhysMap.resize(NumRegs);
82 Virt2StackSlotMap.resize(NumRegs);
83 Virt2SplitMap.resize(NumRegs);
84}
85
87 assert(virtReg.isVirtual() && physReg.isPhysical());
88 assert(!Virt2PhysMap[virtReg] &&
89 "attempt to assign physical register to already mapped "
90 "virtual register");
91 assert(!getRegInfo().isReserved(physReg) &&
92 "Attempt to map virtReg to a reserved physReg");
93 Virt2PhysMap[virtReg] = physReg;
94}
95
96unsigned VirtRegMap::createSpillSlot(const TargetRegisterClass *RC) {
97 unsigned Size = TRI->getSpillSize(*RC);
98 Align Alignment = TRI->getSpillAlign(*RC);
99 // Set preferred alignment if we are still able to realign the stack
100 auto &ST = MF->getSubtarget();
101 Align CurrentAlign = ST.getFrameLowering()->getStackAlign();
102 if (Alignment > CurrentAlign && !TRI->canRealignStack(*MF)) {
103 Alignment = CurrentAlign;
104 }
105 int SS = MF->getFrameInfo().CreateSpillStackObject(Size, Alignment,
106 TRI->getSpillStackID(*RC));
107 ++NumSpillSlots;
108 return SS;
109}
110
112 Register Hint = MRI->getSimpleHint(VirtReg);
113 if (!Hint.isValid())
114 return false;
115 if (Hint.isVirtual())
116 Hint = getPhys(Hint);
117 return Register(getPhys(VirtReg)) == Hint;
118}
119
121 std::pair<unsigned, Register> Hint = MRI->getRegAllocationHint(VirtReg);
122 if (Hint.second.isPhysical())
123 return true;
124 if (Hint.second.isVirtual())
125 return hasPhys(Hint.second);
126 return false;
127}
128
130 assert(virtReg.isVirtual());
131 assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT &&
132 "attempt to assign stack slot to already spilled register");
133 const TargetRegisterClass* RC = MF->getRegInfo().getRegClass(virtReg);
134 return Virt2StackSlotMap[virtReg] = createSpillSlot(RC);
135}
136
138 assert(virtReg.isVirtual());
139 assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT &&
140 "attempt to assign stack slot to already spilled register");
141 assert((SS >= 0 ||
142 (SS >= MF->getFrameInfo().getObjectIndexBegin())) &&
143 "illegal fixed frame index");
144 Virt2StackSlotMap[virtReg] = SS;
145}
146
147void VirtRegMap::print(raw_ostream &OS, const Module*) const {
148 OS << "********** REGISTER MAP **********\n";
149 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
151 if (Virt2PhysMap[Reg]) {
152 OS << '[' << printReg(Reg, TRI) << " -> "
153 << printReg(Virt2PhysMap[Reg], TRI) << "] "
154 << TRI->getRegClassName(MRI->getRegClass(Reg)) << "\n";
155 }
156 }
157
158 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
160 if (Virt2StackSlotMap[Reg] != VirtRegMap::NO_STACK_SLOT) {
161 OS << '[' << printReg(Reg, TRI) << " -> fi#" << Virt2StackSlotMap[Reg]
162 << "] " << TRI->getRegClassName(MRI->getRegClass(Reg)) << "\n";
163 }
164 }
165 OS << '\n';
166}
167
168#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
170 print(dbgs());
171}
172#endif
173
174AnalysisKey VirtRegMapAnalysis::Key;
175
182
189
190//===----------------------------------------------------------------------===//
191// VirtRegRewriter
192//===----------------------------------------------------------------------===//
193//
194// The VirtRegRewriter is the last of the register allocator passes.
195// It rewrites virtual registers to physical registers as specified in the
196// VirtRegMap analysis. It also updates live-in information on basic blocks
197// according to LiveIntervals.
198//
199namespace {
200
201class VirtRegRewriter {
202 MachineFunction *MF = nullptr;
203 const TargetRegisterInfo *TRI = nullptr;
204 const TargetInstrInfo *TII = nullptr;
205 MachineRegisterInfo *MRI = nullptr;
206 SlotIndexes *Indexes = nullptr;
207 LiveIntervals *LIS = nullptr;
208 LiveRegMatrix *LRM = nullptr;
209 VirtRegMap *VRM = nullptr;
210 LiveDebugVariables *DebugVars = nullptr;
211 DenseSet<Register> RewriteRegs;
212 bool ClearVirtRegs;
213
214 void rewrite();
215 void addMBBLiveIns();
216 bool readsUndefSubreg(const MachineOperand &MO) const;
217 void addLiveInsForSubRanges(const LiveInterval &LI, MCRegister PhysReg) const;
218 void handleIdentityCopy(MachineInstr &MI);
219 void expandCopyBundle(MachineInstr &MI) const;
220 bool subRegLiveThrough(const MachineInstr &MI, MCRegister SuperPhysReg) const;
221 LaneBitmask liveOutUndefPhiLanesForUndefSubregDef(
222 const LiveInterval &LI, const MachineBasicBlock &MBB, unsigned SubReg,
223 MCRegister PhysReg, const MachineInstr &MI) const;
224
225public:
226 VirtRegRewriter(bool ClearVirtRegs, SlotIndexes *Indexes, LiveIntervals *LIS,
227 LiveRegMatrix *LRM, VirtRegMap *VRM,
228 LiveDebugVariables *DebugVars)
229 : Indexes(Indexes), LIS(LIS), LRM(LRM), VRM(VRM), DebugVars(DebugVars),
230 ClearVirtRegs(ClearVirtRegs) {}
231
232 bool run(MachineFunction &);
233};
234
235class VirtRegRewriterLegacy : public MachineFunctionPass {
236public:
237 static char ID;
238 bool ClearVirtRegs;
239 VirtRegRewriterLegacy(bool ClearVirtRegs = true)
240 : MachineFunctionPass(ID), ClearVirtRegs(ClearVirtRegs) {}
241
242 void getAnalysisUsage(AnalysisUsage &AU) const override;
243
244 bool runOnMachineFunction(MachineFunction&) override;
245
246 MachineFunctionProperties getSetProperties() const override {
247 if (ClearVirtRegs) {
248 return MachineFunctionProperties().setNoVRegs();
249 }
250
251 return MachineFunctionProperties();
252 }
253};
254
255} // end anonymous namespace
256
257char VirtRegRewriterLegacy::ID = 0;
258
259char &llvm::VirtRegRewriterID = VirtRegRewriterLegacy::ID;
260
261INITIALIZE_PASS_BEGIN(VirtRegRewriterLegacy, "virtregrewriter",
262 "Virtual Register Rewriter", false, false)
269INITIALIZE_PASS_END(VirtRegRewriterLegacy, "virtregrewriter",
270 "Virtual Register Rewriter", false, false)
271
272void VirtRegRewriterLegacy::getAnalysisUsage(AnalysisUsage &AU) const {
273 AU.setPreservesCFG();
274 AU.addRequired<LiveIntervalsWrapperPass>();
275 AU.addPreserved<LiveIntervalsWrapperPass>();
276 AU.addRequired<SlotIndexesWrapperPass>();
277 AU.addPreserved<SlotIndexesWrapperPass>();
278 AU.addRequired<LiveDebugVariablesWrapperLegacy>();
279 AU.addRequired<LiveStacksWrapperLegacy>();
280 AU.addPreserved<LiveStacksWrapperLegacy>();
281 AU.addRequired<VirtRegMapWrapperLegacy>();
282 AU.addRequired<LiveRegMatrixWrapperLegacy>();
283
284 if (!ClearVirtRegs)
285 AU.addPreserved<LiveDebugVariablesWrapperLegacy>();
286
288}
289
290bool VirtRegRewriterLegacy::runOnMachineFunction(MachineFunction &MF) {
291 VirtRegMap &VRM = getAnalysis<VirtRegMapWrapperLegacy>().getVRM();
292 LiveIntervals &LIS = getAnalysis<LiveIntervalsWrapperPass>().getLIS();
293 LiveRegMatrix &LRM = getAnalysis<LiveRegMatrixWrapperLegacy>().getLRM();
294 SlotIndexes &Indexes = getAnalysis<SlotIndexesWrapperPass>().getSI();
295 LiveDebugVariables &DebugVars =
296 getAnalysis<LiveDebugVariablesWrapperLegacy>().getLDV();
297
298 VirtRegRewriter R(ClearVirtRegs, &Indexes, &LIS, &LRM, &VRM, &DebugVars);
299 return R.run(MF);
300}
301
305 MFPropsModifier _(*this, MF);
306
307 VirtRegMap &VRM = MFAM.getResult<VirtRegMapAnalysis>(MF);
310 SlotIndexes &Indexes = MFAM.getResult<SlotIndexesAnalysis>(MF);
311 LiveDebugVariables &DebugVars =
313
314 VirtRegRewriter R(ClearVirtRegs, &Indexes, &LIS, &LRM, &VRM, &DebugVars);
315 if (!R.run(MF))
316 return PreservedAnalyses::all();
317
319 PA.preserveSet<CFGAnalyses>();
320 PA.preserve<LiveIntervalsAnalysis>();
321 PA.preserve<SlotIndexesAnalysis>();
322 PA.preserve<LiveStacksAnalysis>();
323 // LiveDebugVariables is preserved by default, so clear it
324 // if this VRegRewriter is the last one in the pipeline.
325 if (ClearVirtRegs)
326 PA.abandon<LiveDebugVariablesAnalysis>();
327 return PA;
328}
329
330bool VirtRegRewriter::run(MachineFunction &fn) {
331 MF = &fn;
333 TII = MF->getSubtarget().getInstrInfo();
334 MRI = &MF->getRegInfo();
335
336 LLVM_DEBUG(dbgs() << "********** REWRITE VIRTUAL REGISTERS **********\n"
337 << "********** Function: " << MF->getName() << '\n');
338 LLVM_DEBUG(VRM->dump());
339
340 // Add kill flags while we still have virtual registers.
341 LIS->addKillFlags(VRM);
342
343 // Live-in lists on basic blocks are required for physregs.
344 addMBBLiveIns();
345
346 // Rewrite virtual registers.
347 rewrite();
348
349 if (ClearVirtRegs) {
350 // Write out new DBG_VALUE instructions.
351
352 // We only do this if ClearVirtRegs is specified since this should be the
353 // final run of the pass and we don't want to emit them multiple times.
354 DebugVars->emitDebugValues(VRM);
355
356 // All machine operands and other references to virtual registers have been
357 // replaced. Remove the virtual registers and release all the transient data.
358 VRM->clearAllVirt();
359 MRI->clearVirtRegs();
360 }
361
362 return true;
363}
364
365void VirtRegRewriter::addLiveInsForSubRanges(const LiveInterval &LI,
366 MCRegister PhysReg) const {
367 assert(!LI.empty());
368 assert(LI.hasSubRanges());
369
370 using SubRangeIteratorPair =
371 std::pair<const LiveInterval::SubRange *, LiveInterval::const_iterator>;
372
376 for (const LiveInterval::SubRange &SR : LI.subranges()) {
377 SubRanges.push_back(std::make_pair(&SR, SR.begin()));
378 if (!First.isValid() || SR.segments.front().start < First)
379 First = SR.segments.front().start;
380 if (!Last.isValid() || SR.segments.back().end > Last)
381 Last = SR.segments.back().end;
382 }
383
384 // Check all mbb start positions between First and Last while
385 // simultaneously advancing an iterator for each subrange.
387 MBBI != Indexes->MBBIndexEnd() && MBBI->first <= Last; ++MBBI) {
388 SlotIndex MBBBegin = MBBI->first;
389 // Advance all subrange iterators so that their end position is just
390 // behind MBBBegin (or the iterator is at the end).
391 LaneBitmask LaneMask;
392 for (auto &RangeIterPair : SubRanges) {
393 const LiveInterval::SubRange *SR = RangeIterPair.first;
394 LiveInterval::const_iterator &SRI = RangeIterPair.second;
395 while (SRI != SR->end() && SRI->end <= MBBBegin)
396 ++SRI;
397 if (SRI == SR->end())
398 continue;
399 if (SRI->start <= MBBBegin)
400 LaneMask |= SR->LaneMask;
401 }
402 if (LaneMask.none())
403 continue;
404 MachineBasicBlock *MBB = MBBI->second;
405 MBB->addLiveIn(PhysReg, LaneMask);
406 }
407}
408
409// Compute MBB live-in lists from virtual register live ranges and their
410// assignments.
411void VirtRegRewriter::addMBBLiveIns() {
412 for (unsigned Idx = 0, IdxE = MRI->getNumVirtRegs(); Idx != IdxE; ++Idx) {
413 Register VirtReg = Register::index2VirtReg(Idx);
414 if (MRI->reg_nodbg_empty(VirtReg))
415 continue;
416 LiveInterval &LI = LIS->getInterval(VirtReg);
417 if (LI.empty() || LIS->intervalIsInOneMBB(LI))
418 continue;
419 // This is a virtual register that is live across basic blocks. Its
420 // assigned PhysReg must be marked as live-in to those blocks.
421 MCRegister PhysReg = VRM->getPhys(VirtReg);
422 if (!PhysReg) {
423 // There may be no physical register assigned if only some register
424 // classes were already allocated.
425 assert(!ClearVirtRegs && "Unmapped virtual register");
426 continue;
427 }
428
429 if (LI.hasSubRanges()) {
430 addLiveInsForSubRanges(LI, PhysReg);
431 } else {
432 // Go over MBB begin positions and see if we have segments covering them.
433 // The following works because segments and the MBBIndex list are both
434 // sorted by slot indexes.
436 for (const auto &Seg : LI) {
437 I = Indexes->getMBBLowerBound(I, Seg.start);
438 for (; I != Indexes->MBBIndexEnd() && I->first < Seg.end; ++I) {
439 MachineBasicBlock *MBB = I->second;
440 MBB->addLiveIn(PhysReg);
441 }
442 }
443 }
444 }
445
446 // Sort and unique MBB LiveIns as we've not checked if SubReg/PhysReg were in
447 // each MBB's LiveIns set before calling addLiveIn on them.
448 for (MachineBasicBlock &MBB : *MF)
450}
451
452/// Returns true if the given machine operand \p MO only reads undefined lanes.
453/// The function only works for use operands with a subregister set.
454bool VirtRegRewriter::readsUndefSubreg(const MachineOperand &MO) const {
455 // Shortcut if the operand is already marked undef.
456 if (MO.isUndef())
457 return true;
458
459 Register Reg = MO.getReg();
460 const LiveInterval &LI = LIS->getInterval(Reg);
461 const MachineInstr &MI = *MO.getParent();
462 SlotIndex BaseIndex = LIS->getInstructionIndex(MI);
463 // This code is only meant to handle reading undefined subregisters which
464 // we couldn't properly detect before.
465 assert(LI.liveAt(BaseIndex) &&
466 "Reads of completely dead register should be marked undef already");
467 unsigned SubRegIdx = MO.getSubReg();
468 assert(SubRegIdx != 0 && LI.hasSubRanges());
469 LaneBitmask UseMask = TRI->getSubRegIndexLaneMask(SubRegIdx);
470 // See if any of the relevant subregister liveranges is defined at this point.
471 for (const LiveInterval::SubRange &SR : LI.subranges()) {
472 if ((SR.LaneMask & UseMask).any() && SR.liveAt(BaseIndex))
473 return false;
474 }
475 return true;
476}
477
478void VirtRegRewriter::handleIdentityCopy(MachineInstr &MI) {
479 if (!MI.isIdentityCopy())
480 return;
481 LLVM_DEBUG(dbgs() << "Identity copy: " << MI);
482 ++NumIdCopies;
483
484 Register DstReg = MI.getOperand(0).getReg();
485
486 // We may have deferred allocation of the virtual register, and the rewrite
487 // regs code doesn't handle the liveness update.
488 if (DstReg.isVirtual())
489 return;
490
491 RewriteRegs.insert(DstReg);
492
493 // Copies like:
494 // %r0 = COPY undef %r0
495 // %al = COPY %al, implicit-def %eax
496 // give us additional liveness information: The target (super-)register
497 // must not be valid before this point. Replace the COPY with a KILL
498 // instruction to maintain this information.
499 if (MI.getOperand(1).isUndef() || MI.getNumOperands() > 2) {
500 MI.setDesc(TII->get(TargetOpcode::KILL));
501 LLVM_DEBUG(dbgs() << " replace by: " << MI);
502 return;
503 }
504
505 if (Indexes)
507 MI.eraseFromBundle();
508 LLVM_DEBUG(dbgs() << " deleted.\n");
509}
510
511/// The liverange splitting logic sometimes produces bundles of copies when
512/// subregisters are involved. Expand these into a sequence of copy instructions
513/// after processing the last in the bundle. Does not update LiveIntervals
514/// which we shouldn't need for this instruction anymore.
515void VirtRegRewriter::expandCopyBundle(MachineInstr &MI) const {
516 if (!MI.isCopy() && !MI.isKill())
517 return;
518
519 if (MI.isBundledWithPred() && !MI.isBundledWithSucc()) {
521
522 // Only do this when the complete bundle is made out of COPYs and KILLs.
523 MachineBasicBlock &MBB = *MI.getParent();
525 std::next(MI.getReverseIterator()), E = MBB.instr_rend();
526 I != E && I->isBundledWithSucc(); ++I) {
527 if (!I->isCopy() && !I->isKill())
528 return;
529 MIs.push_back(&*I);
530 }
531 MachineInstr *FirstMI = MIs.back();
532
533 auto anyRegsAlias = [](const MachineInstr *Dst,
535 const TargetRegisterInfo *TRI) {
536 for (const MachineInstr *Src : Srcs)
537 if (Src != Dst)
538 if (TRI->regsOverlap(Dst->getOperand(0).getReg(),
539 Src->getOperand(1).getReg()))
540 return true;
541 return false;
542 };
543
544 // If any of the destination registers in the bundle of copies alias any of
545 // the source registers, try to schedule the instructions to avoid any
546 // clobbering.
547 for (int E = MIs.size(), PrevE = E; E > 1; PrevE = E) {
548 for (int I = E; I--; )
549 if (!anyRegsAlias(MIs[I], ArrayRef(MIs).take_front(E), TRI)) {
550 if (I + 1 != E)
551 std::swap(MIs[I], MIs[E - 1]);
552 --E;
553 }
554 if (PrevE == E) {
555 MF->getFunction().getContext().emitError(
556 "register rewriting failed: cycle in copy bundle");
557 break;
558 }
559 }
560
561 MachineInstr *BundleStart = FirstMI;
562 for (MachineInstr *BundledMI : llvm::reverse(MIs)) {
563 // If instruction is in the middle of the bundle, move it before the
564 // bundle starts, otherwise, just unbundle it. When we get to the last
565 // instruction, the bundle will have been completely undone.
566 if (BundledMI != BundleStart) {
567 BundledMI->removeFromBundle();
568 MBB.insert(BundleStart, BundledMI);
569 } else if (BundledMI->isBundledWithSucc()) {
570 BundledMI->unbundleFromSucc();
571 BundleStart = &*std::next(BundledMI->getIterator());
572 }
573
574 if (Indexes && BundledMI != FirstMI)
575 Indexes->insertMachineInstrInMaps(*BundledMI);
576 }
577 }
578}
579
580/// Check whether (part of) \p SuperPhysReg is live through \p MI.
581/// \pre \p MI defines a subregister of a virtual register that
582/// has been assigned to \p SuperPhysReg.
583bool VirtRegRewriter::subRegLiveThrough(const MachineInstr &MI,
584 MCRegister SuperPhysReg) const {
585 SlotIndex MIIndex = LIS->getInstructionIndex(MI);
586 SlotIndex BeforeMIUses = MIIndex.getBaseIndex();
587 SlotIndex AfterMIDefs = MIIndex.getBoundaryIndex();
588 for (MCRegUnit Unit : TRI->regunits(SuperPhysReg)) {
589 const LiveRange &UnitRange = LIS->getRegUnit(Unit);
590 // If the regunit is live both before and after MI,
591 // we assume it is live through.
592 // Generally speaking, this is not true, because something like
593 // "RU = op RU" would match that description.
594 // However, we know that we are trying to assess whether
595 // a def of a virtual reg, vreg, is live at the same time of RU.
596 // If we are in the "RU = op RU" situation, that means that vreg
597 // is defined at the same time as RU (i.e., "vreg, RU = op RU").
598 // Thus, vreg and RU interferes and vreg cannot be assigned to
599 // SuperPhysReg. Therefore, this situation cannot happen.
600 if (UnitRange.liveAt(AfterMIDefs) && UnitRange.liveAt(BeforeMIUses))
601 return true;
602 }
603 return false;
604}
605
606/// Compute a lanemask for undef lanes which need to be preserved out of the
607/// defining block for a register assignment for a subregister def. \p PhysReg
608/// is assigned to \p LI, which is the main range.
609LaneBitmask VirtRegRewriter::liveOutUndefPhiLanesForUndefSubregDef(
610 const LiveInterval &LI, const MachineBasicBlock &MBB, unsigned SubReg,
611 MCRegister PhysReg, const MachineInstr &MI) const {
612 LaneBitmask UndefMask = ~TRI->getSubRegIndexLaneMask(SubReg);
613 LaneBitmask LiveOutUndefLanes;
614
615 for (const LiveInterval::SubRange &SR : LI.subranges()) {
616 // Figure out which lanes are undef live into a successor.
617 LaneBitmask NeedImpDefLanes = UndefMask & SR.LaneMask;
618 if (NeedImpDefLanes.any() && !LIS->isLiveOutOfMBB(SR, &MBB)) {
619 for (const MachineBasicBlock *Succ : MBB.successors()) {
620 if (LIS->isLiveInToMBB(SR, Succ))
621 LiveOutUndefLanes |= NeedImpDefLanes;
622 }
623 }
624 }
625
626 SlotIndex MIIndex = LIS->getInstructionIndex(MI);
627 SlotIndex BeforeMIUses = MIIndex.getBaseIndex();
628 LaneBitmask InterferingLanes =
629 LRM->checkInterferenceLanes(BeforeMIUses, MIIndex.getRegSlot(), PhysReg);
630 LiveOutUndefLanes &= ~InterferingLanes;
631
632 LLVM_DEBUG(if (LiveOutUndefLanes.any()) {
633 dbgs() << "Need live out undef defs for " << printReg(PhysReg)
634 << LiveOutUndefLanes << " from " << printMBBReference(MBB) << '\n';
635 });
636
637 return LiveOutUndefLanes;
638}
639
640void VirtRegRewriter::rewrite() {
641 bool NoSubRegLiveness = !MRI->subRegLivenessEnabled();
642 SmallVector<Register, 8> SuperDeads;
643 SmallVector<Register, 8> SuperDefs;
644 SmallVector<Register, 8> SuperKills;
645
646 for (MachineFunction::iterator MBBI = MF->begin(), MBBE = MF->end();
647 MBBI != MBBE; ++MBBI) {
648 LLVM_DEBUG(MBBI->print(dbgs(), Indexes));
650 for (MachineOperand &MO : MI.operands()) {
651 // Make sure MRI knows about registers clobbered by regmasks.
652 if (MO.isRegMask())
653 MRI->addPhysRegsUsedFromRegMask(MO.getRegMask());
654
655 if (!MO.isReg() || !MO.getReg().isVirtual())
656 continue;
657 Register VirtReg = MO.getReg();
658 MCRegister PhysReg = VRM->getPhys(VirtReg);
659 if (!PhysReg)
660 continue;
661
662 assert(Register(PhysReg).isPhysical());
663
664 RewriteRegs.insert(PhysReg);
665 assert(!MRI->isReserved(PhysReg) && "Reserved register assignment");
666
667 // Preserve semantics of sub-register operands.
668 unsigned SubReg = MO.getSubReg();
669 if (SubReg != 0) {
670 if (NoSubRegLiveness || !MRI->shouldTrackSubRegLiveness(VirtReg)) {
671 // A virtual register kill refers to the whole register, so we may
672 // have to add implicit killed operands for the super-register. A
673 // partial redef always kills and redefines the super-register.
674 if ((MO.readsReg() && (MO.isDef() || MO.isKill())) ||
675 (MO.isDef() && subRegLiveThrough(MI, PhysReg)))
676 SuperKills.push_back(PhysReg);
677
678 if (MO.isDef()) {
679 // Also add implicit defs for the super-register.
680 if (MO.isDead())
681 SuperDeads.push_back(PhysReg);
682 else
683 SuperDefs.push_back(PhysReg);
684 }
685 } else {
686 if (MO.isUse()) {
687 if (readsUndefSubreg(MO))
688 // We need to add an <undef> flag if the subregister is
689 // completely undefined (and we are not adding super-register
690 // defs).
691 MO.setIsUndef(true);
692 } else if (!MO.isDead()) {
693 assert(MO.isDef());
694 if (MO.isUndef()) {
695 const LiveInterval &LI = LIS->getInterval(VirtReg);
696
697 LaneBitmask LiveOutUndefLanes =
698 liveOutUndefPhiLanesForUndefSubregDef(LI, *MBBI, SubReg,
699 PhysReg, MI);
700 if (LiveOutUndefLanes.any()) {
701 SmallVector<unsigned, 16> CoveringIndexes;
702
703 // TODO: Just use one super register def if none of the lanes
704 // are needed?
705 if (!TRI->getCoveringSubRegIndexes(MRI->getRegClass(VirtReg),
706 LiveOutUndefLanes,
707 CoveringIndexes))
709 "cannot represent required subregister defs");
710
711 // Try to represent the minimum needed live out def as a
712 // sequence of subregister defs.
713 //
714 // FIXME: It would be better if we could directly represent
715 // liveness with a lanemask instead of spamming operands.
716 for (unsigned SubIdx : CoveringIndexes)
717 SuperDefs.push_back(TRI->getSubReg(PhysReg, SubIdx));
718 }
719 }
720 }
721 }
722
723 // The def undef and def internal flags only make sense for
724 // sub-register defs, and we are substituting a full physreg. An
725 // implicit killed operand from the SuperKills list will represent the
726 // partial read of the super-register.
727 if (MO.isDef()) {
728 MO.setIsUndef(false);
729 MO.setIsInternalRead(false);
730 }
731
732 // PhysReg operands cannot have subregister indexes.
733 PhysReg = TRI->getSubReg(PhysReg, SubReg);
734 assert(PhysReg.isValid() && "Invalid SubReg for physical register");
735 MO.setSubReg(0);
736 }
737 // Rewrite. Note we could have used MachineOperand::substPhysReg(), but
738 // we need the inlining here.
739 MO.setReg(PhysReg);
740 MO.setIsRenamable(true);
741 }
742
743 // Add any missing super-register kills after rewriting the whole
744 // instruction.
745 while (!SuperKills.empty())
746 MI.addRegisterKilled(SuperKills.pop_back_val(), TRI, true);
747
748 while (!SuperDeads.empty())
749 MI.addRegisterDead(SuperDeads.pop_back_val(), TRI, true);
750
751 while (!SuperDefs.empty())
752 MI.addRegisterDefined(SuperDefs.pop_back_val(), TRI);
753
754 LLVM_DEBUG(dbgs() << "> " << MI);
755
756 expandCopyBundle(MI);
757
758 // We can remove identity copies right now.
759 handleIdentityCopy(MI);
760 }
761 }
762
763 if (LIS) {
764 // Don't bother maintaining accurate LiveIntervals for registers which were
765 // already allocated.
766 for (Register PhysReg : RewriteRegs) {
767 for (MCRegUnit Unit : TRI->regunits(PhysReg)) {
768 LIS->removeRegUnit(Unit);
769 }
770 }
771 }
772
773 RewriteRegs.clear();
774}
775
778 OS << "virt-reg-rewriter";
779 if (!ClearVirtRegs)
780 OS << "<no-clear-vregs>";
781}
782
784 return new VirtRegRewriterLegacy(ClearVirtRegs);
785}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator MBBI
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:661
const HexagonInstrInfo * TII
#define _
IRTranslator LLVM IR MI
A common definition of LaneBitmask for use in TableGen and CodeGen.
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
ModuleAnalysisManager MAM
#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
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
static bool isPhysical(const MachineOperand &MO)
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.
Represent the analysis usage information of a pass.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
Implements a dense probed hash-table based set.
Definition DenseSet.h:289
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
LLVM_ABI void emitDebugValues(VirtRegMap *VRM)
emitDebugValues - Emit new DBG_VALUE instructions reflecting the changes that happened during registe...
A live range for subregisters.
LiveInterval - This class represents the liveness of a register, or stack slot.
bool hasSubRanges() const
Returns true if subregister liveness information is available.
iterator_range< subrange_iterator > subranges()
LLVM_ABI void addKillFlags(const VirtRegMap *)
Add kill flags to any instruction that kills a virtual register.
SlotIndex getInstructionIndex(const MachineInstr &Instr) const
Returns the base index of the given instruction.
void removeRegUnit(MCRegUnit Unit)
Remove computed live range for register unit Unit.
LiveInterval & getInterval(Register Reg)
LiveRange & getRegUnit(MCRegUnit Unit)
Return the live range for register unit Unit.
LLVM_ABI MachineBasicBlock * intervalIsInOneMBB(const LiveInterval &LI) const
If LI is confined to a single basic block, return a pointer to that block.
bool isLiveOutOfMBB(const LiveRange &LR, const MachineBasicBlock *mbb) const
bool isLiveInToMBB(const LiveRange &LR, const MachineBasicBlock *mbb) const
This class represents the liveness of a register, stack slot, etc.
Segments::const_iterator const_iterator
bool liveAt(SlotIndex index) const
bool empty() const
LLVM_ABI LaneBitmask checkInterferenceLanes(SlotIndex Start, SlotIndex End, MCRegister PhysReg)
Check for interference in the segment [Start, End) that may prevent assignment to PhysReg,...
Wrapper class representing physical registers. Should be passed by value.
Definition MCRegister.h:41
constexpr bool isValid() const
Definition MCRegister.h:84
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition MCRegister.h:72
An RAII based helper class to modify MachineFunctionProperties when running pass.
LLVM_ABI instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
LLVM_ABI void sortUniqueLiveIns()
Sorts and uniques the LiveIns vector.
LLVM_ABI void print(raw_ostream &OS, const SlotIndexes *=nullptr, bool IsStandalone=true) const
reverse_instr_iterator instr_rend()
void addLiveIn(MCRegister PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
iterator_range< succ_iterator > successors()
Instructions::reverse_iterator reverse_instr_iterator
LLVM_ABI int CreateSpillStackObject(uint64_t Size, Align Alignment, TargetStackID::Value StackID=TargetStackID::Default)
Create a new statically sized stack object that represents a spill slot, returning a nonnegative iden...
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.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
BasicBlockListType::iterator iterator
Representation of each machine instruction.
MachineOperand class - Representation of each machine instruction operand.
void setSubReg(unsigned subReg)
unsigned getSubReg() const
void setIsInternalRead(bool Val=true)
bool readsReg() const
readsReg - Returns true if this operand reads the previous value of its register.
LLVM_ABI void setIsRenamable(bool Val=true)
bool isReg() const
isReg - Tests if this is a MO_Register operand.
bool isRegMask() const
isRegMask - Tests if this is a MO_RegisterMask operand.
LLVM_ABI void setReg(Register Reg)
Change the register this operand corresponds to.
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
void setIsUndef(bool Val=true)
Register getReg() const
getReg - Returns the register number.
const uint32_t * getRegMask() const
getRegMask - Returns a bit mask of registers preserved by this RegMask operand.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
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
Wrapper class representing virtual and physical registers.
Definition Register.h:20
static Register index2VirtReg(unsigned Index)
Convert a 0-based index to a virtual register number.
Definition Register.h:72
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
SlotIndex - An opaque wrapper around machine indexes.
Definition SlotIndexes.h:66
SlotIndex getBoundaryIndex() const
Returns the boundary index for associated with this index.
SlotIndex getBaseIndex() const
Returns the base index for associated with this index.
SlotIndex getRegSlot(bool EC=false) const
Returns the register use/def slot in the current instruction for a normal or early-clobber def.
SlotIndexes pass.
SlotIndex insertMachineInstrInMaps(MachineInstr &MI, bool Late=false)
Insert the given machine instruction into the mapping.
MBBIndexIterator getMBBLowerBound(MBBIndexIterator Start, SlotIndex Idx) const
Get an iterator pointing to the first IdxMBBPair with SlotIndex greater than or equal to Idx.
LLVM_ABI void removeSingleMachineInstrFromMaps(MachineInstr &MI)
Removes a single machine instruction MI from the mapping.
MBBIndexIterator MBBIndexBegin() const
Returns an iterator for the begin of the idx2MBBMap.
MBBIndexIterator MBBIndexEnd() const
Return an iterator for the end of the idx2MBBMap.
SmallVectorImpl< IdxMBBPair >::const_iterator MBBIndexIterator
Iterator over the idx2MBBMap (sorted pairs of slot index of basic block begin and basic block)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
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.
LLVM_ABI VirtRegMap run(MachineFunction &MF, MachineFunctionAnalysisManager &MAM)
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
static LLVM_ABI char ID
Definition VirtRegMap.h:198
LLVM_ABI bool hasKnownPreference(Register VirtReg) const
returns true if VirtReg has a known preferred register.
LLVM_ABI int assignVirt2StackSlot(Register virtReg)
create a mapping for the specifed virtual register to the next available stack slot
void clearAllVirt()
clears all virtual to physical register mappings
Definition VirtRegMap.h:125
LLVM_ABI void init(MachineFunction &MF)
LLVM_ABI bool hasPreferredPhys(Register VirtReg) const
returns true if VirtReg is assigned to its preferred physreg.
LLVM_ABI void dump() const
MachineRegisterInfo & getRegInfo() const
Definition VirtRegMap.h:80
LLVM_ABI void assignVirt2Phys(Register virtReg, MCRegister physReg)
creates a mapping for the specified virtual register to the specified physical register
MCRegister getPhys(Register virtReg) const
returns the physical register mapped to the specified virtual register
Definition VirtRegMap.h:91
LLVM_ABI void print(raw_ostream &OS, const Module *M=nullptr) const
LLVM_ABI void grow()
bool hasPhys(Register virtReg) const
returns true if the specified virtual register is mapped to a physical register
Definition VirtRegMap.h:87
static constexpr int NO_STACK_SLOT
Definition VirtRegMap.h:66
LLVM_ABI void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)>) const
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
An efficient, type-erasing, non-owning reference to a callable.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
This is an optimization pass for GlobalISel generic memory operations.
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
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI char & VirtRegRewriterID
VirtRegRewriter pass.
LLVM_ABI FunctionPass * createVirtRegRewriter(bool ClearVirtRegs=true)
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.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:862
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29
constexpr bool none() const
Definition LaneBitmask.h:52
constexpr bool any() const
Definition LaneBitmask.h:53