Skip to content

Instantly share code, notes, and snippets.

@heiher
Created November 15, 2023 15:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save heiher/bd7398397f3cb5598dce35cbc04d0075 to your computer and use it in GitHub Desktop.
Save heiher/bd7398397f3cb5598dce35cbc04d0075 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
int
main (int argc, char *argv[])
{
long target;
long dest;
long pc;
long delta;
long pcala_hi20;
long pcala_lo12;
long pcala64_lo20;
long pcala64_hi12;
dest = strtoul (argv[1], NULL, 16);
pc = strtoul (argv[2], NULL, 16);
delta = dest - (pc & ~0xfffUL);
delta = delta + ((delta & 0x800UL) << 1);
delta = delta + ((delta & 0x80000000UL) << 1);
delta = delta - ((delta & 0x800UL) << 21);
pcala_hi20 = (delta >> 12) & 0xfffffUL;
pcala_lo12 = delta & 0xfffUL;
pcala64_lo20 = (delta >> 32) & 0xfffffUL;
pcala64_hi12 = (delta >> 52) & 0xfffUL;
printf ("R_LARCH_PCALA_HI20 = 0x%lx\n", pcala_hi20);
printf ("R_LARCH_PCALA_LO12 = 0x%lx\n", pcala_lo12);
printf ("R_LARCH_PCALA64_LO20 = 0x%lx\n", pcala64_lo20);
printf ("R_LARCH_PCALA64_HI12 = 0x%lx\n", pcala64_hi12);
target = (pc & ~0xfffUL) + ((pcala_hi20 << 44) >> 32) +
((pcala64_hi12 << 52) | (pcala64_lo20 << 32) | (((pcala_lo12 << 52) >> 52) & 0xffffffffUL));
if (target != dest) {
printf ("%0lx != %0lx\n", dest, target);
return -1;
}
return 0;
}
@MQ-mengqing
Copy link

For the most cases, it works well. But for some corner cases, it may work badly.
a), the pc of these four instructions is not the same.
b), at least, in GCC, instructions are not even adjacent if they are scheduled.
Thus, we may need 4 pc as input.

@heiher
Copy link
Author

heiher commented Nov 16, 2023

@MQ-mengqing Even after scheduling, if 4 instructions are still in the same 4k aligned space, there is actually only one pc. If they are in different 4k, then all 4 instructions have a way to calculate the pc of the pcalau12i instruction when relocating. Is this feasible?

@MQ-mengqing
Copy link

It is feasible if we find that way. But it seems difficult.

a),
Refer to RISC-V, we can use

.L1:
  pcalau12i $xx, sym
  addi.d $xx, $r0, .L1
  lu32i $xx, .L1
  lu52i $xx, $xx, .L1

They are not current abi.

b),
Mark they are always adjacent. Like call36.

c),
Set imm in instructions to indicate the bytes distance with pcalau12i.

.L1:
  pcalau12i $xx, sym
  addi.d $xx, $r0, (. - .L1), sym
  lu32i $xx, (. - .L1), sym
  lu52i $xx, $xx, (. - .L1), sym

It looks even more difficult to implement with linker relaxation enabling. They are not current abi, too.

@heiher
Copy link
Author

heiher commented Nov 16, 2023

Yes. The instruction's free encoding bit-field can be used to maintain the relationship before relocation. But this is no longer compatible with what it used to be.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment