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