LLVM 20.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() && Register::isPhysicalRegister(physReg));
88 assert(!Virt2PhysMap[virtReg] &&
89 "attempt to assign physical register to already mapped "
90 "virtual register");
91 assert((!getRegInfo().isReserved(physReg) ||
94 "Attempt to map virtReg to a reserved physReg");
95 Virt2PhysMap[virtReg] = physReg;
96}
97
98unsigned VirtRegMap::createSpillSlot(const TargetRegisterClass *RC) {
99 unsigned Size = TRI->getSpillSize(*RC);
100 Align Alignment = TRI->getSpillAlign(*RC);
101 // Set preferred alignment if we are still able to realign the stack
102 auto &ST = MF->getSubtarget();
103 Align CurrentAlign = ST.getFrameLowering()->getStackAlign();
104 if (Alignment > CurrentAlign && !ST.getRegisterInfo()->canRealignStack(*MF)) {
105 Alignment = CurrentAlign;
106 }
107 int SS = MF->getFrameInfo().CreateSpillStackObject(Size, Alignment);
108 ++NumSpillSlots;
109 return SS;
110}
111
113 Register Hint = MRI->getSimpleHint(VirtReg);
114 if (!Hint.isValid())
115 return false;
116 if (Hint.isVirtual())
117 Hint = getPhys(Hint);
118 return Register(getPhys(VirtReg)) == Hint;
119}
120
122 std::pair<unsigned, Register> Hint = MRI->getRegAllocationHint(VirtReg);
123 if (Hint.second.isPhysical())
124 return true;
125 if (Hint.second.isVirtual())
126 return hasPhys(Hint.second);
127 return false;
128}
129
131 assert(virtReg.isVirtual());
132 assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT &&
133 "attempt to assign stack slot to already spilled register");
134 const TargetRegisterClass* RC = MF->getRegInfo().getRegClass(virtReg);
135 return Virt2StackSlotMap[virtReg] = createSpillSlot(RC);
136}
137
139 assert(virtReg.isVirtual());
140 assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT &&
141 "attempt to assign stack slot to already spilled register");
142 assert((SS >= 0 ||
143 (SS >= MF->getFrameInfo().getObjectIndexBegin())) &&
144 "illegal fixed frame index");
145 Virt2StackSlotMap[virtReg] = SS;
146}
147
149 OS << "********** REGISTER MAP **********\n";
150 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
152 if (Virt2PhysMap[Reg]) {
153 OS << '[' << printReg(Reg, TRI) << " -> "
154 << printReg(Virt2PhysMap[Reg], TRI) << "] "
155 << TRI->getRegClassName(MRI->getRegClass(Reg)) << "\n";
156 }
157 }
158
159 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
161 if (Virt2StackSlotMap[Reg] != VirtRegMap::NO_STACK_SLOT) {
162 OS << '[' << printReg(Reg, TRI) << " -> fi#" << Virt2StackSlotMap[Reg]
163 << "] " << TRI->getRegClassName(MRI->getRegClass(Reg)) << "\n";
164 }
165 }
166 OS << '\n';
167}
168
169#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
171 print(dbgs());
172}
173#endif
174
175AnalysisKey VirtRegMapAnalysis::Key;
176
180 OS << MFAM.getResult<VirtRegMapAnalysis>(MF);
181 return PreservedAnalyses::all();
182}
183
186 VirtRegMap VRM;
187 VRM.init(MF);
188 return VRM;
189}
190
191//===----------------------------------------------------------------------===//
192// VirtRegRewriter
193//===----------------------------------------------------------------------===//
194//
195// The VirtRegRewriter is the last of the register allocator passes.
196// It rewrites virtual registers to physical registers as specified in the
197// VirtRegMap analysis. It also updates live-in information on basic blocks
198// according to LiveIntervals.
199//
200namespace {
201
202class VirtRegRewriter : public MachineFunctionPass {
203 MachineFunction *MF = nullptr;
204 const TargetRegisterInfo *TRI = nullptr;
205 const TargetInstrInfo *TII = nullptr;
206 MachineRegisterInfo *MRI = nullptr;
207 SlotIndexes *Indexes = nullptr;
208 LiveIntervals *LIS = nullptr;
209 LiveRegMatrix *LRM = nullptr;
210 VirtRegMap *VRM = nullptr;
211 LiveDebugVariables *DebugVars = nullptr;
212 DenseSet<Register> RewriteRegs;
213 bool ClearVirtRegs;
214
215 void rewrite();
216 void addMBBLiveIns();
217 bool readsUndefSubreg(const MachineOperand &MO) const;
218 void addLiveInsForSubRanges(const LiveInterval &LI, MCRegister PhysReg) const;
219 void handleIdentityCopy(MachineInstr &MI);
220 void expandCopyBundle(MachineInstr &MI) const;
221 bool subRegLiveThrough(const MachineInstr &MI, MCRegister SuperPhysReg) const;
222 LaneBitmask liveOutUndefPhiLanesForUndefSubregDef(
223 const LiveInterval &LI, const MachineBasicBlock &MBB, unsigned SubReg,
224 MCPhysReg PhysReg, const MachineInstr &MI) const;
225
226public:
227 static char ID;
228 VirtRegRewriter(bool ClearVirtRegs_ = true) :
230 ClearVirtRegs(ClearVirtRegs_) {}
231
232 void getAnalysisUsage(AnalysisUsage &AU) const override;
233
234 bool runOnMachineFunction(MachineFunction&) override;
235
236 MachineFunctionProperties getSetProperties() const override {
237 if (ClearVirtRegs) {
239 MachineFunctionProperties::Property::NoVRegs);
240 }
241
243 }
244};
245
246} // end anonymous namespace
247
248char VirtRegRewriter::ID = 0;
249
250char &llvm::VirtRegRewriterID = VirtRegRewriter::ID;
251
252INITIALIZE_PASS_BEGIN(VirtRegRewriter, "virtregrewriter",
253 "Virtual Register Rewriter", false, false)
261 "Virtual Register Rewriter", false, false)
262
263void VirtRegRewriter::getAnalysisUsage(AnalysisUsage &AU) const {
264 AU.setPreservesCFG();
265 AU.addRequired<LiveIntervalsWrapperPass>();
266 AU.addPreserved<LiveIntervalsWrapperPass>();
267 AU.addRequired<SlotIndexesWrapperPass>();
268 AU.addPreserved<SlotIndexesWrapperPass>();
269 AU.addRequired<LiveDebugVariablesWrapperLegacy>();
270 AU.addRequired<LiveStacksWrapperLegacy>();
271 AU.addPreserved<LiveStacksWrapperLegacy>();
272 AU.addRequired<VirtRegMapWrapperLegacy>();
273 AU.addRequired<LiveRegMatrixWrapperLegacy>();
274
275 if (!ClearVirtRegs)
276 AU.addPreserved<LiveDebugVariablesWrapperLegacy>();
277
279}
280
281bool VirtRegRewriter::runOnMachineFunction(MachineFunction &fn) {
282 MF = &fn;
284 TII = MF->getSubtarget().getInstrInfo();
285 MRI = &MF->getRegInfo();
286 Indexes = &getAnalysis<SlotIndexesWrapperPass>().getSI();
287 LIS = &getAnalysis<LiveIntervalsWrapperPass>().getLIS();
288 LRM = &getAnalysis<LiveRegMatrixWrapperLegacy>().getLRM();
289 VRM = &getAnalysis<VirtRegMapWrapperLegacy>().getVRM();
290 DebugVars = &getAnalysis<LiveDebugVariablesWrapperLegacy>().getLDV();
291 LLVM_DEBUG(dbgs() << "********** REWRITE VIRTUAL REGISTERS **********\n"
292 << "********** Function: " << MF->getName() << '\n');
293 LLVM_DEBUG(VRM->dump());
294
295 // Add kill flags while we still have virtual registers.
296 LIS->addKillFlags(VRM);
297
298 // Live-in lists on basic blocks are required for physregs.
299 addMBBLiveIns();
300
301 // Rewrite virtual registers.
302 rewrite();
303
304 if (ClearVirtRegs) {
305 // Write out new DBG_VALUE instructions.
306
307 // We only do this if ClearVirtRegs is specified since this should be the
308 // final run of the pass and we don't want to emit them multiple times.
309 DebugVars->emitDebugValues(VRM);
310
311 // All machine operands and other references to virtual registers have been
312 // replaced. Remove the virtual registers and release all the transient data.
313 VRM->clearAllVirt();
314 MRI->clearVirtRegs();
315 }
316
317 return true;
318}
319
320void VirtRegRewriter::addLiveInsForSubRanges(const LiveInterval &LI,
321 MCRegister PhysReg) const {
322 assert(!LI.empty());
323 assert(LI.hasSubRanges());
324
325 using SubRangeIteratorPair =
326 std::pair<const LiveInterval::SubRange *, LiveInterval::const_iterator>;
327
331 for (const LiveInterval::SubRange &SR : LI.subranges()) {
332 SubRanges.push_back(std::make_pair(&SR, SR.begin()));
333 if (!First.isValid() || SR.segments.front().start < First)
334 First = SR.segments.front().start;
335 if (!Last.isValid() || SR.segments.back().end > Last)
336 Last = SR.segments.back().end;
337 }
338
339 // Check all mbb start positions between First and Last while
340 // simultaneously advancing an iterator for each subrange.
342 MBBI != Indexes->MBBIndexEnd() && MBBI->first <= Last; ++MBBI) {
343 SlotIndex MBBBegin = MBBI->first;
344 // Advance all subrange iterators so that their end position is just
345 // behind MBBBegin (or the iterator is at the end).
346 LaneBitmask LaneMask;
347 for (auto &RangeIterPair : SubRanges) {
348 const LiveInterval::SubRange *SR = RangeIterPair.first;
349 LiveInterval::const_iterator &SRI = RangeIterPair.second;
350 while (SRI != SR->end() && SRI->end <= MBBBegin)
351 ++SRI;
352 if (SRI == SR->end())
353 continue;
354 if (SRI->start <= MBBBegin)
355 LaneMask |= SR->LaneMask;
356 }
357 if (LaneMask.none())
358 continue;
359 MachineBasicBlock *MBB = MBBI->second;
360 MBB->addLiveIn(PhysReg, LaneMask);
361 }
362}
363
364// Compute MBB live-in lists from virtual register live ranges and their
365// assignments.
366void VirtRegRewriter::addMBBLiveIns() {
367 for (unsigned Idx = 0, IdxE = MRI->getNumVirtRegs(); Idx != IdxE; ++Idx) {
369 if (MRI->reg_nodbg_empty(VirtReg))
370 continue;
371 LiveInterval &LI = LIS->getInterval(VirtReg);
372 if (LI.empty() || LIS->intervalIsInOneMBB(LI))
373 continue;
374 // This is a virtual register that is live across basic blocks. Its
375 // assigned PhysReg must be marked as live-in to those blocks.
376 MCRegister PhysReg = VRM->getPhys(VirtReg);
377 if (!PhysReg) {
378 // There may be no physical register assigned if only some register
379 // classes were already allocated.
380 assert(!ClearVirtRegs && "Unmapped virtual register");
381 continue;
382 }
383
384 if (LI.hasSubRanges()) {
385 addLiveInsForSubRanges(LI, PhysReg);
386 } else {
387 // Go over MBB begin positions and see if we have segments covering them.
388 // The following works because segments and the MBBIndex list are both
389 // sorted by slot indexes.
391 for (const auto &Seg : LI) {
392 I = Indexes->getMBBLowerBound(I, Seg.start);
393 for (; I != Indexes->MBBIndexEnd() && I->first < Seg.end; ++I) {
394 MachineBasicBlock *MBB = I->second;
395 MBB->addLiveIn(PhysReg);
396 }
397 }
398 }
399 }
400
401 // Sort and unique MBB LiveIns as we've not checked if SubReg/PhysReg were in
402 // each MBB's LiveIns set before calling addLiveIn on them.
403 for (MachineBasicBlock &MBB : *MF)
405}
406
407/// Returns true if the given machine operand \p MO only reads undefined lanes.
408/// The function only works for use operands with a subregister set.
409bool VirtRegRewriter::readsUndefSubreg(const MachineOperand &MO) const {
410 // Shortcut if the operand is already marked undef.
411 if (MO.isUndef())
412 return true;
413
414 Register Reg = MO.getReg();
415 const LiveInterval &LI = LIS->getInterval(Reg);
416 const MachineInstr &MI = *MO.getParent();
417 SlotIndex BaseIndex = LIS->getInstructionIndex(MI);
418 // This code is only meant to handle reading undefined subregisters which
419 // we couldn't properly detect before.
420 assert(LI.liveAt(BaseIndex) &&
421 "Reads of completely dead register should be marked undef already");
422 unsigned SubRegIdx = MO.getSubReg();
423 assert(SubRegIdx != 0 && LI.hasSubRanges());
424 LaneBitmask UseMask = TRI->getSubRegIndexLaneMask(SubRegIdx);
425 // See if any of the relevant subregister liveranges is defined at this point.
426 for (const LiveInterval::SubRange &SR : LI.subranges()) {
427 if ((SR.LaneMask & UseMask).any() && SR.liveAt(BaseIndex))
428 return false;
429 }
430 return true;
431}
432
433void VirtRegRewriter::handleIdentityCopy(MachineInstr &MI) {
434 if (!MI.isIdentityCopy())
435 return;
436 LLVM_DEBUG(dbgs() << "Identity copy: " << MI);
437 ++NumIdCopies;
438
439 Register DstReg = MI.getOperand(0).getReg();
440
441 // We may have deferred allocation of the virtual register, and the rewrite
442 // regs code doesn't handle the liveness update.
443 if (DstReg.isVirtual())
444 return;
445
446 RewriteRegs.insert(DstReg);
447
448 // Copies like:
449 // %r0 = COPY undef %r0
450 // %al = COPY %al, implicit-def %eax
451 // give us additional liveness information: The target (super-)register
452 // must not be valid before this point. Replace the COPY with a KILL
453 // instruction to maintain this information.
454 if (MI.getOperand(1).isUndef() || MI.getNumOperands() > 2) {
455 MI.setDesc(TII->get(TargetOpcode::KILL));
456 LLVM_DEBUG(dbgs() << " replace by: " << MI);
457 return;
458 }
459
460 if (Indexes)
462 MI.eraseFromBundle();
463 LLVM_DEBUG(dbgs() << " deleted.\n");
464}
465
466/// The liverange splitting logic sometimes produces bundles of copies when
467/// subregisters are involved. Expand these into a sequence of copy instructions
468/// after processing the last in the bundle. Does not update LiveIntervals
469/// which we shouldn't need for this instruction anymore.
470void VirtRegRewriter::expandCopyBundle(MachineInstr &MI) const {
471 if (!MI.isCopy() && !MI.isKill())
472 return;
473
474 if (MI.isBundledWithPred() && !MI.isBundledWithSucc()) {
476
477 // Only do this when the complete bundle is made out of COPYs and KILLs.
478 MachineBasicBlock &MBB = *MI.getParent();
480 std::next(MI.getReverseIterator()), E = MBB.instr_rend();
481 I != E && I->isBundledWithSucc(); ++I) {
482 if (!I->isCopy() && !I->isKill())
483 return;
484 MIs.push_back(&*I);
485 }
486 MachineInstr *FirstMI = MIs.back();
487
488 auto anyRegsAlias = [](const MachineInstr *Dst,
490 const TargetRegisterInfo *TRI) {
491 for (const MachineInstr *Src : Srcs)
492 if (Src != Dst)
493 if (TRI->regsOverlap(Dst->getOperand(0).getReg(),
494 Src->getOperand(1).getReg()))
495 return true;
496 return false;
497 };
498
499 // If any of the destination registers in the bundle of copies alias any of
500 // the source registers, try to schedule the instructions to avoid any
501 // clobbering.
502 for (int E = MIs.size(), PrevE = E; E > 1; PrevE = E) {
503 for (int I = E; I--; )
504 if (!anyRegsAlias(MIs[I], ArrayRef(MIs).take_front(E), TRI)) {
505 if (I + 1 != E)
506 std::swap(MIs[I], MIs[E - 1]);
507 --E;
508 }
509 if (PrevE == E) {
510 MF->getFunction().getContext().emitError(
511 "register rewriting failed: cycle in copy bundle");
512 break;
513 }
514 }
515
516 MachineInstr *BundleStart = FirstMI;
517 for (MachineInstr *BundledMI : llvm::reverse(MIs)) {
518 // If instruction is in the middle of the bundle, move it before the
519 // bundle starts, otherwise, just unbundle it. When we get to the last
520 // instruction, the bundle will have been completely undone.
521 if (BundledMI != BundleStart) {
522 BundledMI->removeFromBundle();
523 MBB.insert(BundleStart, BundledMI);
524 } else if (BundledMI->isBundledWithSucc()) {
525 BundledMI->unbundleFromSucc();
526 BundleStart = &*std::next(BundledMI->getIterator());
527 }
528
529 if (Indexes && BundledMI != FirstMI)
530 Indexes->insertMachineInstrInMaps(*BundledMI);
531 }
532 }
533}
534
535/// Check whether (part of) \p SuperPhysReg is live through \p MI.
536/// \pre \p MI defines a subregister of a virtual register that
537/// has been assigned to \p SuperPhysReg.
538bool VirtRegRewriter::subRegLiveThrough(const MachineInstr &MI,
539 MCRegister SuperPhysReg) const {
540 SlotIndex MIIndex = LIS->getInstructionIndex(MI);
541 SlotIndex BeforeMIUses = MIIndex.getBaseIndex();
542 SlotIndex AfterMIDefs = MIIndex.getBoundaryIndex();
543 for (MCRegUnit Unit : TRI->regunits(SuperPhysReg)) {
544 const LiveRange &UnitRange = LIS->getRegUnit(Unit);
545 // If the regunit is live both before and after MI,
546 // we assume it is live through.
547 // Generally speaking, this is not true, because something like
548 // "RU = op RU" would match that description.
549 // However, we know that we are trying to assess whether
550 // a def of a virtual reg, vreg, is live at the same time of RU.
551 // If we are in the "RU = op RU" situation, that means that vreg
552 // is defined at the same time as RU (i.e., "vreg, RU = op RU").
553 // Thus, vreg and RU interferes and vreg cannot be assigned to
554 // SuperPhysReg. Therefore, this situation cannot happen.
555 if (UnitRange.liveAt(AfterMIDefs) && UnitRange.liveAt(BeforeMIUses))
556 return true;
557 }
558 return false;
559}
560
561/// Compute a lanemask for undef lanes which need to be preserved out of the
562/// defining block for a register assignment for a subregister def. \p PhysReg
563/// is assigned to \p LI, which is the main range.
564LaneBitmask VirtRegRewriter::liveOutUndefPhiLanesForUndefSubregDef(
565 const LiveInterval &LI, const MachineBasicBlock &MBB, unsigned SubReg,
566 MCPhysReg PhysReg, const MachineInstr &MI) const {
567 LaneBitmask UndefMask = ~TRI->getSubRegIndexLaneMask(SubReg);
568 LaneBitmask LiveOutUndefLanes;
569
570 for (const LiveInterval::SubRange &SR : LI.subranges()) {
571 // Figure out which lanes are undef live into a successor.
572 LaneBitmask NeedImpDefLanes = UndefMask & SR.LaneMask;
573 if (NeedImpDefLanes.any() && !LIS->isLiveOutOfMBB(SR, &MBB)) {
574 for (const MachineBasicBlock *Succ : MBB.successors()) {
575 if (LIS->isLiveInToMBB(SR, Succ))
576 LiveOutUndefLanes |= NeedImpDefLanes;
577 }
578 }
579 }
580
581 SlotIndex MIIndex = LIS->getInstructionIndex(MI);
582 SlotIndex BeforeMIUses = MIIndex.getBaseIndex();
583 LaneBitmask InterferingLanes =
584 LRM->checkInterferenceLanes(BeforeMIUses, MIIndex.getRegSlot(), PhysReg);
585 LiveOutUndefLanes &= ~InterferingLanes;
586
587 LLVM_DEBUG(if (LiveOutUndefLanes.any()) {
588 dbgs() << "Need live out undef defs for " << printReg(PhysReg)
589 << LiveOutUndefLanes << " from " << printMBBReference(MBB) << '\n';
590 });
591
592 return LiveOutUndefLanes;
593}
594
595void VirtRegRewriter::rewrite() {
596 bool NoSubRegLiveness = !MRI->subRegLivenessEnabled();
597 SmallVector<Register, 8> SuperDeads;
598 SmallVector<Register, 8> SuperDefs;
599 SmallVector<Register, 8> SuperKills;
600
601 for (MachineFunction::iterator MBBI = MF->begin(), MBBE = MF->end();
602 MBBI != MBBE; ++MBBI) {
603 LLVM_DEBUG(MBBI->print(dbgs(), Indexes));
605 for (MachineOperand &MO : MI.operands()) {
606 // Make sure MRI knows about registers clobbered by regmasks.
607 if (MO.isRegMask())
608 MRI->addPhysRegsUsedFromRegMask(MO.getRegMask());
609
610 if (!MO.isReg() || !MO.getReg().isVirtual())
611 continue;
612 Register VirtReg = MO.getReg();
613 MCRegister PhysReg = VRM->getPhys(VirtReg);
614 if (!PhysReg)
615 continue;
616
617 assert(Register(PhysReg).isPhysical());
618
619 RewriteRegs.insert(PhysReg);
620 assert((!MRI->isReserved(PhysReg) ||
621 MF->getProperties().hasProperty(
623 "Reserved register assignment");
624
625 // Preserve semantics of sub-register operands.
626 unsigned SubReg = MO.getSubReg();
627 if (SubReg != 0) {
628 if (NoSubRegLiveness || !MRI->shouldTrackSubRegLiveness(VirtReg)) {
629 // A virtual register kill refers to the whole register, so we may
630 // have to add implicit killed operands for the super-register. A
631 // partial redef always kills and redefines the super-register.
632 if ((MO.readsReg() && (MO.isDef() || MO.isKill())) ||
633 (MO.isDef() && subRegLiveThrough(MI, PhysReg)))
634 SuperKills.push_back(PhysReg);
635
636 if (MO.isDef()) {
637 // Also add implicit defs for the super-register.
638 if (MO.isDead())
639 SuperDeads.push_back(PhysReg);
640 else
641 SuperDefs.push_back(PhysReg);
642 }
643 } else {
644 if (MO.isUse()) {
645 if (readsUndefSubreg(MO))
646 // We need to add an <undef> flag if the subregister is
647 // completely undefined (and we are not adding super-register
648 // defs).
649 MO.setIsUndef(true);
650 } else if (!MO.isDead()) {
651 assert(MO.isDef());
652 if (MO.isUndef()) {
653 const LiveInterval &LI = LIS->getInterval(VirtReg);
654
655 LaneBitmask LiveOutUndefLanes =
656 liveOutUndefPhiLanesForUndefSubregDef(LI, *MBBI, SubReg,
657 PhysReg, MI);
658 if (LiveOutUndefLanes.any()) {
659 SmallVector<unsigned, 16> CoveringIndexes;
660
661 // TODO: Just use one super register def if none of the lanes
662 // are needed?
663 if (!TRI->getCoveringSubRegIndexes(
664 *MRI, MRI->getRegClass(VirtReg), LiveOutUndefLanes,
665 CoveringIndexes))
667 "cannot represent required subregister defs");
668
669 // Try to represent the minimum needed live out def as a
670 // sequence of subregister defs.
671 //
672 // FIXME: It would be better if we could directly represent
673 // liveness with a lanemask instead of spamming operands.
674 for (unsigned SubIdx : CoveringIndexes)
675 SuperDefs.push_back(TRI->getSubReg(PhysReg, SubIdx));
676 }
677 }
678 }
679 }
680
681 // The def undef and def internal flags only make sense for
682 // sub-register defs, and we are substituting a full physreg. An
683 // implicit killed operand from the SuperKills list will represent the
684 // partial read of the super-register.
685 if (MO.isDef()) {
686 MO.setIsUndef(false);
687 MO.setIsInternalRead(false);
688 }
689
690 // PhysReg operands cannot have subregister indexes.
691 PhysReg = TRI->getSubReg(PhysReg, SubReg);
692 assert(PhysReg.isValid() && "Invalid SubReg for physical register");
693 MO.setSubReg(0);
694 }
695 // Rewrite. Note we could have used MachineOperand::substPhysReg(), but
696 // we need the inlining here.
697 MO.setReg(PhysReg);
698 MO.setIsRenamable(true);
699 }
700
701 // Add any missing super-register kills after rewriting the whole
702 // instruction.
703 while (!SuperKills.empty())
704 MI.addRegisterKilled(SuperKills.pop_back_val(), TRI, true);
705
706 while (!SuperDeads.empty())
707 MI.addRegisterDead(SuperDeads.pop_back_val(), TRI, true);
708
709 while (!SuperDefs.empty())
710 MI.addRegisterDefined(SuperDefs.pop_back_val(), TRI);
711
712 LLVM_DEBUG(dbgs() << "> " << MI);
713
714 expandCopyBundle(MI);
715
716 // We can remove identity copies right now.
717 handleIdentityCopy(MI);
718 }
719 }
720
721 if (LIS) {
722 // Don't bother maintaining accurate LiveIntervals for registers which were
723 // already allocated.
724 for (Register PhysReg : RewriteRegs) {
725 for (MCRegUnit Unit : TRI->regunits(PhysReg)) {
726 LIS->removeRegUnit(Unit);
727 }
728 }
729 }
730
731 RewriteRegs.clear();
732}
733
735 return new VirtRegRewriter(ClearVirtRegs);
736}
unsigned SubReg
unsigned const MachineRegisterInfo * MRI
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator MBBI
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition: Compiler.h:622
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
#define LLVM_DEBUG(...)
Definition: Debug.h:106
uint64_t Size
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
A common definition of LaneBitmask for use in TableGen and CodeGen.
#define I(x, y, z)
Definition: MD5.cpp:58
unsigned const TargetRegisterInfo * TRI
ModuleAnalysisManager MAM
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:55
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:57
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:52
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:38
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
raw_pwrite_stream & OS
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:166
virtregrewriter
Definition: VirtRegMap.cpp:260
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:253
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:410
Represent the analysis usage information of a pass.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
Implements a dense probed hash-table based set.
Definition: DenseSet.h:278
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:310
void emitDebugValues(VirtRegMap *VRM)
emitDebugValues - Emit new DBG_VALUE instructions reflecting the changes that happened during registe...
A live range for subregisters.
Definition: LiveInterval.h:694
LiveInterval - This class represents the liveness of a register, or stack slot.
Definition: LiveInterval.h:687
bool hasSubRanges() const
Returns true if subregister liveness information is available.
Definition: LiveInterval.h:810
iterator_range< subrange_iterator > subranges()
Definition: LiveInterval.h:782
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.
LiveRange & getRegUnit(unsigned Unit)
Return the live range for register unit Unit.
LiveInterval & getInterval(Register Reg)
MachineBasicBlock * intervalIsInOneMBB(const LiveInterval &LI) const
If LI is confined to a single basic block, return a pointer to that block.
void removeRegUnit(unsigned Unit)
Remove computed live range for register unit Unit.
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.
Definition: LiveInterval.h:157
bool liveAt(SlotIndex index) const
Definition: LiveInterval.h:401
bool empty() const
Definition: LiveInterval.h:382
iterator end()
Definition: LiveInterval.h:216
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:33
constexpr bool isValid() const
Definition: MCRegister.h:81
instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
void sortUniqueLiveIns()
Sorts and uniques the LiveIns vector.
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
int CreateSpillStackObject(uint64_t Size, Align Alignment)
Create a new statically sized stack object that represents a spill slot, returning a nonnegative iden...
int getObjectIndexBegin() const
Return the minimum frame object index.
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.
Properties which a MachineFunction may have at a given point in time.
MachineFunctionProperties & set(Property P)
bool hasProperty(Property P) const
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.
const MachineFunctionProperties & getProperties() const
Get the function properties.
Representation of each machine instruction.
Definition: MachineInstr.h:69
MachineInstr * removeFromBundle()
Unlink this instruction from its basic block and return it without deleting it.
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.
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.
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,...
Register getSimpleHint(Register VReg) const
getSimpleHint - same as getRegAllocationHint except it will only return a target independent hint.
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
std::pair< unsigned, Register > getRegAllocationHint(Register VReg) const
getRegAllocationHint - Return the register allocation hint for the specified virtual register.
unsigned getNumVirtRegs() const
getNumVirtRegs - Return the number of virtual registers created.
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
A set of analyses that are preserved following a run of a transformation pass.
Definition: Analysis.h:111
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: Analysis.h:117
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
static Register index2VirtReg(unsigned Index)
Convert a 0-based index to a virtual register number.
Definition: Register.h:84
constexpr bool isValid() const
Definition: Register.h:116
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition: Register.h:91
static constexpr bool isPhysicalRegister(unsigned Reg)
Return true if the specified register number is in the physical register namespace.
Definition: Register.h:65
SlotIndex - An opaque wrapper around machine indexes.
Definition: SlotIndexes.h:65
SlotIndex getBoundaryIndex() const
Returns the boundary index for associated with this index.
Definition: SlotIndexes.h:231
SlotIndex getBaseIndex() const
Returns the base index for associated with this index.
Definition: SlotIndexes.h:224
SlotIndex getRegSlot(bool EC=false) const
Returns the register use/def slot in the current instruction for a normal or early-clobber def.
Definition: SlotIndexes.h:237
SlotIndexes pass.
Definition: SlotIndexes.h:297
SlotIndex insertMachineInstrInMaps(MachineInstr &MI, bool Late=false)
Insert the given machine instruction into the mapping.
Definition: SlotIndexes.h:531
MBBIndexIterator getMBBLowerBound(MBBIndexIterator Start, SlotIndex Idx) const
Get an iterator pointing to the first IdxMBBPair with SlotIndex greater than or equal to Idx.
Definition: SlotIndexes.h:486
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.
Definition: SlotIndexes.h:505
MBBIndexIterator MBBIndexEnd() const
Return an iterator for the end of the idx2MBBMap.
Definition: SlotIndexes.h:510
SmallVectorImpl< IdxMBBPair >::const_iterator MBBIndexIterator
Iterator over the idx2MBBMap (sorted pairs of slot index of basic block begin and basic block)
Definition: SlotIndexes.h:481
bool empty() const
Definition: SmallVector.h:81
void push_back(const T &Elt)
Definition: SmallVector.h:413
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1196
TargetInstrInfo - Interface to description of machine instruction set.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
Align getSpillAlign(const TargetRegisterClass &RC) const
Return the minimum required alignment in bytes for a spill slot for a register of this class.
unsigned getSpillSize(const TargetRegisterClass &RC) const
Return the size in bytes of the stack slot allocated to hold a spilled copy of a register from class ...
const char * getRegClassName(const TargetRegisterClass *Class) const
Returns the name of the register class.
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
virtual const TargetInstrInfo * getInstrInfo() const
VirtRegMap run(MachineFunction &MF, MachineFunctionAnalysisManager &MAM)
Definition: VirtRegMap.cpp:184
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
Definition: VirtRegMap.cpp:178
bool hasKnownPreference(Register VirtReg) const
returns true if VirtReg has a known preferred register.
Definition: VirtRegMap.cpp:121
void init(MachineFunction &MF)
int assignVirt2StackSlot(Register virtReg)
create a mapping for the specifed virtual register to the next available stack slot
Definition: VirtRegMap.cpp:130
void clearAllVirt()
clears all virtual to physical register mappings
Definition: VirtRegMap.h:124
bool hasPreferredPhys(Register VirtReg) const
returns true if VirtReg is assigned to its preferred physreg.
Definition: VirtRegMap.cpp:112
void dump() const
Definition: VirtRegMap.cpp:170
MachineRegisterInfo & getRegInfo() const
Definition: VirtRegMap.h:79
MCRegister getPhys(Register virtReg) const
returns the physical register mapped to the specified virtual register
Definition: VirtRegMap.h:90
void print(raw_ostream &OS, const Module *M=nullptr) const
Definition: VirtRegMap.cpp:148
bool hasPhys(Register virtReg) const
returns true if the specified virtual register is mapped to a physical register
Definition: VirtRegMap.h:86
static constexpr int NO_STACK_SLOT
Definition: VirtRegMap.h:65
void assignVirt2Phys(Register virtReg, MCPhysReg physReg)
creates a mapping for the specified virtual register to the specified physical register
Definition: VirtRegMap.cpp:86
std::pair< iterator, bool > insert(const ValueT &V)
Definition: DenseSet.h:213
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
#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
Reg
All possible values of the reg field in the ModR/M byte.
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
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:657
auto reverse(ContainerTy &&C)
Definition: STLExtras.h:420
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
char & VirtRegRewriterID
VirtRegRewriter pass.
Definition: VirtRegMap.cpp:250
FunctionPass * createVirtRegRewriter(bool ClearVirtRegs=true)
Definition: VirtRegMap.cpp:734
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:860
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:28
constexpr bool none() const
Definition: LaneBitmask.h:52
constexpr bool any() const
Definition: LaneBitmask.h:53