LLVM 23.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)) {}
32
33 bool runOnMachineFunction(MachineFunction &MF) override;
34
35 private:
36 std::function<bool(const MachineFunction &)> PredicateFtor;
37 };
38} // end anonymous namespace
39
40char UnpackMachineBundles::ID = 0;
41char &llvm::UnpackMachineBundlesID = UnpackMachineBundles::ID;
42INITIALIZE_PASS(UnpackMachineBundles, "unpack-mi-bundles",
43 "Unpack machine instruction bundles", false, false)
44
45bool UnpackMachineBundles::runOnMachineFunction(MachineFunction &MF) {
46 if (PredicateFtor && !PredicateFtor(MF))
47 return false;
48
49 bool Changed = false;
50 for (MachineBasicBlock &MBB : MF) {
51 for (MachineBasicBlock::instr_iterator MII = MBB.instr_begin(),
52 MIE = MBB.instr_end(); MII != MIE; ) {
53 MachineInstr *MI = &*MII;
54
55 // Remove BUNDLE instruction and the InsideBundle flags from bundled
56 // instructions.
57 if (MI->isBundle()) {
58 while (++MII != MIE && MII->isBundledWithPred()) {
59 MII->unbundleFromPred();
60 for (MachineOperand &MO : MII->operands()) {
61 if (MO.isReg() && MO.isInternalRead())
62 MO.setIsInternalRead(false);
63 }
64 }
65 MI->eraseFromParent();
66
67 Changed = true;
68 continue;
69 }
70
71 ++MII;
72 }
73 }
74
75 return Changed;
76}
77
80 std::function<bool(const MachineFunction &)> Ftor) {
81 return new UnpackMachineBundles(std::move(Ftor));
82}
83
84/// Return the first DebugLoc that has line number information, given a
85/// range of instructions. The search range is from FirstMI to LastMI
86/// (exclusive). Otherwise return the first DILocation or an empty location if
87/// there are none.
91 for (auto MII = FirstMI; MII != LastMI; ++MII) {
92 if (DebugLoc MIIDL = MII->getDebugLoc()) {
93 if (MIIDL.getLine() != 0)
94 return MIIDL;
95 DL = MIIDL.get();
96 }
97 }
98 return DL;
99}
100
101/// Check if target reg is contained in given lists, which are:
102/// LocalDefsV as given list for virtual regs
103/// LocalDefsP as given list for physical regs, in BitVector[RegUnit] form
105 const BitVector &LocalDefsP, Register Reg,
106 const TargetRegisterInfo *TRI) {
107 if (Reg.isPhysical()) {
108 for (MCRegUnit Unit : TRI->regunits(Reg.asMCReg()))
109 if (!LocalDefsP[static_cast<unsigned>(Unit)])
110 return false;
111
112 return true;
113 }
114 return LocalDefsV.contains(Reg);
115}
116
117/// finalizeBundle - Finalize a machine instruction bundle which includes
118/// a sequence of instructions starting from FirstMI to LastMI (exclusive).
119/// This routine adds a BUNDLE instruction to represent the bundle, it adds
120/// IsInternalRead markers to MachineOperands which are defined inside the
121/// bundle, and it copies externally visible defs and uses to the BUNDLE
122/// instruction.
126 assert(FirstMI != LastMI && "Empty bundle?");
127 MIBundleBuilder Bundle(MBB, FirstMI, LastMI);
128
129 MachineFunction &MF = *MBB.getParent();
132
134 BuildMI(MF, getDebugLoc(FirstMI, LastMI), TII->get(TargetOpcode::BUNDLE));
135 Bundle.prepend(MIB);
136
138 BitVector LocalDefsP(TRI->getNumRegUnits());
139 SmallSet<Register, 8> DeadDefSet;
141 SmallSet<Register, 8> KilledUseSet;
142 SmallSet<Register, 8> UndefUseSet;
145 for (auto MII = FirstMI; MII != LastMI; ++MII) {
146 // Debug instructions have no effects to track.
147 if (MII->isDebugInstr())
148 continue;
149
150 for (MachineOperand &MO : MII->all_uses()) {
151 Register Reg = MO.getReg();
152 if (!Reg)
153 continue;
154
155 if (containsReg(LocalDefs, LocalDefsP, Reg, TRI)) {
156 MO.setIsInternalRead();
157 if (MO.isKill()) {
158 // Internal def is now killed.
159 DeadDefSet.insert(Reg);
160 }
161 } else {
162 if (ExternUses.insert(Reg)) {
163 if (MO.isUndef())
164 UndefUseSet.insert(Reg);
165 }
166 if (MO.isKill()) {
167 // External def is now killed.
168 KilledUseSet.insert(Reg);
169 }
170 if (MO.isTied() && Reg.isVirtual()) {
171 // Record tied operand constraints that involve virtual registers so
172 // that bundles that are formed pre-register allocation reflect the
173 // relevant constraints.
174 unsigned TiedIdx = MII->findTiedOperandIdx(MO.getOperandNo());
175 MachineOperand &TiedMO = MII->getOperand(TiedIdx);
176 Register DefReg = TiedMO.getReg();
177 TiedOperands.emplace_back(DefReg, Reg);
178 }
179 }
180 }
181
182 for (MachineOperand &MO : MII->all_defs()) {
183 Register Reg = MO.getReg();
184 if (!Reg)
185 continue;
186
187 if (LocalDefs.insert(Reg)) {
188 if (!MO.isDead() && Reg.isPhysical()) {
189 for (MCRegUnit Unit : TRI->regunits(Reg.asMCReg()))
190 LocalDefsP.set(static_cast<unsigned>(Unit));
191 }
192 } else {
193 if (!MO.isDead()) {
194 // Re-defined inside the bundle, it's no longer dead.
195 DeadDefSet.erase(Reg);
196 }
197 }
198 if (MO.isDead())
199 DeadDefSet.insert(Reg);
200 }
201
202 // Set FrameSetup/FrameDestroy for the bundle. If any of the instructions
203 // got the property, then also set it on the bundle.
204 if (MII->getFlag(MachineInstr::FrameSetup))
206 if (MII->getFlag(MachineInstr::FrameDestroy))
208
209 if (MII->mayLoadOrStore())
210 MemMIs.push_back(&*MII);
211 }
212
213 for (Register Reg : LocalDefs) {
214 // If it's not live beyond end of the bundle, mark it dead.
215 bool isDead = DeadDefSet.contains(Reg);
216 MIB.addReg(Reg, getDefRegState(true) | getDeadRegState(isDead) |
217 getImplRegState(true));
218 }
219
220 for (Register Reg : ExternUses) {
221 bool isKill = KilledUseSet.contains(Reg);
222 bool isUndef = UndefUseSet.contains(Reg);
223 MIB.addReg(Reg, getKillRegState(isKill) | getUndefRegState(isUndef) |
224 getImplRegState(true));
225 }
226
227 for (auto [DefReg, UseReg] : TiedOperands) {
228 unsigned DefIdx =
229 std::distance(LocalDefs.begin(), llvm::find(LocalDefs, DefReg));
230 unsigned UseIdx =
231 std::distance(ExternUses.begin(), llvm::find(ExternUses, UseReg));
232 assert(DefIdx < LocalDefs.size());
233 assert(UseIdx < ExternUses.size());
234 MIB->tieOperands(DefIdx, LocalDefs.size() + UseIdx);
235 }
236
237 MIB->cloneMergedMemRefs(MF, MemMIs);
238}
239
240/// finalizeBundle - Same functionality as the previous finalizeBundle except
241/// the last instruction in the bundle is not provided as an input. This is
242/// used in cases where bundles are pre-determined by marking instructions
243/// with 'InsideBundle' marker. It returns the MBB instruction iterator that
244/// points to the end of the bundle.
249 MachineBasicBlock::instr_iterator LastMI = std::next(FirstMI);
250 while (LastMI != E && LastMI->isInsideBundle())
251 ++LastMI;
252 finalizeBundle(MBB, FirstMI, LastMI);
253 return LastMI;
254}
255
256/// finalizeBundles - Finalize instruction bundles in the specified
257/// MachineFunction. Return true if any bundles are finalized.
259 bool Changed = false;
260 for (MachineBasicBlock &MBB : MF) {
261 MachineBasicBlock::instr_iterator MII = MBB.instr_begin();
262 MachineBasicBlock::instr_iterator MIE = MBB.instr_end();
263 if (MII == MIE)
264 continue;
265 assert(!MII->isInsideBundle() &&
266 "First instr cannot be inside bundle before finalization!");
267
268 for (++MII; MII != MIE; ) {
269 if (!MII->isInsideBundle())
270 ++MII;
271 else {
272 MII = finalizeBundle(MBB, std::prev(MII));
273 Changed = true;
274 }
275 }
276 }
277
278 return Changed;
279}
280
283 SmallVectorImpl<std::pair<MachineInstr *, unsigned>> *Ops) {
284 VirtRegInfo RI = {false, false, false};
285 for (MIBundleOperands O(MI); O.isValid(); ++O) {
286 MachineOperand &MO = *O;
287 if (!MO.isReg() || MO.getReg() != Reg)
288 continue;
289
290 // Remember each (MI, OpNo) that refers to Reg.
291 if (Ops)
292 Ops->push_back(std::make_pair(MO.getParent(), O.getOperandNo()));
293
294 // Both defs and uses can read virtual registers.
295 if (MO.readsReg()) {
296 RI.Reads = true;
297 if (MO.isDef())
298 RI.Tied = true;
299 }
300
301 // Only defs can write.
302 if (MO.isDef())
303 RI.Writes = true;
304 else if (!RI.Tied &&
305 MO.getParent()->isRegTiedToDefOperand(O.getOperandNo()))
306 RI.Tied = true;
307 }
308 return RI;
309}
310
311std::pair<LaneBitmask, LaneBitmask>
314 const TargetRegisterInfo &TRI) {
315
316 LaneBitmask UseMask, DefMask;
317
318 for (const MachineOperand &MO : const_mi_bundle_ops(MI)) {
319 if (!MO.isReg() || MO.getReg() != Reg)
320 continue;
321
322 unsigned SubReg = MO.getSubReg();
323 if (SubReg == 0 && MO.isUse() && !MO.isUndef())
324 UseMask |= MRI.getMaxLaneMaskForVReg(Reg);
325
326 LaneBitmask SubRegMask = TRI.getSubRegIndexLaneMask(SubReg);
327 if (MO.isDef()) {
328 if (!MO.isUndef())
329 UseMask |= ~SubRegMask;
330 DefMask |= SubRegMask;
331 } else if (!MO.isUndef())
332 UseMask |= SubRegMask;
333 }
334
335 return {UseMask, DefMask};
336}
337
339 const TargetRegisterInfo *TRI) {
340 bool AllDefsDead = true;
341 PhysRegInfo PRI = {false, false, false, false, false, false, false, false};
342
343 assert(Reg.isPhysical() && "analyzePhysReg not given a physical register!");
344 for (const MachineOperand &MO : const_mi_bundle_ops(MI)) {
345 if (MO.isRegMask() && MO.clobbersPhysReg(Reg)) {
346 PRI.Clobbered = true;
347 continue;
348 }
349
350 if (!MO.isReg())
351 continue;
352
353 Register MOReg = MO.getReg();
354 if (!MOReg || !MOReg.isPhysical())
355 continue;
356
357 if (!TRI->regsOverlap(MOReg, Reg))
358 continue;
359
360 bool Covered = TRI->isSuperRegisterEq(Reg, MOReg);
361 if (MO.readsReg()) {
362 PRI.Read = true;
363 if (Covered) {
364 PRI.FullyRead = true;
365 if (MO.isKill())
366 PRI.Killed = true;
367 }
368 } else if (MO.isDef()) {
369 PRI.Defined = true;
370 if (Covered)
371 PRI.FullyDefined = true;
372 if (!MO.isDead())
373 AllDefsDead = false;
374 }
375 }
376
377 if (AllDefsDead) {
378 if (PRI.FullyDefined || PRI.Clobbered)
379 PRI.DeadDef = true;
380 else if (PRI.Defined)
381 PRI.PartialDeadDef = true;
382 }
383
384 return PRI;
385}
386
390 // For testing purposes, bundle the entire contents of each basic block
391 // except for terminators.
392 for (MachineBasicBlock &MBB : MF)
393 finalizeBundle(MBB, MBB.instr_begin(), MBB.getFirstInstrTerminator());
395}
unsigned SubReg
unsigned const MachineRegisterInfo * MRI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static Register UseReg(const MachineOperand &MO)
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
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 DebugLoc that has line number information, given a range of instructions.
static bool isUndef(const MachineInstr &MI)
Register Reg
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.
BitVector & set()
Definition BitVector.h:370
A debug info location.
Definition DebugLoc.h:123
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.
Instructions::iterator instr_iterator
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & setMIFlag(MachineInstr::MIFlag Flag) const
Representation of each machine instruction.
bool isRegTiedToDefOperand(unsigned UseOpIdx, unsigned *DefOpIdx=nullptr) const
Return true if the use operand of the specified index is tied to a def operand.
LLVM_ABI void cloneMergedMemRefs(MachineFunction &MF, ArrayRef< const MachineInstr * > MIs)
Clone the merge of multiple MachineInstrs' memory reference descriptors list and replace ours with it...
LLVM_ABI void tieOperands(unsigned DefIdx, unsigned UseIdx)
Add a tie between the register operands at DefIdx and UseIdx.
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,...
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition Register.h:83
size_type size() const
Determine the number of elements in the SetVector.
Definition SetVector.h:103
bool contains(const_arg_type key) const
Check if the SetVector contains the given key.
Definition SetVector.h:252
iterator begin()
Get an iterator to the beginning of the SetVector.
Definition SetVector.h:106
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:151
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:339
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition SmallSet.h:133
bool erase(const T &V)
Definition SmallSet.h:199
bool contains(const T &V) const
Check if the SmallSet contains the given element.
Definition SmallSet.h:228
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:183
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
TargetInstrInfo - Interface to description of machine instruction set.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
Changed
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
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...
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1763
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
constexpr RegState getImplRegState(bool B)
constexpr RegState getKillRegState(bool B)
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.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
constexpr RegState getDeadRegState(bool B)
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
constexpr RegState getDefRegState(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.
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:1915
constexpr RegState getUndefRegState(bool B)
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.
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.