LLVM 24.0.0git
RISCVMergeBaseOffset.cpp
Go to the documentation of this file.
1//===----- RISCVMergeBaseOffset.cpp - Optimise address calculations ------===//
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// Merge the offset of address calculation into the offset field
10// of instructions in a global address lowering sequence.
11//
12//===----------------------------------------------------------------------===//
13
14#include "RISCV.h"
15#include "RISCVSubtarget.h"
16#include "RISCVTargetMachine.h"
21#include "llvm/CodeGen/Passes.h"
22#include "llvm/IR/Analysis.h"
25#include "llvm/Support/Debug.h"
27#include <optional>
28using namespace llvm;
29
30#define DEBUG_TYPE "riscv-merge-base-offset"
31#define RISCV_MERGE_BASE_OFFSET_NAME "RISC-V Merge Base Offset"
32namespace {
33
34class RISCVMergeBaseOffsetLegacy : public MachineFunctionPass {
35public:
36 static char ID;
37 bool runOnMachineFunction(MachineFunction &MF) override;
38
39 RISCVMergeBaseOffsetLegacy() : MachineFunctionPass(ID) {}
40
41 MachineFunctionProperties getRequiredProperties() const override {
42 return MachineFunctionProperties().setIsSSA();
43 }
44
45 void getAnalysisUsage(AnalysisUsage &AU) const override {
46 AU.setPreservesCFG();
48 }
49
50 StringRef getPassName() const override {
52 }
53};
54} // end anonymous namespace
55
56char RISCVMergeBaseOffsetLegacy::ID = 0;
57INITIALIZE_PASS(RISCVMergeBaseOffsetLegacy, DEBUG_TYPE,
58 RISCV_MERGE_BASE_OFFSET_NAME, false, false)
59
60// Detect either of the patterns:
61//
62// 1. (medlow pattern):
63// a. lui vreg1, %hi(s)
64// addi vreg2, vreg1, %lo(s)
65//
66// b. qc.e.li vreg1, s
67//
68// 2. (medany pattern):
69// .Lpcrel_hi1:
70// auipc vreg1, %pcrel_hi(s)
71// addi vreg2, vreg1, %pcrel_lo(.Lpcrel_hi1)
72//
73// The pattern is only accepted if:
74// 1) The first instruction has only one use, which is the ADDI.
75// 2) The address operands have the appropriate type, reflecting the
76// lowering of a global address or constant pool using medlow or medany.
77// 3) The offset value in the Global Address or Constant Pool is 0.
78static bool detectFoldable(MachineInstr &Hi, MachineInstr *&Lo,
80 auto HiOpc = Hi.getOpcode();
81 if (HiOpc != RISCV::LUI && HiOpc != RISCV::AUIPC &&
82 HiOpc != RISCV::PseudoMovAddr && HiOpc != RISCV::QC_E_LI)
83 return false;
84
85 const MachineOperand &HiOp1 = Hi.getOperand(1);
86 unsigned ExpectedFlags = HiOpc == RISCV::AUIPC ? RISCVII::MO_PCREL_HI
87 : HiOpc == RISCV::QC_E_LI ? RISCVII::MO_None
89 if (HiOp1.getTargetFlags() != ExpectedFlags)
90 return false;
91
92 if (!(HiOp1.isGlobal() || HiOp1.isCPI() || HiOp1.isBlockAddress()) ||
93 HiOp1.getOffset() != 0)
94 return false;
95
96 if (HiOpc == RISCV::PseudoMovAddr || HiOpc == RISCV::QC_E_LI) {
97 // Most of the code should handle it correctly without modification by
98 // setting Lo and Hi both point to PseudoMovAddr/QC_E_LI
99 Lo = &Hi;
100 } else {
101 Register HiDestReg = Hi.getOperand(0).getReg();
102 if (!MRI->hasOneUse(HiDestReg))
103 return false;
104
105 Lo = &*MRI->use_instr_begin(HiDestReg);
106 if (Lo->getOpcode() != RISCV::ADDI)
107 return false;
108 }
109
110 if (HiOpc != RISCV::QC_E_LI) {
111 const MachineOperand &LoOp2 = Lo->getOperand(2);
112 if (HiOpc == RISCV::LUI || HiOpc == RISCV::PseudoMovAddr) {
113 if (LoOp2.getTargetFlags() != RISCVII::MO_LO ||
114 !(LoOp2.isGlobal() || LoOp2.isCPI() || LoOp2.isBlockAddress()) ||
115 LoOp2.getOffset() != 0)
116 return false;
117 } else {
118 assert(HiOpc == RISCV::AUIPC);
119 if (LoOp2.getTargetFlags() != RISCVII::MO_PCREL_LO ||
121 return false;
122 }
123 }
124
125 if (HiOp1.isGlobal()) {
126 LLVM_DEBUG(dbgs() << " Found lowered global address: "
127 << *HiOp1.getGlobal() << "\n");
128 } else if (HiOp1.isBlockAddress()) {
129 LLVM_DEBUG(dbgs() << " Found lowered basic address: "
130 << *HiOp1.getBlockAddress() << "\n");
131 } else if (HiOp1.isCPI()) {
132 LLVM_DEBUG(dbgs() << " Found lowered constant pool: " << HiOp1.getIndex()
133 << "\n");
134 }
135
136 return true;
137}
138
139// Update the offset in Hi and Lo instructions.
140// Delete the tail instruction and update all the uses to use the
141// output from Lo.
143 int64_t Offset, MachineRegisterInfo *MRI) {
144 assert(isInt<32>(Offset) && "Unexpected offset");
145
146 // If Hi is an AUIPC, don't fold the offset if it is outside the bounds of
147 // the global object. The object may be within 2GB of the PC, but addresses
148 // outside of the object might not be.
149 auto HiOpc = Hi.getOpcode();
150 if (HiOpc == RISCV::AUIPC && Hi.getOperand(1).isGlobal()) {
151 const GlobalValue *GV = Hi.getOperand(1).getGlobal();
152 Type *Ty = GV->getValueType();
153 if (!Ty->isSized() || Offset < 0 ||
155 return false;
156 }
157
158 // Salvage the debug users of Lo's result by subtracting the offset again.
159 SmallVector<uint64_t, 3> UndoOffset;
161 for (MachineOperand &MO : MRI->use_operands(Lo.getOperand(0).getReg())) {
162 MachineInstr &DbgMI = *MO.getParent();
163 if (!DbgMI.isDebugValue())
164 continue;
167 DbgMI.getDebugOperandIndex(&MO)));
168 }
169
170 // Put the offset back in Hi and the Lo
171 Hi.getOperand(1).setOffset(Offset);
172 if (Hi.getOpcode() != RISCV::AUIPC && Hi.getOpcode() != RISCV::QC_E_LI)
173 Lo.getOperand(2).setOffset(Offset);
174 // Delete the tail instruction.
175 Register LoOp0Reg = Lo.getOperand(0).getReg();
176 Register TailOp0Reg = Tail.getOperand(0).getReg();
177 MRI->constrainRegClass(LoOp0Reg, MRI->getRegClass(TailOp0Reg));
178 MRI->replaceRegWith(TailOp0Reg, LoOp0Reg);
179 Tail.eraseFromParent();
180 LLVM_DEBUG(dbgs() << " Merged offset " << Offset << " into base.\n"
181 << " " << Hi << " " << Lo;);
182 return true;
183}
184
185// Detect patterns for large offsets that are passed into an ADD instruction.
186// If the pattern is found, updates the offset in Hi and Lo instructions
187// and deletes TailAdd and the instructions that produced the offset.
188//
189// Base address lowering is of the form:
190// Hi: lui vreg1, %hi(s)
191// Lo: addi vreg2, vreg1, %lo(s)
192// / \
193// / \
194// / \
195// / The large offset can be of two forms: \
196// 1) Offset that has non zero bits in lower 2) Offset that has non zero
197// 12 bits and upper 20 bits bits in upper 20 bits only
198// OffseLUI: lui vreg3, 4
199// OffsetTail: addi voff, vreg3, 188 OffsetTail: lui voff, 128
200// \ /
201// \ /
202// \ /
203// \ /
204// TailAdd: add vreg4, vreg2, voff
206 MachineInstr &TailAdd, Register GAReg,
208 const RISCVSubtarget *ST) {
209 assert((TailAdd.getOpcode() == RISCV::ADD) && "Expected ADD instruction!");
210 Register Rs = TailAdd.getOperand(1).getReg();
211 Register Rt = TailAdd.getOperand(2).getReg();
212 Register Reg = Rs == GAReg ? Rt : Rs;
213
214 // Can't fold if the register has more than one use.
215 if (!Reg.isVirtual() || !MRI->hasOneNonDBGUse(Reg))
216 return false;
217 // This can point to an ADDI(W) or a LUI:
218 MachineInstr &OffsetTail = *MRI->getVRegDef(Reg);
219 auto OffsetTailOpc = OffsetTail.getOpcode();
220 if (OffsetTailOpc == RISCV::ADDI || OffsetTailOpc == RISCV::ADDIW) {
221 // The offset value has non zero bits in both %hi and %lo parts.
222 // Detect an ADDI that feeds from a LUI instruction.
223 MachineOperand &AddiImmOp = OffsetTail.getOperand(2);
224 if (AddiImmOp.getTargetFlags() != RISCVII::MO_None)
225 return false;
226 // Make sure this isn't something weird like a frame index.
227 if (!OffsetTail.getOperand(1).isReg())
228 return false;
229 Register AddiReg = OffsetTail.getOperand(1).getReg();
230 int64_t OffLo = AddiImmOp.getImm();
231
232 // Handle rs1 of ADDI is X0.
233 if (AddiReg == RISCV::X0) {
234 LLVM_DEBUG(dbgs() << " Offset Instrs: " << OffsetTail);
235 if (!foldOffset(Hi, Lo, TailAdd, OffLo, MRI))
236 return false;
237 OffsetTail.eraseFromParent();
238 return true;
239 }
240
241 MachineInstr &OffsetLui = *MRI->getVRegDef(AddiReg);
242 MachineOperand &LuiImmOp = OffsetLui.getOperand(1);
243 if (OffsetLui.getOpcode() != RISCV::LUI ||
244 LuiImmOp.getTargetFlags() != RISCVII::MO_None ||
245 !MRI->hasOneNonDBGUse(OffsetLui.getOperand(0).getReg()))
246 return false;
247 int64_t Offset = SignExtend64<32>(LuiImmOp.getImm() << 12);
248 Offset += OffLo;
249 // RV32 ignores the upper 32 bits. ADDIW sign extends the result.
250 if (!ST->is64Bit() || OffsetTailOpc == RISCV::ADDIW)
252 // We can only fold simm32 offsets.
253 if (!isInt<32>(Offset))
254 return false;
255 LLVM_DEBUG(dbgs() << " Offset Instrs: " << OffsetTail
256 << " " << OffsetLui);
257 if (!foldOffset(Hi, Lo, TailAdd, Offset, MRI))
258 return false;
259 OffsetTail.eraseFromParent();
260 OffsetLui.eraseFromParent();
261 return true;
262 } else if (OffsetTailOpc == RISCV::LUI) {
263 // The offset value has all zero bits in the lower 12 bits. Only LUI
264 // exists.
265 LLVM_DEBUG(dbgs() << " Offset Instr: " << OffsetTail);
266 int64_t Offset = SignExtend64<32>(OffsetTail.getOperand(1).getImm() << 12);
267 if (!foldOffset(Hi, Lo, TailAdd, Offset, MRI))
268 return false;
269 OffsetTail.eraseFromParent();
270 return true;
271 }
272 return false;
273}
274
275// Detect patterns for offsets that are passed into a SHXADD instruction.
276// The offset has 1, 2, or 3 trailing zeros and fits in simm13, simm14, simm15.
277// The constant is created with addi voff, x0, C, and shXadd is used to
278// fill insert the trailing zeros and do the addition.
279// If the pattern is found, updates the offset in Hi and Lo instructions
280// and deletes TailShXAdd and the instructions that produced the offset.
281//
282// Hi: lui vreg1, %hi(s)
283// Lo: addi vreg2, vreg1, %lo(s)
284// OffsetTail: addi voff, x0, C
285// TailAdd: shXadd vreg4, voff, vreg2
287 MachineInstr &TailShXAdd, Register GAReg,
289 assert((TailShXAdd.getOpcode() == RISCV::SH1ADD ||
290 TailShXAdd.getOpcode() == RISCV::SH2ADD ||
291 TailShXAdd.getOpcode() == RISCV::SH3ADD) &&
292 "Expected SHXADD instruction!");
293
294 if (GAReg != TailShXAdd.getOperand(2).getReg())
295 return false;
296
297 // The first source is the shifted operand.
298 Register Rs1 = TailShXAdd.getOperand(1).getReg();
299
300 // Can't fold if the register has more than one use.
301 if (!Rs1.isVirtual() || !MRI->hasOneNonDBGUse(Rs1))
302 return false;
303 // This can point to an ADDI X0, C.
304 MachineInstr &OffsetTail = *MRI->getVRegDef(Rs1);
305 if (OffsetTail.getOpcode() != RISCV::ADDI)
306 return false;
307 if (!OffsetTail.getOperand(1).isReg() ||
308 OffsetTail.getOperand(1).getReg() != RISCV::X0 ||
309 !OffsetTail.getOperand(2).isImm())
310 return false;
311
312 int64_t Offset = OffsetTail.getOperand(2).getImm();
313 assert(isInt<12>(Offset) && "Unexpected offset");
314
315 unsigned ShAmt;
316 switch (TailShXAdd.getOpcode()) {
317 default: llvm_unreachable("Unexpected opcode");
318 case RISCV::SH1ADD: ShAmt = 1; break;
319 case RISCV::SH2ADD: ShAmt = 2; break;
320 case RISCV::SH3ADD: ShAmt = 3; break;
321 }
322
323 Offset = (uint64_t)Offset << ShAmt;
324
325 LLVM_DEBUG(dbgs() << " Offset Instr: " << OffsetTail);
326 if (!foldOffset(Hi, Lo, TailShXAdd, Offset, MRI))
327 return false;
328 OffsetTail.eraseFromParent();
329 return true;
330}
331
334 const RISCVSubtarget *ST) {
335 Register DestReg = Lo.getOperand(0).getReg();
336
337 // Look for arithmetic instructions we can get an offset from.
338 // We might be able to remove the arithmetic instructions by folding the
339 // offset into the LUI+ADDI.
340 if (!MRI->hasOneNonDBGUse(DestReg))
341 return false;
342
343 // Lo has only one use.
344 MachineInstr &Tail = *MRI->use_instr_nodbg_begin(DestReg);
345 switch (Tail.getOpcode()) {
346 default:
347 LLVM_DEBUG(dbgs() << "Don't know how to get offset from this instr: "
348 << Tail);
349 break;
350 case RISCV::ADDI:
351 case RISCV::QC_E_ADDI:
352 case RISCV::QC_E_ADDAI: {
353 // Offset is simply an immediate operand.
354 int64_t Offset = Tail.getOperand(2).getImm();
355 if (Tail.getOpcode() == RISCV::ADDI) {
356 // We might have two ADDIs in a row.
357 Register TailDestReg = Tail.getOperand(0).getReg();
358 if (MRI->hasOneNonDBGUse(TailDestReg)) {
359 MachineInstr &TailTail = *MRI->use_instr_nodbg_begin(TailDestReg);
360 if (TailTail.getOpcode() == RISCV::ADDI) {
361 Offset += TailTail.getOperand(2).getImm();
362 LLVM_DEBUG(dbgs() << " Offset Instrs: " << Tail << TailTail);
363 if (!foldOffset(Hi, Lo, TailTail, Offset, MRI))
364 return false;
365 Tail.eraseFromParent();
366 return true;
367 }
368 }
369 }
370
371 LLVM_DEBUG(dbgs() << " Offset Instr: " << Tail);
372 return foldOffset(Hi, Lo, Tail, Offset, MRI);
373 }
374 case RISCV::ADD:
375 // The offset is too large to fit in the immediate field of ADDI.
376 // This can be in two forms:
377 // 1) LUI hi_Offset followed by:
378 // ADDI lo_offset
379 // This happens in case the offset has non zero bits in
380 // both hi 20 and lo 12 bits.
381 // 2) LUI (offset20)
382 // This happens in case the lower 12 bits of the offset are zeros.
383 return foldLargeOffset(Hi, Lo, Tail, DestReg, MRI, ST);
384 case RISCV::SH1ADD:
385 case RISCV::SH2ADD:
386 case RISCV::SH3ADD:
387 // The offset is too large to fit in the immediate field of ADDI.
388 // It may be encoded as (SH2ADD (ADDI X0, C), DestReg) or
389 // (SH3ADD (ADDI X0, C), DestReg).
390 return foldShiftedOffset(Hi, Lo, Tail, DestReg, MRI);
391 }
392
393 return false;
394}
395
397 const MachineOperand &ImmOp) {
398 switch (ImmOp.getType()) {
400 MO.ChangeToCPI(ImmOp.getIndex(), ImmOp.getOffset(), ImmOp.getTargetFlags());
401 break;
403 MO.ChangeToGA(ImmOp.getGlobal(), ImmOp.getOffset(), ImmOp.getTargetFlags());
404 break;
406 MO.ChangeToMCSymbol(ImmOp.getMCSymbol(), ImmOp.getTargetFlags());
407 MO.setOffset(ImmOp.getOffset());
408 break;
410 MO.ChangeToBA(ImmOp.getBlockAddress(), ImmOp.getOffset(),
411 ImmOp.getTargetFlags());
412 break;
413 default:
414 report_fatal_error("unsupported machine operand type");
415 break;
416 }
417}
418
421 const RISCVSubtarget *ST) {
422 Register DestReg = Lo.getOperand(0).getReg();
423
424 // If all the uses are memory ops with the same offset, we can transform:
425 //
426 // 1. (medlow pattern):
427 // a. Hi: lui vreg1, %hi(foo) ---> lui vreg1, %hi(foo+8)
428 // Lo: addi vreg2, vreg1, %lo(foo) ---> lw vreg3, lo(foo+8)(vreg1)
429 // Tail: lw vreg3, 8(vreg2)
430 //
431 // b. Hi: qc.e.li vreg1, foo ---> qc.e.li vreg1, foo+8
432 // Tail: lw vreg2, 8(vreg1) ---> lw vreg2, 0(vreg1)
433 //
434 // 2. (medany pattern):
435 // Hi: 1:auipc vreg1, %pcrel_hi(s) ---> auipc vreg1, %pcrel_hi(foo+8)
436 // Lo: addi vreg2, vreg1, %pcrel_lo(1b) ---> lw vreg3, %pcrel_lo(1b)(vreg1)
437 // Tail: lw vreg3, 8(vreg2)
438
439 std::optional<int64_t> CommonOffset;
441 InlineAsmMemoryOpIndexesMap;
442 for (const MachineInstr &UseMI : MRI->use_nodbg_instructions(DestReg)) {
443 switch (UseMI.getOpcode()) {
444 default:
445 LLVM_DEBUG(dbgs() << "Not a load or store instruction: " << UseMI);
446 return false;
447 case RISCV::LB:
448 case RISCV::LH:
449 case RISCV::LH_INX:
450 case RISCV::LW:
451 case RISCV::LW_INX:
452 case RISCV::LBU:
453 case RISCV::LHU:
454 case RISCV::LWU:
455 case RISCV::LD:
456 case RISCV::LD_RV32:
457 case RISCV::FLH:
458 case RISCV::FLW:
459 case RISCV::FLD:
460 case RISCV::SB:
461 case RISCV::SH:
462 case RISCV::SH_INX:
463 case RISCV::SW:
464 case RISCV::SW_INX:
465 case RISCV::SD:
466 case RISCV::SD_RV32:
467 case RISCV::FSH:
468 case RISCV::FSW:
469 case RISCV::FSD: {
470 if (UseMI.getOperand(1).isFI())
471 return false;
472 // Register defined by Lo should not be the value register.
473 if (DestReg == UseMI.getOperand(0).getReg())
474 return false;
475 assert(DestReg == UseMI.getOperand(1).getReg() &&
476 "Expected base address use");
477 // All load/store instructions must use the same offset.
478 int64_t Offset = UseMI.getOperand(2).getImm();
479 if (CommonOffset && Offset != CommonOffset)
480 return false;
481 CommonOffset = Offset;
482 break;
483 }
484 case RISCV::PseudoCCLD:
485 case RISCV::PseudoCCLW:
486 case RISCV::PseudoCCLWU:
487 case RISCV::PseudoCCLH:
488 case RISCV::PseudoCCLHU:
489 case RISCV::PseudoCCLB:
490 case RISCV::PseudoCCLBU: {
491 // The SFB Pseudos are like their non-SFB counterparts but have more
492 // operands.
493 if (UseMI.getOperand(2).isFI())
494 return false;
495 // Register defined by Lo should not be the (tied) false value, or a
496 // register used in the branch predicate.
497 if (DestReg == UseMI.getOperand(1).getReg() ||
498 DestReg == UseMI.getOperand(5).getReg())
499 return false;
500 if (UseMI.getOperand(6).isReg() &&
501 DestReg == UseMI.getOperand(6).getReg())
502 return false;
503 assert(DestReg == UseMI.getOperand(2).getReg() &&
504 "Expected base address use");
505 // All load/store instructions must use the same offset.
506 int64_t Offset = UseMI.getOperand(3).getImm();
507 if (CommonOffset && Offset != CommonOffset)
508 return false;
509 CommonOffset = Offset;
510 break;
511 }
512 case RISCV::INLINEASM:
513 case RISCV::INLINEASM_BR: {
514 SmallVector<unsigned> InlineAsmMemoryOpIndexes;
515 unsigned NumOps = 0;
516 for (unsigned I = InlineAsm::MIOp_FirstOperand;
517 I < UseMI.getNumOperands(); I += 1 + NumOps) {
518 const MachineOperand &FlagsMO = UseMI.getOperand(I);
519 // Should be an imm.
520 if (!FlagsMO.isImm())
521 continue;
522
523 const InlineAsm::Flag Flags(FlagsMO.getImm());
524 NumOps = Flags.getNumOperandRegisters();
525
526 // Memory constraints have two operands.
527 if (NumOps != 2 || !Flags.isMemKind()) {
528 // If the register is used by something other than a memory
529 // constraint, we should not fold.
530 for (unsigned J = 0; J < NumOps; ++J) {
531 const MachineOperand &MO = UseMI.getOperand(I + 1 + J);
532 if (MO.isReg() && MO.getReg() == DestReg)
533 return false;
534 }
535 continue;
536 }
537
538 // We can't do this for constraint A because AMO instructions don't have
539 // an immediate offset field.
540 if (Flags.getMemoryConstraintID() == InlineAsm::ConstraintCode::A)
541 return false;
542
543 const MachineOperand &AddrMO = UseMI.getOperand(I + 1);
544 if (!AddrMO.isReg() || AddrMO.getReg() != DestReg)
545 continue;
546
547 const MachineOperand &OffsetMO = UseMI.getOperand(I + 2);
548 if (!OffsetMO.isImm())
549 continue;
550
551 // All inline asm memory operands must use the same offset.
552 int64_t Offset = OffsetMO.getImm();
553 if (CommonOffset && Offset != CommonOffset)
554 return false;
555 CommonOffset = Offset;
556 InlineAsmMemoryOpIndexes.push_back(I + 1);
557 }
558 InlineAsmMemoryOpIndexesMap.insert(
559 std::make_pair(&UseMI, InlineAsmMemoryOpIndexes));
560 break;
561 }
562 }
563 }
564
565 if (!CommonOffset)
566 return false;
567
568 // We found a common offset.
569 // Update the offsets in global address lowering.
570 // We may have already folded some arithmetic so we need to add to any
571 // existing offset.
572 int64_t NewOffset = Hi.getOperand(1).getOffset() + *CommonOffset;
573 // RV32 ignores the upper 32 bits.
574 if (!ST->is64Bit())
575 NewOffset = SignExtend64<32>(NewOffset);
576 // We can only fold simm32 offsets.
577 if (!isInt<32>(NewOffset))
578 return false;
579
580 // Folding changes the value represented by DestReg, so its debug users can
581 // no longer describe the same address.
582 MRI->markUsesInDebugValueAsUndef(DestReg);
583
584 Hi.getOperand(1).setOffset(NewOffset);
585 MachineOperand &ImmOp =
586 Hi.getOpcode() == RISCV::QC_E_LI ? Lo.getOperand(1) : Lo.getOperand(2);
587 auto HiOpc = Hi.getOpcode();
588 // Expand PseudoMovAddr into LUI
589 if (HiOpc == RISCV::PseudoMovAddr) {
590 auto *TII = ST->getInstrInfo();
591 Hi.setDesc(TII->get(RISCV::LUI));
592 Hi.removeOperand(2);
593 }
594
595 if (HiOpc != RISCV::AUIPC)
596 ImmOp.setOffset(NewOffset);
597
598 // Update the immediate in the load/store instructions to add the offset.
599 for (MachineInstr &UseMI :
600 llvm::make_early_inc_range(MRI->use_nodbg_instructions(DestReg))) {
601 if (UseMI.getOpcode() == RISCV::INLINEASM ||
602 UseMI.getOpcode() == RISCV::INLINEASM_BR) {
603 auto &InlineAsmMemoryOpIndexes = InlineAsmMemoryOpIndexesMap[&UseMI];
604 for (unsigned I : InlineAsmMemoryOpIndexes) {
605 MachineOperand &MO = UseMI.getOperand(I + 1);
607 }
608 } else {
609 unsigned ImmIdx;
610 switch (UseMI.getOpcode()) {
611 case RISCV::INLINEASM:
612 case RISCV::INLINEASM_BR:
613 llvm_unreachable("Should have been dealt with before this else");
614 case RISCV::PseudoCCLD:
615 case RISCV::PseudoCCLW:
616 case RISCV::PseudoCCLWU:
617 case RISCV::PseudoCCLH:
618 case RISCV::PseudoCCLHU:
619 case RISCV::PseudoCCLB:
620 case RISCV::PseudoCCLBU:
621 ImmIdx = 3;
622 break;
623 case RISCV::LB:
624 case RISCV::LH:
625 case RISCV::LH_INX:
626 case RISCV::LW:
627 case RISCV::LW_INX:
628 case RISCV::LBU:
629 case RISCV::LHU:
630 case RISCV::LWU:
631 case RISCV::LD:
632 case RISCV::LD_RV32:
633 case RISCV::FLH:
634 case RISCV::FLW:
635 case RISCV::FLD:
636 case RISCV::SB:
637 case RISCV::SH:
638 case RISCV::SH_INX:
639 case RISCV::SW:
640 case RISCV::SW_INX:
641 case RISCV::SD:
642 case RISCV::SD_RV32:
643 case RISCV::FSH:
644 case RISCV::FSW:
645 case RISCV::FSD:
646 ImmIdx = 2;
647 break;
648 default:
649 llvm_unreachable("Unknown Instruction");
650 }
651
652 MachineOperand &MO = UseMI.getOperand(ImmIdx);
653 if (Hi.getOpcode() == RISCV::QC_E_LI) {
654 MO.ChangeToImmediate(0);
655 } else {
657 }
658 }
659 }
660
661 // Prevent Lo (originally PseudoMovAddr, which is also pointed by Hi) from
662 // being erased
663 if (&Lo == &Hi)
664 return true;
665
666 MRI->replaceRegWith(Lo.getOperand(0).getReg(), Hi.getOperand(0).getReg());
667 Lo.eraseFromParent();
668 return true;
669}
670
671// Try to fold sequences of the form:
672// Hi/lo: qc.e.li vreg1, s -> qc.e.li vreg1, s+imm
673// TailAdd: shxadd vreg2, vreg3, vreg1 -> deleted
674// Tail: lx vreg4, imm(vreg2) -> qc.lrx vreg4, vreg1, vreg3, (1-7)
677 const RISCVSubtarget *ST) {
678 if (!ST->hasVendorXqcisls() || ST->is64Bit())
679 return false;
680
681 if (Hi.getOpcode() != RISCV::QC_E_LI)
682 return false;
683
684 Register BaseReg = Hi.getOperand(0).getReg();
685 if (!BaseReg.isVirtual() || !MRI->hasOneUse(BaseReg))
686 return false;
687
688 MachineInstr &ShxAdd = *MRI->use_instr_begin(BaseReg);
689 unsigned ShxOpc = ShxAdd.getOpcode();
690 unsigned ShAmt = 0;
691 switch (ShxOpc) {
692 default:
693 return false;
694 case RISCV::SH1ADD:
695 ShAmt = 1;
696 break;
697 case RISCV::SH2ADD:
698 ShAmt = 2;
699 break;
700 case RISCV::SH3ADD:
701 ShAmt = 3;
702 break;
703 case RISCV::QC_SHLADD:
704 uint8_t ShlImm = ShxAdd.getOperand(3).getImm();
705 if (ShlImm > 7)
706 return false;
707 ShAmt = ShlImm;
708 break;
709 }
710
711 // shxadd Rd, Rs1, Rs2
712 Register ScaledReg = ShxAdd.getOperand(0).getReg();
713 Register IndexReg = ShxAdd.getOperand(1).getReg();
714
715 if (!IndexReg.isVirtual())
716 return false;
717
718 if (ShxAdd.getOperand(2).getReg() != BaseReg)
719 return false;
720
721 if (!ScaledReg.isVirtual() || !MRI->hasOneUse(ScaledReg))
722 return false;
723
724 MachineInstr &TailMem = *MRI->use_instr_begin(ScaledReg);
725 unsigned Opc = TailMem.getOpcode();
726 unsigned NewOpc = 0;
727
728 switch (Opc) {
729 case RISCV::LB:
730 NewOpc = RISCV::QC_LRB;
731 break;
732 case RISCV::LBU:
733 NewOpc = RISCV::QC_LRBU;
734 break;
735 case RISCV::LH:
736 NewOpc = RISCV::QC_LRH;
737 break;
738 case RISCV::LHU:
739 NewOpc = RISCV::QC_LRHU;
740 break;
741 case RISCV::LW:
742 NewOpc = RISCV::QC_LRW;
743 break;
744 case RISCV::SB:
745 NewOpc = RISCV::QC_SRB;
746 break;
747 case RISCV::SH:
748 NewOpc = RISCV::QC_SRH;
749 break;
750 case RISCV::SW:
751 NewOpc = RISCV::QC_SRW;
752 break;
753 default:
754 return false;
755 }
756
757 if (!TailMem.getOperand(1).isReg() ||
758 TailMem.getOperand(1).getReg() != ScaledReg)
759 return false;
760 if (!TailMem.getOperand(2).isImm())
761 return false;
762 int64_t Imm = TailMem.getOperand(2).getImm();
763
764 // Update QC_E_LI offset.
765 int64_t NewOffset = SignExtend64<32>(Hi.getOperand(1).getOffset() + Imm);
766
767 Hi.getOperand(1).setOffset(NewOffset);
768
769 // Build scaled load/store.
770 auto *TII = ST->getInstrInfo();
771 auto *MBB = TailMem.getParent();
772
773 // Ensure index register satisfies GPRNoX0 class required by QC_LR*/QC_SR*.
774 MRI->constrainRegClass(IndexReg, &RISCV::GPRNoX0RegClass);
775
776 BuildMI(*MBB, TailMem, TailMem.getDebugLoc(), TII->get(NewOpc))
777 .add(TailMem.getOperand(0))
778 .addReg(BaseReg, getKillRegState(ShxAdd.getOperand(2).isKill()))
779 .addReg(IndexReg, getKillRegState(ShxAdd.getOperand(1).isKill()))
780 .addImm(ShAmt)
781 .cloneMemRefs(TailMem);
782
783 TailMem.eraseFromParent();
784 ShxAdd.eraseFromParent();
785 return true;
786}
787
789 const RISCVSubtarget *ST = &Fn.getSubtarget<RISCVSubtarget>();
790
791 bool MadeChange = false;
793 for (MachineBasicBlock &MBB : Fn) {
794 LLVM_DEBUG(dbgs() << "MBB: " << MBB.getName() << "\n");
795 for (MachineInstr &Hi : MBB) {
796 MachineInstr *Lo = nullptr;
797 if (!detectFoldable(Hi, Lo, MRI))
798 continue;
799 MadeChange |= detectAndFoldOffset(Hi, *Lo, MRI, ST);
800 MadeChange |= foldIntoMemoryOps(Hi, *Lo, MRI, ST);
801 MadeChange |= foldShxaddIntoScaledMemory(Hi, *Lo, MRI, ST);
802 }
803 }
804
805 return MadeChange;
806}
807
808/// Returns an instance of the Merge Base Offset Optimization pass.
810 return new RISCVMergeBaseOffsetLegacy();
811}
812
813bool RISCVMergeBaseOffsetLegacy::runOnMachineFunction(MachineFunction &MF) {
814 if (skipFunction(MF.getFunction()))
815 return false;
816 return runMergeBaseOffset(MF);
817}
818
819PreservedAnalyses
MachineInstrBuilder & UseMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
uint64_t Imm
MachineBasicBlock & MBB
#define DEBUG_TYPE
const HexagonInstrInfo * TII
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
if(PassOpts->AAPipeline)
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
MachineRegisterInfo & MRI
static void overwriteMachineOperandInPlace(MachineOperand &MO, const MachineOperand &ImmOp)
static bool detectAndFoldOffset(MachineInstr &Hi, MachineInstr &Lo, MachineRegisterInfo *MRI, const RISCVSubtarget *ST)
unsigned ExpectedFlags
static bool foldShxaddIntoScaledMemory(MachineInstr &Hi, MachineInstr &Lo, MachineRegisterInfo *MRI, const RISCVSubtarget *ST)
static bool foldShiftedOffset(MachineInstr &Hi, MachineInstr &Lo, MachineInstr &TailShXAdd, Register GAReg, MachineRegisterInfo *MRI)
static bool foldIntoMemoryOps(MachineInstr &Hi, MachineInstr &Lo, MachineRegisterInfo *MRI, const RISCVSubtarget *ST)
const MachineOperand & HiOp1
#define RISCV_MERGE_BASE_OFFSET_NAME
static bool foldOffset(MachineInstr &Hi, MachineInstr &Lo, MachineInstr &Tail, int64_t Offset, MachineRegisterInfo *MRI)
static bool foldLargeOffset(MachineInstr &Hi, MachineInstr &Lo, MachineInstr &TailAdd, Register GAReg, MachineRegisterInfo *MRI, const RISCVSubtarget *ST)
static bool runMergeBaseOffset(MachineFunction &Fn)
MachineInstr *& Lo
#define LLVM_DEBUG(...)
Definition Debug.h:119
Represent the analysis usage information of a pass.
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:280
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
static LLVM_ABI void appendOffset(SmallVectorImpl< uint64_t > &Ops, int64_t Offset)
Append Ops with operations to apply the Offset.
static LLVM_ABI DIExpression * appendOpsToArg(const DIExpression *Expr, ArrayRef< uint64_t > Ops, unsigned ArgNo, bool StackValue=false)
Create a copy of Expr by appending the given list of Ops to each instance of the operand DW_OP_LLVM_a...
LLVM_ABI TypeSize getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:827
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this global belongs to.
Definition Globals.cpp:205
Type * getValueType() const
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.
Properties which a MachineFunction may have at a given point in time.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & add(const MachineOperand &MO) const
const MachineInstrBuilder & cloneMemRefs(const MachineInstr &OtherMI) const
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
const MachineBasicBlock * getParent() const
LLVM_ABI const MachineOperand & getDebugExpressionOp() const
Return the operand for the complex address expression referenced by this DBG_VALUE instruction.
LLVM_ABI const DIExpression * getDebugExpression() const
Return the complex address expression referenced by this DBG_VALUE instruction.
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
bool isDebugValue() const
unsigned getDebugOperandIndex(const MachineOperand *Op) const
const MachineOperand & getOperand(unsigned i) const
LLVM_ABI MachineInstrBundleIterator< MachineInstr > eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
MachineOperand class - Representation of each machine instruction operand.
const GlobalValue * getGlobal() const
int64_t getImm() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
bool isCPI() const
isCPI - Tests if this is a MO_ConstantPoolIndex operand.
LLVM_ABI void ChangeToMCSymbol(MCSymbol *Sym, unsigned TargetFlags=0)
ChangeToMCSymbol - Replace this operand with a new MC symbol operand.
void setMetadata(const MDNode *MD)
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
LLVM_ABI void ChangeToImmediate(int64_t ImmVal, unsigned TargetFlags=0)
ChangeToImmediate - Replace this operand with a new immediate operand of the specified value.
LLVM_ABI void ChangeToGA(const GlobalValue *GV, int64_t Offset, unsigned TargetFlags=0)
ChangeToGA - Replace this operand with a new global address operand.
LLVM_ABI void ChangeToBA(const BlockAddress *BA, int64_t Offset, unsigned TargetFlags=0)
ChangeToBA - Replace this operand with a new block address operand.
const BlockAddress * getBlockAddress() const
void setOffset(int64_t Offset)
unsigned getTargetFlags() const
bool isGlobal() const
isGlobal - Tests if this is a MO_GlobalAddress operand.
MachineOperandType getType() const
getType - Returns the MachineOperandType for this operand.
bool isBlockAddress() const
isBlockAddress - Tests if this is a MO_BlockAddress operand.
Register getReg() const
getReg - Returns the register number.
LLVM_ABI void ChangeToCPI(unsigned Idx, int Offset, unsigned TargetFlags=0)
ChangeToCPI - Replace this operand with a new constant pool index operand.
MCSymbol * getMCSymbol() const
@ MO_ConstantPoolIndex
Address of indexed Constant in Constant Pool.
@ MO_MCSymbol
MCSymbol reference (for debug/eh info)
@ MO_GlobalAddress
Address of a global value.
@ MO_BlockAddress
Address of a basic block.
int64_t getOffset() const
Return the offset from the symbol in this operand.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
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
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
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
Pass manager infrastructure for declaring and invalidating analyses.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition MathExtras.h:166
constexpr RegState getKillRegState(bool B)
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
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
FunctionPass * createRISCVMergeBaseOffsetLegacyPass()
Returns an instance of the Merge Base Offset Optimization pass.
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
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