LLVM 24.0.0git
RISCVOptWInstrs.cpp
Go to the documentation of this file.
1//===- RISCVOptWInstrs.cpp - MI W instruction optimizations ---------------===//
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 does some optimizations for *W instructions at the MI level.
10//
11// First it removes unneeded sext.w instructions. Either because the sign
12// extended bits aren't consumed or because the input was already sign extended
13// by an earlier instruction.
14//
15// Then:
16// 1. Unless explicit disabled or the target prefers instructions with W suffix,
17// it removes the -w suffix from opw instructions whenever all users are
18// dependent only on the lower word of the result of the instruction.
19// The cases handled are:
20// * addw because c.add has a larger register encoding than c.addw.
21// * addiw because it helps reduce test differences between RV32 and RV64
22// w/o being a pessimization.
23// * mulw because c.mulw doesn't exist but c.mul does (w/ zcb)
24// * slliw because c.slliw doesn't exist and c.slli does
25//
26// 2. Or if explicit enabled or the target prefers instructions with W suffix,
27// it adds the W suffix to the instruction whenever all users are dependent
28// only on the lower word of the result of the instruction.
29// The cases handled are:
30// * add/addi/sub/mul.
31// * slli with imm < 32.
32// * ld/lwu.
33//===---------------------------------------------------------------------===//
34
35#include "RISCV.h"
37#include "RISCVSubtarget.h"
38#include "llvm/ADT/SmallSet.h"
39#include "llvm/ADT/Statistic.h"
42
43using namespace llvm;
44
45#define DEBUG_TYPE "riscv-opt-w-instrs"
46#define RISCV_OPT_W_INSTRS_NAME "RISC-V Optimize W Instructions"
47
48STATISTIC(NumRemovedSExtW, "Number of removed sign-extensions");
49STATISTIC(NumTransformedToWInstrs,
50 "Number of instructions transformed to W-ops");
51STATISTIC(NumTransformedToNonWInstrs,
52 "Number of instructions transformed to non-W-ops");
53
54static cl::opt<bool> DisableSExtWRemoval("riscv-disable-sextw-removal",
55 cl::desc("Disable removal of sext.w"),
56 cl::init(false), cl::Hidden);
57static cl::opt<bool> DisableStripWSuffix("riscv-disable-strip-w-suffix",
58 cl::desc("Disable strip W suffix"),
59 cl::init(false), cl::Hidden);
60
61namespace {
62
63class RISCVOptWInstrsImpl {
64public:
65 bool run(MachineFunction &MF);
66
67private:
68 bool removeSExtWInstrs(MachineFunction &MF, const RISCVInstrInfo &TII,
69 const RISCVSubtarget &ST, MachineRegisterInfo &MRI);
70 bool canonicalizeWSuffixes(MachineFunction &MF, const RISCVInstrInfo &TII,
71 const RISCVSubtarget &ST,
73};
74
75class RISCVOptWInstrsLegacy : public MachineFunctionPass {
76public:
77 static char ID;
78
79 RISCVOptWInstrsLegacy() : MachineFunctionPass(ID) {}
80
81 bool runOnMachineFunction(MachineFunction &MF) override;
82
83 void getAnalysisUsage(AnalysisUsage &AU) const override {
84 AU.setPreservesCFG();
86 }
87
88 StringRef getPassName() const override { return RISCV_OPT_W_INSTRS_NAME; }
89};
90
91} // end anonymous namespace
92
93char RISCVOptWInstrsLegacy::ID = 0;
95 false, false)
96
98 return new RISCVOptWInstrsLegacy();
99}
100
101static bool vectorPseudoHasAllNBitUsers(const MachineInstr &MI, unsigned OpIdx,
102 unsigned Bits) {
103 unsigned MCOpcode = RISCV::getRVVMCOpcode(MI.getOpcode());
104
105 if (!MCOpcode)
106 return false;
107
108 const MCInstrDesc &MCID = MI.getDesc();
109 const uint64_t TSFlags = MCID.TSFlags;
110 if (!RISCVII::hasSEWOp(TSFlags))
111 return false;
112 assert(RISCVII::hasVLOp(TSFlags));
113 const unsigned Log2SEW = MI.getOperand(RISCVII::getSEWOpNum(MCID)).getImm();
114
115 if (OpIdx == RISCVII::getVLOpNum(MCID))
116 return false;
117
118 auto NumDemandedBits =
119 RISCV::getVectorLowDemandedScalarBits(MCOpcode, Log2SEW);
120 return NumDemandedBits && Bits >= *NumDemandedBits;
121}
122
123// Checks if all users only demand the lower \p OrigBits of the original
124// instruction's result.
125// TODO: handle multiple interdependent transformations
126static bool hasAllNBitUsers(const MachineInstr &OrigMI,
127 const RISCVSubtarget &ST,
128 const MachineRegisterInfo &MRI, unsigned OrigBits) {
129
132
133 Worklist.emplace_back(&OrigMI, OrigBits);
134
135 while (!Worklist.empty()) {
136 auto P = Worklist.pop_back_val();
137 const MachineInstr *MI = P.first;
138 unsigned Bits = P.second;
139
140 if (!Visited.insert(P).second)
141 continue;
142
143 // Only handle instructions with one def.
144 if (MI->getNumExplicitDefs() != 1)
145 return false;
146
147 Register DestReg = MI->getOperand(0).getReg();
148 if (!DestReg.isVirtual())
149 return false;
150
151 for (auto &UserOp : MRI.use_nodbg_operands(DestReg)) {
152 const MachineInstr *UserMI = UserOp.getParent();
153 unsigned OpIdx = UserOp.getOperandNo();
154
155 switch (UserMI->getOpcode()) {
156 default:
157 if (vectorPseudoHasAllNBitUsers(*UserMI, OpIdx, Bits))
158 break;
159 return false;
160
161 case RISCV::ADDIW:
162 case RISCV::ADDW:
163 case RISCV::DIVUW:
164 case RISCV::DIVW:
165 case RISCV::MULW:
166 case RISCV::REMUW:
167 case RISCV::REMW:
168 case RISCV::SLLW:
169 case RISCV::SRAIW:
170 case RISCV::SRAW:
171 case RISCV::SRLIW:
172 case RISCV::SRLW:
173 case RISCV::SUBW:
174 case RISCV::ROLW:
175 case RISCV::RORW:
176 case RISCV::RORIW:
177 case RISCV::CLSW:
178 case RISCV::CLZW:
179 case RISCV::CTZW:
180 case RISCV::CPOPW:
181 case RISCV::SLLI_UW:
182 case RISCV::ABSW:
183 case RISCV::FMV_W_X:
184 case RISCV::FCVT_H_W:
185 case RISCV::FCVT_H_W_INX:
186 case RISCV::FCVT_H_WU:
187 case RISCV::FCVT_H_WU_INX:
188 case RISCV::FCVT_S_W:
189 case RISCV::FCVT_S_W_INX:
190 case RISCV::FCVT_S_WU:
191 case RISCV::FCVT_S_WU_INX:
192 case RISCV::FCVT_D_W:
193 case RISCV::FCVT_D_W_INX:
194 case RISCV::FCVT_D_WU:
195 case RISCV::FCVT_D_WU_INX:
196 if (Bits >= 32)
197 break;
198 return false;
199
200 case RISCV::SEXT_B:
201 case RISCV::PACKH:
202 if (Bits >= 8)
203 break;
204 return false;
205 case RISCV::SEXT_H:
206 case RISCV::FMV_H_X:
207 case RISCV::ZEXT_H_RV32:
208 case RISCV::ZEXT_H_RV64:
209 case RISCV::PACKW:
210 if (Bits >= 16)
211 break;
212 return false;
213
214 case RISCV::PACK:
215 if (Bits >= (ST.getXLen() / 2))
216 break;
217 return false;
218
219 case RISCV::SRLI: {
220 // If we are shifting right by less than Bits, and users don't demand
221 // any bits that were shifted into [Bits-1:0], then we can consider this
222 // as an N-Bit user.
223 unsigned ShAmt = UserMI->getOperand(2).getImm();
224 if (Bits > ShAmt) {
225 Worklist.emplace_back(UserMI, Bits - ShAmt);
226 break;
227 }
228 return false;
229 }
230
231 // these overwrite higher input bits, otherwise the lower word of output
232 // depends only on the lower word of input. So check their uses read W.
233 case RISCV::SLLI: {
234 unsigned ShAmt = UserMI->getOperand(2).getImm();
235 if (Bits >= (ST.getXLen() - ShAmt))
236 break;
237 Worklist.emplace_back(UserMI, Bits + ShAmt);
238 break;
239 }
240 case RISCV::SLLIW: {
241 unsigned ShAmt = UserMI->getOperand(2).getImm();
242 if (Bits >= 32 - ShAmt)
243 break;
244 Worklist.emplace_back(UserMI, Bits + ShAmt);
245 break;
246 }
247
248 case RISCV::ANDI: {
249 uint64_t Imm = UserMI->getOperand(2).getImm();
250 if (Bits >= (unsigned)llvm::bit_width(Imm))
251 break;
252 Worklist.emplace_back(UserMI, Bits);
253 break;
254 }
255 case RISCV::ORI: {
256 uint64_t Imm = UserMI->getOperand(2).getImm();
257 if (Bits >= (unsigned)llvm::bit_width<uint64_t>(~Imm))
258 break;
259 Worklist.emplace_back(UserMI, Bits);
260 break;
261 }
262
263 case RISCV::SLL:
264 case RISCV::BSET:
265 case RISCV::BCLR:
266 case RISCV::BINV:
267 // Operand 2 is the shift amount which uses log2(xlen) bits.
268 if (OpIdx == 2) {
269 if (Bits >= Log2_32(ST.getXLen()))
270 break;
271 return false;
272 }
273 Worklist.emplace_back(UserMI, Bits);
274 break;
275
276 case RISCV::SRA:
277 case RISCV::SRL:
278 case RISCV::ROL:
279 case RISCV::ROR:
280 // Operand 2 is the shift amount which uses 6 bits.
281 if (OpIdx == 2 && Bits >= Log2_32(ST.getXLen()))
282 break;
283 return false;
284
285 case RISCV::ADD_UW:
286 case RISCV::SH1ADD_UW:
287 case RISCV::SH2ADD_UW:
288 case RISCV::SH3ADD_UW:
289 // Operand 1 is implicitly zero extended.
290 if (OpIdx == 1 && Bits >= 32)
291 break;
292 Worklist.emplace_back(UserMI, Bits);
293 break;
294
295 case RISCV::BEXTI:
296 if (UserMI->getOperand(2).getImm() >= Bits)
297 return false;
298 break;
299
300 case RISCV::SB:
301 // The first argument is the value to store.
302 if (OpIdx == 0 && Bits >= 8)
303 break;
304 return false;
305 case RISCV::SH:
306 // The first argument is the value to store.
307 if (OpIdx == 0 && Bits >= 16)
308 break;
309 return false;
310 case RISCV::SW:
311 // The first argument is the value to store.
312 if (OpIdx == 0 && Bits >= 32)
313 break;
314 return false;
315
316 // For these, lower word of output in these operations, depends only on
317 // the lower word of input. So, we check all uses only read lower word.
318 case RISCV::COPY:
319 case RISCV::PHI:
320
321 case RISCV::ADD:
322 case RISCV::ADDI:
323 case RISCV::AND:
324 case RISCV::MUL:
325 case RISCV::OR:
326 case RISCV::SUB:
327 case RISCV::XOR:
328 case RISCV::XORI:
329
330 case RISCV::ANDN:
331 case RISCV::CLMUL:
332 case RISCV::ORN:
333 case RISCV::SH1ADD:
334 case RISCV::SH2ADD:
335 case RISCV::SH3ADD:
336 case RISCV::XNOR:
337 case RISCV::BSETI:
338 case RISCV::BCLRI:
339 case RISCV::BINVI:
340 Worklist.emplace_back(UserMI, Bits);
341 break;
342
343 case RISCV::BREV8:
344 case RISCV::ORC_B:
345 // BREV8 and ORC_B work on bytes. Round Bits down to the nearest byte.
346 Worklist.emplace_back(UserMI, alignDown(Bits, 8));
347 break;
348
349 case RISCV::PseudoCCMOVGPR:
350 case RISCV::PseudoCCMOVGPRNoX0:
351 // Either operand 1 or operand 2 is returned by this instruction. If
352 // only the lower word of the result is used, then only the lower word
353 // of operand 1 and 2 is used.
354 if (OpIdx != 1 && OpIdx != 2)
355 return false;
356 Worklist.emplace_back(UserMI, Bits);
357 break;
358
359 case RISCV::CZERO_EQZ:
360 case RISCV::CZERO_NEZ:
361 if (OpIdx != 1)
362 return false;
363 Worklist.emplace_back(UserMI, Bits);
364 break;
365 case RISCV::TH_EXT:
366 case RISCV::TH_EXTU:
367 unsigned Msb = UserMI->getOperand(2).getImm();
368 unsigned Lsb = UserMI->getOperand(3).getImm();
369 // Behavior of Msb < Lsb is not well documented.
370 if (Msb >= Lsb && Bits > Msb)
371 break;
372 return false;
373 }
374 }
375 }
376
377 return true;
378}
379
380static bool hasAllWUsers(const MachineInstr &OrigMI, const RISCVSubtarget &ST,
381 const MachineRegisterInfo &MRI) {
382 return hasAllNBitUsers(OrigMI, ST, MRI, 32);
383}
384
385// This function returns true if the machine instruction always outputs a value
386// where bits 63:32 match bit 31.
387static bool isSignExtendingOpW(const MachineInstr &MI, unsigned OpNo) {
388 uint64_t TSFlags = MI.getDesc().TSFlags;
389
390 // Instructions that can be determined from opcode are marked in tablegen.
392 return true;
393
394 // Special cases that require checking operands.
395 switch (MI.getOpcode()) {
396 // shifting right sufficiently makes the value 32-bit sign-extended
397 case RISCV::SRAI:
398 return MI.getOperand(2).getImm() >= 32;
399 case RISCV::SRLI:
400 return MI.getOperand(2).getImm() > 32;
401 // The LI pattern ADDI rd, X0, imm is sign extended.
402 case RISCV::ADDI:
403 return MI.getOperand(1).isReg() && MI.getOperand(1).getReg() == RISCV::X0;
404 // An ANDI with an 11 bit immediate will zero bits 63:11.
405 case RISCV::ANDI:
406 return isUInt<11>(MI.getOperand(2).getImm());
407 // An ORI with an >11 bit immediate (negative 12-bit) will set bits 63:11.
408 case RISCV::ORI:
409 return !isUInt<11>(MI.getOperand(2).getImm());
410 // A bseti with X0 is sign extended if the immediate is less than 31.
411 case RISCV::BSETI:
412 return MI.getOperand(2).getImm() < 31 &&
413 MI.getOperand(1).getReg() == RISCV::X0;
414 // Copying from X0 produces zero.
415 case RISCV::COPY:
416 return MI.getOperand(1).getReg() == RISCV::X0;
417 // Ignore the scratch register destination.
418 case RISCV::PseudoAtomicLoadNand32:
419 return OpNo == 0;
420 case RISCV::PseudoVMV_X_S: {
421 // vmv.x.s has at least 33 sign bits if log2(sew) <= 5.
422 int64_t Log2SEW = MI.getOperand(2).getImm();
423 assert(Log2SEW >= 3 && Log2SEW <= 6 && "Unexpected Log2SEW");
424 return Log2SEW <= 5;
425 }
426 case RISCV::TH_EXT: {
427 unsigned Msb = MI.getOperand(2).getImm();
428 unsigned Lsb = MI.getOperand(3).getImm();
429 return Msb >= Lsb && (Msb - Lsb + 1) <= 32;
430 }
431 case RISCV::TH_EXTU: {
432 unsigned Msb = MI.getOperand(2).getImm();
433 unsigned Lsb = MI.getOperand(3).getImm();
434 return Msb >= Lsb && (Msb - Lsb + 1) < 32;
435 }
436 case RISCV::SATI_RV64:
437 // Saturates to signed range [-2^(imm-1), 2^(imm-1)-1].
438 // If imm <= 32, result fits in 32-bit signed range, thus sign-extended.
439 return MI.getOperand(2).getImm() <= 32;
440 case RISCV::USATI_RV64:
441 // Saturates to unsigned range [0, 2^imm-1].
442 // If imm < 32, result has bit 31 clear, thus sign-extended.
443 return MI.getOperand(2).getImm() < 32;
444 }
445
446 return false;
447}
448
449static bool isSignExtendedW(Register SrcReg, const RISCVSubtarget &ST,
450 const MachineRegisterInfo &MRI,
452 SmallSet<Register, 4> Visited;
454
455 auto AddRegToWorkList = [&](Register SrcReg) {
456 if (!SrcReg.isVirtual())
457 return false;
458 Worklist.push_back(SrcReg);
459 return true;
460 };
461
462 if (!AddRegToWorkList(SrcReg))
463 return false;
464
465 while (!Worklist.empty()) {
466 Register Reg = Worklist.pop_back_val();
467
468 // If we already visited this register, we don't need to check it again.
469 if (!Visited.insert(Reg).second)
470 continue;
471
473 if (!MI)
474 continue;
475
476 int OpNo = MI->findRegisterDefOperandIdx(Reg, /*TRI=*/nullptr);
477 assert(OpNo != -1 && "Couldn't find register");
478
479 // If this is a sign extending operation we don't need to look any further.
480 if (isSignExtendingOpW(*MI, OpNo))
481 continue;
482
483 // Is this an instruction that propagates sign extend?
484 switch (MI->getOpcode()) {
485 default:
486 // Unknown opcode, give up.
487 return false;
488 case RISCV::COPY: {
489 const MachineFunction *MF = MI->getMF();
490 const RISCVMachineFunctionInfo *RVFI =
492
493 // If this is the entry block and the register is livein, see if we know
494 // it is sign extended.
495 if (MI->getParent() == &MF->front()) {
496 Register VReg = MI->getOperand(0).getReg();
497 if (MF->getRegInfo().isLiveIn(VReg) && RVFI->isSExt32Register(VReg))
498 continue;
499 }
500
501 Register CopySrcReg = MI->getOperand(1).getReg();
502 if (CopySrcReg == RISCV::X10) {
503 // For a method return value, we check the ZExt/SExt flags in attribute.
504 // We assume the following code sequence for method call.
505 // PseudoCALL @bar, ...
506 // ADJCALLSTACKUP 0, 0, implicit-def dead $x2, implicit $x2
507 // %0:gpr = COPY $x10
508 //
509 // We use the PseudoCall to look up the IR function being called to find
510 // its return attributes.
511 const MachineBasicBlock *MBB = MI->getParent();
512 auto II = MI->getIterator();
513 if (II == MBB->instr_begin() ||
514 (--II)->getOpcode() != RISCV::ADJCALLSTACKUP)
515 return false;
516
517 const MachineInstr &CallMI = *(--II);
518 if (!CallMI.isCall() || !CallMI.getOperand(0).isGlobal())
519 return false;
520
521 auto *CalleeFn =
523 if (!CalleeFn)
524 return false;
525
526 auto *IntTy = dyn_cast<IntegerType>(CalleeFn->getReturnType());
527 if (!IntTy)
528 return false;
529
530 const AttributeSet &Attrs = CalleeFn->getAttributes().getRetAttrs();
531 unsigned BitWidth = IntTy->getBitWidth();
532 if ((BitWidth <= 32 && Attrs.hasAttribute(Attribute::SExt)) ||
533 (BitWidth < 32 && Attrs.hasAttribute(Attribute::ZExt)))
534 continue;
535 }
536
537 if (!AddRegToWorkList(CopySrcReg))
538 return false;
539
540 break;
541 }
542
543 // For these, we just need to check if the 1st operand is sign extended.
544 case RISCV::BCLRI:
545 case RISCV::BINVI:
546 case RISCV::BSETI:
547 if (MI->getOperand(2).getImm() >= 31)
548 return false;
549 [[fallthrough]];
550 case RISCV::REM:
551 case RISCV::ANDI:
552 case RISCV::ORI:
553 case RISCV::XORI:
554 case RISCV::SRAI:
555 // |Remainder| is always <= |Dividend|. If D is 32-bit, then so is R.
556 // DIV doesn't work because of the edge case 0xf..f 8000 0000 / (long)-1
557 // Logical operations use a sign extended 12-bit immediate.
558 // Arithmetic shift right can only increase the number of sign bits.
559 if (!AddRegToWorkList(MI->getOperand(1).getReg()))
560 return false;
561
562 break;
563 case RISCV::PseudoCCADDW:
564 case RISCV::PseudoCCADDIW:
565 case RISCV::PseudoCCSUBW:
566 case RISCV::PseudoCCSLLW:
567 case RISCV::PseudoCCSRLW:
568 case RISCV::PseudoCCSRAW:
569 case RISCV::PseudoCCSLLIW:
570 case RISCV::PseudoCCSRLIW:
571 case RISCV::PseudoCCSRAIW:
572 // Returns operand 1 or an ADDW/SUBW/etc. of operands 2 and 3. We only
573 // need to check if operand 1 is sign extended.
574 if (!AddRegToWorkList(MI->getOperand(1).getReg()))
575 return false;
576 break;
577 case RISCV::REMU:
578 case RISCV::AND:
579 case RISCV::OR:
580 case RISCV::XOR:
581 case RISCV::ANDN:
582 case RISCV::ORN:
583 case RISCV::XNOR:
584 case RISCV::MAX:
585 case RISCV::MAXU:
586 case RISCV::MIN:
587 case RISCV::MINU:
588 case RISCV::PseudoCCMOVGPR:
589 case RISCV::PseudoCCMOVGPRNoX0:
590 case RISCV::PseudoCCAND:
591 case RISCV::PseudoCCOR:
592 case RISCV::PseudoCCXOR:
593 case RISCV::PseudoCCANDN:
594 case RISCV::PseudoCCORN:
595 case RISCV::PseudoCCXNOR:
596 case RISCV::PHI:
597 case RISCV::MERGE:
598 case RISCV::MVM:
599 case RISCV::MVMN: {
600 // If all incoming values are sign-extended, the output of AND, OR, XOR,
601 // MIN, MAX, PHI, or bitwise merge instructions is also sign-extended.
602
603 // The input registers for PHI are operand 1, 3, ...
604 // The input registers for PseudoCCMOVGPR(NoX0) are 1 and 2.
605 // The input registers for PseudoCCAND/OR/XOR are 1, 2, and 3.
606 // The input registers for MERGE/MVM/MVMN are 1, 2, and 3.
607 // The input registers for others are operand 1 and 2.
608 unsigned B = 1, E = 3, D = 1;
609 switch (MI->getOpcode()) {
610 case RISCV::PHI:
611 E = MI->getNumOperands();
612 D = 2;
613 break;
614 case RISCV::PseudoCCMOVGPR:
615 case RISCV::PseudoCCMOVGPRNoX0:
616 B = 1;
617 E = 3;
618 break;
619 case RISCV::PseudoCCAND:
620 case RISCV::PseudoCCOR:
621 case RISCV::PseudoCCXOR:
622 case RISCV::PseudoCCANDN:
623 case RISCV::PseudoCCORN:
624 case RISCV::PseudoCCXNOR:
625 B = 1;
626 E = 4;
627 break;
628 case RISCV::MERGE:
629 case RISCV::MVM:
630 case RISCV::MVMN:
631 B = 1;
632 E = 4;
633 break;
634 }
635
636 for (unsigned I = B; I != E; I += D) {
637 if (!MI->getOperand(I).isReg())
638 return false;
639
640 if (!AddRegToWorkList(MI->getOperand(I).getReg()))
641 return false;
642 }
643
644 break;
645 }
646
647 case RISCV::CZERO_EQZ:
648 case RISCV::CZERO_NEZ:
649 // Instructions return zero or operand 1. Result is sign extended if
650 // operand 1 is sign extended.
651 if (!AddRegToWorkList(MI->getOperand(1).getReg()))
652 return false;
653 break;
654
655 case RISCV::ADDI: {
656 if (MI->getOperand(1).isReg() && MI->getOperand(1).getReg().isVirtual()) {
657 if (MachineInstr *SrcMI = MRI.getVRegDef(MI->getOperand(1).getReg())) {
658 if (SrcMI->getOpcode() == RISCV::LUI &&
659 SrcMI->getOperand(1).isImm()) {
660 uint64_t Imm = SrcMI->getOperand(1).getImm();
661 Imm = SignExtend64<32>(Imm << 12);
662 Imm += (uint64_t)MI->getOperand(2).getImm();
663 if (isInt<32>(Imm))
664 continue;
665 }
666 }
667 }
668
669 if (hasAllWUsers(*MI, ST, MRI)) {
670 FixableDef.insert(MI);
671 break;
672 }
673 return false;
674 }
675
676 case RISCV::LD:
677 case RISCV::LXD: {
678 if (MI->hasOneMemOperand() && !(*MI->memoperands_begin())->isVolatile() &&
679 hasAllWUsers(*MI, ST, MRI)) {
680 FixableDef.insert(MI);
681 break;
682 }
683 return false;
684 }
685
686 // With these opcode, we can "fix" them with the W-version
687 // if we know all users of the result only rely on bits 31:0
688 case RISCV::SLLI:
689 // SLLIW reads the lowest 5 bits, while SLLI reads lowest 6 bits
690 if (MI->getOperand(2).getImm() >= 32)
691 return false;
692 [[fallthrough]];
693 case RISCV::ADD:
694 case RISCV::LWU:
695 case RISCV::LXWU:
696 case RISCV::MUL:
697 case RISCV::SUB:
698 if (hasAllWUsers(*MI, ST, MRI)) {
699 FixableDef.insert(MI);
700 break;
701 }
702 return false;
703 }
704 }
705
706 // If we get here, then every node we visited produces a sign extended value
707 // or propagated sign extended values. So the result must be sign extended.
708 return true;
709}
710
711static unsigned getWOp(unsigned Opcode) {
712 switch (Opcode) {
713 case RISCV::ADDI:
714 return RISCV::ADDIW;
715 case RISCV::ADD:
716 return RISCV::ADDW;
717 case RISCV::LD:
718 case RISCV::LWU:
719 return RISCV::LW;
720 case RISCV::LXD:
721 case RISCV::LXWU:
722 return RISCV::LXW;
723 case RISCV::MUL:
724 return RISCV::MULW;
725 case RISCV::SLLI:
726 return RISCV::SLLIW;
727 case RISCV::SUB:
728 return RISCV::SUBW;
729 default:
730 llvm_unreachable("Unexpected opcode for replacement with W variant");
731 }
732}
733
734bool RISCVOptWInstrsImpl::removeSExtWInstrs(MachineFunction &MF,
735 const RISCVInstrInfo &TII,
736 const RISCVSubtarget &ST,
737 MachineRegisterInfo &MRI) {
739 return false;
740
741 bool MadeChange = false;
742 for (MachineBasicBlock &MBB : MF) {
743 for (MachineInstr &MI : llvm::make_early_inc_range(MBB)) {
744 // We're looking for the sext.w pattern ADDIW rd, rs1, 0.
745 if (!RISCVInstrInfo::isSEXT_W(MI))
746 continue;
747
748 Register SrcReg = MI.getOperand(1).getReg();
749
750 SmallPtrSet<MachineInstr *, 4> FixableDefs;
751
752 // If all users only use the lower bits, this sext.w is redundant.
753 // Or if all definitions reaching MI sign-extend their output,
754 // then sext.w is redundant.
755 if (!hasAllWUsers(MI, ST, MRI) &&
756 !isSignExtendedW(SrcReg, ST, MRI, FixableDefs))
757 continue;
758
759 Register DstReg = MI.getOperand(0).getReg();
760 if (!MRI.constrainRegClass(SrcReg, MRI.getRegClass(DstReg)))
761 continue;
762
763 // Convert Fixable instructions to their W versions.
764 for (MachineInstr *Fixable : FixableDefs) {
765 LLVM_DEBUG(dbgs() << "Replacing " << *Fixable);
766 Fixable->setDesc(TII.get(getWOp(Fixable->getOpcode())));
767 Fixable->clearFlag(MachineInstr::MIFlag::NoSWrap);
768 Fixable->clearFlag(MachineInstr::MIFlag::NoUWrap);
769 Fixable->clearFlag(MachineInstr::MIFlag::IsExact);
770 LLVM_DEBUG(dbgs() << " with " << *Fixable);
771 ++NumTransformedToWInstrs;
772 }
773
774 LLVM_DEBUG(dbgs() << "Removing redundant sign-extension\n");
775 MRI.replaceRegWith(DstReg, SrcReg);
776 MRI.clearKillFlags(SrcReg);
777 MI.eraseFromParent();
778 ++NumRemovedSExtW;
779 MadeChange = true;
780 }
781 }
782
783 return MadeChange;
784}
785
786// Strips or adds W suffixes to eligible instructions depending on the
787// subtarget preferences.
788bool RISCVOptWInstrsImpl::canonicalizeWSuffixes(MachineFunction &MF,
789 const RISCVInstrInfo &TII,
790 const RISCVSubtarget &ST,
791 MachineRegisterInfo &MRI) {
792 bool ShouldStripW = !(DisableStripWSuffix || ST.preferWInst());
793 bool ShouldPreferW = ST.preferWInst();
794 bool MadeChange = false;
795
796 for (MachineBasicBlock &MBB : MF) {
797 for (MachineInstr &MI : MBB) {
798 std::optional<unsigned> WOpc;
799 std::optional<unsigned> NonWOpc;
800 unsigned OrigOpc = MI.getOpcode();
801 switch (OrigOpc) {
802 default:
803 continue;
804 case RISCV::ADDW:
805 NonWOpc = RISCV::ADD;
806 break;
807 case RISCV::ADDIW:
808 NonWOpc = RISCV::ADDI;
809 break;
810 case RISCV::MULW:
811 NonWOpc = RISCV::MUL;
812 break;
813 case RISCV::SLLIW:
814 NonWOpc = RISCV::SLLI;
815 break;
816 case RISCV::SUBW:
817 NonWOpc = RISCV::SUB;
818 break;
819 case RISCV::ADD:
820 WOpc = RISCV::ADDW;
821 break;
822 case RISCV::ADDI:
823 WOpc = RISCV::ADDIW;
824 break;
825 case RISCV::SUB:
826 WOpc = RISCV::SUBW;
827 break;
828 case RISCV::MUL:
829 WOpc = RISCV::MULW;
830 break;
831 case RISCV::SLLI:
832 // SLLIW reads the lowest 5 bits, while SLLI reads lowest 6 bits.
833 if (MI.getOperand(2).getImm() >= 32)
834 continue;
835 WOpc = RISCV::SLLIW;
836 break;
837 case RISCV::LD:
838 if (!MI.hasOneMemOperand() || (*MI.memoperands_begin())->isVolatile())
839 continue;
840 WOpc = RISCV::LW;
841 break;
842 case RISCV::LWU:
843 WOpc = RISCV::LW;
844 break;
845 case RISCV::LXD:
846 if (!MI.hasOneMemOperand() || (*MI.memoperands_begin())->isVolatile())
847 continue;
848 WOpc = RISCV::LXW;
849 break;
850 case RISCV::LXWU:
851 WOpc = RISCV::LXW;
852 break;
853 }
854
855 if (ShouldStripW && NonWOpc.has_value() && hasAllWUsers(MI, ST, MRI)) {
856 LLVM_DEBUG(dbgs() << "Replacing " << MI);
857 MI.setDesc(TII.get(NonWOpc.value()));
858 LLVM_DEBUG(dbgs() << " with " << MI);
859 ++NumTransformedToNonWInstrs;
860 MadeChange = true;
861 continue;
862 }
863 // LWU is always converted to LW when possible as 1) LW is compressible
864 // and 2) it helps minimise differences vs RV32.
865 if ((ShouldPreferW || OrigOpc == RISCV::LWU) && WOpc.has_value() &&
866 hasAllWUsers(MI, ST, MRI)) {
867 LLVM_DEBUG(dbgs() << "Replacing " << MI);
868 MI.setDesc(TII.get(WOpc.value()));
869 MI.clearFlag(MachineInstr::MIFlag::NoSWrap);
870 MI.clearFlag(MachineInstr::MIFlag::NoUWrap);
871 MI.clearFlag(MachineInstr::MIFlag::IsExact);
872 LLVM_DEBUG(dbgs() << " with " << MI);
873 ++NumTransformedToWInstrs;
874 MadeChange = true;
875 continue;
876 }
877 }
878 }
879 return MadeChange;
880}
881
882bool RISCVOptWInstrsImpl::run(MachineFunction &MF) {
883 MachineRegisterInfo &MRI = MF.getRegInfo();
884 const RISCVSubtarget &ST = MF.getSubtarget<RISCVSubtarget>();
885 const RISCVInstrInfo &TII = *ST.getInstrInfo();
886
887 if (!ST.is64Bit())
888 return false;
889
890 bool MadeChange = false;
891 MadeChange |= removeSExtWInstrs(MF, TII, ST, MRI);
892 MadeChange |= canonicalizeWSuffixes(MF, TII, ST, MRI);
893 return MadeChange;
894}
895
896bool RISCVOptWInstrsLegacy::runOnMachineFunction(MachineFunction &MF) {
897 if (skipFunction(MF.getFunction()))
898 return false;
899 return RISCVOptWInstrsImpl().run(MF);
900}
901
902PreservedAnalyses
905 bool Changed = RISCVOptWInstrsImpl().run(MF);
906 if (!Changed)
907 return PreservedAnalyses::all();
908
911 return PA;
912}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned Imm
unsigned uint64_t
MachineBasicBlock & MBB
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define DEBUG_TYPE
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
static cl::opt< bool > DisableSExtWRemoval("loongarch-disable-sextw-removal", cl::desc("Disable removal of sign-extend insn"), cl::init(false), cl::Hidden)
static bool hasAllWUsers(const MachineInstr &OrigMI, const LoongArchSubtarget &ST, const MachineRegisterInfo &MRI)
static bool isSignExtendedW(Register SrcReg, const LoongArchSubtarget &ST, const MachineRegisterInfo &MRI, SmallPtrSetImpl< MachineInstr * > &FixableDef)
static unsigned getWOp(unsigned Opcode)
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Promote Memory to Register
Definition Mem2Reg.cpp:110
uint64_t IntrinsicInst * II
#define P(N)
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
static bool vectorPseudoHasAllNBitUsers(const MachineInstr &MI, unsigned OpIdx, unsigned Bits)
static bool isSignExtendedW(Register SrcReg, const RISCVSubtarget &ST, const MachineRegisterInfo &MRI, SmallPtrSetImpl< MachineInstr * > &FixableDef)
static bool hasAllWUsers(const MachineInstr &OrigMI, const RISCVSubtarget &ST, const MachineRegisterInfo &MRI)
static bool isSignExtendingOpW(const MachineInstr &MI, unsigned OpNo)
static cl::opt< bool > DisableStripWSuffix("riscv-disable-strip-w-suffix", cl::desc("Disable strip W suffix"), cl::init(false), cl::Hidden)
static bool hasAllNBitUsers(const MachineInstr &OrigMI, const RISCVSubtarget &ST, const MachineRegisterInfo &MRI, unsigned OrigBits)
#define RISCV_OPT_W_INSTRS_NAME
static cl::opt< bool > DisableSExtWRemoval("riscv-disable-sextw-removal", cl::desc("Disable removal of sext.w"), cl::init(false), cl::Hidden)
static unsigned getWOp(unsigned Opcode)
This file defines the SmallSet class.
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:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:278
This class holds the attributes for a particular argument, parameter, function, or return value.
Definition Attributes.h:410
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.
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.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
const MachineBasicBlock & front() const
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
const MachineBasicBlock * getParent() const
bool isCall(QueryType Type=AnyInBundle) const
const MachineOperand & getOperand(unsigned i) const
const GlobalValue * getGlobal() const
int64_t getImm() const
bool isGlobal() const
isGlobal - Tests if this is a MO_GlobalAddress operand.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
LLVM_ABI void clearKillFlags(Register Reg) const
clearKillFlags - Iterate over all the uses of the given register and clear the kill flag from the Mac...
LLVM_ABI LLVM_READONLY MachineInstr * getVRegDef(Register Reg) const
getVRegDef - Return the machine instr that defines the specified virtual register or null if none is ...
iterator_range< use_nodbg_iterator > use_nodbg_operands(Register Reg) const
LLVM_ABI bool isLiveIn(Register Reg) const
LLVM_ABI const TargetRegisterClass * constrainRegClass(Register Reg, const TargetRegisterClass *RC, unsigned MinNumRegs=0)
constrainRegClass - Constrain the register class of the specified virtual register to be a common sub...
LLVM_ABI void replaceRegWith(Register FromReg, Register ToReg)
replaceRegWith - Replace all instances of FromReg with ToReg in the machine function.
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
RISCVMachineFunctionInfo - This class is derived from MachineFunctionInfo and contains private RISCV-...
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
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
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition SmallSet.h:134
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
static unsigned getVLOpNum(const MCInstrDesc &Desc)
static bool hasVLOp(uint64_t TSFlags)
static unsigned getSEWOpNum(const MCInstrDesc &Desc)
static bool hasSEWOp(uint64_t TSFlags)
unsigned getRVVMCOpcode(unsigned RVVPseudoOpcode)
std::optional< unsigned > getVectorLowDemandedScalarBits(unsigned Opcode, unsigned Log2SEW)
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition MathExtras.h:166
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
FunctionPass * createRISCVOptWInstrsLegacyPass()
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
Definition Casting.h:732
int bit_width(T Value)
Returns the number of bits needed to represent Value if Value is nonzero.
Definition bit.h:325
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
constexpr T alignDown(U Value, V Align, W Skew=0)
Returns the largest unsigned integer less than or equal to Value and is Skew mod Align.
Definition MathExtras.h:541
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:326
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:190
constexpr unsigned BitWidth
constexpr int64_t SignExtend64(uint64_t x)
Sign-extend the number in the bottom B bits of X to a 64-bit integer.
Definition MathExtras.h:567