LLVM 24.0.0git
LoongArchMergeBaseOffset.cpp
Go to the documentation of this file.
1//===---- LoongArchMergeBaseOffset.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 "LoongArch.h"
15#include "LoongArchSubtarget.h"
20#include "llvm/CodeGen/Passes.h"
21#include "llvm/IR/Analysis.h"
23#include "llvm/Support/Debug.h"
25#include <optional>
26
27using namespace llvm;
28
29#define DEBUG_TYPE "loongarch-merge-base-offset"
30#define LoongArch_MERGE_BASE_OFFSET_NAME "LoongArch Merge Base Offset"
31
32namespace {
33
34class LoongArchMergeBaseOffsetLegacy : public MachineFunctionPass {
35public:
36 static char ID;
37 bool runOnMachineFunction(MachineFunction &MF) override;
38
39 LoongArchMergeBaseOffsetLegacy() : 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 LoongArchMergeBaseOffsetLegacy::ID = 0;
57INITIALIZE_PASS(LoongArchMergeBaseOffsetLegacy, DEBUG_TYPE,
59
60static inline bool isPCAddLo(unsigned Flags) {
61 switch (Flags) {
68 return true;
69 }
70 return false;
71}
72
73// Detect either of the patterns:
74//
75// 1. (small/medium):
76// pcaxxu12i vreg1, %pc_hi20(s)
77// addi.d vreg2, vreg1, %pc_lo12(s)
78//
79// 2. (large):
80// pcalau12i vreg1, %pc_hi20(s)
81// addi.d vreg2, $zero, %pc_lo12(s)
82// lu32i.d vreg3, vreg2, %pc64_lo20(s)
83// lu52i.d vreg4, vreg3, %pc64_hi12(s)
84// add.d vreg5, vreg4, vreg1
85
86// The pattern is only accepted if:
87// 1) For small and medium pattern, the first instruction has only one use,
88// which is the ADDI.
89// 2) For large pattern, the first four instructions each have only one use,
90// and the user of the fourth instruction is ADD.
91// 3) The address operands have the appropriate type, reflecting the
92// lowering of a global address or constant pool using the pattern.
93// 4) The offset value in the Global Address or Constant Pool is 0.
94static bool detectFoldable(MachineInstr &Hi20, MachineInstr *&Lo12,
95 MachineInstr *&Lo20, MachineInstr *&Hi12,
98 if (Hi20.getOpcode() != LoongArch::PCALAU12I &&
99 Hi20.getOpcode() != LoongArch::PCADDU12I)
100 return false;
101
102 const MachineOperand &Hi20Op1 = Hi20.getOperand(1);
105 return false;
106
107 auto isGlobalOrCPIOrBlockAddress = [](const MachineOperand &Op) {
108 return Op.isGlobal() || Op.isCPI() || Op.isBlockAddress();
109 };
110
111 if (!isGlobalOrCPIOrBlockAddress(Hi20Op1) || Hi20Op1.getOffset() != 0)
112 return false;
113
114 Register HiDestReg = Hi20.getOperand(0).getReg();
115 if (!MRI->hasOneUse(HiDestReg))
116 return false;
117
118 MachineInstr *UseInst = &*MRI->use_instr_begin(HiDestReg);
119 if (UseInst->getOpcode() != LoongArch::ADD_D) {
120 Lo12 = UseInst;
121 if ((ST->is64Bit() && Lo12->getOpcode() != LoongArch::ADDI_D) ||
122 (!ST->is64Bit() && Lo12->getOpcode() != LoongArch::ADDI_W))
123 return false;
124 } else {
125 assert(ST->is64Bit());
126 Last = UseInst;
127
128 Register LastOp1Reg = Last->getOperand(1).getReg();
129 if (!LastOp1Reg.isVirtual())
130 return false;
131 Hi12 = MRI->getVRegDef(LastOp1Reg);
132 const MachineOperand &Hi12Op2 = Hi12->getOperand(2);
134 return false;
135 if (!isGlobalOrCPIOrBlockAddress(Hi12Op2) || Hi12Op2.getOffset() != 0)
136 return false;
137 if (!MRI->hasOneUse(Hi12->getOperand(0).getReg()))
138 return false;
139
140 Lo20 = MRI->getVRegDef(Hi12->getOperand(1).getReg());
141 const MachineOperand &Lo20Op2 = Lo20->getOperand(2);
143 return false;
144 if (!isGlobalOrCPIOrBlockAddress(Lo20Op2) || Lo20Op2.getOffset() != 0)
145 return false;
146 if (!MRI->hasOneUse(Lo20->getOperand(0).getReg()))
147 return false;
148
149 Lo12 = MRI->getVRegDef(Lo20->getOperand(1).getReg());
150 if (!MRI->hasOneUse(Lo12->getOperand(0).getReg()))
151 return false;
152 }
153
154 const MachineOperand &Lo12Op2 = Lo12->getOperand(2);
155 assert(Hi20.getOpcode() == LoongArch::PCALAU12I ||
156 Hi20.getOpcode() == LoongArch::PCADDU12I);
158 !isPCAddLo(LoongArchII::getDirectFlags(Lo12Op2))) ||
159 !(isGlobalOrCPIOrBlockAddress(Lo12Op2) || Lo12Op2.isMCSymbol()) ||
160 Lo12Op2.getOffset() != 0)
161 return false;
162
163 if (Hi20Op1.isGlobal()) {
164 LLVM_DEBUG(dbgs() << " Found lowered global address: "
165 << *Hi20Op1.getGlobal() << "\n");
166 } else if (Hi20Op1.isBlockAddress()) {
167 LLVM_DEBUG(dbgs() << " Found lowered basic address: "
168 << *Hi20Op1.getBlockAddress() << "\n");
169 } else if (Hi20Op1.isCPI()) {
170 LLVM_DEBUG(dbgs() << " Found lowered constant pool: " << Hi20Op1.getIndex()
171 << "\n");
172 }
173
174 return true;
175}
176
177// Detect the pattern:
178//
179// (small/medium):
180// lu12i.w vreg1, %le_hi20_r(s)
181// add.w/d vreg2, vreg1, r2, %le_add_r(s)
182// addi.w/d vreg3, vreg2, %le_lo12_r(s)
183
184// The pattern is only accepted if:
185// 1) The first instruction has only one use, which is the PseudoAddTPRel.
186// The second instruction has only one use, which is the ADDI. The
187// second instruction's last operand is the tp register.
188// 2) The address operands have the appropriate type, reflecting the
189// lowering of a thread_local global address using the pattern.
190// 3) The offset value in the ThreadLocal Global Address is 0.
192 MachineInstr *&Lo12, const LoongArchSubtarget *ST,
194 if (Hi20.getOpcode() != LoongArch::LU12I_W)
195 return false;
196
197 auto isGlobalOrCPI = [](const MachineOperand &Op) {
198 return Op.isGlobal() || Op.isCPI();
199 };
200
201 const MachineOperand &Hi20Op1 = Hi20.getOperand(1);
203 !isGlobalOrCPI(Hi20Op1) || Hi20Op1.getOffset() != 0)
204 return false;
205
206 Register HiDestReg = Hi20.getOperand(0).getReg();
207 if (!MRI->hasOneUse(HiDestReg))
208 return false;
209
210 Add = &*MRI->use_instr_begin(HiDestReg);
211 if ((ST->is64Bit() && Add->getOpcode() != LoongArch::PseudoAddTPRel_D) ||
212 (!ST->is64Bit() && Add->getOpcode() != LoongArch::PseudoAddTPRel_W))
213 return false;
214
215 if (Add->getOperand(2).getReg() != LoongArch::R2)
216 return false;
217
218 const MachineOperand &AddOp3 = Add->getOperand(3);
220 !(isGlobalOrCPI(AddOp3) || AddOp3.isMCSymbol()) ||
221 AddOp3.getOffset() != 0)
222 return false;
223
224 Register AddDestReg = Add->getOperand(0).getReg();
225 if (!MRI->hasOneUse(AddDestReg))
226 return false;
227
228 Lo12 = &*MRI->use_instr_begin(AddDestReg);
229 if ((ST->is64Bit() && Lo12->getOpcode() != LoongArch::ADDI_D) ||
230 (!ST->is64Bit() && Lo12->getOpcode() != LoongArch::ADDI_W))
231 return false;
232
233 const MachineOperand &Lo12Op2 = Lo12->getOperand(2);
235 !(isGlobalOrCPI(Lo12Op2) || Lo12Op2.isMCSymbol()) ||
236 Lo12Op2.getOffset() != 0)
237 return false;
238
239 if (Hi20Op1.isGlobal()) {
240 LLVM_DEBUG(dbgs() << " Found lowered global address: "
241 << *Hi20Op1.getGlobal() << "\n");
242 } else if (Hi20Op1.isCPI()) {
243 LLVM_DEBUG(dbgs() << " Found lowered constant pool: " << Hi20Op1.getIndex()
244 << "\n");
245 }
246
247 return true;
248}
249
250// Update the offset in Hi20, (Add), Lo12, (Lo20 and Hi12) instructions.
251// Delete the tail instruction and update all the uses to use the
252// output from Last.
253static void foldOffset(MachineInstr &Hi20, MachineInstr &Lo12,
254 MachineInstr *&Lo20, MachineInstr *&Hi12,
255 MachineInstr *&Last, MachineInstr &Tail, int64_t Offset,
257 // Put the offset back in Hi and the Lo
258 MachineOperand &Lo12Op2 = Lo12.getOperand(2);
259 Hi20.getOperand(1).setOffset(Offset);
260 if (!isPCAddLo(LoongArchII::getDirectFlags(Lo12Op2)))
261 Lo12Op2.setOffset(Offset);
262 if (Lo20 && Hi12) {
263 Lo20->getOperand(2).setOffset(Offset);
264 Hi12->getOperand(2).setOffset(Offset);
265 }
266
267 // For tls-le, offset of the second PseudoAddTPRel instr should also be
268 // updated.
269 MachineInstr *Add = &*MRI->use_instr_begin(Hi20.getOperand(0).getReg());
270 if (Hi20.getOpcode() == LoongArch::LU12I_W)
271 Add->getOperand(3).setOffset(Offset);
272
273 // Delete the tail instruction.
274 MachineInstr *Def = Last ? Last : &Lo12;
275 MRI->constrainRegClass(Def->getOperand(0).getReg(),
276 MRI->getRegClass(Tail.getOperand(0).getReg()));
277 MRI->replaceRegWith(Tail.getOperand(0).getReg(), Def->getOperand(0).getReg());
278 Tail.eraseFromParent();
279
280 LLVM_DEBUG(dbgs() << " Merged offset " << Offset << " into base.\n"
281 << " " << Hi20;);
282 if (Hi20.getOpcode() == LoongArch::LU12I_W) {
283 LLVM_DEBUG(dbgs() << " " << *Add;);
284 }
285 LLVM_DEBUG(dbgs() << " " << Lo12;);
286 if (Lo20 && Hi12) {
287 LLVM_DEBUG(dbgs() << " " << *Lo20 << " " << *Hi12;);
288 }
289}
290
291// Detect patterns for large offsets that are passed into an ADD instruction.
292// If the pattern is found, updates the offset in Hi20, (Add), Lo12,
293// (Lo20 and Hi12) instructions and deletes TailAdd and the instructions that
294// produced the offset.
295//
296// (The instructions marked with "!" are not necessarily present)
297//
298// Base address lowering is of the form:
299// 1) pcala:
300// Hi20: pcaxxu12i vreg1, %pc_hi20(s)
301// +--- Lo12: addi.d vreg2, vreg1, %pc_lo12(s)
302// | Lo20: lu32i.d vreg2, %pc64_lo20(s) !
303// +--- Hi12: lu52i.d vreg2, vreg2, %pc64_hi12(s) !
304// |
305// | 2) tls-le:
306// | Hi20: lu12i.w vreg1, %le_hi20_r(s)
307// | Add: add.w/d vreg1, vreg1, r2, %le_add_r(s)
308// +--- Lo12: addi.w/d vreg2, vreg1, %le_lo12_r(s)
309// |
310// | The large offset can be one of the forms:
311// |
312// +-> 1) Offset that has non zero bits in Hi20 and Lo12 bits:
313// | OffsetHi20: lu12i.w vreg3, 4
314// | OffsetLo12: ori voff, vreg3, 188 ------------------+
315// | |
316// +-> 2) Offset that has non zero bits in Hi20 bits only: |
317// | OffsetHi20: lu12i.w voff, 128 ------------------+
318// | |
319// +-> 3) Offset that has non zero bits in Lo20 bits: |
320// | OffsetHi20: lu12i.w vreg3, 121 ! |
321// | OffsetLo12: ori voff, vreg3, 122 ! |
322// | OffsetLo20: lu32i.d voff, 123 ------------------+
323// +-> 4) Offset that has non zero bits in Hi12 bits: |
324// | OffsetHi20: lu12i.w vreg3, 121 ! |
325// | OffsetLo12: ori voff, vreg3, 122 ! |
326// | OffsetLo20: lu32i.d vreg3, 123 ! |
327// | OffsetHi12: lu52i.d voff, vreg3, 124 -----------------+
328// +-> 5) Offset that is a field shifted into place: |
329// lu12i.w voff, 4 |
330// slli.d voff, voff, 20 ------------------+
331// |
332// TailAdd: add.d vreg4, vreg2, voff <------------------+
333//
335 MachineInstr *&Lo20, MachineInstr *&Hi12,
336 MachineInstr *&Last, MachineInstr &TailAdd,
338 assert((TailAdd.getOpcode() == LoongArch::ADD_W ||
339 TailAdd.getOpcode() == LoongArch::ADD_D) &&
340 "Expected ADD instruction!");
341 Register Rs = TailAdd.getOperand(1).getReg();
342 Register Rt = TailAdd.getOperand(2).getReg();
343 Register Reg = Rs == GAReg ? Rt : Rs;
345
346 // Walk backwards through the single-use chain that materializes the offset.
347 // This can point to one of [ORI, LU12I.W, LU32I.D, LU52I.D, SLLI.D]:
348 for (int I = 0; I < 4; I++) {
349 // Handle Reg is R0.
350 if (Reg == LoongArch::R0)
351 break;
352
353 // Can't fold if the register has more than one non-debug use.
354 if (!Reg.isVirtual() || !MRI->hasOneNonDBGUse(Reg))
355 return false;
356
357 MachineInstr *Curr = MRI->getVRegDef(Reg);
358 if (!Curr)
359 break;
360
361 switch (Curr->getOpcode()) {
362 default:
363 // Can't fold if the instruction opcode is unexpected.
364 return false;
365 case LoongArch::ORI:
367 return false;
368 Reg = Curr->getOperand(1).getReg();
369 break;
370 case LoongArch::LU12I_W:
372 return false;
373 Reg = LoongArch::R0;
374 break;
375 case LoongArch::LU32I_D:
376 if (Curr->getOperand(2).getTargetFlags() != LoongArchII::MO_None || !Lo20)
377 return false;
378 Reg = Curr->getOperand(1).getReg();
379 break;
380 case LoongArch::LU52I_D:
381 if (Curr->getOperand(2).getTargetFlags() != LoongArchII::MO_None || !Hi12)
382 return false;
383 Reg = Curr->getOperand(1).getReg();
384 break;
385 case LoongArch::SLLI_D:
387 !(Lo20 && Hi12))
388 return false;
389 Reg = Curr->getOperand(1).getReg();
390 break;
391 }
392 Instrs.push_back(Curr);
393 }
394
395 // Can't fold if the current register does not reach R0.
396 if (Reg != LoongArch::R0)
397 return false;
398
399 // Compute the offset by evaluating the chain in program order with the exact
400 // semantics of each instruction. The chain is not necessarily in the
401 // canonical form produced by LoongArchMatInt (e.g. when part of the constant
402 // is materialized in another basic block), so the instructions may write
403 // overlapping bits.
404 uint64_t Val = 0;
405 for (MachineInstr *MI : reverse(Instrs)) {
406 switch (MI->getOpcode()) {
407 default:
408 llvm_unreachable("Unexpected opcode");
409 case LoongArch::ORI:
410 Val |= static_cast<uint64_t>(MI->getOperand(2).getImm()) & 0xFFF;
411 break;
412 case LoongArch::LU12I_W:
413 Val = SignExtend64<32>(static_cast<uint64_t>(MI->getOperand(1).getImm())
414 << 12);
415 break;
416 case LoongArch::LU32I_D:
417 Val = (Val & 0xFFFFFFFF) |
418 SignExtend64<52>(static_cast<uint64_t>(MI->getOperand(2).getImm())
419 << 32);
420 break;
421 case LoongArch::LU52I_D:
422 Val = (Val & 0x000FFFFFFFFFFFFF) |
423 (static_cast<uint64_t>(MI->getOperand(2).getImm()) << 52);
424 break;
425 case LoongArch::SLLI_D:
426 Val <<= MI->getOperand(2).getImm() & 0x3F;
427 break;
428 }
429 }
430 int64_t Offset = Val;
431
432 // Can't fold if the offset is not extracted.
433 if (!Offset)
434 return false;
435
436 foldOffset(Hi20, Lo12, Lo20, Hi12, Last, TailAdd, Offset, MRI);
437 LLVM_DEBUG(dbgs() << " Offset Instrs:\n");
438 for (auto I : Instrs) {
439 LLVM_DEBUG(dbgs() << " " << *I);
440 // The offset instruction is about to be erased, so its debug users can no
441 // longer be described.
442 MRI->markUsesInDebugValueAsUndef(I->getOperand(0).getReg());
443 I->eraseFromParent();
444 }
445
446 return true;
447}
448
450 MachineInstr *&Lo20, MachineInstr *&Hi12,
452 const LoongArchSubtarget *ST,
454 Register DestReg =
455 Last ? Last->getOperand(0).getReg() : Lo12.getOperand(0).getReg();
456
457 // Look for arithmetic instructions we can get an offset from.
458 // We might be able to remove the arithmetic instructions by folding the
459 // offset into the PCAXXU12I+(ADDI/ADDI+LU32I+LU52I) or
460 // LU12I_W+PseudoAddTPRel+ADDI.
461 if (!MRI->hasOneUse(DestReg))
462 return false;
463
464 // DestReg has only one use.
465 MachineInstr &Tail = *MRI->use_instr_begin(DestReg);
466 switch (Tail.getOpcode()) {
467 default:
468 LLVM_DEBUG(dbgs() << "Don't know how to get offset from this instr:"
469 << Tail);
470 break;
471 case LoongArch::ADDI_W:
472 if (ST->is64Bit())
473 return false;
474 [[fallthrough]];
475 case LoongArch::ADDI_D:
476 case LoongArch::ADDU16I_D: {
477 // Offset is simply an immediate operand.
478 int64_t Offset = Tail.getOperand(2).getImm();
479 if (Tail.getOpcode() == LoongArch::ADDU16I_D)
480 Offset = SignExtend64<32>(static_cast<uint64_t>(Offset) << 16);
481
482 // We might have two ADDIs in a row.
483 Register TailDestReg = Tail.getOperand(0).getReg();
484 if (MRI->hasOneUse(TailDestReg)) {
485 MachineInstr &TailTail = *MRI->use_instr_begin(TailDestReg);
486 if (ST->is64Bit() && TailTail.getOpcode() == LoongArch::ADDI_W)
487 return false;
488 if (TailTail.getOpcode() == LoongArch::ADDI_W ||
489 TailTail.getOpcode() == LoongArch::ADDI_D) {
490 Offset += TailTail.getOperand(2).getImm();
491 LLVM_DEBUG(dbgs() << " Offset Instrs: " << Tail << TailTail);
492 foldOffset(Hi20, Lo12, Lo20, Hi12, Last, TailTail, Offset, MRI);
493 Tail.eraseFromParent();
494 return true;
495 }
496 }
497
498 LLVM_DEBUG(dbgs() << " Offset Instr: " << Tail);
499 foldOffset(Hi20, Lo12, Lo20, Hi12, Last, Tail, Offset, MRI);
500 return true;
501 }
502 case LoongArch::ADD_W:
503 if (ST->is64Bit())
504 return false;
505 [[fallthrough]];
506 case LoongArch::ADD_D:
507 // The offset is too large to fit in the immediate field of ADDI.
508 return foldLargeOffset(Hi20, Lo12, Lo20, Hi12, Last, Tail, DestReg, MRI);
509 break;
510 }
511
512 return false;
513}
514
515// Memory access opcode mapping for transforms.
516static unsigned getNewOpc(unsigned Op, bool isLarge) {
517 switch (Op) {
518 case LoongArch::LD_B:
519 return isLarge ? LoongArch::LDX_B : LoongArch::LD_B;
520 case LoongArch::LD_H:
521 return isLarge ? LoongArch::LDX_H : LoongArch::LD_H;
522 case LoongArch::LD_W:
523 case LoongArch::LDPTR_W:
524 return isLarge ? LoongArch::LDX_W : LoongArch::LD_W;
525 case LoongArch::LD_D:
526 case LoongArch::LDPTR_D:
527 return isLarge ? LoongArch::LDX_D : LoongArch::LD_D;
528 case LoongArch::LD_BU:
529 return isLarge ? LoongArch::LDX_BU : LoongArch::LD_BU;
530 case LoongArch::LD_HU:
531 return isLarge ? LoongArch::LDX_HU : LoongArch::LD_HU;
532 case LoongArch::LD_WU:
533 return isLarge ? LoongArch::LDX_WU : LoongArch::LD_WU;
534 case LoongArch::FLD_S:
535 return isLarge ? LoongArch::FLDX_S : LoongArch::FLD_S;
536 case LoongArch::FLD_D:
537 return isLarge ? LoongArch::FLDX_D : LoongArch::FLD_D;
538 case LoongArch::VLD:
539 return isLarge ? LoongArch::VLDX : LoongArch::VLD;
540 case LoongArch::XVLD:
541 return isLarge ? LoongArch::XVLDX : LoongArch::XVLD;
542 case LoongArch::VLDREPL_B:
543 return LoongArch::VLDREPL_B;
544 case LoongArch::XVLDREPL_B:
545 return LoongArch::XVLDREPL_B;
546 case LoongArch::ST_B:
547 return isLarge ? LoongArch::STX_B : LoongArch::ST_B;
548 case LoongArch::ST_H:
549 return isLarge ? LoongArch::STX_H : LoongArch::ST_H;
550 case LoongArch::ST_W:
551 case LoongArch::STPTR_W:
552 return isLarge ? LoongArch::STX_W : LoongArch::ST_W;
553 case LoongArch::ST_D:
554 case LoongArch::STPTR_D:
555 return isLarge ? LoongArch::STX_D : LoongArch::ST_D;
556 case LoongArch::FST_S:
557 return isLarge ? LoongArch::FSTX_S : LoongArch::FST_S;
558 case LoongArch::FST_D:
559 return isLarge ? LoongArch::FSTX_D : LoongArch::FST_D;
560 case LoongArch::VST:
561 return isLarge ? LoongArch::VSTX : LoongArch::VST;
562 case LoongArch::XVST:
563 return isLarge ? LoongArch::XVSTX : LoongArch::XVST;
564 default:
565 llvm_unreachable("Unexpected opcode for replacement");
566 }
567}
568
570 MachineInstr *&Lo20, MachineInstr *&Hi12,
573 Register DestReg =
574 Last ? Last->getOperand(0).getReg() : Lo12.getOperand(0).getReg();
575
576 // If all the uses are memory ops with the same offset, we can transform:
577 //
578 // 1. (small/medium):
579 // 1.1. pcala
580 // pcaxxu12i vreg1, %pc_hi20(s)
581 // addi.d vreg2, vreg1, %pc_lo12(s)
582 // ld.w vreg3, 8(vreg2)
583 //
584 // =>
585 //
586 // pcalxx12i vreg1, %pc_hi20(s+8)
587 // ld.w vreg3, vreg1, %pc_lo12(s+8)(vreg1)
588 //
589 // 1.2. tls-le
590 // lu12i.w vreg1, %le_hi20_r(s)
591 // add.w/d vreg2, vreg1, r2, %le_add_r(s)
592 // addi.w/d vreg3, vreg2, %le_lo12_r(s)
593 // ld.w vreg4, 8(vreg3)
594 //
595 // =>
596 //
597 // lu12i.w vreg1, %le_hi20_r(s+8)
598 // add.w/d vreg2, vreg1, r2, %le_add_r(s+8)
599 // ld.w vreg4, vreg2, %le_lo12_r(s+8)(vreg2)
600 //
601 // 2. (large):
602 // pcalau12i vreg1, %pc_hi20(s)
603 // addi.d vreg2, $zero, %pc_lo12(s)
604 // lu32i.d vreg3, vreg2, %pc64_lo20(s)
605 // lu52i.d vreg4, vreg3, %pc64_hi12(s)
606 // add.d vreg5, vreg4, vreg1
607 // ld.w vreg6, 8(vreg5)
608 //
609 // =>
610 //
611 // pcalau12i vreg1, %pc_hi20(s+8)
612 // addi.d vreg2, $zero, %pc_lo12(s+8)
613 // lu32i.d vreg3, vreg2, %pc64_lo20(s+8)
614 // lu52i.d vreg4, vreg3, %pc64_hi12(s+8)
615 // ldx.w vreg6, vreg4, vreg1
616
617 std::optional<int64_t> CommonOffset;
619 InlineAsmMemoryOpIndexesMap;
620 for (const MachineInstr &UseMI : MRI->use_nodbg_instructions(DestReg)) {
621 switch (UseMI.getOpcode()) {
622 default:
623 LLVM_DEBUG(dbgs() << "Not a load or store instruction: " << UseMI);
624 return false;
625 case LoongArch::VLDREPL_B:
626 case LoongArch::XVLDREPL_B:
627 // We can't do this for large pattern.
628 if (Last)
629 return false;
630 [[fallthrough]];
631 case LoongArch::LD_B:
632 case LoongArch::LD_H:
633 case LoongArch::LD_W:
634 case LoongArch::LD_D:
635 case LoongArch::LD_BU:
636 case LoongArch::LD_HU:
637 case LoongArch::LD_WU:
638 case LoongArch::LDPTR_W:
639 case LoongArch::LDPTR_D:
640 case LoongArch::FLD_S:
641 case LoongArch::FLD_D:
642 case LoongArch::VLD:
643 case LoongArch::XVLD:
644 case LoongArch::ST_B:
645 case LoongArch::ST_H:
646 case LoongArch::ST_W:
647 case LoongArch::ST_D:
648 case LoongArch::STPTR_W:
649 case LoongArch::STPTR_D:
650 case LoongArch::FST_S:
651 case LoongArch::FST_D:
652 case LoongArch::VST:
653 case LoongArch::XVST: {
654 if (UseMI.getOperand(1).isFI())
655 return false;
656 // Register defined by Lo should not be the value register.
657 if (DestReg == UseMI.getOperand(0).getReg())
658 return false;
659 assert(DestReg == UseMI.getOperand(1).getReg() &&
660 "Expected base address use");
661 // All load/store instructions must use the same offset.
662 int64_t Offset = UseMI.getOperand(2).getImm();
663 if (CommonOffset && Offset != CommonOffset)
664 return false;
665 CommonOffset = Offset;
666 break;
667 }
668 case LoongArch::INLINEASM:
669 case LoongArch::INLINEASM_BR: {
670 // We can't do this for large pattern.
671 if (Last)
672 return false;
673 SmallVector<unsigned> InlineAsmMemoryOpIndexes;
674 unsigned NumOps = 0;
675 for (unsigned I = InlineAsm::MIOp_FirstOperand;
676 I < UseMI.getNumOperands(); I += 1 + NumOps) {
677 const MachineOperand &FlagsMO = UseMI.getOperand(I);
678 // Should be an imm.
679 if (!FlagsMO.isImm())
680 continue;
681
682 const InlineAsm::Flag Flags(FlagsMO.getImm());
683 NumOps = Flags.getNumOperandRegisters();
684
685 // Memory constraints have two operands.
686 if (NumOps != 2 || !Flags.isMemKind()) {
687 // If the register is used by something other than a memory contraint,
688 // we should not fold.
689 for (unsigned J = 0; J < NumOps; ++J) {
690 const MachineOperand &MO = UseMI.getOperand(I + 1 + J);
691 if (MO.isReg() && MO.getReg() == DestReg)
692 return false;
693 }
694 continue;
695 }
696
697 // We can only do this for constraint m.
698 if (Flags.getMemoryConstraintID() != InlineAsm::ConstraintCode::m)
699 return false;
700
701 const MachineOperand &AddrMO = UseMI.getOperand(I + 1);
702 if (!AddrMO.isReg() || AddrMO.getReg() != DestReg)
703 continue;
704
705 const MachineOperand &OffsetMO = UseMI.getOperand(I + 2);
706 if (!OffsetMO.isImm())
707 continue;
708
709 // All inline asm memory operands must use the same offset.
710 int64_t Offset = OffsetMO.getImm();
711 if (CommonOffset && Offset != CommonOffset)
712 return false;
713 CommonOffset = Offset;
714 InlineAsmMemoryOpIndexes.push_back(I + 1);
715 }
716 InlineAsmMemoryOpIndexesMap.insert(
717 std::make_pair(&UseMI, InlineAsmMemoryOpIndexes));
718 break;
719 }
720 }
721 }
722
723 if (!CommonOffset)
724 return false;
725
726 // We found a common offset.
727 // Update the offsets in global address lowering.
728 // We may have already folded some arithmetic so we need to add to any
729 // existing offset.
730 int64_t NewOffset = Hi20.getOperand(1).getOffset() + *CommonOffset;
731 // LA32 ignores the upper 32 bits.
732 if (!ST->is64Bit())
733 NewOffset = SignExtend64<32>(NewOffset);
734 // We can only fold simm32 offsets.
735 if (!isInt<32>(NewOffset))
736 return false;
737
738 // Folding changes the value represented by DestReg, so its debug users can
739 // no longer describe the same address.
740 MRI->markUsesInDebugValueAsUndef(DestReg);
741
742 // If optimized by this pass successfully, MO_RELAX bitmask target-flag should
743 // be removed from the pcala code sequence. Code sequence of tls-le can still
744 // be relaxed after being optimized.
745 //
746 // For example:
747 // pcaxxu12i $a0, %pc_hi20(symbol)
748 // addi.d $a0, $a0, %pc_lo12(symbol)
749 // ld.w $a0, $a0, 0
750 //
751 // =>
752 //
753 // pcaxxu12i $a0, %pc_hi20(symbol)
754 // ld.w $a0, $a0, %pc_lo12(symbol)
755 //
756 // Code sequence optimized before can be relax by linker. But after being
757 // optimized, it cannot be relaxed any more. So MO_RELAX flag should not be
758 // carried by them.
759 Hi20.getOperand(1).setOffset(NewOffset);
760 MachineOperand &ImmOp = Lo12.getOperand(2);
761 if (!isPCAddLo(LoongArchII::getDirectFlags(ImmOp)))
762 ImmOp.setOffset(NewOffset);
763 if (Lo20 && Hi12) {
764 Lo20->getOperand(2).setOffset(NewOffset);
765 Hi12->getOperand(2).setOffset(NewOffset);
766 }
767 if (Hi20.getOpcode() == LoongArch::PCADDU12I ||
768 Hi20.getOpcode() == LoongArch::PCALAU12I) {
772 } else if (Hi20.getOpcode() == LoongArch::LU12I_W) {
773 MachineInstr *Add = &*MRI->use_instr_begin(Hi20.getOperand(0).getReg());
774 Add->getOperand(3).setOffset(NewOffset);
775 }
776
777 // Update the immediate in the load/store instructions to add the offset.
778 const LoongArchInstrInfo &TII = *ST->getInstrInfo();
779 for (MachineInstr &UseMI :
780 llvm::make_early_inc_range(MRI->use_nodbg_instructions(DestReg))) {
781 if (UseMI.getOpcode() == LoongArch::INLINEASM ||
782 UseMI.getOpcode() == LoongArch::INLINEASM_BR) {
783 auto &InlineAsmMemoryOpIndexes = InlineAsmMemoryOpIndexesMap[&UseMI];
784 for (unsigned I : InlineAsmMemoryOpIndexes) {
785 MachineOperand &MO = UseMI.getOperand(I + 1);
786 switch (ImmOp.getType()) {
788 MO.ChangeToGA(ImmOp.getGlobal(), ImmOp.getOffset(),
790 break;
792 MO.ChangeToMCSymbol(ImmOp.getMCSymbol(),
794 MO.setOffset(ImmOp.getOffset());
795 break;
797 MO.ChangeToBA(ImmOp.getBlockAddress(), ImmOp.getOffset(),
799 break;
801 MO.ChangeToCPI(ImmOp.getIndex(), ImmOp.getOffset(),
803 break;
804 default:
805 report_fatal_error("unsupported machine operand type");
806 break;
807 }
808 }
809 } else {
810 UseMI.setDesc(TII.get(getNewOpc(UseMI.getOpcode(), Last)));
811 if (Last) {
812 UseMI.removeOperand(2);
813 UseMI.removeOperand(1);
814 UseMI.addOperand(Last->getOperand(1));
815 UseMI.addOperand(Last->getOperand(2));
816 UseMI.getOperand(1).setIsKill(false);
817 UseMI.getOperand(2).setIsKill(false);
818 } else {
819 UseMI.removeOperand(2);
820 UseMI.addOperand(ImmOp);
821 }
822 }
823 }
824
825 if (Last) {
826 Last->eraseFromParent();
827 return true;
828 }
829
830 if (Hi20.getOpcode() == LoongArch::PCADDU12I ||
831 Hi20.getOpcode() == LoongArch::PCALAU12I) {
832 MRI->replaceRegWith(Lo12.getOperand(0).getReg(),
833 Hi20.getOperand(0).getReg());
834 } else if (Hi20.getOpcode() == LoongArch::LU12I_W) {
835 MachineInstr *Add = &*MRI->use_instr_begin(Hi20.getOperand(0).getReg());
836 MRI->replaceRegWith(Lo12.getOperand(0).getReg(),
837 Add->getOperand(0).getReg());
838 }
839 Lo12.eraseFromParent();
840 return true;
841}
842
845
846 bool MadeChange = false;
848 for (MachineBasicBlock &MBB : MF) {
849 LLVM_DEBUG(dbgs() << "MBB: " << MBB.getName() << "\n");
850 for (MachineInstr &Hi20 : MBB) {
851 MachineInstr *Lo12 = nullptr;
852 MachineInstr *Lo20 = nullptr;
853 MachineInstr *Hi12 = nullptr;
854 MachineInstr *Last = nullptr;
855 if (Hi20.getOpcode() == LoongArch::PCADDU12I ||
856 Hi20.getOpcode() == LoongArch::PCALAU12I) {
857 // Detect foldable pcala code sequence in small/medium/large code model.
858 if (!detectFoldable(Hi20, Lo12, Lo20, Hi12, Last, ST, MRI))
859 continue;
860 } else if (Hi20.getOpcode() == LoongArch::LU12I_W) {
861 MachineInstr *Add = nullptr;
862 // Detect foldable tls-le code sequence in small/medium code model.
863 if (!detectFoldable(Hi20, Add, Lo12, ST, MRI))
864 continue;
865 } else {
866 continue;
867 }
868 // For tls-le, we do not pass the second PseudoAddTPRel instr in order to
869 // reuse the existing hooks and the last three paramaters should always be
870 // nullptr.
871 MadeChange |= detectAndFoldOffset(Hi20, *Lo12, Lo20, Hi12, Last, ST, MRI);
872 MadeChange |= foldIntoMemoryOps(Hi20, *Lo12, Lo20, Hi12, Last, ST, MRI);
873 }
874 }
875
876 return MadeChange;
877}
878
879bool LoongArchMergeBaseOffsetLegacy::runOnMachineFunction(MachineFunction &MF) {
880 if (skipFunction(MF.getFunction()))
881 return false;
882 return runMergeBaseOffsetOpt(MF);
883}
884
885/// Returns an instance of the Merge Base Offset Optimization pass.
887 return new LoongArchMergeBaseOffsetLegacy();
888}
889
MachineInstrBuilder & UseMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const AArch64InstrInfo & TII
uint64_t uint64_t
MachineBasicBlock & MBB
always inline
#define DEBUG_TYPE
#define _
IRTranslator LLVM IR MI
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
static void foldOffset(MachineInstr &Hi20, MachineInstr &Lo12, MachineInstr *&Lo20, MachineInstr *&Hi12, MachineInstr *&Last, MachineInstr &Tail, int64_t Offset, MachineRegisterInfo *MRI)
static bool foldLargeOffset(MachineInstr &Hi20, MachineInstr &Lo12, MachineInstr *&Lo20, MachineInstr *&Hi12, MachineInstr *&Last, MachineInstr &TailAdd, Register GAReg, MachineRegisterInfo *MRI)
static bool foldIntoMemoryOps(MachineInstr &Hi20, MachineInstr &Lo12, MachineInstr *&Lo20, MachineInstr *&Hi12, MachineInstr *&Last, const LoongArchSubtarget *ST, MachineRegisterInfo *MRI)
static unsigned getNewOpc(unsigned Op, bool isLarge)
#define LoongArch_MERGE_BASE_OFFSET_NAME
static bool detectFoldable(MachineInstr &Hi20, MachineInstr *&Lo12, MachineInstr *&Lo20, MachineInstr *&Hi12, MachineInstr *&Last, const LoongArchSubtarget *ST, MachineRegisterInfo *MRI)
static bool detectAndFoldOffset(MachineInstr &Hi20, MachineInstr &Lo12, MachineInstr *&Lo20, MachineInstr *&Hi12, MachineInstr *&Last, const LoongArchSubtarget *ST, MachineRegisterInfo *MRI)
static bool runMergeBaseOffsetOpt(MachineFunction &MF)
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
MachineRegisterInfo & MRI
#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
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
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
An RAII based helper class to modify MachineFunctionProperties when running pass.
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.
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
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.
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
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.
void setTargetFlags(unsigned F)
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,...
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
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
Pass manager infrastructure for declaring and invalidating analyses.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
static unsigned getDirectFlags(const MachineOperand &MO)
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition MathExtras.h:166
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
FunctionPass * createLoongArchMergeBaseOffsetLegacyPass()
Returns an instance of the Merge Base Offset Optimization pass.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
MachineInstr * getImm(const MachineOperand &MO, const MachineRegisterInfo *MRI)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
@ Add
Sum of integers.
DWARFExpression::Operation Op
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