Converting a C source code to LLVM assembly

Here we will convert a C code to intermediate representation in LLVM using the C frontend Clang.

Getting ready

Clang must be installed in the PATH.

How to do it...

  1. Lets create a C code in the multiply.c file, which will look something like the following:
    $ cat multiply.c
    int mult() {
    int a =5;
    int b = 3;
    int c = a * b;
    return c;
    }
    
  2. Use the following command to generate LLVM IR from the C code:
    $ clang -emit-llvm -S multiply.c -o multiply.ll
    
  3. Have a look at the generated IR:
    $ cat multiply.ll
    ; ModuleID = 'multiply.c'
    target datalayout = "e-m:e-i64:64-f80:128-n8:16:32:64-S128"
    target triple = "x86_64-unknown-linux-gnu"
    
    ; Function Attrs: nounwind uwtable
    define i32 @mult() #0 {
      %a = alloca i32, align 4
     %b ...

Get LLVM Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.