LLVM 24.0.0git
X86FixupSetCC.cpp
Go to the documentation of this file.
1//===- X86FixupSetCC.cpp - fix zero-extension of setcc and movbe ----------===//
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 defines a pass that fixes zero-extension of setcc patterns and
10// movbe patterns.
11// X86 setcc instructions are modeled to have no input arguments, and a single
12// GR8 output argument. This is consistent with other similar instructions
13// (e.g. movb), but means it is impossible to directly generate a setcc into
14// the lower GR8 of a specified GR32.
15// This means that ISel must select (zext (setcc)) into something like
16// seta %al; movzbl %al, %eax.
17// Unfortunately, this can cause a stall due to the partial register write
18// performed by the setcc. Instead, we can use:
19// xor %eax, %eax; seta %al
20// This both avoids the stall, and encodes shorter.
21//
22// Furthurmore, we can use:
23// setzua %al
24// if feature zero-upper is available. It's faster than the xor+setcc sequence.
25// When r16-r31 is used, it even encodes shorter.
26//
27// The same applies to a 16-bit MOVBE load, which also writes only the low
28// part of its destination:
29// movbew (%rdi), %ax; movzwl %ax, %eax
30// becomes
31// xorl %eax, %eax; movbew (%rdi), %ax
32// If EFLAGS is live at the load, the xor goes before the instruction that
33// defines EFLAGS, as for setcc.
34//===----------------------------------------------------------------------===//
35
36#include "X86.h"
37#include "X86InstrInfo.h"
38#include "X86Subtarget.h"
39#include "llvm/ADT/Statistic.h"
44
45using namespace llvm;
46
47#define DEBUG_TYPE "x86-fixup-setcc"
48
49STATISTIC(NumSubstZexts, "Number of setcc + zext pairs substituted");
50STATISTIC(NumSubstMovbeZexts, "Number of movbe + zext pairs substituted");
51
52namespace {
53class X86FixupSetCCLegacy : public MachineFunctionPass {
54public:
55 static char ID;
56
57 X86FixupSetCCLegacy() : MachineFunctionPass(ID) {}
58
59 StringRef getPassName() const override { return "X86 Fixup SetCC"; }
60
61 bool runOnMachineFunction(MachineFunction &MF) override;
62
63 void getAnalysisUsage(AnalysisUsage &AU) const override {
64 AU.addPreserved<MachineRegisterClassInfoWrapperPass>();
66 }
67};
68} // end anonymous namespace
69
70char X86FixupSetCCLegacy::ID = 0;
71
72INITIALIZE_PASS(X86FixupSetCCLegacy, DEBUG_TYPE, DEBUG_TYPE, false, false)
73
75 return new X86FixupSetCCLegacy();
76}
77
78static bool fixupSetCC(MachineFunction &MF) {
79 bool Changed = false;
81 const X86Subtarget *ST = &MF.getSubtarget<X86Subtarget>();
82 const X86InstrInfo *TII = ST->getInstrInfo();
83
85
86 for (auto &MBB : MF) {
87 MachineInstr *FlagsDefMI = nullptr;
88 for (auto &MI : MBB) {
89 // Remember the most recent preceding eflags defining instruction.
90 if (MI.definesRegister(X86::EFLAGS, /*TRI=*/nullptr))
91 FlagsDefMI = &MI;
92
93 // Find a setcc/setzucc (if ZU is enabled) that is used by a zext.
94 // This doesn't have to be the only use, the transformation is safe
95 // regardless.
96 if (MI.getOpcode() != X86::SETCCr && MI.getOpcode() != X86::SETZUCCr)
97 continue;
98
99 MachineInstr *ZExt = nullptr;
100 Register Reg0 = MI.getOperand(0).getReg();
101 for (auto &Use : MRI->use_instructions(Reg0))
102 if (Use.getOpcode() == X86::MOVZX32rr8)
103 ZExt = &Use;
104
105 if (!ZExt)
106 continue;
107
108 if (!FlagsDefMI)
109 continue;
110
111 // When ZU is available and not disabled by tuning, we rewrite to
112 // setzucc, which doesn't clobber eflags; otherwise we insert a MOV32r0
113 // (which does clobber eflags) before FlagsDefMI.
114 bool UseSetZUCC = ST->hasZU() && !ST->preferLegacySetCC();
115
116 // We'd like to put something that clobbers eflags directly before
117 // FlagsDefMI. This can't hurt anything after FlagsDefMI, because
118 // it, itself, by definition, clobbers eflags. But it may happen that
119 // FlagsDefMI also *uses* eflags, in which case the transformation is
120 // invalid.
121 if (!UseSetZUCC &&
122 FlagsDefMI->readsRegister(X86::EFLAGS, /*TRI=*/nullptr))
123 continue;
124
125 // On 32-bit, we need to be careful to force an ABCD register.
126 const TargetRegisterClass *RC =
127 ST->is64Bit() ? &X86::GR32RegClass : &X86::GR32_ABCDRegClass;
128 if (!MRI->constrainRegClass(ZExt->getOperand(0).getReg(), RC)) {
129 // If we cannot constrain the register, we would need an additional copy
130 // and are better off keeping the MOVZX32rr8 we have now.
131 continue;
132 }
133
134 ++NumSubstZexts;
135 Changed = true;
136
137 // X86 setcc/setzucc only takes an output GR8, so fake a GR32 input by
138 // inserting the setcc/setzucc result into the low byte of the zeroed
139 // register.
140 Register ZeroReg = MRI->createVirtualRegister(RC);
141 if (UseSetZUCC) {
142 MI.setDesc(TII->get(X86::SETZUCCr));
143 BuildMI(*ZExt->getParent(), ZExt, ZExt->getDebugLoc(),
144 TII->get(TargetOpcode::IMPLICIT_DEF), ZeroReg);
145 } else {
146 // Initialize a register with 0. This must go before the eflags def
147 BuildMI(MBB, FlagsDefMI, MI.getDebugLoc(), TII->get(X86::MOV32r0),
148 ZeroReg)
149 .setOperandDead(1);
150 }
151
152 BuildMI(*ZExt->getParent(), ZExt, ZExt->getDebugLoc(),
153 TII->get(X86::INSERT_SUBREG), ZExt->getOperand(0).getReg())
154 .addReg(ZeroReg)
155 .addReg(Reg0)
156 .addImm(X86::sub_8bit);
157
158 // Redirect the debug-instr-number to the setcc.
159 if (unsigned InstrNum = ZExt->peekDebugInstrNum())
160 MF.makeDebugValueSubstitution({InstrNum, 0},
161 {MI.getDebugInstrNum(), 0});
162
163 ToErase.push_back(ZExt);
164 }
165 }
166
167 for (auto &I : ToErase)
168 I->eraseFromParent();
169
170 return Changed;
171}
172
174 bool Changed = false;
176 const X86Subtarget *ST = &MF.getSubtarget<X86Subtarget>();
177 const X86InstrInfo *TII = ST->getInstrInfo();
178 const TargetRegisterInfo *TRI = ST->getRegisterInfo();
179
181
182 for (auto &MBB : MF) {
183 for (auto &MI : MBB) {
184 if (MI.getOpcode() != X86::MOVZX32rr16)
185 continue;
186
187 // Look for a zero-extension whose source is a 16-bit MOVBE load
188 // (legacy or EVEX encoded).
189 Register SrcReg = MI.getOperand(1).getReg();
190 if (!SrcReg.isVirtual())
191 continue;
192 MachineInstr *MovbeInstruction = MRI->getVRegDef(SrcReg);
193 if (!MovbeInstruction ||
194 (MovbeInstruction->getOpcode() != X86::MOVBE16rm &&
195 MovbeInstruction->getOpcode() != X86::MOVBE16rm_EVEX))
196 continue;
197
198 MachineBasicBlock *MovbeMBB = MovbeInstruction->getParent();
199 MachineInstr *InsertBefore = nullptr;
201 MovbeMBB->computeRegisterLiveness(TRI, X86::EFLAGS, MovbeInstruction);
202 if (Liveness == MachineBasicBlock::LQR_Dead) {
203 InsertBefore = MovbeInstruction;
204 } else {
205 // EFLAGS may be live at the load, or its liveness is unknown. Walk back
206 // to the instruction that defines EFLAGS; if it does not read EFLAGS,
207 // put the xor right before it, where the flags it clobbers are
208 // overwritten at once.
209 MachineBasicBlock::iterator I = MovbeInstruction->getIterator();
210 while (I != MovbeMBB->begin()) {
211 --I;
212 if (I->modifiesRegister(X86::EFLAGS, TRI)) {
213 // If this instruction also reads EFLAGS (e.g. ADC), give up, like
214 // fixupSetCC does; walking further back is possible but rare.
215 if (!I->readsRegister(X86::EFLAGS, TRI))
216 InsertBefore = &*I;
217 break;
218 }
219 }
220 }
221 if (!InsertBefore)
222 continue;
223 Register ZeroReg = MRI->createVirtualRegister(&X86::GR32RegClass);
224 BuildMI(*InsertBefore->getParent(), InsertBefore,
225 MovbeInstruction->getDebugLoc(), TII->get(X86::MOV32r0), ZeroReg)
226 .setOperandDead(1);
227 BuildMI(MBB, MI, MI.getDebugLoc(), TII->get(X86::INSERT_SUBREG),
228 MI.getOperand(0).getReg())
229 .addReg(ZeroReg)
230 .addReg(SrcReg)
231 .addImm(X86::sub_16bit);
232 // Redirect the debug-instr-number to the movbe.
233 if (unsigned InstrNum = MI.peekDebugInstrNum())
235 {InstrNum, 0}, {MovbeInstruction->getDebugInstrNum(), 0});
236 ToErase.push_back(&MI);
237 Changed = true;
238 ++NumSubstMovbeZexts;
239 }
240 }
241 for (MachineInstr *ZExt : ToErase)
242 ZExt->eraseFromParent();
243
244 return Changed;
245}
246
247bool X86FixupSetCCLegacy::runOnMachineFunction(MachineFunction &MF) {
248 bool Changed = fixupSetCC(MF);
249 Changed |= fixupMovbeZExt(MF);
250 return Changed;
251}
252
const AArch64InstrInfo & TII
MachineBasicBlock & MBB
#define DEBUG_TYPE
IRTranslator LLVM IR MI
#define I(x, y, z)
Definition MD5.cpp:57
Register const TargetRegisterInfo * TRI
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
MachineRegisterInfo & MRI
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:170
static bool fixupSetCC(MachineFunction &MF)
static bool fixupMovbeZExt(MachineFunction &MF)
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
LLVM_ABI LivenessQueryResult computeRegisterLiveness(const TargetRegisterInfo *TRI, MCRegister Reg, const_iterator Before, unsigned Neighborhood=10) const
Return whether (physical) register Reg has been defined and not killed as of just before Before.
MachineInstrBundleIterator< MachineInstr > iterator
LivenessQueryResult
Possible outcome of a register liveness query to computeRegisterLiveness()
@ LQR_Dead
Register is known to be fully dead.
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.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
void makeDebugValueSubstitution(DebugInstrOperandPair, DebugInstrOperandPair, unsigned SubReg=0)
Create a substitution between one <instr,operand> value to a different, new value.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
const MachineInstrBuilder & setOperandDead(unsigned OpIdx) const
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
const MachineBasicBlock * getParent() const
bool readsRegister(Register Reg, const TargetRegisterInfo *TRI) const
Return true if the MachineInstr reads the specified register.
unsigned peekDebugInstrNum() const
Examine the instruction number of this MachineInstr.
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
LLVM_ABI unsigned getDebugInstrNum()
Fetch the instruction number of this MachineInstr.
const MachineOperand & getOperand(unsigned i) const
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
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
self_iterator getIterator()
Definition ilist_node.h:123
This is an optimization pass for GlobalISel generic memory operations.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
FunctionPass * createX86FixupSetCCLegacyPass()
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58