Ben Little
Ben Little

Reputation: 77

Is it possible to use clang to produce RISC V assembly without linking?

I am trying to learn more about compilers and RISC V assembly was specifically designed to be easy to learn and teach. I am interested in compiling some simple C code to assembly using clang for the purpose of understanding the semantics. I'm planning on using venus to step through the assembly and the source code does NOT actually need to be fully compiled to machine code in order to run on a real machine.

  1. I want to avoid compiler optimizations so I can see what I've actually instructed the processor to do.
  2. I don't actually need the program to compile to machine code--I just want the assembly.
  3. I don't want to worry about linking to the system library because this code doesn't actually need to run
  4. The code does not make any explicit use of system calls and so I think a std lib should not be required

This answer seems to indicate that clang definitely can compile to RISC V targets, but it requires having a version of the OS's standard library built for RISC V.

This answer indicates that some form of cross-compiling is necessary, but again I don't need to fully compile the code to machine instructions so this should not apply if I'm understanding correctly.

Upvotes: 1

Views: 859

Answers (1)

that other guy
that other guy

Reputation: 123400

Use clang -S to stop after generating an assembly file:

$ cat foo.c
int main() { return 2+2; }

$ clang -target riscv64 -S foo.c

$ cat foo.s
        .text
        .attribute      4, 16
        .attribute      5, "rv64i2p0_m2p0_a2p0_c2p0"
        .file   "foo.c"
        .globl  main
        .p2align        1
        .type   main,@function
main:
        addi    sp, sp, -32
        sd      ra, 24(sp)
        sd      s0, 16(sp)
        addi    s0, sp, 32
        li      a0, 0
        sw      a0, -20(s0)
        li      a0, 4
        ld      ra, 24(sp)
        ld      s0, 16(sp)
        addi    sp, sp, 32
        ret
.Lfunc_end0:
        .size   main, .Lfunc_end0-main

        .ident  "Ubuntu clang version 14.0.0-1ubuntu1"
        .section        ".note.GNU-stack","",@progbits
        .addrsig

You can also use Compiler Explorer conveniently online.

Upvotes: 1

Related Questions