1 //===-- LiveVariables.cpp - Live Variable Analysis for Machine Code -------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file implements the LiveVariable analysis pass. For each machine
10 // instruction in the function, this pass calculates the set of registers that
11 // are immediately dead after the instruction (i.e., the instruction calculates
12 // the value, but it is never used) and the set of registers that are used by
13 // the instruction, but are never used after the instruction (i.e., they are
16 // This class computes live variables using a sparse implementation based on
17 // the machine code SSA form. This class computes live variable information for
18 // each virtual and _register allocatable_ physical register in a function. It
19 // uses the dominance properties of SSA form to efficiently compute live
20 // variables for virtual registers, and assumes that physical registers are only
21 // live within a single basic block (allowing it to do a single local analysis
22 // to resolve physical register lifetimes in each basic block). If a physical
23 // register is not register allocatable, it is not tracked. This is useful for
24 // things like the stack pointer and condition codes.
26 //===----------------------------------------------------------------------===//
28 #include "llvm/CodeGen/LiveVariables.h"
29 #include "llvm/ADT/DepthFirstIterator.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include "llvm/ADT/SmallPtrSet.h"
32 #include "llvm/ADT/SmallSet.h"
33 #include "llvm/CodeGen/MachineInstr.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/Passes.h"
36 #include "llvm/Config/llvm-config.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/raw_ostream.h"
43 char LiveVariables::ID
= 0;
44 char &llvm::LiveVariablesID
= LiveVariables::ID
;
45 INITIALIZE_PASS_BEGIN(LiveVariables
, "livevars",
46 "Live Variable Analysis", false, false)
47 INITIALIZE_PASS_DEPENDENCY(UnreachableMachineBlockElim
)
48 INITIALIZE_PASS_END(LiveVariables
, "livevars",
49 "Live Variable Analysis", false, false)
52 void LiveVariables::getAnalysisUsage(AnalysisUsage
&AU
) const {
53 AU
.addRequiredID(UnreachableMachineBlockElimID
);
55 MachineFunctionPass::getAnalysisUsage(AU
);
59 LiveVariables::VarInfo::findKill(const MachineBasicBlock
*MBB
) const {
60 for (unsigned i
= 0, e
= Kills
.size(); i
!= e
; ++i
)
61 if (Kills
[i
]->getParent() == MBB
)
66 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
67 LLVM_DUMP_METHOD
void LiveVariables::VarInfo::dump() const {
68 dbgs() << " Alive in blocks: ";
69 for (SparseBitVector
<>::iterator I
= AliveBlocks
.begin(),
70 E
= AliveBlocks
.end(); I
!= E
; ++I
)
72 dbgs() << "\n Killed by:";
74 dbgs() << " No instructions.\n";
76 for (unsigned i
= 0, e
= Kills
.size(); i
!= e
; ++i
)
77 dbgs() << "\n #" << i
<< ": " << *Kills
[i
];
83 /// getVarInfo - Get (possibly creating) a VarInfo object for the given vreg.
84 LiveVariables::VarInfo
&LiveVariables::getVarInfo(unsigned RegIdx
) {
85 assert(Register::isVirtualRegister(RegIdx
) &&
86 "getVarInfo: not a virtual register!");
87 VirtRegInfo
.grow(RegIdx
);
88 return VirtRegInfo
[RegIdx
];
91 void LiveVariables::MarkVirtRegAliveInBlock(VarInfo
& VRInfo
,
92 MachineBasicBlock
*DefBlock
,
93 MachineBasicBlock
*MBB
,
94 std::vector
<MachineBasicBlock
*> &WorkList
) {
95 unsigned BBNum
= MBB
->getNumber();
97 // Check to see if this basic block is one of the killing blocks. If so,
99 for (unsigned i
= 0, e
= VRInfo
.Kills
.size(); i
!= e
; ++i
)
100 if (VRInfo
.Kills
[i
]->getParent() == MBB
) {
101 VRInfo
.Kills
.erase(VRInfo
.Kills
.begin()+i
); // Erase entry
105 if (MBB
== DefBlock
) return; // Terminate recursion
107 if (VRInfo
.AliveBlocks
.test(BBNum
))
108 return; // We already know the block is live
110 // Mark the variable known alive in this bb
111 VRInfo
.AliveBlocks
.set(BBNum
);
113 assert(MBB
!= &MF
->front() && "Can't find reaching def for virtreg");
114 WorkList
.insert(WorkList
.end(), MBB
->pred_rbegin(), MBB
->pred_rend());
117 void LiveVariables::MarkVirtRegAliveInBlock(VarInfo
&VRInfo
,
118 MachineBasicBlock
*DefBlock
,
119 MachineBasicBlock
*MBB
) {
120 std::vector
<MachineBasicBlock
*> WorkList
;
121 MarkVirtRegAliveInBlock(VRInfo
, DefBlock
, MBB
, WorkList
);
123 while (!WorkList
.empty()) {
124 MachineBasicBlock
*Pred
= WorkList
.back();
126 MarkVirtRegAliveInBlock(VRInfo
, DefBlock
, Pred
, WorkList
);
130 void LiveVariables::HandleVirtRegUse(unsigned reg
, MachineBasicBlock
*MBB
,
132 assert(MRI
->getVRegDef(reg
) && "Register use before def!");
134 unsigned BBNum
= MBB
->getNumber();
136 VarInfo
& VRInfo
= getVarInfo(reg
);
138 // Check to see if this basic block is already a kill block.
139 if (!VRInfo
.Kills
.empty() && VRInfo
.Kills
.back()->getParent() == MBB
) {
140 // Yes, this register is killed in this basic block already. Increase the
141 // live range by updating the kill instruction.
142 VRInfo
.Kills
.back() = &MI
;
147 for (unsigned i
= 0, e
= VRInfo
.Kills
.size(); i
!= e
; ++i
)
148 assert(VRInfo
.Kills
[i
]->getParent() != MBB
&& "entry should be at end!");
151 // This situation can occur:
156 // | t2 = phi ... t1 ...
160 // | ... = ... t1 ...
164 // where there is a use in a PHI node that's a predecessor to the defining
165 // block. We don't want to mark all predecessors as having the value "alive"
167 if (MBB
== MRI
->getVRegDef(reg
)->getParent()) return;
169 // Add a new kill entry for this basic block. If this virtual register is
170 // already marked as alive in this basic block, that means it is alive in at
171 // least one of the successor blocks, it's not a kill.
172 if (!VRInfo
.AliveBlocks
.test(BBNum
))
173 VRInfo
.Kills
.push_back(&MI
);
175 // Update all dominating blocks to mark them as "known live".
176 for (MachineBasicBlock::const_pred_iterator PI
= MBB
->pred_begin(),
177 E
= MBB
->pred_end(); PI
!= E
; ++PI
)
178 MarkVirtRegAliveInBlock(VRInfo
, MRI
->getVRegDef(reg
)->getParent(), *PI
);
181 void LiveVariables::HandleVirtRegDef(unsigned Reg
, MachineInstr
&MI
) {
182 VarInfo
&VRInfo
= getVarInfo(Reg
);
184 if (VRInfo
.AliveBlocks
.empty())
185 // If vr is not alive in any block, then defaults to dead.
186 VRInfo
.Kills
.push_back(&MI
);
189 /// FindLastPartialDef - Return the last partial def of the specified register.
190 /// Also returns the sub-registers that're defined by the instruction.
191 MachineInstr
*LiveVariables::FindLastPartialDef(unsigned Reg
,
192 SmallSet
<unsigned,4> &PartDefRegs
) {
193 unsigned LastDefReg
= 0;
194 unsigned LastDefDist
= 0;
195 MachineInstr
*LastDef
= nullptr;
196 for (MCSubRegIterator
SubRegs(Reg
, TRI
); SubRegs
.isValid(); ++SubRegs
) {
197 unsigned SubReg
= *SubRegs
;
198 MachineInstr
*Def
= PhysRegDef
[SubReg
];
201 unsigned Dist
= DistanceMap
[Def
];
202 if (Dist
> LastDefDist
) {
212 PartDefRegs
.insert(LastDefReg
);
213 for (unsigned i
= 0, e
= LastDef
->getNumOperands(); i
!= e
; ++i
) {
214 MachineOperand
&MO
= LastDef
->getOperand(i
);
215 if (!MO
.isReg() || !MO
.isDef() || MO
.getReg() == 0)
217 Register DefReg
= MO
.getReg();
218 if (TRI
->isSubRegister(Reg
, DefReg
)) {
219 for (MCSubRegIterator
SubRegs(DefReg
, TRI
, /*IncludeSelf=*/true);
220 SubRegs
.isValid(); ++SubRegs
)
221 PartDefRegs
.insert(*SubRegs
);
227 /// HandlePhysRegUse - Turn previous partial def's into read/mod/writes. Add
228 /// implicit defs to a machine instruction if there was an earlier def of its
230 void LiveVariables::HandlePhysRegUse(unsigned Reg
, MachineInstr
&MI
) {
231 MachineInstr
*LastDef
= PhysRegDef
[Reg
];
232 // If there was a previous use or a "full" def all is well.
233 if (!LastDef
&& !PhysRegUse
[Reg
]) {
234 // Otherwise, the last sub-register def implicitly defines this register.
237 // AL = ... implicit-def EAX, implicit killed AH
241 // All of the sub-registers must have been defined before the use of Reg!
242 SmallSet
<unsigned, 4> PartDefRegs
;
243 MachineInstr
*LastPartialDef
= FindLastPartialDef(Reg
, PartDefRegs
);
244 // If LastPartialDef is NULL, it must be using a livein register.
245 if (LastPartialDef
) {
246 LastPartialDef
->addOperand(MachineOperand::CreateReg(Reg
, true/*IsDef*/,
248 PhysRegDef
[Reg
] = LastPartialDef
;
249 SmallSet
<unsigned, 8> Processed
;
250 for (MCSubRegIterator
SubRegs(Reg
, TRI
); SubRegs
.isValid(); ++SubRegs
) {
251 unsigned SubReg
= *SubRegs
;
252 if (Processed
.count(SubReg
))
254 if (PartDefRegs
.count(SubReg
))
256 // This part of Reg was defined before the last partial def. It's killed
258 LastPartialDef
->addOperand(MachineOperand::CreateReg(SubReg
,
261 PhysRegDef
[SubReg
] = LastPartialDef
;
262 for (MCSubRegIterator
SS(SubReg
, TRI
); SS
.isValid(); ++SS
)
263 Processed
.insert(*SS
);
266 } else if (LastDef
&& !PhysRegUse
[Reg
] &&
267 !LastDef
->findRegisterDefOperand(Reg
))
268 // Last def defines the super register, add an implicit def of reg.
269 LastDef
->addOperand(MachineOperand::CreateReg(Reg
, true/*IsDef*/,
272 // Remember this use.
273 for (MCSubRegIterator
SubRegs(Reg
, TRI
, /*IncludeSelf=*/true);
274 SubRegs
.isValid(); ++SubRegs
)
275 PhysRegUse
[*SubRegs
] = &MI
;
278 /// FindLastRefOrPartRef - Return the last reference or partial reference of
279 /// the specified register.
280 MachineInstr
*LiveVariables::FindLastRefOrPartRef(unsigned Reg
) {
281 MachineInstr
*LastDef
= PhysRegDef
[Reg
];
282 MachineInstr
*LastUse
= PhysRegUse
[Reg
];
283 if (!LastDef
&& !LastUse
)
286 MachineInstr
*LastRefOrPartRef
= LastUse
? LastUse
: LastDef
;
287 unsigned LastRefOrPartRefDist
= DistanceMap
[LastRefOrPartRef
];
288 unsigned LastPartDefDist
= 0;
289 for (MCSubRegIterator
SubRegs(Reg
, TRI
); SubRegs
.isValid(); ++SubRegs
) {
290 unsigned SubReg
= *SubRegs
;
291 MachineInstr
*Def
= PhysRegDef
[SubReg
];
292 if (Def
&& Def
!= LastDef
) {
293 // There was a def of this sub-register in between. This is a partial
294 // def, keep track of the last one.
295 unsigned Dist
= DistanceMap
[Def
];
296 if (Dist
> LastPartDefDist
)
297 LastPartDefDist
= Dist
;
298 } else if (MachineInstr
*Use
= PhysRegUse
[SubReg
]) {
299 unsigned Dist
= DistanceMap
[Use
];
300 if (Dist
> LastRefOrPartRefDist
) {
301 LastRefOrPartRefDist
= Dist
;
302 LastRefOrPartRef
= Use
;
307 return LastRefOrPartRef
;
310 bool LiveVariables::HandlePhysRegKill(unsigned Reg
, MachineInstr
*MI
) {
311 MachineInstr
*LastDef
= PhysRegDef
[Reg
];
312 MachineInstr
*LastUse
= PhysRegUse
[Reg
];
313 if (!LastDef
&& !LastUse
)
316 MachineInstr
*LastRefOrPartRef
= LastUse
? LastUse
: LastDef
;
317 unsigned LastRefOrPartRefDist
= DistanceMap
[LastRefOrPartRef
];
318 // The whole register is used.
323 // = AL, implicit killed AX
326 // Or whole register is defined, but not used at all.
331 // Or whole register is defined, but only partly used.
332 // dead AX = implicit-def AL
335 MachineInstr
*LastPartDef
= nullptr;
336 unsigned LastPartDefDist
= 0;
337 SmallSet
<unsigned, 8> PartUses
;
338 for (MCSubRegIterator
SubRegs(Reg
, TRI
); SubRegs
.isValid(); ++SubRegs
) {
339 unsigned SubReg
= *SubRegs
;
340 MachineInstr
*Def
= PhysRegDef
[SubReg
];
341 if (Def
&& Def
!= LastDef
) {
342 // There was a def of this sub-register in between. This is a partial
343 // def, keep track of the last one.
344 unsigned Dist
= DistanceMap
[Def
];
345 if (Dist
> LastPartDefDist
) {
346 LastPartDefDist
= Dist
;
351 if (MachineInstr
*Use
= PhysRegUse
[SubReg
]) {
352 for (MCSubRegIterator
SS(SubReg
, TRI
, /*IncludeSelf=*/true); SS
.isValid();
354 PartUses
.insert(*SS
);
355 unsigned Dist
= DistanceMap
[Use
];
356 if (Dist
> LastRefOrPartRefDist
) {
357 LastRefOrPartRefDist
= Dist
;
358 LastRefOrPartRef
= Use
;
363 if (!PhysRegUse
[Reg
]) {
364 // Partial uses. Mark register def dead and add implicit def of
365 // sub-registers which are used.
366 // dead EAX = op implicit-def AL
367 // That is, EAX def is dead but AL def extends pass it.
368 PhysRegDef
[Reg
]->addRegisterDead(Reg
, TRI
, true);
369 for (MCSubRegIterator
SubRegs(Reg
, TRI
); SubRegs
.isValid(); ++SubRegs
) {
370 unsigned SubReg
= *SubRegs
;
371 if (!PartUses
.count(SubReg
))
374 if (PhysRegDef
[Reg
] == PhysRegDef
[SubReg
]) {
375 MachineOperand
*MO
= PhysRegDef
[Reg
]->findRegisterDefOperand(SubReg
);
378 assert(!MO
->isDead());
382 PhysRegDef
[Reg
]->addOperand(MachineOperand::CreateReg(SubReg
,
383 true/*IsDef*/, true/*IsImp*/));
384 MachineInstr
*LastSubRef
= FindLastRefOrPartRef(SubReg
);
386 LastSubRef
->addRegisterKilled(SubReg
, TRI
, true);
388 LastRefOrPartRef
->addRegisterKilled(SubReg
, TRI
, true);
389 for (MCSubRegIterator
SS(SubReg
, TRI
, /*IncludeSelf=*/true);
391 PhysRegUse
[*SS
] = LastRefOrPartRef
;
393 for (MCSubRegIterator
SS(SubReg
, TRI
); SS
.isValid(); ++SS
)
396 } else if (LastRefOrPartRef
== PhysRegDef
[Reg
] && LastRefOrPartRef
!= MI
) {
398 // The last partial def kills the register.
399 LastPartDef
->addOperand(MachineOperand::CreateReg(Reg
, false/*IsDef*/,
400 true/*IsImp*/, true/*IsKill*/));
403 LastRefOrPartRef
->findRegisterDefOperand(Reg
, false, false, TRI
);
404 bool NeedEC
= MO
->isEarlyClobber() && MO
->getReg() != Reg
;
405 // If the last reference is the last def, then it's not used at all.
406 // That is, unless we are currently processing the last reference itself.
407 LastRefOrPartRef
->addRegisterDead(Reg
, TRI
, true);
409 // If we are adding a subreg def and the superreg def is marked early
410 // clobber, add an early clobber marker to the subreg def.
411 MO
= LastRefOrPartRef
->findRegisterDefOperand(Reg
);
413 MO
->setIsEarlyClobber();
417 LastRefOrPartRef
->addRegisterKilled(Reg
, TRI
, true);
421 void LiveVariables::HandleRegMask(const MachineOperand
&MO
) {
422 // Call HandlePhysRegKill() for all live registers clobbered by Mask.
423 // Clobbered registers are always dead, sp there is no need to use
424 // HandlePhysRegDef().
425 for (unsigned Reg
= 1, NumRegs
= TRI
->getNumRegs(); Reg
!= NumRegs
; ++Reg
) {
427 if (!PhysRegDef
[Reg
] && !PhysRegUse
[Reg
])
429 // Skip mask-preserved regs.
430 if (!MO
.clobbersPhysReg(Reg
))
432 // Kill the largest clobbered super-register.
433 // This avoids needless implicit operands.
434 unsigned Super
= Reg
;
435 for (MCSuperRegIterator
SR(Reg
, TRI
); SR
.isValid(); ++SR
)
436 if ((PhysRegDef
[*SR
] || PhysRegUse
[*SR
]) && MO
.clobbersPhysReg(*SR
))
438 HandlePhysRegKill(Super
, nullptr);
442 void LiveVariables::HandlePhysRegDef(unsigned Reg
, MachineInstr
*MI
,
443 SmallVectorImpl
<unsigned> &Defs
) {
444 // What parts of the register are previously defined?
445 SmallSet
<unsigned, 32> Live
;
446 if (PhysRegDef
[Reg
] || PhysRegUse
[Reg
]) {
447 for (MCSubRegIterator
SubRegs(Reg
, TRI
, /*IncludeSelf=*/true);
448 SubRegs
.isValid(); ++SubRegs
)
449 Live
.insert(*SubRegs
);
451 for (MCSubRegIterator
SubRegs(Reg
, TRI
); SubRegs
.isValid(); ++SubRegs
) {
452 unsigned SubReg
= *SubRegs
;
453 // If a register isn't itself defined, but all parts that make up of it
454 // are defined, then consider it also defined.
459 if (Live
.count(SubReg
))
461 if (PhysRegDef
[SubReg
] || PhysRegUse
[SubReg
]) {
462 for (MCSubRegIterator
SS(SubReg
, TRI
, /*IncludeSelf=*/true);
469 // Start from the largest piece, find the last time any part of the register
471 HandlePhysRegKill(Reg
, MI
);
472 // Only some of the sub-registers are used.
473 for (MCSubRegIterator
SubRegs(Reg
, TRI
); SubRegs
.isValid(); ++SubRegs
) {
474 unsigned SubReg
= *SubRegs
;
475 if (!Live
.count(SubReg
))
476 // Skip if this sub-register isn't defined.
478 HandlePhysRegKill(SubReg
, MI
);
482 Defs
.push_back(Reg
); // Remember this def.
485 void LiveVariables::UpdatePhysRegDefs(MachineInstr
&MI
,
486 SmallVectorImpl
<unsigned> &Defs
) {
487 while (!Defs
.empty()) {
488 unsigned Reg
= Defs
.back();
490 for (MCSubRegIterator
SubRegs(Reg
, TRI
, /*IncludeSelf=*/true);
491 SubRegs
.isValid(); ++SubRegs
) {
492 unsigned SubReg
= *SubRegs
;
493 PhysRegDef
[SubReg
] = &MI
;
494 PhysRegUse
[SubReg
] = nullptr;
499 void LiveVariables::runOnInstr(MachineInstr
&MI
,
500 SmallVectorImpl
<unsigned> &Defs
) {
501 assert(!MI
.isDebugInstr());
502 // Process all of the operands of the instruction...
503 unsigned NumOperandsToProcess
= MI
.getNumOperands();
505 // Unless it is a PHI node. In this case, ONLY process the DEF, not any
506 // of the uses. They will be handled in other basic blocks.
508 NumOperandsToProcess
= 1;
510 // Clear kill and dead markers. LV will recompute them.
511 SmallVector
<unsigned, 4> UseRegs
;
512 SmallVector
<unsigned, 4> DefRegs
;
513 SmallVector
<unsigned, 1> RegMasks
;
514 for (unsigned i
= 0; i
!= NumOperandsToProcess
; ++i
) {
515 MachineOperand
&MO
= MI
.getOperand(i
);
516 if (MO
.isRegMask()) {
517 RegMasks
.push_back(i
);
520 if (!MO
.isReg() || MO
.getReg() == 0)
522 Register MOReg
= MO
.getReg();
524 if (!(Register::isPhysicalRegister(MOReg
) && MRI
->isReserved(MOReg
)))
527 UseRegs
.push_back(MOReg
);
530 // FIXME: We should not remove any dead flags. However the MIPS RDDSP
531 // instruction needs it at the moment: http://llvm.org/PR27116.
532 if (Register::isPhysicalRegister(MOReg
) && !MRI
->isReserved(MOReg
))
534 DefRegs
.push_back(MOReg
);
538 MachineBasicBlock
*MBB
= MI
.getParent();
540 for (unsigned i
= 0, e
= UseRegs
.size(); i
!= e
; ++i
) {
541 unsigned MOReg
= UseRegs
[i
];
542 if (Register::isVirtualRegister(MOReg
))
543 HandleVirtRegUse(MOReg
, MBB
, MI
);
544 else if (!MRI
->isReserved(MOReg
))
545 HandlePhysRegUse(MOReg
, MI
);
548 // Process all masked registers. (Call clobbers).
549 for (unsigned i
= 0, e
= RegMasks
.size(); i
!= e
; ++i
)
550 HandleRegMask(MI
.getOperand(RegMasks
[i
]));
553 for (unsigned i
= 0, e
= DefRegs
.size(); i
!= e
; ++i
) {
554 unsigned MOReg
= DefRegs
[i
];
555 if (Register::isVirtualRegister(MOReg
))
556 HandleVirtRegDef(MOReg
, MI
);
557 else if (!MRI
->isReserved(MOReg
))
558 HandlePhysRegDef(MOReg
, &MI
, Defs
);
560 UpdatePhysRegDefs(MI
, Defs
);
563 void LiveVariables::runOnBlock(MachineBasicBlock
*MBB
, const unsigned NumRegs
) {
564 // Mark live-in registers as live-in.
565 SmallVector
<unsigned, 4> Defs
;
566 for (const auto &LI
: MBB
->liveins()) {
567 assert(Register::isPhysicalRegister(LI
.PhysReg
) &&
568 "Cannot have a live-in virtual register!");
569 HandlePhysRegDef(LI
.PhysReg
, nullptr, Defs
);
572 // Loop over all of the instructions, processing them.
575 for (MachineInstr
&MI
: *MBB
) {
576 if (MI
.isDebugInstr())
578 DistanceMap
.insert(std::make_pair(&MI
, Dist
++));
580 runOnInstr(MI
, Defs
);
583 // Handle any virtual assignments from PHI nodes which might be at the
584 // bottom of this basic block. We check all of our successor blocks to see
585 // if they have PHI nodes, and if so, we simulate an assignment at the end
586 // of the current block.
587 if (!PHIVarInfo
[MBB
->getNumber()].empty()) {
588 SmallVectorImpl
<unsigned> &VarInfoVec
= PHIVarInfo
[MBB
->getNumber()];
590 for (SmallVectorImpl
<unsigned>::iterator I
= VarInfoVec
.begin(),
591 E
= VarInfoVec
.end(); I
!= E
; ++I
)
592 // Mark it alive only in the block we are representing.
593 MarkVirtRegAliveInBlock(getVarInfo(*I
),MRI
->getVRegDef(*I
)->getParent(),
597 // MachineCSE may CSE instructions which write to non-allocatable physical
598 // registers across MBBs. Remember if any reserved register is liveout.
599 SmallSet
<unsigned, 4> LiveOuts
;
600 for (MachineBasicBlock::const_succ_iterator SI
= MBB
->succ_begin(),
601 SE
= MBB
->succ_end(); SI
!= SE
; ++SI
) {
602 MachineBasicBlock
*SuccMBB
= *SI
;
603 if (SuccMBB
->isEHPad())
605 for (const auto &LI
: SuccMBB
->liveins()) {
606 if (!TRI
->isInAllocatableClass(LI
.PhysReg
))
607 // Ignore other live-ins, e.g. those that are live into landing pads.
608 LiveOuts
.insert(LI
.PhysReg
);
612 // Loop over PhysRegDef / PhysRegUse, killing any registers that are
613 // available at the end of the basic block.
614 for (unsigned i
= 0; i
!= NumRegs
; ++i
)
615 if ((PhysRegDef
[i
] || PhysRegUse
[i
]) && !LiveOuts
.count(i
))
616 HandlePhysRegDef(i
, nullptr, Defs
);
619 bool LiveVariables::runOnMachineFunction(MachineFunction
&mf
) {
621 MRI
= &mf
.getRegInfo();
622 TRI
= MF
->getSubtarget().getRegisterInfo();
624 const unsigned NumRegs
= TRI
->getNumRegs();
625 PhysRegDef
.assign(NumRegs
, nullptr);
626 PhysRegUse
.assign(NumRegs
, nullptr);
627 PHIVarInfo
.resize(MF
->getNumBlockIDs());
630 // FIXME: LiveIntervals will be updated to remove its dependence on
631 // LiveVariables to improve compilation time and eliminate bizarre pass
632 // dependencies. Until then, we can't change much in -O0.
634 report_fatal_error("regalloc=... not currently supported with -O0");
638 // Calculate live variable information in depth first order on the CFG of the
639 // function. This guarantees that we will see the definition of a virtual
640 // register before its uses due to dominance properties of SSA (except for PHI
641 // nodes, which are treated as a special case).
642 MachineBasicBlock
*Entry
= &MF
->front();
643 df_iterator_default_set
<MachineBasicBlock
*,16> Visited
;
645 for (MachineBasicBlock
*MBB
: depth_first_ext(Entry
, Visited
)) {
646 runOnBlock(MBB
, NumRegs
);
648 PhysRegDef
.assign(NumRegs
, nullptr);
649 PhysRegUse
.assign(NumRegs
, nullptr);
652 // Convert and transfer the dead / killed information we have gathered into
653 // VirtRegInfo onto MI's.
654 for (unsigned i
= 0, e1
= VirtRegInfo
.size(); i
!= e1
; ++i
) {
655 const unsigned Reg
= Register::index2VirtReg(i
);
656 for (unsigned j
= 0, e2
= VirtRegInfo
[Reg
].Kills
.size(); j
!= e2
; ++j
)
657 if (VirtRegInfo
[Reg
].Kills
[j
] == MRI
->getVRegDef(Reg
))
658 VirtRegInfo
[Reg
].Kills
[j
]->addRegisterDead(Reg
, TRI
);
660 VirtRegInfo
[Reg
].Kills
[j
]->addRegisterKilled(Reg
, TRI
);
663 // Check to make sure there are no unreachable blocks in the MC CFG for the
664 // function. If so, it is due to a bug in the instruction selector or some
665 // other part of the code generator if this happens.
667 for(MachineFunction::iterator i
= MF
->begin(), e
= MF
->end(); i
!= e
; ++i
)
668 assert(Visited
.count(&*i
) != 0 && "unreachable basic block found");
678 /// replaceKillInstruction - Update register kill info by replacing a kill
679 /// instruction with a new one.
680 void LiveVariables::replaceKillInstruction(unsigned Reg
, MachineInstr
&OldMI
,
681 MachineInstr
&NewMI
) {
682 VarInfo
&VI
= getVarInfo(Reg
);
683 std::replace(VI
.Kills
.begin(), VI
.Kills
.end(), &OldMI
, &NewMI
);
686 /// removeVirtualRegistersKilled - Remove all killed info for the specified
688 void LiveVariables::removeVirtualRegistersKilled(MachineInstr
&MI
) {
689 for (unsigned i
= 0, e
= MI
.getNumOperands(); i
!= e
; ++i
) {
690 MachineOperand
&MO
= MI
.getOperand(i
);
691 if (MO
.isReg() && MO
.isKill()) {
693 Register Reg
= MO
.getReg();
694 if (Register::isVirtualRegister(Reg
)) {
695 bool removed
= getVarInfo(Reg
).removeKill(MI
);
696 assert(removed
&& "kill not in register's VarInfo?");
703 /// analyzePHINodes - Gather information about the PHI nodes in here. In
704 /// particular, we want to map the variable information of a virtual register
705 /// which is used in a PHI node. We map that to the BB the vreg is coming from.
707 void LiveVariables::analyzePHINodes(const MachineFunction
& Fn
) {
708 for (const auto &MBB
: Fn
)
709 for (const auto &BBI
: MBB
) {
712 for (unsigned i
= 1, e
= BBI
.getNumOperands(); i
!= e
; i
+= 2)
713 if (BBI
.getOperand(i
).readsReg())
714 PHIVarInfo
[BBI
.getOperand(i
+ 1).getMBB()->getNumber()]
715 .push_back(BBI
.getOperand(i
).getReg());
719 bool LiveVariables::VarInfo::isLiveIn(const MachineBasicBlock
&MBB
,
721 MachineRegisterInfo
&MRI
) {
722 unsigned Num
= MBB
.getNumber();
724 // Reg is live-through.
725 if (AliveBlocks
.test(Num
))
728 // Registers defined in MBB cannot be live in.
729 const MachineInstr
*Def
= MRI
.getVRegDef(Reg
);
730 if (Def
&& Def
->getParent() == &MBB
)
733 // Reg was not defined in MBB, was it killed here?
734 return findKill(&MBB
);
737 bool LiveVariables::isLiveOut(unsigned Reg
, const MachineBasicBlock
&MBB
) {
738 LiveVariables::VarInfo
&VI
= getVarInfo(Reg
);
740 SmallPtrSet
<const MachineBasicBlock
*, 8> Kills
;
741 for (unsigned i
= 0, e
= VI
.Kills
.size(); i
!= e
; ++i
)
742 Kills
.insert(VI
.Kills
[i
]->getParent());
744 // Loop over all of the successors of the basic block, checking to see if
745 // the value is either live in the block, or if it is killed in the block.
746 for (const MachineBasicBlock
*SuccMBB
: MBB
.successors()) {
747 // Is it alive in this successor?
748 unsigned SuccIdx
= SuccMBB
->getNumber();
749 if (VI
.AliveBlocks
.test(SuccIdx
))
751 // Or is it live because there is a use in a successor that kills it?
752 if (Kills
.count(SuccMBB
))
759 /// addNewBlock - Add a new basic block BB as an empty succcessor to DomBB. All
760 /// variables that are live out of DomBB will be marked as passing live through
762 void LiveVariables::addNewBlock(MachineBasicBlock
*BB
,
763 MachineBasicBlock
*DomBB
,
764 MachineBasicBlock
*SuccBB
) {
765 const unsigned NumNew
= BB
->getNumber();
767 DenseSet
<unsigned> Defs
, Kills
;
769 MachineBasicBlock::iterator BBI
= SuccBB
->begin(), BBE
= SuccBB
->end();
770 for (; BBI
!= BBE
&& BBI
->isPHI(); ++BBI
) {
771 // Record the def of the PHI node.
772 Defs
.insert(BBI
->getOperand(0).getReg());
774 // All registers used by PHI nodes in SuccBB must be live through BB.
775 for (unsigned i
= 1, e
= BBI
->getNumOperands(); i
!= e
; i
+= 2)
776 if (BBI
->getOperand(i
+1).getMBB() == BB
)
777 getVarInfo(BBI
->getOperand(i
).getReg()).AliveBlocks
.set(NumNew
);
780 // Record all vreg defs and kills of all instructions in SuccBB.
781 for (; BBI
!= BBE
; ++BBI
) {
782 for (MachineInstr::mop_iterator I
= BBI
->operands_begin(),
783 E
= BBI
->operands_end(); I
!= E
; ++I
) {
784 if (I
->isReg() && Register::isVirtualRegister(I
->getReg())) {
786 Defs
.insert(I
->getReg());
787 else if (I
->isKill())
788 Kills
.insert(I
->getReg());
793 // Update info for all live variables
794 for (unsigned i
= 0, e
= MRI
->getNumVirtRegs(); i
!= e
; ++i
) {
795 unsigned Reg
= Register::index2VirtReg(i
);
797 // If the Defs is defined in the successor it can't be live in BB.
801 // If the register is either killed in or live through SuccBB it's also live
803 VarInfo
&VI
= getVarInfo(Reg
);
804 if (Kills
.count(Reg
) || VI
.AliveBlocks
.test(SuccBB
->getNumber()))
805 VI
.AliveBlocks
.set(NumNew
);