Book Image

LLVM Cookbook

Book Image

LLVM Cookbook

Overview of this book

Table of Contents (16 chapters)
LLVM Cookbook
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface
Index

Converting LLVM bitcode to target machine assembly


In this recipe, you will learn how to convert the LLVM bitcode file to target specific assembly code.

Getting ready

The LLVM static compiler llc should be in installed from the LLVM toolchain.

How to do it...

Do the following steps:

  1. The bitcode file created in the previous recipe, test.bc, can be used as input to llc here. Using the following command, we can convert LLVM bitcode to assembly code:

    $ llc test.bc –o test.s
    
  2. The output is generated in the test.s file, which is the assembly code. To have a look at that, use the following command lines:

    $ cat test.s
    .text
    .file "test.bc"
    .globl mult
    .align 16, 0x90
    .type mult,@function
    mult:                                   # @mult
    .cfi_startproc
    # BB#0:
    Pushq  %rbp
    .Ltmp0:
    .cfi_def_cfa_offset 16
    .Ltmp1:
    .cfi_offset %rbp, -16
    movq %rsp, %rbp
    .Ltmp2:
    .cfi_def_cfa_register %rbp
    imull %esi, %edi
    movl %edi, %eax
    popq %rbp
    retq
    .Ltmp3:
    .size mult, .Ltmp3-mult
    .cfi_endproc
    
  3. You can also use Clang to dump assembly code from the bitcode file format. By passing the –S option to Clang, we get test.s in assembly format when the test.bc file is in bitstream file format:

    $ clang -S test.bc -o test.s –fomit-frame-pointer # using the clang front end
    

    The test.s file output is the same as that of the preceding example. We use the additional option fomit-frame-pointer, as Clang by default does not eliminate the frame pointer whereas llc eliminates it by default.

How it works...

The llc command compiles LLVM input into assembly language for a specified architecture. If we do not mention any architecture as in the preceding command, the assembly will be generated for the host machine where the llc command is being used. To generate executable from this assembly file, you can use assembler and linker.

There's more...

By specifying -march=architecture flag in the preceding command, you can specify the target architecture for which the assembly needs to be generated. Using the -mcpu=cpu flag setting, you can specify a CPU within the architecture to generate code. Also by specifying -regalloc=basic/greedy/fast/pbqp, you can specify the type of register allocation to be used.