LLVM  10.0.0
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/SmallSet.h"
11 #include "llvm/ADT/SmallVector.h"
14 #include "llvm/CodeGen/Passes.h"
18 #include "llvm/InitializePasses.h"
20 #include <utility>
21 using namespace llvm;
22 
23 namespace {
24  class UnpackMachineBundles : public MachineFunctionPass {
25  public:
26  static char ID; // Pass identification
27  UnpackMachineBundles(
28  std::function<bool(const MachineFunction &)> Ftor = nullptr)
29  : MachineFunctionPass(ID), PredicateFtor(std::move(Ftor)) {
31  }
32 
33  bool runOnMachineFunction(MachineFunction &MF) override;
34 
35  private:
36  std::function<bool(const MachineFunction &)> PredicateFtor;
37  };
38 } // end anonymous namespace
39 
42 INITIALIZE_PASS(UnpackMachineBundles, "unpack-mi-bundles",
43  "Unpack machine instruction bundles", false, false)
44 
45 bool UnpackMachineBundles::runOnMachineFunction(MachineFunction &MF) {
46  if (PredicateFtor && !PredicateFtor(MF))
47  return false;
48 
49  bool Changed = false;
50  for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
51  MachineBasicBlock *MBB = &*I;
52 
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 (unsigned i = 0, e = MII->getNumOperands(); i != e; ++i) {
63  MachineOperand &MO = MII->getOperand(i);
64  if (MO.isReg() && MO.isInternalRead())
65  MO.setIsInternalRead(false);
66  }
67  }
68  MI->eraseFromParent();
69 
70  Changed = true;
71  continue;
72  }
73 
74  ++MII;
75  }
76  }
77 
78  return Changed;
79 }
80 
83  std::function<bool(const MachineFunction &)> Ftor) {
84  return new UnpackMachineBundles(std::move(Ftor));
85 }
86 
87 namespace {
88  class FinalizeMachineBundles : public MachineFunctionPass {
89  public:
90  static char ID; // Pass identification
91  FinalizeMachineBundles() : MachineFunctionPass(ID) {
93  }
94 
95  bool runOnMachineFunction(MachineFunction &MF) override;
96  };
97 } // end anonymous namespace
98 
101 INITIALIZE_PASS(FinalizeMachineBundles, "finalize-mi-bundles",
102  "Finalize machine instruction bundles", false, false)
103 
104 bool FinalizeMachineBundles::runOnMachineFunction(MachineFunction &MF) {
105  return llvm::finalizeBundles(MF);
106 }
107 
108 /// Return the first found DebugLoc that has a DILocation, given a range of
109 /// instructions. The search range is from FirstMI to LastMI (exclusive). If no
110 /// DILocation is found, then an empty location is returned.
113  for (auto MII = FirstMI; MII != LastMI; ++MII)
114  if (MII->getDebugLoc().get())
115  return MII->getDebugLoc();
116  return DebugLoc();
117 }
118 
119 /// finalizeBundle - Finalize a machine instruction bundle which includes
120 /// a sequence of instructions starting from FirstMI to LastMI (exclusive).
121 /// This routine adds a BUNDLE instruction to represent the bundle, it adds
122 /// IsInternalRead markers to MachineOperands which are defined inside the
123 /// bundle, and it copies externally visible defs and uses to the BUNDLE
124 /// instruction.
128  assert(FirstMI != LastMI && "Empty bundle?");
129  MIBundleBuilder Bundle(MBB, FirstMI, LastMI);
130 
131  MachineFunction &MF = *MBB.getParent();
134 
135  MachineInstrBuilder MIB =
136  BuildMI(MF, getDebugLoc(FirstMI, LastMI), TII->get(TargetOpcode::BUNDLE));
137  Bundle.prepend(MIB);
138 
139  SmallVector<unsigned, 32> LocalDefs;
140  SmallSet<unsigned, 32> LocalDefSet;
141  SmallSet<unsigned, 8> DeadDefSet;
142  SmallSet<unsigned, 16> KilledDefSet;
143  SmallVector<unsigned, 8> ExternUses;
144  SmallSet<unsigned, 8> ExternUseSet;
145  SmallSet<unsigned, 8> KilledUseSet;
146  SmallSet<unsigned, 8> UndefUseSet;
148  for (auto MII = FirstMI; MII != LastMI; ++MII) {
149  for (unsigned i = 0, e = MII->getNumOperands(); i != e; ++i) {
150  MachineOperand &MO = MII->getOperand(i);
151  if (!MO.isReg())
152  continue;
153  if (MO.isDef()) {
154  Defs.push_back(&MO);
155  continue;
156  }
157 
158  Register Reg = MO.getReg();
159  if (!Reg)
160  continue;
161 
162  if (LocalDefSet.count(Reg)) {
163  MO.setIsInternalRead();
164  if (MO.isKill())
165  // Internal def is now killed.
166  KilledDefSet.insert(Reg);
167  } else {
168  if (ExternUseSet.insert(Reg).second) {
169  ExternUses.push_back(Reg);
170  if (MO.isUndef())
171  UndefUseSet.insert(Reg);
172  }
173  if (MO.isKill())
174  // External def is now killed.
175  KilledUseSet.insert(Reg);
176  }
177  }
178 
179  for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
180  MachineOperand &MO = *Defs[i];
181  Register Reg = MO.getReg();
182  if (!Reg)
183  continue;
184 
185  if (LocalDefSet.insert(Reg).second) {
186  LocalDefs.push_back(Reg);
187  if (MO.isDead()) {
188  DeadDefSet.insert(Reg);
189  }
190  } else {
191  // Re-defined inside the bundle, it's no longer killed.
192  KilledDefSet.erase(Reg);
193  if (!MO.isDead())
194  // Previously defined but dead.
195  DeadDefSet.erase(Reg);
196  }
197 
198  if (!MO.isDead() && Register::isPhysicalRegister(Reg)) {
199  for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
200  unsigned SubReg = *SubRegs;
201  if (LocalDefSet.insert(SubReg).second)
202  LocalDefs.push_back(SubReg);
203  }
204  }
205  }
206 
207  Defs.clear();
208  }
209 
211  for (unsigned i = 0, e = LocalDefs.size(); i != e; ++i) {
212  unsigned Reg = LocalDefs[i];
213  if (Added.insert(Reg).second) {
214  // If it's not live beyond end of the bundle, mark it dead.
215  bool isDead = DeadDefSet.count(Reg) || KilledDefSet.count(Reg);
216  MIB.addReg(Reg, getDefRegState(true) | getDeadRegState(isDead) |
217  getImplRegState(true));
218  }
219  }
220 
221  for (unsigned i = 0, e = ExternUses.size(); i != e; ++i) {
222  unsigned Reg = ExternUses[i];
223  bool isKill = KilledUseSet.count(Reg);
224  bool isUndef = UndefUseSet.count(Reg);
225  MIB.addReg(Reg, getKillRegState(isKill) | getUndefRegState(isUndef) |
226  getImplRegState(true));
227  }
228 
229  // Set FrameSetup/FrameDestroy for the bundle. If any of the instructions got
230  // the property, then also set it on the bundle.
231  for (auto MII = FirstMI; MII != LastMI; ++MII) {
232  if (MII->getFlag(MachineInstr::FrameSetup))
234  if (MII->getFlag(MachineInstr::FrameDestroy))
236  }
237 }
238 
239 /// finalizeBundle - Same functionality as the previous finalizeBundle except
240 /// the last instruction in the bundle is not provided as an input. This is
241 /// used in cases where bundles are pre-determined by marking instructions
242 /// with 'InsideBundle' marker. It returns the MBB instruction iterator that
243 /// points to the end of the bundle.
248  MachineBasicBlock::instr_iterator LastMI = std::next(FirstMI);
249  while (LastMI != E && LastMI->isInsideBundle())
250  ++LastMI;
251  finalizeBundle(MBB, FirstMI, LastMI);
252  return LastMI;
253 }
254 
255 /// finalizeBundles - Finalize instruction bundles in the specified
256 /// MachineFunction. Return true if any bundles are finalized.
258  bool Changed = false;
259  for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
260  MachineBasicBlock &MBB = *I;
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 
282  MachineInstr &MI, unsigned Reg,
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 
312  const TargetRegisterInfo *TRI) {
313  bool AllDefsDead = true;
314  PhysRegInfo PRI = {false, false, false, false, false, false, false, false};
315 
317  "analyzePhysReg not given a physical register!");
318  for (ConstMIBundleOperands O(MI); O.isValid(); ++O) {
319  const MachineOperand &MO = *O;
320 
321  if (MO.isRegMask() && MO.clobbersPhysReg(Reg)) {
322  PRI.Clobbered = true;
323  continue;
324  }
325 
326  if (!MO.isReg())
327  continue;
328 
329  Register MOReg = MO.getReg();
330  if (!MOReg || !Register::isPhysicalRegister(MOReg))
331  continue;
332 
333  if (!TRI->regsOverlap(MOReg, Reg))
334  continue;
335 
336  bool Covered = TRI->isSuperRegisterEq(Reg, MOReg);
337  if (MO.readsReg()) {
338  PRI.Read = true;
339  if (Covered) {
340  PRI.FullyRead = true;
341  if (MO.isKill())
342  PRI.Killed = true;
343  }
344  } else if (MO.isDef()) {
345  PRI.Defined = true;
346  if (Covered)
347  PRI.FullyDefined = true;
348  if (!MO.isDead())
349  AllDefsDead = false;
350  }
351  }
352 
353  if (AllDefsDead) {
354  if (PRI.FullyDefined || PRI.Clobbered)
355  PRI.DeadDef = true;
356  else if (PRI.Defined)
357  PRI.PartialDeadDef = true;
358  }
359 
360  return PRI;
361 }
bool isRegMask() const
isRegMask - Tests if this is a MO_RegisterMask operand.
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
instr_iterator instr_begin()
instr_iterator instr_end()
This class represents lattice values for constants.
Definition: AllocatorList.h:23
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
static bool isPhysicalRegister(unsigned Reg)
Return true if the specified register number is in the physical register namespace.
Definition: Register.h:63
MIBundleOperands - Iterate over all operands in a bundle of machine instructions. ...
unsigned Reg
void initializeFinalizeMachineBundlesPass(PassRegistry &)
VirtRegInfo AnalyzeVirtRegInBundle(MachineInstr &MI, unsigned Reg, SmallVectorImpl< std::pair< MachineInstr *, unsigned >> *Ops=nullptr)
AnalyzeVirtRegInBundle - Analyze how the current instruction or bundle uses a virtual register...
PhysRegInfo AnalyzePhysRegInBundle(const MachineInstr &MI, unsigned Reg, const TargetRegisterInfo *TRI)
AnalyzePhysRegInBundle - Analyze how the current instruction or bundle uses a physical register...
unsigned const TargetRegisterInfo * TRI
A debug info location.
Definition: DebugLoc.h:33
void initializeUnpackMachineBundlesPass(PassRegistry &)
bool erase(const T &V)
Definition: SmallSet.h:207
bool isInternalRead() const
const MachineInstrBuilder & setMIFlag(MachineInstr::MIFlag Flag) const
Definition: BitVector.h:937
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
const HexagonInstrInfo * TII
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: APFloat.h:42
void eraseFromParent()
Unlink &#39;this&#39; from the containing basic block and delete it.
unsigned SubReg
char & FinalizeMachineBundlesID
FinalizeMachineBundles - This pass finalize machine instruction bundles (created earlier, e.g.
INITIALIZE_PASS(UnpackMachineBundles, "unpack-mi-bundles", "Unpack machine instruction bundles", false, false) bool UnpackMachineBundles
bool regsOverlap(Register regA, Register regB) const
Returns true if the two registers are equal or alias each other.
bool readsReg() const
readsReg - Returns true if this operand reads the previous value of its register. ...
MIBundleBuilder & prepend(MachineInstr *MI)
Insert MI into MBB by prepending it to the instructions in the bundle.
bool Killed
There is a use operand of reg or a super-register with kill flag set.
bool isBundle() const
bool Reads
Reads - One of the operands read the virtual register.
virtual const TargetInstrInfo * getInstrInfo() const
bool Defined
Reg or one of its aliases is defined.
unsigned getUndefRegState(bool B)
unsigned getKillRegState(bool B)
TargetInstrInfo - Interface to description of machine instruction set.
unsigned getDeadRegState(bool B)
unsigned getDefRegState(bool B)
MachineInstrBuilder BuildMI(MachineFunction &MF, const DebugLoc &DL, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
bool Read
Reg or one of its aliases is read.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition: SmallSet.h:134
constexpr double e
Definition: MathExtras.h:57
bool FullyDefined
Reg or a super-register is defined.
void setIsInternalRead(bool Val=true)
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:282
bool isRegTiedToDefOperand(unsigned UseOpIdx, unsigned *DefOpIdx=nullptr) const
Return true if the use operand of the specified index is tied to a def operand.
std::pair< NoneType, bool > insert(const T &V)
insert - Insert an element into the set if it isn&#39;t already there.
Definition: SmallSet.h:180
char & UnpackMachineBundlesID
UnpackMachineBundles - This pass unpack machine instruction bundles.
bool isSuperRegisterEq(MCRegister RegA, MCRegister RegB) const
Returns true if RegB is a super-register of RegA or if RegB == RegA.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
MCSubRegIterator enumerates all sub-registers of Reg.
size_t size() const
Definition: SmallVector.h:52
static bool isUndef(ArrayRef< int > Mask)
Iterator for intrusive lists based on ilist_node.
Information about how a physical register Reg is used by a set of operands.
ConstMIBundleOperands - Iterate over all operands in a const bundle of machine instructions.
MachineOperand class - Representation of each machine instruction operand.
bool finalizeBundles(MachineFunction &MF)
finalizeBundles - Finalize instruction bundles in the specified MachineFunction.
bool Tied
Tied - Uses and defs must use the same register.
FunctionPass * createUnpackMachineBundles(std::function< bool(const MachineFunction &)> Ftor)
static bool clobbersPhysReg(const uint32_t *RegMask, unsigned PhysReg)
clobbersPhysReg - Returns true if this RegMask clobbers PhysReg.
bool isValid() const
isValid - returns true if this iterator is not yet at the end.
Representation of each machine instruction.
Definition: MachineInstr.h:63
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
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.
const MCInstrDesc & get(unsigned Opcode) const
Return the machine instruction descriptor that corresponds to the specified instruction opcode...
Definition: MCInstrInfo.h:44
#define I(x, y, z)
Definition: MD5.cpp:58
unsigned getImplRegState(bool B)
bool PartialDeadDef
Reg is Defined and all defs of reg or an overlapping register are dead.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
Instructions::iterator instr_iterator
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
VirtRegInfo - Information about a virtual register used by a set of operands.
print Print MemDeps of function
IRTranslator LLVM IR MI
bool Writes
Writes - One of the operands writes the virtual register.
Register getReg() const
getReg - Returns the register number.
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...
const MachineInstrBuilder & addReg(Register RegNo, unsigned flags=0, unsigned SubReg=0) const
Add a new virtual register operand.
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.
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
Helper class for constructing bundles of MachineInstrs.
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
Definition: SmallSet.h:164