xref: /llvm-project/llvm/lib/CodeGen/MachineInstrBundle.cpp (revision c121f3a9fbf1bcabfd64a62edec79a292e1f7d51)
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 
9 #include "llvm/CodeGen/MachineInstrBundle.h"
10 #include "llvm/ADT/SmallSet.h"
11 #include "llvm/ADT/SmallVector.h"
12 #include "llvm/CodeGen/MachineFunctionPass.h"
13 #include "llvm/CodeGen/MachineInstrBuilder.h"
14 #include "llvm/CodeGen/Passes.h"
15 #include "llvm/CodeGen/TargetInstrInfo.h"
16 #include "llvm/CodeGen/TargetRegisterInfo.h"
17 #include "llvm/CodeGen/TargetSubtargetInfo.h"
18 #include "llvm/InitializePasses.h"
19 #include "llvm/Pass.h"
20 #include "llvm/PassRegistry.h"
21 #include <utility>
22 using namespace llvm;
23 
24 namespace {
25   class UnpackMachineBundles : public MachineFunctionPass {
26   public:
27     static char ID; // Pass identification
28     UnpackMachineBundles(
29         std::function<bool(const MachineFunction &)> Ftor = nullptr)
30         : MachineFunctionPass(ID), PredicateFtor(std::move(Ftor)) {
31       initializeUnpackMachineBundlesPass(*PassRegistry::getPassRegistry());
32     }
33 
34     bool runOnMachineFunction(MachineFunction &MF) override;
35 
36   private:
37     std::function<bool(const MachineFunction &)> PredicateFtor;
38   };
39 } // end anonymous namespace
40 
41 char UnpackMachineBundles::ID = 0;
42 char &llvm::UnpackMachineBundlesID = UnpackMachineBundles::ID;
43 INITIALIZE_PASS(UnpackMachineBundles, "unpack-mi-bundles",
44                 "Unpack machine instruction bundles", false, false)
45 
46 bool UnpackMachineBundles::runOnMachineFunction(MachineFunction &MF) {
47   if (PredicateFtor && !PredicateFtor(MF))
48     return false;
49 
50   bool Changed = false;
51   for (MachineBasicBlock &MBB : MF) {
52     for (MachineBasicBlock::instr_iterator MII = MBB.instr_begin(),
53            MIE = MBB.instr_end(); MII != MIE; ) {
54       MachineInstr *MI = &*MII;
55 
56       // Remove BUNDLE instruction and the InsideBundle flags from bundled
57       // instructions.
58       if (MI->isBundle()) {
59         while (++MII != MIE && MII->isBundledWithPred()) {
60           MII->unbundleFromPred();
61           for (MachineOperand &MO  : MII->operands()) {
62             if (MO.isReg() && MO.isInternalRead())
63               MO.setIsInternalRead(false);
64           }
65         }
66         MI->eraseFromParent();
67 
68         Changed = true;
69         continue;
70       }
71 
72       ++MII;
73     }
74   }
75 
76   return Changed;
77 }
78 
79 FunctionPass *
80 llvm::createUnpackMachineBundles(
81     std::function<bool(const MachineFunction &)> Ftor) {
82   return new UnpackMachineBundles(std::move(Ftor));
83 }
84 
85 namespace {
86   class FinalizeMachineBundles : public MachineFunctionPass {
87   public:
88     static char ID; // Pass identification
89     FinalizeMachineBundles() : MachineFunctionPass(ID) {
90       initializeFinalizeMachineBundlesPass(*PassRegistry::getPassRegistry());
91     }
92 
93     bool runOnMachineFunction(MachineFunction &MF) override;
94   };
95 } // end anonymous namespace
96 
97 char FinalizeMachineBundles::ID = 0;
98 char &llvm::FinalizeMachineBundlesID = FinalizeMachineBundles::ID;
99 INITIALIZE_PASS(FinalizeMachineBundles, "finalize-mi-bundles",
100                 "Finalize machine instruction bundles", false, false)
101 
102 bool FinalizeMachineBundles::runOnMachineFunction(MachineFunction &MF) {
103   return llvm::finalizeBundles(MF);
104 }
105 
106 /// Return the first found DebugLoc that has a DILocation, given a range of
107 /// instructions. The search range is from FirstMI to LastMI (exclusive). If no
108 /// DILocation is found, then an empty location is returned.
109 static DebugLoc getDebugLoc(MachineBasicBlock::instr_iterator FirstMI,
110                             MachineBasicBlock::instr_iterator LastMI) {
111   for (auto MII = FirstMI; MII != LastMI; ++MII)
112     if (MII->getDebugLoc())
113       return MII->getDebugLoc();
114   return DebugLoc();
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.
123 void llvm::finalizeBundle(MachineBasicBlock &MBB,
124                           MachineBasicBlock::instr_iterator FirstMI,
125                           MachineBasicBlock::instr_iterator LastMI) {
126   assert(FirstMI != LastMI && "Empty bundle?");
127   MIBundleBuilder Bundle(MBB, FirstMI, LastMI);
128 
129   MachineFunction &MF = *MBB.getParent();
130   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
131   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
132 
133   MachineInstrBuilder MIB =
134       BuildMI(MF, getDebugLoc(FirstMI, LastMI), TII->get(TargetOpcode::BUNDLE));
135   Bundle.prepend(MIB);
136 
137   SmallVector<Register, 32> LocalDefs;
138   SmallSet<Register, 32> LocalDefSet;
139   SmallSet<Register, 8> DeadDefSet;
140   SmallSet<Register, 16> KilledDefSet;
141   SmallVector<Register, 8> ExternUses;
142   SmallSet<Register, 8> ExternUseSet;
143   SmallSet<Register, 8> KilledUseSet;
144   SmallSet<Register, 8> UndefUseSet;
145   SmallVector<MachineOperand*, 4> Defs;
146   for (auto MII = FirstMI; MII != LastMI; ++MII) {
147     // Debug instructions have no effects to track.
148     if (MII->isDebugInstr())
149       continue;
150 
151     for (MachineOperand &MO : MII->operands()) {
152       if (!MO.isReg())
153         continue;
154       if (MO.isDef()) {
155         Defs.push_back(&MO);
156         continue;
157       }
158 
159       Register Reg = MO.getReg();
160       if (!Reg)
161         continue;
162 
163       if (LocalDefSet.count(Reg)) {
164         MO.setIsInternalRead();
165         if (MO.isKill())
166           // Internal def is now killed.
167           KilledDefSet.insert(Reg);
168       } else {
169         if (ExternUseSet.insert(Reg).second) {
170           ExternUses.push_back(Reg);
171           if (MO.isUndef())
172             UndefUseSet.insert(Reg);
173         }
174         if (MO.isKill())
175           // External def is now killed.
176           KilledUseSet.insert(Reg);
177       }
178     }
179 
180     for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
181       MachineOperand &MO = *Defs[i];
182       Register Reg = MO.getReg();
183       if (!Reg)
184         continue;
185 
186       if (LocalDefSet.insert(Reg).second) {
187         LocalDefs.push_back(Reg);
188         if (MO.isDead()) {
189           DeadDefSet.insert(Reg);
190         }
191       } else {
192         // Re-defined inside the bundle, it's no longer killed.
193         KilledDefSet.erase(Reg);
194         if (!MO.isDead())
195           // Previously defined but dead.
196           DeadDefSet.erase(Reg);
197       }
198 
199       if (!MO.isDead() && Reg.isPhysical()) {
200         for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
201           unsigned SubReg = *SubRegs;
202           if (LocalDefSet.insert(SubReg).second)
203             LocalDefs.push_back(SubReg);
204         }
205       }
206     }
207 
208     Defs.clear();
209   }
210 
211   SmallSet<Register, 32> Added;
212   for (unsigned i = 0, e = LocalDefs.size(); i != e; ++i) {
213     Register Reg = LocalDefs[i];
214     if (Added.insert(Reg).second) {
215       // If it's not live beyond end of the bundle, mark it dead.
216       bool isDead = DeadDefSet.count(Reg) || KilledDefSet.count(Reg);
217       MIB.addReg(Reg, getDefRegState(true) | getDeadRegState(isDead) |
218                  getImplRegState(true));
219     }
220   }
221 
222   for (unsigned i = 0, e = ExternUses.size(); i != e; ++i) {
223     Register Reg = ExternUses[i];
224     bool isKill = KilledUseSet.count(Reg);
225     bool isUndef = UndefUseSet.count(Reg);
226     MIB.addReg(Reg, getKillRegState(isKill) | getUndefRegState(isUndef) |
227                getImplRegState(true));
228   }
229 
230   // Set FrameSetup/FrameDestroy for the bundle. If any of the instructions got
231   // the property, then also set it on the bundle.
232   for (auto MII = FirstMI; MII != LastMI; ++MII) {
233     if (MII->getFlag(MachineInstr::FrameSetup))
234       MIB.setMIFlag(MachineInstr::FrameSetup);
235     if (MII->getFlag(MachineInstr::FrameDestroy))
236       MIB.setMIFlag(MachineInstr::FrameDestroy);
237   }
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.
245 MachineBasicBlock::instr_iterator
246 llvm::finalizeBundle(MachineBasicBlock &MBB,
247                      MachineBasicBlock::instr_iterator FirstMI) {
248   MachineBasicBlock::instr_iterator E = MBB.instr_end();
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.
258 bool llvm::finalizeBundles(MachineFunction &MF) {
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 
281 VirtRegInfo llvm::AnalyzeVirtRegInBundle(
282     MachineInstr &MI, Register 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 
311 PhysRegInfo llvm::AnalyzePhysRegInBundle(const MachineInstr &MI, Register Reg,
312                                          const TargetRegisterInfo *TRI) {
313   bool AllDefsDead = true;
314   PhysRegInfo PRI = {false, false, false, false, false, false, false, false};
315 
316   assert(Reg.isPhysical() && "analyzePhysReg not given a physical register!");
317   for (ConstMIBundleOperands O(MI); O.isValid(); ++O) {
318     const MachineOperand &MO = *O;
319 
320     if (MO.isRegMask() && MO.clobbersPhysReg(Reg)) {
321       PRI.Clobbered = true;
322       continue;
323     }
324 
325     if (!MO.isReg())
326       continue;
327 
328     Register MOReg = MO.getReg();
329     if (!MOReg || !MOReg.isPhysical())
330       continue;
331 
332     if (!TRI->regsOverlap(MOReg, Reg))
333       continue;
334 
335     bool Covered = TRI->isSuperRegisterEq(Reg, MOReg);
336     if (MO.readsReg()) {
337       PRI.Read = true;
338       if (Covered) {
339         PRI.FullyRead = true;
340         if (MO.isKill())
341           PRI.Killed = true;
342       }
343     } else if (MO.isDef()) {
344       PRI.Defined = true;
345       if (Covered)
346         PRI.FullyDefined = true;
347       if (!MO.isDead())
348         AllDefsDead = false;
349     }
350   }
351 
352   if (AllDefsDead) {
353     if (PRI.FullyDefined || PRI.Clobbered)
354       PRI.DeadDef = true;
355     else if (PRI.Defined)
356       PRI.PartialDeadDef = true;
357   }
358 
359   return PRI;
360 }
361