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