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

Linking LLVM bitcode


In this section, you will link previously generated .bc files to get one single bitcode file containing all the needed references.

Getting ready

To link the .bc files, you need the llvm-link tool.

How to do it...

Do the following steps:

  1. To show the working of llvm-link, first write two codes in different files, where one makes a reference to the other:

    $ cat test1.c
    int func(int a) {
    a = a*2;
    return a;
    }
    $ cat test2.c
    #include<stdio.h>
    extern int func(int a);
    int main() {
    int num = 5;
    num = func(num);
    printf("number is %d\n", num);
    return num;
    }
    
  2. Using the following formats to convert this C code to bitstream file format, first convert to .ll files, then from .ll files to .bc files:

    $ clang -emit-llvm -S test1.c -o test1.ll
    $ clang -emit-llvm -S test2.c -o test2.ll
    $ llvm-as test1.ll -o test1.bc
    $ llvm-as test2.ll -o test2.bc
    

    We get test1.bc and test2.bc with test2.bc making a reference to func syntax in the test1.bc file.

  3. Invoke the llvm-link command in the following way to link the two LLVM bitcode files:

    $ llvm-link test1.bc test2.bc –o output.bc
    

We provide multiple bitcode files to the llvm-link tool, which links them together to generate a single bitcode file. Here, output.bc is the generated output file. We will execute this bitcode file in the next recipe Executing LLVM bitcode.

How it works...

The llvm-link works using the basic functionality of a linker—that is, if a function or variable referenced in one file is defined in the other file, it is the job of linker to resolve all the references made in a file and defined in the other file. But note that this is not the traditional linker that links various object files to generate a binary. The llvm-link tool links bitcode files only.

In the preceding scenario, it is linking test1.bc and test2.bc files to generate the output.bc file, which has references resolved.

Note

After linking the bitcode files, we can generate the output as an IR file by giving –S option to the llvm-link tool.