[LLVMdev] Inserting a function call using LLVM

teja tamboli tamboli.teja at gmail.com
Sun Oct 7 16:03:59 PDT 2012


I am new to LLVM and interested in using LLVM to work on a research project
for my Master's degree.
My idea is following -

1. I have a simple C program basic.c -
#include <stdio.h>
int main() {
   printf("Hello World");
   return 0;

2. I will generate IR byte code for this basic.c using -
llvm-gcc -emit-llvm -S basic.c

This will give me basic.s which has IR byte code like this -

; ModuleID = 'basic.c'
target datalayout =
target triple = "x86_64-apple-darwin10.8"

@.str = private constant [12 x i8] c"hello world\00", align 1 ; <[12 x
i8]*> [#uses=1]

define i32 @main() nounwind ssp {
  %retval = alloca i32                            ; <i32*> [#uses=2]
  %0 = alloca i32                                 ; <i32*> [#uses=2]
  %"alloca point" = bitcast i32 0 to i32          ; <i32> [#uses=0]
  %1 = call i32 @puts(i8* getelementptr inbounds ([12 x i8]* @.str, i64 0,
i64 0)) nounwind ; <i32> [#uses=0]
  store i32 0, i32* %0, align 4
  %2 = load i32* %0, align 4                      ; <i32> [#uses=1]
  store i32 %2, i32* %retval, align 4
  br label %return

return:                                           ; preds = %entry
  %retval1 = load i32* %retval                    ; <i32> [#uses=1]
  ret i32 %retval1

declare i32 @puts(i8*)

3. I want to write a pass to insert a call foo(int a) after the printf()
call, so that it looks like this -
#include <stdio.h>
int main() {
   printf("Hello World");
   return 0;

void foo(int a) {
   printf("a + 5 is : %d", a + 5);

How can I achieve this? I looked online but couldn't find a definite source
which tells me how to do this.
I think I can use Cloning.h and CloneFunction.cpp to clone a given function
and then insert my call to foo().
But I'm not sure if this is the right way to do this. The documentation
obviously did not say this explicitly.
Any thoughts / pointers ?

Thanks in advance !
- Teja
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/llvm-dev/attachments/20121007/bb9a6857/attachment.html>

More information about the llvm-dev mailing list