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 case RISCV::VT_MASKC:
362 case RISCV::VT_MASKCN:
363 if (OpIdx != 1)
364 return false;
365 Worklist.emplace_back(UserMI, Bits);
366 break;
367 case RISCV::TH_EXT:
368 case RISCV::TH_EXTU:
369 unsigned Msb = UserMI->getOperand(2).getImm();
370 unsigned Lsb = UserMI->getOperand(3).getImm();
371 // Behavior of Msb < Lsb is not well documented.
372 if (Msb >= Lsb && Bits > Msb)
373 break;
374 return false;
375 }
376 }
377 }
378
379 return true;
380}
381
382static bool hasAllWUsers(const MachineInstr &OrigMI, const RISCVSubtarget &ST,
383 const MachineRegisterInfo &MRI) {
384 return hasAllNBitUsers(OrigMI, ST, MRI, 32);
385}
386
387// This function returns true if the machine instruction always outputs a value
388// where bits 63:32 match bit 31.
389static bool isSignExtendingOpW(const MachineInstr &MI, unsigned OpNo) {
390 uint64_t TSFlags = MI.getDesc().TSFlags;
391
392 // Instructions that can be determined from opcode are marked in tablegen.
394 return true;
395
396 // Special cases that require checking operands.
397 switch (MI.getOpcode()) {
398 // shifting right sufficiently makes the value 32-bit sign-extended
399 case RISCV::SRAI:
400 return MI.getOperand(2).getImm() >= 32;
401 case RISCV::SRLI:
402 return MI.getOperand(2).getImm() > 32;
403 // The LI pattern ADDI rd, X0, imm is sign extended.
404 case RISCV::ADDI:
405 return MI.getOperand(1).isReg() && MI.getOperand(1).getReg() == RISCV::X0;
406 // An ANDI with an 11 bit immediate will zero bits 63:11.
407 case RISCV::ANDI:
408 return isUInt<11>(MI.getOperand(2).getImm());
409 // An ORI with an >11 bit immediate (negative 12-bit) will set bits 63:11.
410 case RISCV::ORI:
411 return !isUInt<11>(MI.getOperand(2).getImm());
412 // A bseti with X0 is sign extended if the immediate is less than 31.
413 case RISCV::BSETI:
414 return MI.getOperand(2).getImm() < 31 &&
415 MI.getOperand(1).getReg() == RISCV::X0;
416 // Copying from X0 produces zero.
417 case RISCV::COPY:
418 return MI.getOperand(1).getReg() == RISCV::X0;
419 // Ignore the scratch register destination.
420 case RISCV::PseudoAtomicLoadNand32:
421 return OpNo == 0;
422 case RISCV::PseudoVMV_X_S: {
423 // vmv.x.s has at least 33 sign bits if log2(sew) <= 5.
424 int64_t Log2SEW = MI.getOperand(2).getImm();
425 assert(Log2SEW >= 3 && Log2SEW <= 6 && "Unexpected Log2SEW");
426 return Log2SEW <= 5;
427 }
428 case RISCV::TH_EXT: {
429 unsigned Msb = MI.getOperand(2).getImm();
430 unsigned Lsb = MI.getOperand(3).getImm();
431 return Msb >= Lsb && (Msb - Lsb + 1) <= 32;
432 }
433 case RISCV::TH_EXTU: {
434 unsigned Msb = MI.getOperand(2).getImm();
435 unsigned Lsb = MI.getOperand(3).getImm();
436 return Msb >= Lsb && (Msb - Lsb + 1) < 32;
437 }
438 case RISCV::SATI_RV64:
439 // Saturates to signed range [-2^(imm-1), 2^(imm-1)-1].
440 // If imm <= 32, result fits in 32-bit signed range, thus sign-extended.
441 return MI.getOperand(2).getImm() <= 32;
442 case RISCV::USATI_RV64:
443 // Saturates to unsigned range [0, 2^imm-1].
444 // If imm < 32, result has bit 31 clear, thus sign-extended.
445 return MI.getOperand(2).getImm() < 32;
446 }
447
448 return false;
449}
450
451static bool isSignExtendedW(Register SrcReg, const RISCVSubtarget &ST,
452 const MachineRegisterInfo &MRI,
454 SmallSet<Register, 4> Visited;
456
457 auto AddRegToWorkList = [&](Register SrcReg) {
458 if (!SrcReg.isVirtual())
459 return false;
460 Worklist.push_back(SrcReg);
461 return true;
462 };
463
464 if (!AddRegToWorkList(SrcReg))
465 return false;
466
467 while (!Worklist.empty()) {
468 Register Reg = Worklist.pop_back_val();
469
470 // If we already visited this register, we don't need to check it again.
471 if (!Visited.insert(Reg).second)
472 continue;
473
475 if (!MI)
476 continue;
477
478 int OpNo = MI->findRegisterDefOperandIdx(Reg, /*TRI=*/nullptr);
479 assert(OpNo != -1 && "Couldn't find register");
480
481 // If this is a sign extending operation we don't need to look any further.
482 if (isSignExtendingOpW(*MI, OpNo))
483 continue;
484
485 // Is this an instruction that propagates sign extend?
486 switch (MI->getOpcode()) {
487 default:
488 // Unknown opcode, give up.
489 return false;
490 case RISCV::COPY: {
491 const MachineFunction *MF = MI->getMF();
492 const RISCVMachineFunctionInfo *RVFI =
494
495 // If this is the entry block and the register is livein, see if we know
496 // it is sign extended.
497 if (MI->getParent() == &MF->front()) {
498 Register VReg = MI->getOperand(0).getReg();
499 if (MF->getRegInfo().isLiveIn(VReg) && RVFI->isSExt32Register(VReg))
500 continue;
501 }
502
503 Register CopySrcReg = MI->getOperand(1).getReg();
504 if (CopySrcReg == RISCV::X10) {
505 // For a method return value, we check the ZExt/SExt flags in attribute.
506 // We assume the following code sequence for method call.
507 // PseudoCALL @bar, ...
508 // ADJCALLSTACKUP 0, 0, implicit-def dead $x2, implicit $x2
509 // %0:gpr = COPY $x10
510 //
511 // We use the PseudoCall to look up the IR function being called to find
512 // its return attributes.
513 const MachineBasicBlock *MBB = MI->getParent();
514 auto II = MI->getIterator();
515 if (II == MBB->instr_begin() ||
516 (--II)->getOpcode() != RISCV::ADJCALLSTACKUP)
517 return false;
518
519 const MachineInstr &CallMI = *(--II);
520 if (!CallMI.isCall() || !CallMI.getOperand(0).isGlobal())
521 return false;
522
523 auto *CalleeFn =
525 if (!CalleeFn)
526 return false;
527
528 auto *IntTy = dyn_cast<IntegerType>(CalleeFn->getReturnType());
529 if (!IntTy)
530 return false;
531
532 const AttributeSet &Attrs = CalleeFn->getAttributes().getRetAttrs();
533 unsigned BitWidth = IntTy->getBitWidth();
534 if ((BitWidth <= 32 && Attrs.hasAttribute(Attribute::SExt)) ||
535 (BitWidth < 32 && Attrs.hasAttribute(Attribute::ZExt)))
536 continue;
537 }
538
539 if (!AddRegToWorkList(CopySrcReg))
540 return false;
541
542 break;
543 }
544
545 // For these, we just need to check if the 1st operand is sign extended.
546 case RISCV::BCLRI:
547 case RISCV::BINVI:
548 case RISCV::BSETI:
549 if (MI->getOperand(2).getImm() >= 31)
550 return false;
551 [[fallthrough]];
552 case RISCV::REM:
553 case RISCV::ANDI:
554 case RISCV::ORI:
555 case RISCV::XORI:
556 case RISCV::SRAI:
557 // |Remainder| is always <= |Dividend|. If D is 32-bit, then so is R.
558 // DIV doesn't work because of the edge case 0xf..f 8000 0000 / (long)-1
559 // Logical operations use a sign extended 12-bit immediate.
560 // Arithmetic shift right can only increase the number of sign bits.
561 if (!AddRegToWorkList(MI->getOperand(1).getReg()))
562 return false;
563
564 break;
565 case RISCV::PseudoCCADDW:
566 case RISCV::PseudoCCADDIW:
567 case RISCV::PseudoCCSUBW:
568 case RISCV::PseudoCCSLLW:
569 case RISCV::PseudoCCSRLW:
570 case RISCV::PseudoCCSRAW:
571 case RISCV::PseudoCCSLLIW:
572 case RISCV::PseudoCCSRLIW:
573 case RISCV::PseudoCCSRAIW:
574 // Returns operand 1 or an ADDW/SUBW/etc. of operands 2 and 3. We only
575 // need to check if operand 1 is sign extended.
576 if (!AddRegToWorkList(MI->getOperand(1).getReg()))
577 return false;
578 break;
579 case RISCV::REMU:
580 case RISCV::AND:
581 case RISCV::OR:
582 case RISCV::XOR:
583 case RISCV::ANDN:
584 case RISCV::ORN:
585 case RISCV::XNOR:
586 case RISCV::MAX:
587 case RISCV::MAXU:
588 case RISCV::MIN:
589 case RISCV::MINU:
590 case RISCV::PseudoCCMOVGPR:
591 case RISCV::PseudoCCMOVGPRNoX0:
592 case RISCV::PseudoCCAND:
593 case RISCV::PseudoCCOR:
594 case RISCV::PseudoCCXOR:
595 case RISCV::PseudoCCANDN:
596 case RISCV::PseudoCCORN:
597 case RISCV::PseudoCCXNOR:
598 case RISCV::PHI:
599 case RISCV::MERGE:
600 case RISCV::MVM:
601 case RISCV::MVMN: {
602 // If all incoming values are sign-extended, the output of AND, OR, XOR,
603 // MIN, MAX, PHI, or bitwise merge instructions is also sign-extended.
604
605 // The input registers for PHI are operand 1, 3, ...
606 // The input registers for PseudoCCMOVGPR(NoX0) are 1 and 2.
607 // The input registers for PseudoCCAND/OR/XOR are 1, 2, and 3.
608 // The input registers for MERGE/MVM/MVMN are 1, 2, and 3.
609 // The input registers for others are operand 1 and 2.
610 unsigned B = 1, E = 3, D = 1;
611 switch (MI->getOpcode()) {
612 case RISCV::PHI:
613 E = MI->getNumOperands();
614 D = 2;
615 break;
616 case RISCV::PseudoCCMOVGPR:
617 case RISCV::PseudoCCMOVGPRNoX0:
618 B = 1;
619 E = 3;
620 break;
621 case RISCV::PseudoCCAND:
622 case RISCV::PseudoCCOR:
623 case RISCV::PseudoCCXOR:
624 case RISCV::PseudoCCANDN:
625 case RISCV::PseudoCCORN:
626 case RISCV::PseudoCCXNOR:
627 B = 1;
628 E = 4;
629 break;
630 case RISCV::MERGE:
631 case RISCV::MVM:
632 case RISCV::MVMN:
633 B = 1;
634 E = 4;
635 break;
636 }
637
638 for (unsigned I = B; I != E; I += D) {
639 if (!MI->getOperand(I).isReg())
640 return false;
641
642 if (!AddRegToWorkList(MI->getOperand(I).getReg()))
643 return false;
644 }
645
646 break;
647 }
648
649 case RISCV::CZERO_EQZ:
650 case RISCV::CZERO_NEZ:
651 case RISCV::VT_MASKC:
652 case RISCV::VT_MASKCN:
653 // Instructions return zero or operand 1. Result is sign extended if
654 // operand 1 is sign extended.
655 if (!AddRegToWorkList(MI->getOperand(1).getReg()))
656 return false;
657 break;
658
659 case RISCV::ADDI: {
660 if (MI->getOperand(1).isReg() && MI->getOperand(1).getReg().isVirtual()) {
661 if (MachineInstr *SrcMI = MRI.getVRegDef(MI->getOperand(1).getReg())) {
662 if (SrcMI->getOpcode() == RISCV::LUI &&
663 SrcMI->getOperand(1).isImm()) {
664 uint64_t Imm = SrcMI->getOperand(1).getImm();
665 Imm = SignExtend64<32>(Imm << 12);
666 Imm += (uint64_t)MI->getOperand(2).getImm();
667 if (isInt<32>(Imm))
668 continue;
669 }
670 }
671 }
672
673 if (hasAllWUsers(*MI, ST, MRI)) {
674 FixableDef.insert(MI);
675 break;
676 }
677 return false;
678 }
679
680 case RISCV::LD:
681 case RISCV::LXD: {
682 if (MI->hasOneMemOperand() && !(*MI->memoperands_begin())->isVolatile() &&
683 hasAllWUsers(*MI, ST, MRI)) {
684 FixableDef.insert(MI);
685 break;
686 }
687 return false;
688 }
689
690 // With these opcode, we can "fix" them with the W-version
691 // if we know all users of the result only rely on bits 31:0
692 case RISCV::SLLI:
693 // SLLIW reads the lowest 5 bits, while SLLI reads lowest 6 bits
694 if (MI->getOperand(2).getImm() >= 32)
695 return false;
696 [[fallthrough]];
697 case RISCV::ADD:
698 case RISCV::LWU:
699 case RISCV::LXWU:
700 case RISCV::MUL:
701 case RISCV::SUB:
702 if (hasAllWUsers(*MI, ST, MRI)) {
703 FixableDef.insert(MI);
704 break;
705 }
706 return false;
707 }
708 }
709
710 // If we get here, then every node we visited produces a sign extended value
711 // or propagated sign extended values. So the result must be sign extended.
712 return true;
713}
714
715static unsigned getWOp(unsigned Opcode) {
716 switch (Opcode) {
717 case RISCV::ADDI:
718 return RISCV::ADDIW;
719 case RISCV::ADD:
720 return RISCV::ADDW;
721 case RISCV::LD:
722 case RISCV::LWU:
723 return RISCV::LW;
724 case RISCV::LXD:
725 case RISCV::LXWU:
726 return RISCV::LXW;
727 case RISCV::MUL:
728 return RISCV::MULW;
729 case RISCV::SLLI:
730 return RISCV::SLLIW;
731 case RISCV::SUB:
732 return RISCV::SUBW;
733 default:
734 llvm_unreachable("Unexpected opcode for replacement with W variant");
735 }
736}
737
738bool RISCVOptWInstrsImpl::removeSExtWInstrs(MachineFunction &MF,
739 const RISCVInstrInfo &TII,
740 const RISCVSubtarget &ST,
741 MachineRegisterInfo &MRI) {
743 return false;
744
745 bool MadeChange = false;
746 for (MachineBasicBlock &MBB : MF) {
747 for (MachineInstr &MI : llvm::make_early_inc_range(MBB)) {
748 // We're looking for the sext.w pattern ADDIW rd, rs1, 0.
749 if (!RISCVInstrInfo::isSEXT_W(MI))
750 continue;
751
752 Register SrcReg = MI.getOperand(1).getReg();
753
754 SmallPtrSet<MachineInstr *, 4> FixableDefs;
755
756 // If all users only use the lower bits, this sext.w is redundant.
757 // Or if all definitions reaching MI sign-extend their output,
758 // then sext.w is redundant.
759 if (!hasAllWUsers(MI, ST, MRI) &&
760 !isSignExtendedW(SrcReg, ST, MRI, FixableDefs))
761 continue;
762
763 Register DstReg = MI.getOperand(0).getReg();
764 if (!MRI.constrainRegClass(SrcReg, MRI.getRegClass(DstReg)))
765 continue;
766
767 // Convert Fixable instructions to their W versions.
768 for (MachineInstr *Fixable : FixableDefs) {
769 LLVM_DEBUG(dbgs() << "Replacing " << *Fixable);
770 Fixable->setDesc(TII.get(getWOp(Fixable->getOpcode())));
771 Fixable->clearFlag(MachineInstr::MIFlag::NoSWrap);
772 Fixable->clearFlag(MachineInstr::MIFlag::NoUWrap);
773 Fixable->clearFlag(MachineInstr::MIFlag::IsExact);
774 LLVM_DEBUG(dbgs() << " with " << *Fixable);
775 ++NumTransformedToWInstrs;
776 }
777
778 LLVM_DEBUG(dbgs() << "Removing redundant sign-extension\n");
779 MRI.replaceRegWith(DstReg, SrcReg);
780 MRI.clearKillFlags(SrcReg);
781 MI.eraseFromParent();
782 ++NumRemovedSExtW;
783 MadeChange = true;
784 }
785 }
786
787 return MadeChange;
788}
789
790// Strips or adds W suffixes to eligible instructions depending on the
791// subtarget preferences.
792bool RISCVOptWInstrsImpl::canonicalizeWSuffixes(MachineFunction &MF,
793 const RISCVInstrInfo &TII,
794 const RISCVSubtarget &ST,
795 MachineRegisterInfo &MRI) {
796 bool ShouldStripW = !(DisableStripWSuffix || ST.preferWInst());
797 bool ShouldPreferW = ST.preferWInst();
798 bool MadeChange = false;
799
800 for (MachineBasicBlock &MBB : MF) {
801 for (MachineInstr &MI : MBB) {
802 std::optional<unsigned> WOpc;
803 std::optional<unsigned> NonWOpc;
804 unsigned OrigOpc = MI.getOpcode();
805 switch (OrigOpc) {
806 default:
807 continue;
808 case RISCV::ADDW:
809 NonWOpc = RISCV::ADD;
810 break;
811 case RISCV::ADDIW:
812 NonWOpc = RISCV::ADDI;
813 break;
814 case RISCV::MULW:
815 NonWOpc = RISCV::MUL;
816 break;
817 case RISCV::SLLIW:
818 NonWOpc = RISCV::SLLI;
819 break;
820 case RISCV::SUBW:
821 NonWOpc = RISCV::SUB;
822 break;
823 case RISCV::ADD:
824 WOpc = RISCV::ADDW;
825 break;
826 case RISCV::ADDI:
827 WOpc = RISCV::ADDIW;
828 break;
829 case RISCV::SUB:
830 WOpc = RISCV::SUBW;
831 break;
832 case RISCV::MUL:
833 WOpc = RISCV::MULW;
834 break;
835 case RISCV::SLLI:
836 // SLLIW reads the lowest 5 bits, while SLLI reads lowest 6 bits.
837 if (MI.getOperand(2).getImm() >= 32)
838 continue;
839 WOpc = RISCV::SLLIW;
840 break;
841 case RISCV::LD:
842 if (!MI.hasOneMemOperand() || (*MI.memoperands_begin())->isVolatile())
843 continue;
844 WOpc = RISCV::LW;
845 break;
846 case RISCV::LWU:
847 WOpc = RISCV::LW;
848 break;
849 case RISCV::LXD:
850 if (!MI.hasOneMemOperand() || (*MI.memoperands_begin())->isVolatile())
851 continue;
852 WOpc = RISCV::LXW;
853 break;
854 case RISCV::LXWU:
855 WOpc = RISCV::LXW;
856 break;
857 }
858
859 if (ShouldStripW && NonWOpc.has_value() && hasAllWUsers(MI, ST, MRI)) {
860 LLVM_DEBUG(dbgs() << "Replacing " << MI);
861 MI.setDesc(TII.get(NonWOpc.value()));
862 LLVM_DEBUG(dbgs() << " with " << MI);
863 ++NumTransformedToNonWInstrs;
864 MadeChange = true;
865 continue;
866 }
867 // LWU is always converted to LW when possible as 1) LW is compressible
868 // and 2) it helps minimise differences vs RV32.
869 if ((ShouldPreferW || OrigOpc == RISCV::LWU) && WOpc.has_value() &&
870 hasAllWUsers(MI, ST, MRI)) {
871 LLVM_DEBUG(dbgs() << "Replacing " << MI);
872 MI.setDesc(TII.get(WOpc.value()));
873 MI.clearFlag(MachineInstr::MIFlag::NoSWrap);
874 MI.clearFlag(MachineInstr::MIFlag::NoUWrap);
875 MI.clearFlag(MachineInstr::MIFlag::IsExact);
876 LLVM_DEBUG(dbgs() << " with " << MI);
877 ++NumTransformedToWInstrs;
878 MadeChange = true;
879 continue;
880 }
881 }
882 }
883 return MadeChange;
884}
885
886bool RISCVOptWInstrsImpl::run(MachineFunction &MF) {
887 MachineRegisterInfo &MRI = MF.getRegInfo();
888 const RISCVSubtarget &ST = MF.getSubtarget<RISCVSubtarget>();
889 const RISCVInstrInfo &TII = *ST.getInstrInfo();
890
891 if (!ST.is64Bit())
892 return false;
893
894 bool MadeChange = false;
895 MadeChange |= removeSExtWInstrs(MF, TII, ST, MRI);
896 MadeChange |= canonicalizeWSuffixes(MF, TII, ST, MRI);
897 return MadeChange;
898}
899
900bool RISCVOptWInstrsLegacy::runOnMachineFunction(MachineFunction &MF) {
901 if (skipFunction(MF.getFunction()))
902 return false;
903 return RISCVOptWInstrsImpl().run(MF);
904}
905
906PreservedAnalyses
909 bool Changed = RISCVOptWInstrsImpl().run(MF);
910 if (!Changed)
911 return PreservedAnalyses::all();
912
915 return PA;
916}
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:407
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