Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile, Assemble and Disassemble Using the LLVM Tool Chain

Tags:

llvm

I'm trying to run the following example to Compile, Assemble and Disassemble an small program using the LLVM tool chain.

My intention is to learn how it works so in further tries I could do some performance test by changing and/or reordering the assmbly's instructions.

To start with, I first get the bite code of a dummy program:

    % llvm-gcc -O3 -emit-llvm hello.c -c -o hello.bc

Once I have the bite code, i try to use the llvm-dis utility to take a look at the LLVM assembly code and llc to compile the program back to native assembly using the LLC code generator (just for the shake of trying):

    % llvm-dis < hello.bc | less
    % llc hello.bc -o hello.s

But in both cases I get the following error:

    llvm-dis: Invalid MODULE_CODE_GLOBALVAR record

Any ideas on how to solve this problem?

I've googled and I haven't found a solution. I have also tried to use

    otool -tV hello

But the output is not compatible with llvm. Instead of getting the following assembly format:

.section    __TEXT,__text,regular,pure_instructions
.globl  _main
.align  4, 0x90
    _main:
    Leh_func_begin1:
pushq   %rbp
    Ltmp0:
movq    %rsp, %rbp
    Ltmp1:
subq    $16, %rsp
    Ltmp2:
leaq    L_.str(%rip), %rax

I get:

__TEXT,__text) section
start:
0000000100000eb0    pushq   $0x00
0000000100000eb2    movq    %rsp,%rbp
0000000100000eb5    andq    $0xf0,%rsp
0000000100000eb9    movq    0x08(%rbp),%rdi
0000000100000ebd    leaq    0x10(%rbp),%rsi
0000000100000ec1    movl    %edi,%edx
0000000100000ec3    addl    $0x01,%edx

Which is not valid for me as I cat compile the latter assembly with for example:

    % gcc hello.s -o hello.native

Thanks in advance.

like image 565
gtangil Avatar asked Jan 03 '12 19:01

gtangil


1 Answers

Make sure your llvm-gcc's version match the version of LLVM you installed - the binary IR format changes quite fast and is not backward compatible across several version.

Alternatively, you might try to emit text representation of LLVM IR out of llvm-gcc and assemble it through llvm-as.

Something like this:

llvm-gcc -emit-llvm -S foo.c -o foo.ll
llvm-as foo.ll -o foo.bc
llc foo.ll -o foo.S

etc.

like image 83
Anton Korobeynikov Avatar answered Oct 03 '22 21:10

Anton Korobeynikov