LLVM 24.0.0git
X86CompressEVEX.cpp
Go to the documentation of this file.
1//===- X86CompressEVEX.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// This pass compresses instructions from EVEX space to legacy/VEX/EVEX space
10// when possible in order to reduce code size or facilitate HW decoding.
11//
12// Possible compression:
13// a. AVX512 instruction (EVEX) -> AVX instruction (VEX)
14// b. Promoted instruction (EVEX) -> pre-promotion instruction (legacy/VEX)
15// c. NDD (EVEX) -> non-NDD (legacy)
16// d. NF_ND (EVEX) -> NF (EVEX)
17// e. NonNF (EVEX) -> NF (EVEX)
18// f. SETZUCCm (EVEX) -> SETCCm (legacy)
19// g. VPMOV*2M (EVEX) + KMOV -> VMOVMSK/VPMOVMSKB (VEX)
20// h. VPMOV*2M (EVEX) + masked VMOV* -> VBLENDV* (VEX)
21//
22// Compression a, b and c can always reduce code size, with some exceptions
23// such as promoted 16-bit CRC32 which is as long as the legacy version.
24//
25// legacy:
26// crc32w %si, %eax ## encoding: [0x66,0xf2,0x0f,0x38,0xf1,0xc6]
27// promoted:
28// crc32w %si, %eax ## encoding: [0x62,0xf4,0x7d,0x08,0xf1,0xc6]
29//
30// From performance perspective, these should be same (same uops and same EXE
31// ports). From a FMV perspective, an older legacy encoding is preferred b/c it
32// can execute in more places (broader HW install base). So we will still do
33// the compression.
34//
35// Compression d can help hardware decode (HW may skip reading the NDD
36// register) although the instruction length remains unchanged.
37//
38// Compression e can help hardware skip updating EFLAGS although the instruction
39// length remains unchanged.
40//===----------------------------------------------------------------------===//
41
43#include "X86.h"
44#include "X86InstrInfo.h"
45#include "X86Subtarget.h"
47#include "llvm/ADT/StringRef.h"
54#include "llvm/IR/Analysis.h"
55#include "llvm/MC/MCInstrDesc.h"
56#include "llvm/Pass.h"
57#include <atomic>
58#include <cassert>
59#include <cstdint>
60
61using namespace llvm;
62
63#define COMP_EVEX_DESC "Compressing EVEX instrs when possible"
64#define COMP_EVEX_NAME "x86-compress-evex"
65
66#define DEBUG_TYPE COMP_EVEX_NAME
67
69
70namespace {
71// Including the generated EVEX compression tables.
72#define GET_X86_COMPRESS_EVEX_TABLE
73#include "X86GenInstrMapping.inc"
74
75class CompressEVEXLegacy : public MachineFunctionPass {
76public:
77 static char ID;
78 CompressEVEXLegacy() : MachineFunctionPass(ID) {}
79 StringRef getPassName() const override { return COMP_EVEX_DESC; }
80
81 bool runOnMachineFunction(MachineFunction &MF) override;
82
83 // This pass runs after regalloc and doesn't support VReg operands.
84 MachineFunctionProperties getRequiredProperties() const override {
85 return MachineFunctionProperties().setNoVRegs();
86 }
87};
88
89} // end anonymous namespace
90
91char CompressEVEXLegacy::ID = 0;
92
94 auto isHiRegIdx = [](MCRegister Reg) {
95 // Check for XMM register with indexes between 16 - 31.
96 if (Reg >= X86::XMM16 && Reg <= X86::XMM31)
97 return true;
98 // Check for YMM register with indexes between 16 - 31.
99 if (Reg >= X86::YMM16 && Reg <= X86::YMM31)
100 return true;
101 // Check for GPR with indexes between 16 - 31.
103 return true;
104 return false;
105 };
106
107 // Check that operands are not ZMM regs or
108 // XMM/YMM regs with hi indexes between 16 - 31.
109 for (const MachineOperand &MO : MI.explicit_operands()) {
110 if (!MO.isReg())
111 continue;
112
113 MCRegister Reg = MO.getReg().asMCReg();
115 "ZMM instructions should not be in the EVEX->VEX tables");
116 if (isHiRegIdx(Reg))
117 return true;
118 }
119
120 return false;
121}
122
123// Do any custom cleanup needed to finalize the conversion.
124static bool performCustomAdjustments(MachineInstr &MI, unsigned NewOpc) {
125 (void)NewOpc;
126 unsigned Opc = MI.getOpcode();
127 switch (Opc) {
128 case X86::VALIGNDZ128rri:
129 case X86::VALIGNDZ128rmi:
130 case X86::VALIGNQZ128rri:
131 case X86::VALIGNQZ128rmi: {
132 assert((NewOpc == X86::VPALIGNRrri || NewOpc == X86::VPALIGNRrmi) &&
133 "Unexpected new opcode!");
134 unsigned Scale =
135 (Opc == X86::VALIGNQZ128rri || Opc == X86::VALIGNQZ128rmi) ? 8 : 4;
136 MachineOperand &Imm = MI.getOperand(MI.getNumExplicitOperands() - 1);
137 Imm.setImm(Imm.getImm() * Scale);
138 break;
139 }
140 case X86::VSHUFF32X4Z256rmi:
141 case X86::VSHUFF32X4Z256rri:
142 case X86::VSHUFF64X2Z256rmi:
143 case X86::VSHUFF64X2Z256rri:
144 case X86::VSHUFI32X4Z256rmi:
145 case X86::VSHUFI32X4Z256rri:
146 case X86::VSHUFI64X2Z256rmi:
147 case X86::VSHUFI64X2Z256rri: {
148 assert((NewOpc == X86::VPERM2F128rri || NewOpc == X86::VPERM2I128rri ||
149 NewOpc == X86::VPERM2F128rmi || NewOpc == X86::VPERM2I128rmi) &&
150 "Unexpected new opcode!");
151 MachineOperand &Imm = MI.getOperand(MI.getNumExplicitOperands() - 1);
152 int64_t ImmVal = Imm.getImm();
153 // Set bit 5, move bit 1 to bit 4, copy bit 0.
154 Imm.setImm(0x20 | ((ImmVal & 2) << 3) | (ImmVal & 1));
155 break;
156 }
157 case X86::VRNDSCALEPDZ128rri:
158 case X86::VRNDSCALEPDZ128rmi:
159 case X86::VRNDSCALEPSZ128rri:
160 case X86::VRNDSCALEPSZ128rmi:
161 case X86::VRNDSCALEPDZ256rri:
162 case X86::VRNDSCALEPDZ256rmi:
163 case X86::VRNDSCALEPSZ256rri:
164 case X86::VRNDSCALEPSZ256rmi:
165 case X86::VRNDSCALESDZrri:
166 case X86::VRNDSCALESDZrmi:
167 case X86::VRNDSCALESSZrri:
168 case X86::VRNDSCALESSZrmi:
169 case X86::VRNDSCALESDZrri_Int:
170 case X86::VRNDSCALESDZrmi_Int:
171 case X86::VRNDSCALESSZrri_Int:
172 case X86::VRNDSCALESSZrmi_Int:
173 const MachineOperand &Imm = MI.getOperand(MI.getNumExplicitOperands() - 1);
174 int64_t ImmVal = Imm.getImm();
175 // Ensure that only bits 3:0 of the immediate are used.
176 if ((ImmVal & 0xf) != ImmVal)
177 return false;
178 break;
179 }
180
181 return true;
182}
183
184static unsigned getMovMskBits(unsigned Opc) {
185 switch (Opc) {
186 case X86::VPMOVQ2MZ128kr:
187 case X86::VPCMPQZ128rri:
188 return 2;
189 case X86::VPMOVQ2MZ256kr:
190 case X86::VPMOVD2MZ128kr:
191 case X86::VPCMPQZ256rri:
192 case X86::VPCMPDZ128rri:
193 return 4;
194 case X86::VPMOVD2MZ256kr:
195 case X86::VPCMPDZ256rri:
196 return 8;
197 case X86::VPMOVB2MZ128kr:
198 case X86::VPCMPBZ128rri:
199 return 16;
200 case X86::VPMOVB2MZ256kr:
201 case X86::VPCMPBZ256rri:
202 return 32;
203 default:
204 llvm_unreachable("Unknown opcode");
205 }
206}
207
208static bool isKMovNarrowing(unsigned MaskBits, unsigned KMOVOpc) {
209 unsigned KMOVSize = 0;
210 switch (KMOVOpc) {
211 case X86::KMOVBrk:
212 KMOVSize = 8;
213 break;
214 case X86::KMOVWrk:
215 KMOVSize = 16;
216 break;
217 case X86::KMOVDrk:
218 KMOVSize = 32;
219 break;
220 default:
221 llvm_unreachable("Unknown KMOV opcode");
222 }
223
224 return KMOVSize < MaskBits;
225}
226
227static bool isZeroVector(const MachineInstr &MI) {
228 switch (MI.getOpcode()) {
229 case X86::VPXORrr:
230 case X86::VPXORYrr:
231 case X86::VXORPSrr:
232 case X86::VXORPSYrr:
233 return MI.getOperand(1).getReg() == MI.getOperand(2).getReg();
234 default:
235 return false;
236 }
237}
238
239static bool isAllOnesVector(const MachineInstr &MI, bool Is256Bit) {
240 switch (MI.getOpcode()) {
241 case X86::VPCMPEQDrr:
242 return !Is256Bit && MI.getOperand(1).getReg() == MI.getOperand(2).getReg();
243 case X86::VPCMPEQDYrr:
244 return MI.getOperand(1).getReg() == MI.getOperand(2).getReg();
245 default:
246 return false;
247 }
248}
249
251 bool IsZero, bool Is256Bit,
252 const TargetRegisterInfo *TRI) {
254 MI.getParent()->begin(), MachineBasicBlock::iterator(MI)))) {
255 if (!DefMI.modifiesRegister(Reg, TRI))
256 continue;
257 // Stop at the nearest def/clobber; an older matching constant may no
258 // longer be the reaching definition.
259 if (IsZero ? isZeroVector(DefMI) : isAllOnesVector(DefMI, Is256Bit))
260 return &DefMI;
261 break;
262 }
263 return nullptr;
264}
265
266static bool isCompressibleBlendVUse(unsigned BlendOpc, unsigned UseOpc) {
267 switch (BlendOpc) {
268 case X86::VBLENDVPSrrr:
269 switch (UseOpc) {
270 case X86::VMOVAPSZ128rrk:
271 case X86::VMOVUPSZ128rrk:
272 case X86::VMOVDQA32Z128rrk:
273 case X86::VMOVDQU32Z128rrk:
274 return true;
275 default:
276 return false;
277 }
278 case X86::VBLENDVPSYrrr:
279 switch (UseOpc) {
280 case X86::VMOVAPSZ256rrk:
281 case X86::VMOVUPSZ256rrk:
282 case X86::VMOVDQA32Z256rrk:
283 case X86::VMOVDQU32Z256rrk:
284 return true;
285 default:
286 return false;
287 }
288 case X86::VBLENDVPDrrr:
289 switch (UseOpc) {
290 case X86::VMOVAPDZ128rrk:
291 case X86::VMOVUPDZ128rrk:
292 case X86::VMOVDQA64Z128rrk:
293 case X86::VMOVDQU64Z128rrk:
294 return true;
295 default:
296 return false;
297 }
298 case X86::VBLENDVPDYrrr:
299 switch (UseOpc) {
300 case X86::VMOVAPDZ256rrk:
301 case X86::VMOVUPDZ256rrk:
302 case X86::VMOVDQA64Z256rrk:
303 case X86::VMOVDQU64Z256rrk:
304 return true;
305 default:
306 return false;
307 }
308 case X86::VPBLENDVBrrr:
309 return UseOpc == X86::VMOVDQU8Z128rrk;
310 case X86::VPBLENDVBYrrr:
311 return UseOpc == X86::VMOVDQU8Z256rrk;
312 default:
313 return false;
314 }
315}
316
317// Try to compress mask producer chains:
318// vpmov*2m %xmm0, %k0 -> (erase this)
319// kmov* %k0, %eax -> vmovmskp* %xmm0, %eax
320//
321// vpcmpge* $0, %xmm0, %k0 -> (erase this) (X >= 0)
322// vpcmpgt* $-1, %xmm0, %k0 -> (erase this) (X > -1)
323// kmov* %k0, %eax -> vmovmskp* %xmm0, %eax
324// bounded complement of %eax
325//
326// vpmov*2m %xmm0, %k1 -> (erase this)
327// vmov* %xmm1, %xmm2 {%k1} -> vblendv* %xmm0, %xmm2, %xmm1, %xmm2
329 const X86Subtarget &ST,
331 const X86InstrInfo *TII = ST.getInstrInfo();
332 const TargetRegisterInfo *TRI = ST.getRegisterInfo();
333 MachineRegisterInfo *MRI = &MBB.getParent()->getRegInfo();
334
335 unsigned Opc = MI.getOpcode();
336 bool IsSignMaskCmp = Opc == X86::VPCMPBZ128rri || Opc == X86::VPCMPBZ256rri ||
337 Opc == X86::VPCMPDZ128rri || Opc == X86::VPCMPDZ256rri ||
338 Opc == X86::VPCMPQZ128rri || Opc == X86::VPCMPQZ256rri;
339 if (!IsSignMaskCmp && Opc != X86::VPMOVD2MZ128kr &&
340 Opc != X86::VPMOVD2MZ256kr && Opc != X86::VPMOVQ2MZ128kr &&
341 Opc != X86::VPMOVQ2MZ256kr && Opc != X86::VPMOVB2MZ128kr &&
342 Opc != X86::VPMOVB2MZ256kr)
343 return false;
344
346 return false;
347
348 Register MaskReg = MI.getOperand(0).getReg();
349 Register SrcVecReg = MI.getOperand(1).getReg();
350 MachineInstr *ConstantDef = nullptr;
351 bool ConstantDefOnlyFeedsCmp = false;
352
353 if (IsSignMaskCmp) {
354 int64_t Pred = MI.getOperand(3).getImm();
355 // VPCMP signed predicates: nlt (5) folds X >= 0, nle (6) folds X > -1.
356 if (Pred != 5 && Pred != 6)
357 return false;
358 Register ConstantReg = MI.getOperand(2).getReg();
359 bool Is256Bit = Opc == X86::VPCMPBZ256rri || Opc == X86::VPCMPDZ256rri ||
360 Opc == X86::VPCMPQZ256rri;
361 // The sign-mask fold is valid only for compares against the reaching
362 // zero/all-ones vector definition.
363 ConstantDef =
364 getSignMaskConstantDef(MI, ConstantReg, Pred == 5, Is256Bit, TRI);
365 if (!ConstantDef)
366 return false;
367 // If the constant feeds only this compare, erase it with the compare.
368 ConstantDefOnlyFeedsCmp = !TRI->regsOverlap(ConstantReg, SrcVecReg);
369 for (MachineInstr &UseMI :
370 llvm::make_range(std::next(MachineBasicBlock::iterator(*ConstantDef)),
372 if (UseMI.readsRegister(ConstantReg, TRI)) {
373 ConstantDefOnlyFeedsCmp = false;
374 break;
375 }
376 }
377
378 unsigned MovMskOpc = 0;
379 unsigned BlendOpc = 0;
380 switch (Opc) {
381 case X86::VPCMPDZ128rri:
382 case X86::VPMOVD2MZ128kr:
383 MovMskOpc = X86::VMOVMSKPSrr;
384 BlendOpc = X86::VBLENDVPSrrr;
385 break;
386 case X86::VPCMPDZ256rri:
387 case X86::VPMOVD2MZ256kr:
388 MovMskOpc = X86::VMOVMSKPSYrr;
389 BlendOpc = X86::VBLENDVPSYrrr;
390 break;
391 case X86::VPCMPQZ128rri:
392 case X86::VPMOVQ2MZ128kr:
393 MovMskOpc = X86::VMOVMSKPDrr;
394 BlendOpc = X86::VBLENDVPDrrr;
395 break;
396 case X86::VPCMPQZ256rri:
397 case X86::VPMOVQ2MZ256kr:
398 MovMskOpc = X86::VMOVMSKPDYrr;
399 BlendOpc = X86::VBLENDVPDYrrr;
400 break;
401 case X86::VPCMPBZ128rri:
402 case X86::VPMOVB2MZ128kr:
403 MovMskOpc = X86::VPMOVMSKBrr;
404 BlendOpc = X86::VPBLENDVBrrr;
405 break;
406 case X86::VPCMPBZ256rri:
407 case X86::VPMOVB2MZ256kr:
408 MovMskOpc = X86::VPMOVMSKBYrr;
409 BlendOpc = X86::VPBLENDVBYrrr;
410 break;
411 default:
412 llvm_unreachable("Unknown VPMOV opcode");
413 }
414
415 MachineInstr *KMovMI = nullptr;
416 MachineInstr *BlendMI = nullptr;
417
418 for (MachineInstr &CurMI : llvm::make_range(
419 std::next(MachineBasicBlock::iterator(MI)), MBB.end())) {
420 if (CurMI.readsRegister(MaskReg, TRI)) {
421 if (KMovMI || BlendMI)
422 return false; // Fail: Mask has MULTIPLE uses
423
424 unsigned UseOpc = CurMI.getOpcode();
425 bool IsKMOV = UseOpc == X86::KMOVBrk || UseOpc == X86::KMOVWrk ||
426 UseOpc == X86::KMOVDrk;
427 // Only allow non-narrowing KMOV uses of the mask.
428 if (IsKMOV && CurMI.getOperand(1).getReg() == MaskReg &&
429 !usesExtendedRegister(CurMI) &&
430 !isKMovNarrowing(getMovMskBits(Opc), UseOpc)) {
431 KMovMI = &CurMI;
432 // continue scanning to ensure
433 // there are no *other* uses of the mask later in the block.
434 } else if (!IsSignMaskCmp && isCompressibleBlendVUse(BlendOpc, UseOpc) &&
435 CurMI.getOperand(2).getReg() == MaskReg &&
436 !usesExtendedRegister(CurMI) &&
437 checkPredicate(BlendOpc, &ST)) {
438 BlendMI = &CurMI;
439 } else {
440 return false;
441 }
442 }
443
444 if (CurMI.modifiesRegister(MaskReg, TRI)) {
445 if (!KMovMI && !BlendMI)
446 return false; // Mask clobbered before use
447 break;
448 }
449
450 if (!KMovMI && !BlendMI && CurMI.modifiesRegister(SrcVecReg, TRI)) {
451 return false; // SrcVecReg modified before it could be reused
452 }
453 }
454
455 if (!KMovMI && !BlendMI)
456 return false;
457
458 unsigned MovMskBits = getMovMskBits(Opc);
459 // Bounded complements define EFLAGS, unlike VPCMP + KMOV. A 32-bit
460 // complement uses NOT, which does not modify EFLAGS.
461 if (IsSignMaskCmp && KMovMI) {
462 if (KMovMI->getOperand(0).isDead() ||
463 (MovMskBits != 32 &&
464 MBB.computeRegisterLiveness(
465 TRI, X86::EFLAGS,
466 std::next(MachineBasicBlock::const_iterator(*KMovMI)),
468 return false;
469 }
470
471 // Check if MaskReg is used in any other basic blocks
472 for (const MachineInstr &UseMI : MRI->use_instructions(MaskReg))
473 if (UseMI.getParent() != &MBB)
474 return false;
475
476 // Apply the transformation
477 MachineInstr *NewMI = nullptr;
478 if (KMovMI) {
479 MachineOperand OldDst = KMovMI->getOperand(0);
480 KMovMI->setDesc(TII->get(MovMskOpc));
481 MachineOperand &NewSrc = KMovMI->getOperand(1);
482 NewSrc.setReg(SrcVecReg);
483 // setReg() keeps the mask operand's kill flag; take the source's kill
484 // state from the VPMOV instead.
485 NewSrc.setIsKill(MI.getOperand(1).isKill());
486 NewMI = KMovMI;
487 if (IsSignMaskCmp) {
488 Register DstReg = OldDst.getReg();
489 int64_t ComplementMask =
490 APInt::getLowBitsSet(32, MovMskBits).getSExtValue();
491 unsigned ComplementOpc =
492 MovMskBits == 32
493 ? X86::NOT32r
494 : (isInt<8>(ComplementMask) ? X86::XOR32ri8 : X86::XOR32ri);
495 auto MIB = BuildMI(MBB, std::next(MachineBasicBlock::iterator(*KMovMI)),
496 KMovMI->getDebugLoc(), TII->get(ComplementOpc), DstReg)
497 .addReg(DstReg, RegState::Kill);
498 if (MovMskBits != 32) {
499 MIB.addImm(ComplementMask);
500 MIB->findRegisterDefOperand(X86::EFLAGS, TRI)->setIsDead();
501 }
502 MIB->getOperand(0).setIsRenamable(OldDst.isRenamable());
503 }
504 } else if (BlendMI) {
505 const MachineOperand &MaskVec = MI.getOperand(1);
506 const MachineOperand &Dst = BlendMI->getOperand(0);
507 const MachineOperand &Passthru = BlendMI->getOperand(1);
508 const MachineOperand &Src = BlendMI->getOperand(3);
509
510 // Build a replacement instead of changing BlendMI in place because
511 // VMOV*rrk has a tied passthrough operand and a different operand order
512 // than VBLENDV.
513 auto MIB =
514 BuildMI(MBB, *BlendMI, BlendMI->getDebugLoc(), TII->get(BlendOpc))
515 .addReg(Dst.getReg(), getRegState(Dst))
516 .addReg(Passthru.getReg(), getRegState(Passthru))
517 .addReg(Src.getReg(), getRegState(Src))
518 .addReg(MaskVec.getReg(), getRegState(MaskVec));
519 NewMI = MIB;
520 ToErase.push_back(BlendMI);
521 }
522 assert(NewMI && "Expected a compressed instruction");
524 ToErase.push_back(&MI);
525 if (ConstantDefOnlyFeedsCmp && MI.getOperand(2).isKill())
526 ToErase.push_back(ConstantDef);
527 return true;
528}
529
531 const X86Subtarget &ST,
533 uint64_t TSFlags = MI.getDesc().TSFlags;
534
535 // Check for EVEX instructions only.
536 if ((TSFlags & X86II::EncodingMask) != X86II::EVEX)
537 return false;
538
539 // Instructions with mask or 512-bit vector can't be converted to VEX.
540 if (TSFlags & (X86II::EVEX_K | X86II::EVEX_L2))
541 return false;
542
543 // Specialized mask-producing folds to MOVMSK/VBLENDV first.
544 if (tryCompressMaskProducer(MI, MBB, ST, ToErase))
545 return true;
546
547 auto IsRedundantNewDataDest = [&](unsigned &Opc) {
548 // $rbx = ADD64rr_ND $rbx, $rax / $rbx = ADD64rr_ND $rax, $rbx
549 // ->
550 // $rbx = ADD64rr $rbx, $rax
551 const MCInstrDesc &Desc = MI.getDesc();
552 Register Reg0 = MI.getOperand(0).getReg();
553 const MachineOperand &Op1 = MI.getOperand(1);
554 if (!Op1.isReg() || X86::getFirstAddrOperandIdx(MI) == 1 ||
555 X86::isCFCMOVCC(MI.getOpcode()))
556 return false;
557 Register Reg1 = Op1.getReg();
558 if (Reg1 == Reg0)
559 return true;
560
561 // Op1 and Op2 may be commutable for ND instructions.
562 if (!Desc.isCommutable() || Desc.getNumOperands() < 3 ||
563 !MI.getOperand(2).isReg() || MI.getOperand(2).getReg() != Reg0)
564 return false;
565 // Opcode may change after commute, e.g. SHRD -> SHLD
566 ST.getInstrInfo()->commuteInstruction(MI, false, 1, 2);
567 Opc = MI.getOpcode();
568 return true;
569 };
570
571 // EVEX_B has several meanings.
572 // AVX512:
573 // register form: rounding control or SAE
574 // memory form: broadcast
575 //
576 // APX:
577 // MAP4: NDD, ZU
578 //
579 // For AVX512 cases, EVEX prefix is needed in order to carry this information
580 // thus preventing the transformation to VEX encoding.
581 bool IsND = X86II::hasNewDataDest(TSFlags);
582 unsigned Opc = MI.getOpcode();
583 bool IsSetZUCCm = Opc == X86::SETZUCCm;
584 if (TSFlags & X86II::EVEX_B && !IsND && !IsSetZUCCm)
585 return false;
586 // MOVBE*rr is special because it has semantic of NDD but not set EVEX_B.
587 bool IsNDLike = IsND || Opc == X86::MOVBE32rr || Opc == X86::MOVBE64rr;
588 bool IsRedundantNDD = IsNDLike ? IsRedundantNewDataDest(Opc) : false;
589
590 auto GetCompressedOpc = [&](unsigned Opc) -> unsigned {
591 ArrayRef<X86TableEntry> Table = ArrayRef(X86CompressEVEXTable);
592 const auto I = llvm::lower_bound(Table, Opc);
593 if (I == Table.end() || I->OldOpc != Opc)
594 return 0;
595
596 if (usesExtendedRegister(MI) || !checkPredicate(I->NewOpc, &ST) ||
597 !performCustomAdjustments(MI, I->NewOpc))
598 return 0;
599 return I->NewOpc;
600 };
601
602 Register Dst = MI.getOperand(0).getReg();
603 if (IsRedundantNDD) {
604 // Redundant NDD ops cannot be safely compressed if either:
605 // - the legacy op would introduce a partial write that BreakFalseDeps
606 // identified as a potential stall, or
607 // - the op is writing to a subregister of a live register, i.e. the
608 // full (zeroed) result is used.
609 // Both cases are indicated by an implicit def of the superregister.
610 if (Dst &&
611 (X86::GR16RegClass.contains(Dst) || X86::GR8RegClass.contains(Dst))) {
612 Register Super = getX86SubSuperRegister(Dst, 64);
613 if (MI.definesRegister(Super, /*TRI=*/nullptr))
614 IsRedundantNDD = false;
615 }
616
617 // ADDrm/mr instructions with NDD + relocation had been transformed to the
618 // instructions without NDD in X86SuppressAPXForRelocation pass. That is to
619 // keep backward compatibility with linkers without APX support.
622 "Unexpected NDD instruction with relocation!");
623 } else if (Opc == X86::ADD32ri_ND || Opc == X86::ADD64ri32_ND ||
624 Opc == X86::ADD32rr_ND || Opc == X86::ADD64rr_ND) {
625 // Non-redundant NDD ADD can be compressed to LEA when:
626 // - No EGPR register used and
627 // - EFLAGS is dead.
628 if (!usesExtendedRegister(MI) &&
629 MI.registerDefIsDead(X86::EFLAGS, /*TRI=*/nullptr)) {
630 Register Src1 = MI.getOperand(1).getReg();
631 const MachineOperand &Src2 = MI.getOperand(2);
632 bool Is32BitReg = Opc == X86::ADD32ri_ND || Opc == X86::ADD32rr_ND;
633 const MCInstrDesc &NewDesc =
634 ST.getInstrInfo()->get(Is32BitReg ? X86::LEA64_32r : X86::LEA64r);
635 if (Is32BitReg)
636 Src1 = getX86SubSuperRegister(Src1, 64);
637 MachineInstrBuilder MIB = BuildMI(MBB, MI, MI.getDebugLoc(), NewDesc, Dst)
638 .addReg(Src1)
639 .addImm(1);
640 if (Opc == X86::ADD32ri_ND || Opc == X86::ADD64ri32_ND)
641 MIB.addReg(0).add(Src2);
642 else if (Is32BitReg)
643 MIB.addReg(getX86SubSuperRegister(Src2.getReg(), 64)).addImm(0);
644 else
645 MIB.add(Src2).addImm(0);
646 MIB.addReg(0);
647 MI.removeFromParent();
648 return true;
649 }
650 }
651
652 // NonNF -> NF only if it's not a compressible NDD instruction and eflags is
653 // dead.
654 unsigned NewOpc = IsRedundantNDD
656 : ((IsNDLike && ST.hasNF() &&
657 MI.registerDefIsDead(X86::EFLAGS, /*TRI=*/nullptr))
659 : GetCompressedOpc(Opc));
660
661 if (!NewOpc)
662 return false;
663 // NF (No Flags) instructions cannot compress to VEX/legacy encoding.
664 // NF_ND can still compress to NF (both remain EVEX).
665 assert((IsND || !(TSFlags & X86II::EVEX_NF)) &&
666 "Unexpected to compress NF instructions without ND.");
667
668 const MCInstrDesc &NewDesc = ST.getInstrInfo()->get(NewOpc);
669 MI.setDesc(NewDesc);
670 unsigned AsmComment;
671 switch (NewDesc.TSFlags & X86II::EncodingMask) {
672 case X86II::LEGACY:
673 AsmComment = X86::AC_EVEX_2_LEGACY;
674 break;
675 case X86II::VEX:
676 AsmComment = X86::AC_EVEX_2_VEX;
677 break;
678 case X86II::EVEX:
679 AsmComment = X86::AC_EVEX_2_EVEX;
680 assert(IsND && (NewDesc.TSFlags & X86II::EVEX_NF) &&
681 "Unknown EVEX2EVEX compression");
682 break;
683 default:
684 llvm_unreachable("Unknown EVEX compression");
685 }
686 MI.setAsmPrinterFlag(AsmComment);
687 if (IsRedundantNDD)
688 MI.tieOperands(0, 1);
689
690 return true;
691}
692
693static bool runOnMF(MachineFunction &MF) {
694 LLVM_DEBUG(dbgs() << "Start X86CompressEVEXPass\n";);
695#ifndef NDEBUG
696 // Make sure the tables are sorted.
697 static std::atomic<bool> TableChecked(false);
698 if (!TableChecked.load(std::memory_order_relaxed)) {
699 assert(llvm::is_sorted(X86CompressEVEXTable) &&
700 "X86CompressEVEXTable is not sorted!");
701 TableChecked.store(true, std::memory_order_relaxed);
702 }
703#endif
704 const X86Subtarget &ST = MF.getSubtarget<X86Subtarget>();
705 if (!ST.hasAVX512() && !ST.hasEGPR() && !ST.hasNDD() && !ST.hasZU())
706 return false;
707
708 bool Changed = false;
709
710 for (MachineBasicBlock &MBB : MF) {
712
714 Changed |= CompressEVEXImpl(MI, MBB, ST, ToErase);
715 }
716
717 for (MachineInstr *MI : ToErase) {
718 MI->eraseFromParent();
719 }
720 }
721 LLVM_DEBUG(dbgs() << "End X86CompressEVEXPass\n";);
722 return Changed;
723}
724
726 false)
727
729 return new CompressEVEXLegacy();
730}
731
732bool CompressEVEXLegacy::runOnMachineFunction(MachineFunction &MF) {
733 return runOnMF(MF);
734}
735
736PreservedAnalyses
MachineInstrBuilder & UseMI
MachineInstrBuilder MachineInstrBuilder & DefMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned Imm
unsigned uint64_t
MachineBasicBlock & MBB
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition Value.cpp:484
This file defines the SmallVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
#define COMP_EVEX_DESC
static bool performCustomAdjustments(MachineInstr &MI, unsigned NewOpc)
static bool CompressEVEXImpl(MachineInstr &MI, MachineBasicBlock &MBB, const X86Subtarget &ST, SmallVectorImpl< MachineInstr * > &ToErase)
static bool isKMovNarrowing(unsigned MaskBits, unsigned KMOVOpc)
#define COMP_EVEX_NAME
static unsigned getMovMskBits(unsigned Opc)
static bool isZeroVector(const MachineInstr &MI)
static bool isAllOnesVector(const MachineInstr &MI, bool Is256Bit)
static bool isCompressibleBlendVUse(unsigned BlendOpc, unsigned UseOpc)
cl::opt< bool > X86EnableAPXForRelocation
static bool tryCompressMaskProducer(MachineInstr &MI, MachineBasicBlock &MBB, const X86Subtarget &ST, SmallVectorImpl< MachineInstr * > &ToErase)
static bool runOnMF(MachineFunction &MF)
static MachineInstr * getSignMaskConstantDef(MachineInstr &MI, Register Reg, bool IsZero, bool Is256Bit, const TargetRegisterInfo *TRI)
static bool usesExtendedRegister(const MachineInstr &MI)
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:303
int64_t getSExtValue() const
Get sign extended value.
Definition APInt.h:1583
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
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:314
Describe properties that are true of each instruction in the target description file.
Wrapper class representing physical registers. Should be passed by value.
Definition MCRegister.h:41
MachineInstrBundleIterator< const MachineInstr > const_iterator
MachineInstrBundleIterator< MachineInstr > iterator
@ LQR_Dead
Register is known to be fully dead.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
Properties which a MachineFunction may have at a given point in time.
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 & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & add(const MachineOperand &MO) const
Representation of each machine instruction.
bool modifiesRegister(Register Reg, const TargetRegisterInfo *TRI) const
Return true if the MachineInstr modifies (fully define or partially define) the specified register.
void setAsmPrinterFlag(AsmPrinterFlagTy Flag)
Set a flag for the AsmPrinter.
LLVM_ABI void setDesc(const MCInstrDesc &TID)
Replace the instruction descriptor (thus opcode) of the current instruction with a new one.
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
const MachineOperand & getOperand(unsigned i) const
MachineOperand class - Representation of each machine instruction operand.
LLVM_ABI void setIsRenamable(bool Val=true)
bool isReg() const
isReg - Tests if this is a MO_Register operand.
LLVM_ABI void setReg(Register Reg)
Change the register this operand corresponds to.
void setIsKill(bool Val=true)
LLVM_ABI bool isRenamable() const
isRenamable - Returns true if this register may be renamed, i.e.
Register getReg() const
getReg - Returns the register number.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
iterator_range< use_instr_iterator > use_instructions(Register Reg) const
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
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
Changed
Pass manager infrastructure for declaring and invalidating analyses.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
bool isZMMReg(MCRegister Reg)
bool hasNewDataDest(uint64_t TSFlags)
@ EVEX
EVEX - Specifies that this instruction use EVEX form which provides syntax support up to 32 512-bit r...
@ VEX
VEX - encoding using 0xC4/0xC5.
@ LEGACY
LEGACY - encoding using REX/REX2 or w/o opcode prefix.
bool isApxExtendedReg(MCRegister Reg)
int getFirstAddrOperandIdx(const MachineInstr &MI)
Return the index of the instruction's first address operand, if it has a memory reference,...
unsigned getNonNDVariant(unsigned Opc)
unsigned getNFVariant(unsigned Opc)
This is an optimization pass for GlobalISel generic memory operations.
FunctionPass * createX86CompressEVEXLegacyPass()
static bool isAddMemInstrWithRelocation(const MachineInstr &MI)
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition MathExtras.h:166
@ Kill
The last use of a register.
MCRegister getX86SubSuperRegister(MCRegister Reg, unsigned Size, bool High=false)
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:633
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
Op::Description Desc
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
auto reverse(ContainerTy &&C)
Definition STLExtras.h:407
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool is_sorted(R &&Range, Compare C)
Wrapper function around std::is_sorted to check if elements in a range R are sorted with respect to a...
Definition STLExtras.h:1970
RegState getRegState(const MachineOperand &RegOp)
Get all register state flags from machine operand RegOp.
auto lower_bound(R &&Range, T &&Value)
Provide wrappers to std::lower_bound which take ranges instead of having to pass begin/end explicitly...
Definition STLExtras.h:2052
ArrayRef(const T &OneElt) -> ArrayRef< T >