LLVM 22.0.0git
MachineInstrBundle.cpp
Go to the documentation of this file.
1//===-- lib/CodeGen/MachineInstrBundle.cpp --------------------------------===//
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
10#include "llvm/ADT/SetVector.h"
11#include "llvm/ADT/SmallSet.h"
15#include "llvm/CodeGen/Passes.h"
20#include "llvm/Pass.h"
21#include "llvm/PassRegistry.h"
22#include <utility>
23using namespace llvm;
24
25namespace {
26 class UnpackMachineBundles : public MachineFunctionPass {
27 public:
28 static char ID; // Pass identification
29 UnpackMachineBundles(
30 std::function<bool(const MachineFunction &)> Ftor = nullptr)
31 : MachineFunctionPass(ID), PredicateFtor(std::move(Ftor)) {
33 }
34
35 bool runOnMachineFunction(MachineFunction &MF) override;
36
37 private:
38 std::function<bool(const MachineFunction &)> PredicateFtor;
39 };
40} // end anonymous namespace
41
42char UnpackMachineBundles::ID = 0;
43char &llvm::UnpackMachineBundlesID = UnpackMachineBundles::ID;
44INITIALIZE_PASS(UnpackMachineBundles, "unpack-mi-bundles",
45 "Unpack machine instruction bundles", false, false)
46
47bool UnpackMachineBundles::runOnMachineFunction(MachineFunction &MF) {
48 if (PredicateFtor && !PredicateFtor(MF))
49 return false;
50
51 bool Changed = false;
52 for (MachineBasicBlock &MBB : MF) {
54 MIE = MBB.instr_end(); MII != MIE; ) {
55 MachineInstr *MI = &*MII;
56
57 // Remove BUNDLE instruction and the InsideBundle flags from bundled
58 // instructions.
59 if (MI->isBundle()) {
60 while (++MII != MIE && MII->isBundledWithPred()) {
61 MII->unbundleFromPred();
62 for (MachineOperand &MO : MII->operands()) {
63 if (MO.isReg() && MO.isInternalRead())
64 MO.setIsInternalRead(false);
65 }
66 }
67 MI->eraseFromParent();
68
69 Changed = true;
70 continue;
71 }
72
73 ++MII;
74 }
75 }
76
77 return Changed;
78}
79
82 std::function<bool(const MachineFunction &)> Ftor) {
83 return new UnpackMachineBundles(std::move(Ftor));
84}
85
86/// Return the first found DebugLoc that has a DILocation, given a range of
87/// instructions. The search range is from FirstMI to LastMI (exclusive). If no
88/// DILocation is found, then an empty location is returned.
91 for (auto MII = FirstMI; MII != LastMI; ++MII)
92 if (MII->getDebugLoc())
93 return MII->getDebugLoc();
94 return DebugLoc();
95}
96
97/// Check if target reg is contained in given lists, which are:
98/// LocalDefsV as given list for virtual regs
99/// LocalDefsP as given list for physical regs, in BitVector[RegUnit] form
101 const BitVector &LocalDefsP, Register Reg,
102 const TargetRegisterInfo *TRI) {
103 if (Reg.isPhysical()) {
104 for (MCRegUnit Unit : TRI->regunits(Reg.asMCReg()))
105 if (!LocalDefsP[Unit])
106 return false;
107
108 return true;
109 }
110 return LocalDefsV.contains(Reg);
111}
112
113/// finalizeBundle - Finalize a machine instruction bundle which includes
114/// a sequence of instructions starting from FirstMI to LastMI (exclusive).
115/// This routine adds a BUNDLE instruction to represent the bundle, it adds
116/// IsInternalRead markers to MachineOperands which are defined inside the
117/// bundle, and it copies externally visible defs and uses to the BUNDLE
118/// instruction.
122 assert(FirstMI != LastMI && "Empty bundle?");
123 MIBundleBuilder Bundle(MBB, FirstMI, LastMI);
124
128
130 BuildMI(MF, getDebugLoc(FirstMI, LastMI), TII->get(TargetOpcode::BUNDLE));
131 Bundle.prepend(MIB);
132
134 BitVector LocalDefsP(TRI->getNumRegUnits());
135 SmallSet<Register, 8> DeadDefSet;
136 SmallSet<Register, 16> KilledDefSet;
138 SmallSet<Register, 8> KilledUseSet;
139 SmallSet<Register, 8> UndefUseSet;
140 for (auto MII = FirstMI; MII != LastMI; ++MII) {
141 // Debug instructions have no effects to track.
142 if (MII->isDebugInstr())
143 continue;
144
145 for (MachineOperand &MO : MII->all_uses()) {
146 Register Reg = MO.getReg();
147 if (!Reg)
148 continue;
149
150 if (containsReg(LocalDefs, LocalDefsP, Reg, TRI)) {
151 MO.setIsInternalRead();
152 if (MO.isKill()) {
153 // Internal def is now killed.
154 KilledDefSet.insert(Reg);
155 }
156 } else {
157 if (ExternUses.insert(Reg)) {
158 if (MO.isUndef())
159 UndefUseSet.insert(Reg);
160 }
161 if (MO.isKill()) {
162 // External def is now killed.
163 KilledUseSet.insert(Reg);
164 }
165 }
166 }
167
168 for (MachineOperand &MO : MII->all_defs()) {
169 Register Reg = MO.getReg();
170 if (!Reg)
171 continue;
172
173 if (LocalDefs.insert(Reg)) {
174 if (MO.isDead())
175 DeadDefSet.insert(Reg);
176 else if (Reg.isPhysical())
177 for (MCRegUnit Unit : TRI->regunits(Reg.asMCReg()))
178 LocalDefsP.set(Unit);
179 } else {
180 // Re-defined inside the bundle, it's no longer killed.
181 KilledDefSet.erase(Reg);
182 if (!MO.isDead()) {
183 // Previously defined but dead.
184 DeadDefSet.erase(Reg);
185 }
186 }
187 }
188
189 // Set FrameSetup/FrameDestroy for the bundle. If any of the instructions
190 // got the property, then also set it on the bundle.
191 if (MII->getFlag(MachineInstr::FrameSetup))
193 if (MII->getFlag(MachineInstr::FrameDestroy))
195 }
196
197 for (Register Reg : LocalDefs) {
198 // If it's not live beyond end of the bundle, mark it dead.
199 bool isDead = DeadDefSet.contains(Reg) || KilledDefSet.contains(Reg);
200 MIB.addReg(Reg, getDefRegState(true) | getDeadRegState(isDead) |
201 getImplRegState(true));
202 }
203
204 for (Register Reg : ExternUses) {
205 bool isKill = KilledUseSet.contains(Reg);
206 bool isUndef = UndefUseSet.contains(Reg);
207 MIB.addReg(Reg, getKillRegState(isKill) | getUndefRegState(isUndef) |
208 getImplRegState(true));
209 }
210}
211
212/// finalizeBundle - Same functionality as the previous finalizeBundle except
213/// the last instruction in the bundle is not provided as an input. This is
214/// used in cases where bundles are pre-determined by marking instructions
215/// with 'InsideBundle' marker. It returns the MBB instruction iterator that
216/// points to the end of the bundle.
221 MachineBasicBlock::instr_iterator LastMI = std::next(FirstMI);
222 while (LastMI != E && LastMI->isInsideBundle())
223 ++LastMI;
224 finalizeBundle(MBB, FirstMI, LastMI);
225 return LastMI;
226}
227
228/// finalizeBundles - Finalize instruction bundles in the specified
229/// MachineFunction. Return true if any bundles are finalized.
231 bool Changed = false;
232 for (MachineBasicBlock &MBB : MF) {
235 if (MII == MIE)
236 continue;
237 assert(!MII->isInsideBundle() &&
238 "First instr cannot be inside bundle before finalization!");
239
240 for (++MII; MII != MIE; ) {
241 if (!MII->isInsideBundle())
242 ++MII;
243 else {
244 MII = finalizeBundle(MBB, std::prev(MII));
245 Changed = true;
246 }
247 }
248 }
249
250 return Changed;
251}
252
255 SmallVectorImpl<std::pair<MachineInstr *, unsigned>> *Ops) {
256 VirtRegInfo RI = {false, false, false};
257 for (MIBundleOperands O(MI); O.isValid(); ++O) {
258 MachineOperand &MO = *O;
259 if (!MO.isReg() || MO.getReg() != Reg)
260 continue;
261
262 // Remember each (MI, OpNo) that refers to Reg.
263 if (Ops)
264 Ops->push_back(std::make_pair(MO.getParent(), O.getOperandNo()));
265
266 // Both defs and uses can read virtual registers.
267 if (MO.readsReg()) {
268 RI.Reads = true;
269 if (MO.isDef())
270 RI.Tied = true;
271 }
272
273 // Only defs can write.
274 if (MO.isDef())
275 RI.Writes = true;
276 else if (!RI.Tied &&
277 MO.getParent()->isRegTiedToDefOperand(O.getOperandNo()))
278 RI.Tied = true;
279 }
280 return RI;
281}
282
283std::pair<LaneBitmask, LaneBitmask>
286 const TargetRegisterInfo &TRI) {
287
288 LaneBitmask UseMask, DefMask;
289
290 for (const MachineOperand &MO : const_mi_bundle_ops(MI)) {
291 if (!MO.isReg() || MO.getReg() != Reg)
292 continue;
293
294 unsigned SubReg = MO.getSubReg();
295 if (SubReg == 0 && MO.isUse() && !MO.isUndef())
296 UseMask |= MRI.getMaxLaneMaskForVReg(Reg);
297
298 LaneBitmask SubRegMask = TRI.getSubRegIndexLaneMask(SubReg);
299 if (MO.isDef()) {
300 if (!MO.isUndef())
301 UseMask |= ~SubRegMask;
302 DefMask |= SubRegMask;
303 } else if (!MO.isUndef())
304 UseMask |= SubRegMask;
305 }
306
307 return {UseMask, DefMask};
308}
309
311 const TargetRegisterInfo *TRI) {
312 bool AllDefsDead = true;
313 PhysRegInfo PRI = {false, false, false, false, false, false, false, false};
314
315 assert(Reg.isPhysical() && "analyzePhysReg not given a physical register!");
316 for (const MachineOperand &MO : const_mi_bundle_ops(MI)) {
317 if (MO.isRegMask() && MO.clobbersPhysReg(Reg)) {
318 PRI.Clobbered = true;
319 continue;
320 }
321
322 if (!MO.isReg())
323 continue;
324
325 Register MOReg = MO.getReg();
326 if (!MOReg || !MOReg.isPhysical())
327 continue;
328
329 if (!TRI->regsOverlap(MOReg, Reg))
330 continue;
331
332 bool Covered = TRI->isSuperRegisterEq(Reg, MOReg);
333 if (MO.readsReg()) {
334 PRI.Read = true;
335 if (Covered) {
336 PRI.FullyRead = true;
337 if (MO.isKill())
338 PRI.Killed = true;
339 }
340 } else if (MO.isDef()) {
341 PRI.Defined = true;
342 if (Covered)
343 PRI.FullyDefined = true;
344 if (!MO.isDead())
345 AllDefsDead = false;
346 }
347 }
348
349 if (AllDefsDead) {
350 if (PRI.FullyDefined || PRI.Clobbered)
351 PRI.DeadDef = true;
352 else if (PRI.Defined)
353 PRI.PartialDeadDef = true;
354 }
355
356 return PRI;
357}
358
362 // For testing purposes, bundle the entire contents of each basic block
363 // except for terminators.
364 for (MachineBasicBlock &MBB : MF)
367}
unsigned SubReg
unsigned const MachineRegisterInfo * MRI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
static bool containsReg(SmallSetVector< Register, 32 > LocalDefsV, const BitVector &LocalDefsP, Register Reg, const TargetRegisterInfo *TRI)
Check if target reg is contained in given lists, which are: LocalDefsV as given list for virtual regs...
static DebugLoc getDebugLoc(MachineBasicBlock::instr_iterator FirstMI, MachineBasicBlock::instr_iterator LastMI)
Return the first found DebugLoc that has a DILocation, given a range of instructions.
static bool isUndef(const MachineInstr &MI)
Register const TargetRegisterInfo * TRI
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:56
bool isDead(const MachineInstr &MI, const MachineRegisterInfo &MRI)
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallSet class.
This file defines the SmallVector class.
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:255
BitVector & set()
Definition: BitVector.h:351
A debug info location.
Definition: DebugLoc.h:124
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:314
Helper class for constructing bundles of MachineInstrs.
MIBundleBuilder & prepend(MachineInstr *MI)
Insert MI into MBB by prepending it to the instructions in the bundle.
MIBundleOperands - Iterate over all operands in a bundle of machine instructions.
instr_iterator instr_begin()
Instructions::iterator instr_iterator
instr_iterator instr_end()
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
LLVM_ABI instr_iterator getFirstInstrTerminator()
Same getFirstTerminator but it ignores bundles and return an instr_iterator instead.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
virtual bool runOnMachineFunction(MachineFunction &MF)=0
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
const MachineInstrBuilder & setMIFlag(MachineInstr::MIFlag Flag) const
const MachineInstrBuilder & addReg(Register RegNo, unsigned flags=0, unsigned SubReg=0) const
Add a new virtual register operand.
Representation of each machine instruction.
Definition: MachineInstr.h:72
bool isRegTiedToDefOperand(unsigned UseOpIdx, unsigned *DefOpIdx=nullptr) const
Return true if the use operand of the specified index is tied to a def operand.
MachineOperand class - Representation of each machine instruction operand.
bool readsReg() const
readsReg - Returns true if this operand reads the previous value of its register.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
Register getReg() const
getReg - Returns the register number.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
A set of analyses that are preserved following a run of a transformation pass.
Definition: Analysis.h:112
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition: Analysis.h:115
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition: Register.h:78
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition: SetVector.h:168
bool contains(const key_type &key) const
Check if the SetVector contains the given key.
Definition: SetVector.h:269
A SetVector that performs no allocations if smaller than a certain size.
Definition: SetVector.h:356
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition: SmallSet.h:134
bool erase(const T &V)
Definition: SmallSet.h:198
bool contains(const T &V) const
Check if the SmallSet contains the given element.
Definition: SmallSet.h:227
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition: SmallSet.h:182
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:574
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.
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.
Definition: AddressRanges.h:18
LLVM_ABI void finalizeBundle(MachineBasicBlock &MBB, MachineBasicBlock::instr_iterator FirstMI, MachineBasicBlock::instr_iterator LastMI)
finalizeBundle - Finalize a machine instruction bundle which includes a sequence of instructions star...
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
LLVM_ABI bool finalizeBundles(MachineFunction &MF)
finalizeBundles - Finalize instruction bundles in the specified MachineFunction.
LLVM_ABI PhysRegInfo AnalyzePhysRegInBundle(const MachineInstr &MI, Register Reg, const TargetRegisterInfo *TRI)
AnalyzePhysRegInBundle - Analyze how the current instruction or bundle uses a physical register.
unsigned getDeadRegState(bool B)
unsigned getImplRegState(bool B)
iterator_range< ConstMIBundleOperands > const_mi_bundle_ops(const MachineInstr &MI)
LLVM_ABI VirtRegInfo AnalyzeVirtRegInBundle(MachineInstr &MI, Register Reg, SmallVectorImpl< std::pair< MachineInstr *, unsigned > > *Ops=nullptr)
AnalyzeVirtRegInBundle - Analyze how the current instruction or bundle uses a virtual register.
unsigned getUndefRegState(bool B)
unsigned getDefRegState(bool B)
unsigned getKillRegState(bool B)
LLVM_ABI FunctionPass * createUnpackMachineBundles(std::function< bool(const MachineFunction &)> Ftor)
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1886
LLVM_ABI void initializeUnpackMachineBundlesPass(PassRegistry &)
LLVM_ABI char & UnpackMachineBundlesID
UnpackMachineBundles - This pass unpack machine instruction bundles.
LLVM_ABI std::pair< LaneBitmask, LaneBitmask > AnalyzeVirtRegLanesInBundle(const MachineInstr &MI, Register Reg, const MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI)
Return a pair of lane masks (reads, writes) indicating which lanes this instruction uses with Reg.
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:856
Information about how a physical register Reg is used by a set of operands.
bool Read
Reg or one of its aliases is read.
bool Defined
Reg or one of its aliases is defined.
bool Killed
There is a use operand of reg or a super-register with kill flag set.
bool PartialDeadDef
Reg is Defined and all defs of reg or an overlapping register are dead.
bool Clobbered
There is a regmask operand indicating Reg is clobbered.
bool FullyRead
Reg or a super-register is read. The full register is read.
bool FullyDefined
Reg or a super-register is defined.
VirtRegInfo - Information about a virtual register used by a set of operands.
bool Reads
Reads - One of the operands read the virtual register.
bool Tied
Tied - Uses and defs must use the same register.
bool Writes
Writes - One of the operands writes the virtual register.