LLVM 20.0.0git
InitUndef.cpp
Go to the documentation of this file.
1//===- InitUndef.cpp - Initialize undef value to pseudo ----===//
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// This file implements a function pass that initializes undef value to
10// temporary pseudo instruction to prevent register allocation resulting in a
11// constraint violated result for the particular instruction. It also rewrites
12// the NoReg tied operand back to an IMPLICIT_DEF.
13//
14// Certain instructions have register overlapping constraints, and
15// will cause illegal instruction trap if violated, we use early clobber to
16// model this constraint, but it can't prevent register allocator allocating
17// same or overlapped if the input register is undef value, so convert
18// IMPLICIT_DEF to temporary pseudo instruction and remove it later could
19// prevent that happen, it's not best way to resolve this, and it might
20// change the order of program or increase the register pressure, so ideally we
21// should model the constraint right, but before we model the constraint right,
22// it's the only way to prevent that happen.
23//
24// When we enable the subregister liveness option, it will also trigger the same
25// issue due to the partial of register is undef. If we pseudoinit the whole
26// register, then it will generate redundant COPY instruction. Currently, it
27// will generate INSERT_SUBREG to make sure the whole register is occupied
28// when program encounter operation that has early-clobber constraint.
29//
30//
31// See also: https://github.com/llvm/llvm-project/issues/50157
32//
33// Additionally, this pass rewrites tied operands of instructions
34// from NoReg to IMPLICIT_DEF. (Not that this is a non-overlapping set of
35// operands to the above.) We use NoReg to side step a MachineCSE
36// optimization quality problem but need to convert back before
37// TwoAddressInstruction. See pr64282 for context.
38//
39//===----------------------------------------------------------------------===//
40
41#include "llvm/ADT/SmallSet.h"
51#include "llvm/MC/MCRegister.h"
52#include "llvm/Pass.h"
53#include "llvm/Support/Debug.h"
54
55using namespace llvm;
56
57#define DEBUG_TYPE "init-undef"
58#define INIT_UNDEF_NAME "Init Undef Pass"
59
60namespace {
61
62class InitUndef : public MachineFunctionPass {
63 const TargetInstrInfo *TII;
65 const TargetSubtargetInfo *ST;
67
68 // Newly added vregs, assumed to be fully rewritten
71
72public:
73 static char ID;
74
75 InitUndef() : MachineFunctionPass(ID) {}
76 bool runOnMachineFunction(MachineFunction &MF) override;
77
78 void getAnalysisUsage(AnalysisUsage &AU) const override {
79 AU.setPreservesCFG();
81 }
82
83 StringRef getPassName() const override { return INIT_UNDEF_NAME; }
84
85private:
86 bool processBasicBlock(MachineFunction &MF, MachineBasicBlock &MBB,
87 const DeadLaneDetector &DLD);
88 bool handleSubReg(MachineFunction &MF, MachineInstr &MI,
89 const DeadLaneDetector &DLD);
90 bool fixupIllOperand(MachineInstr *MI, MachineOperand &MO);
91 bool handleReg(MachineInstr *MI);
92};
93
94} // end anonymous namespace
95
96char InitUndef::ID = 0;
97INITIALIZE_PASS(InitUndef, DEBUG_TYPE, INIT_UNDEF_NAME, false, false)
98char &llvm::InitUndefID = InitUndef::ID;
99
101 return llvm::any_of(MI.defs(), [](const MachineOperand &DefMO) {
102 return DefMO.isReg() && DefMO.isEarlyClobber();
103 });
104}
105
107 for (auto &DefMI : MRI->def_instructions(Reg)) {
108 if (DefMI.getOpcode() == TargetOpcode::IMPLICIT_DEF)
109 return true;
110 }
111 return false;
112}
113
114bool InitUndef::handleReg(MachineInstr *MI) {
115 bool Changed = false;
116 for (auto &UseMO : MI->uses()) {
117 if (!UseMO.isReg())
118 continue;
119 if (UseMO.isTied())
120 continue;
121 if (!UseMO.getReg().isVirtual())
122 continue;
123 if (!TRI->doesRegClassHavePseudoInitUndef(MRI->getRegClass(UseMO.getReg())))
124 continue;
125
126 if (UseMO.isUndef() || findImplictDefMIFromReg(UseMO.getReg(), MRI))
127 Changed |= fixupIllOperand(MI, UseMO);
128 }
129 return Changed;
130}
131
132bool InitUndef::handleSubReg(MachineFunction &MF, MachineInstr &MI,
133 const DeadLaneDetector &DLD) {
134 bool Changed = false;
135
136 for (MachineOperand &UseMO : MI.uses()) {
137 if (!UseMO.isReg())
138 continue;
139 if (!UseMO.getReg().isVirtual())
140 continue;
141 if (UseMO.isTied())
142 continue;
143 if (!TRI->doesRegClassHavePseudoInitUndef(MRI->getRegClass(UseMO.getReg())))
144 continue;
145
146 Register Reg = UseMO.getReg();
147 if (NewRegs.count(Reg))
148 continue;
151
152 if (Info.UsedLanes == Info.DefinedLanes)
153 continue;
154
155 const TargetRegisterClass *TargetRegClass =
156 TRI->getLargestSuperClass(MRI->getRegClass(Reg));
157
158 LaneBitmask NeedDef = Info.UsedLanes & ~Info.DefinedLanes;
159
160 LLVM_DEBUG({
161 dbgs() << "Instruction has undef subregister.\n";
162 dbgs() << printReg(Reg, nullptr)
163 << " Used: " << PrintLaneMask(Info.UsedLanes)
164 << " Def: " << PrintLaneMask(Info.DefinedLanes)
165 << " Need Def: " << PrintLaneMask(NeedDef) << "\n";
166 });
167
168 SmallVector<unsigned> SubRegIndexNeedInsert;
169 TRI->getCoveringSubRegIndexes(*MRI, TargetRegClass, NeedDef,
170 SubRegIndexNeedInsert);
171
172 Register LatestReg = Reg;
173 for (auto ind : SubRegIndexNeedInsert) {
174 Changed = true;
175 const TargetRegisterClass *SubRegClass = TRI->getLargestSuperClass(
176 TRI->getSubRegisterClass(TargetRegClass, ind));
177 Register TmpInitSubReg = MRI->createVirtualRegister(SubRegClass);
178 LLVM_DEBUG(dbgs() << "Register Class ID" << SubRegClass->getID() << "\n");
179 BuildMI(*MI.getParent(), &MI, MI.getDebugLoc(),
180 TII->get(TII->getUndefInitOpcode(SubRegClass->getID())),
181 TmpInitSubReg);
182 Register NewReg = MRI->createVirtualRegister(TargetRegClass);
183 BuildMI(*MI.getParent(), &MI, MI.getDebugLoc(),
184 TII->get(TargetOpcode::INSERT_SUBREG), NewReg)
185 .addReg(LatestReg)
186 .addReg(TmpInitSubReg)
187 .addImm(ind);
188 LatestReg = NewReg;
189 }
190
191 UseMO.setReg(LatestReg);
192 }
193
194 return Changed;
195}
196
197bool InitUndef::fixupIllOperand(MachineInstr *MI, MachineOperand &MO) {
198
200 dbgs() << "Emitting PseudoInitUndef Instruction for implicit register "
201 << MO.getReg() << '\n');
202
203 const TargetRegisterClass *TargetRegClass =
204 TRI->getLargestSuperClass(MRI->getRegClass(MO.getReg()));
205 LLVM_DEBUG(dbgs() << "Register Class ID" << TargetRegClass->getID() << "\n");
206 unsigned Opcode = TII->getUndefInitOpcode(TargetRegClass->getID());
207 Register NewReg = MRI->createVirtualRegister(TargetRegClass);
208 BuildMI(*MI->getParent(), MI, MI->getDebugLoc(), TII->get(Opcode), NewReg);
209 MO.setReg(NewReg);
210 if (MO.isUndef())
211 MO.setIsUndef(false);
212 return true;
213}
214
215bool InitUndef::processBasicBlock(MachineFunction &MF, MachineBasicBlock &MBB,
216 const DeadLaneDetector &DLD) {
217 bool Changed = false;
218 for (MachineBasicBlock::iterator I = MBB.begin(); I != MBB.end(); ++I) {
219 MachineInstr &MI = *I;
220
221 // If we used NoReg to represent the passthru, switch this back to being
222 // an IMPLICIT_DEF before TwoAddressInstructions.
223 unsigned UseOpIdx;
224 if (MI.getNumDefs() != 0 && MI.isRegTiedToUseOperand(0, &UseOpIdx)) {
225 MachineOperand &UseMO = MI.getOperand(UseOpIdx);
226 if (UseMO.getReg() == MCRegister::NoRegister) {
227 const TargetRegisterClass *RC =
228 TII->getRegClass(MI.getDesc(), UseOpIdx, TRI, MF);
229 Register NewDest = MRI->createVirtualRegister(RC);
230 // We don't have a way to update dead lanes, so keep track of the
231 // new register so that we avoid querying it later.
232 NewRegs.insert(NewDest);
233 BuildMI(MBB, I, I->getDebugLoc(), TII->get(TargetOpcode::IMPLICIT_DEF),
234 NewDest);
235 UseMO.setReg(NewDest);
236 Changed = true;
237 }
238 }
239
240 if (isEarlyClobberMI(MI)) {
241 if (MRI->subRegLivenessEnabled())
242 Changed |= handleSubReg(MF, MI, DLD);
243 Changed |= handleReg(&MI);
244 }
245 }
246 return Changed;
247}
248
249bool InitUndef::runOnMachineFunction(MachineFunction &MF) {
250 ST = &MF.getSubtarget();
251
252 // supportsInitUndef is implemented to reflect if an architecture has support
253 // for the InitUndef pass. Support comes from having the relevant Pseudo
254 // instructions that can be used to initialize the register. The function
255 // returns false by default so requires an implementation per architecture.
256 // Support can be added by overriding the function in a way that best fits
257 // the architecture.
258 if (!ST->supportsInitUndef())
259 return false;
260
261 MRI = &MF.getRegInfo();
262 TII = ST->getInstrInfo();
263 TRI = MRI->getTargetRegisterInfo();
264
265 bool Changed = false;
268
269 for (MachineBasicBlock &BB : MF)
270 Changed |= processBasicBlock(MF, BB, DLD);
271
272 for (auto *DeadMI : DeadInsts)
273 DeadMI->eraseFromParent();
274 DeadInsts.clear();
275
276 return Changed;
277}
unsigned const MachineRegisterInfo * MRI
MachineInstrBuilder MachineInstrBuilder & DefMI
MachineBasicBlock & MBB
Analysis containing CSE Info
Definition: CSEInfo.cpp:27
#define LLVM_DEBUG(X)
Definition: Debug.h:101
Analysis that tracks defined/used subregister lanes across COPY instructions and instructions that ge...
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
static bool isEarlyClobberMI(MachineInstr &MI)
Definition: InitUndef.cpp:100
#define INIT_UNDEF_NAME
Definition: InitUndef.cpp:58
static bool findImplictDefMIFromReg(Register Reg, MachineRegisterInfo *MRI)
Definition: InitUndef.cpp:106
#define DEBUG_TYPE
Definition: InitUndef.cpp:57
#define I(x, y, z)
Definition: MD5.cpp:58
unsigned const TargetRegisterInfo * TRI
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:38
This file defines the SmallSet class.
This file defines the SmallVector class.
Represent the analysis usage information of a pass.
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition: Pass.cpp:256
void computeSubRegisterLaneBitInfo()
Update the DefinedLanes and the UsedLanes for all virtual registers.
const VRegInfo & getVRegInfo(unsigned RegIdx) const
static constexpr unsigned NoRegister
Definition: MCRegister.h:52
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
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.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
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:69
MachineOperand class - Representation of each machine instruction operand.
void setReg(Register Reg)
Change the register this operand corresponds to.
void setIsUndef(bool Val=true)
Register getReg() const
getReg - Returns the register number.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
virtual StringRef getPassName() const
getPassName - Return a nice clean name for a pass.
Definition: Pass.cpp:81
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
static unsigned virtReg2Index(Register Reg)
Convert a virtual register number to a 0-based index.
Definition: Register.h:77
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition: SmallSet.h:135
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
TargetInstrInfo - Interface to description of machine instruction set.
unsigned getID() const
Return the register class ID number.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
TargetSubtargetInfo - Generic base class for all target subtargets.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
Reg
All possible values of the reg field in the ModR/M byte.
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
char & InitUndefID
Definition: InitUndef.cpp:98
Printable PrintLaneMask(LaneBitmask LaneMask)
Create Printable object to print LaneBitmasks on a raw_ostream.
Definition: LaneBitmask.h:92
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1729
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
Contains a bitmask of which lanes of a given virtual register are defined and which ones are actually...