Printf float with LLVM segfaults

I am trying to call printf to print a float number from LLVM. While it works fine with int , it segfaults when using double .

Here is the code (generated from clang but slightly modified so that it works fine with llc ) :

@.str = private unnamed_addr constant [3 x i8] c"%f0", align 1

; Function Attrs: nounwind uwtable
define i32 @main() #0 {
  %1 = alloca i32, align 4
  store i32 0, i32* %1
  %2 = call i32 (i8*, ...)* @printf(i8* getelementptr inbounds ([3 x i8]* @.str, i32 0, i32 0), double 3.140000e+00)
  ret i32 0
}

declare i32 @printf(i8*, ...) #1

attributes #0 = { nounwind uwtable "disable-tail-calls"="false" "less-precise-fpmad"="false" "no-frame-pointer-elim"="true" "no-frame-pointer-elim-non-leaf" "no-infs-fp-math"="false" "no-nans-fp-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+sse,+sse2" "unsafe-fp-math"="false" "use-soft-float"="false" }
attributes #1 = { "disable-tail-calls"="false" "less-precise-fpmad"="false" "no-frame-pointer-elim"="true" "no-frame-pointer-elim-non-leaf" "no-infs-fp-math"="false" "no-nans-fp-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+sse,+sse2" "unsafe-fp-math"="false" "use-soft-float"="false" }

Here is how I produce an executable:

llc main.ll --filetype=obj
ld -lc -e main -dynamic-linker /lib64/ld-linux-x86-64.so.2 main.o -o main

When I run main within valgrind , I get:

Process terminating with default action of signal 11 (SIGSEGV): dumping core
 General Protection Fault

I read somewhere on this site that I need to align the stack to use printf . If this is the issue, how can I do this in LLVM.

Otherwise, what is causing this segfault?

I run Linux 64-bits.


This is NOT llvm issue. when you ran,

llc main.ll --filetype=obj
ld -lc -e main -dynamic-linker /lib64/ld-linux-x86-64.so.2 main.o -o main

here after creating objact file main.o you are trying to link it saying that main is its entry point for execution, which is not correct.

from the c programmer point of view main is the entry point for our program while execution which is not, some extra startup code is added by compiler which is _start, this is the function which is executed first and then interns call main function.

the startup code is relocatable objects and those are passed by compiler to linker. search for crti.o crtn.o and crt1.o, also the printf function is in library libc.so/libc.a which you need to provide while linking.

if you want the easy solution then use gcc for converting object files to executable

gcc main.o -o main

also you can have look here for more clarification, ref http://blog.techveda.org/building-executables-with-gnu-linker/

链接地址: http://www.djcxy.com/p/68698.html

上一篇: 使用LLVM传递加载和存储变量

下一篇: Printf float与LLVM段错误