why it is asking for a token? - llvm

I've written a very simple llvm IR code. However when I try to run it through llc, I get the following error:
llc: add_test.ll:10:16: error: expected value token
%r = load i32, i32* %retval
^
Here is the code:
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 #main() #0 {
entry:
%retval = alloca i32, align 4
store i32 0, i32* %retval
%r = load i32, i32* %retval
ret i32 0
}
attributes #0 = { nounwind uwtable "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" "unsafe-fp-math"="false" "use-soft-float"="false" }
!llvm.ident = !{!0}
!0 = metadata !{metadata !"clang version 3.5.0 "}
The command that i'm running is llc add-test.ll
Does anybody know what could be the problem?

The syntax for load (among others) was changed in LLVM version 3.7. The syntax you're using is the new one. Since you're using version 3.5, you need to use the old syntax, which is:
%r = load i32* %retval
In other words you only specify the type of the parameter, not of the result.
I assume the problem occurred because you're using the current version of the documentation while using an old version of LLVM. The documentation for LLVM 3.5.0 can be found here.

Related

Clang adds noinline attribute to all functions when emitting LLVM IR

Consider the following simple function:
int foo() { return 42; }
Compiling this to LLVM via clang -emit-llvm -S foo.cpp produces the following module:
; ModuleID = 'foo.cpp'
source_filename = "foo.cpp"
target datalayout = "e-m:o-i64:64-f80:128-n8:16:32:64-S128"
target triple = "x86_64-apple-macosx10.13.0"
; Function Attrs: noinline nounwind ssp uwtable
define i32 #_Z3foov() #0 {
ret i32 42
}
attributes #0 = { noinline nounwind ssp uwtable "correctly-rounded-divide-sqrt-fp-math"="false" "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-jump-tables"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="penryn" "target-features"="+cx16,+fxsr,+mmx,+sse,+sse2,+sse3,+sse4.1,+ssse3,+x87" "unsafe-fp-math"="false" "use-soft-float"="false" }
!llvm.module.flags = !{!0}
!llvm.ident = !{!1}
!0 = !{i32 1, !"PIC Level", i32 2}
!1 = !{!"Apple LLVM version 9.0.0 (clang-900.0.37)"}
Why is the foo function declared as noinline? The flag is not added if an optimization level (other than -O0) is specified, but I would like to avoid that.
Is there another way / flag?
With -O0, you can't enable inlining globally, judging from Clang's source code
(Frontend\CompilerInvocation.cpp):
// At O0 we want to fully disable inlining outside of cases marked with
// 'alwaysinline' that are required for correctness.
Opts.setInlining((Opts.OptimizationLevel == 0)
? CodeGenOptions::OnlyAlwaysInlining
: CodeGenOptions::NormalInlining);
Depending on your requirements, you may:
Use -O1, which is the closest to -O0.
Use -O1 in conjuction with disabling of optimization flags that it enables. See the following answer for optimization flags enabled with -O1: Clang optimization levels
Apply always_inline attribute selectively on functions that should be inlined.
For example: int __attribute__((always_inline)) foo() { return 42; }

Using Clang and LLVM

I am compiling this:
int main(){
}
With clang, using this command line:
clang++.exe -S -o %OUTFILE%.clang -emit-llvm %INFILE% -I. -I%INCLUDE_PATH% -std=c++14 -ftemplate-depth=1000
Which gives me llvm byte-code.
Then I use llc like so, to convert the byte-code into c code:
llc "%IN_FILE%.clang" -march=c -o foo.c
And get this error:
error: unterminated attribute group
attributes #0 = { norecurse nounwind uwtable "disable-tail-calls"="false" "less-precise-fpmad"="false" "no-frame-pointer-elim"="false" "no-infs-fp-math"="false" "no-nans-fp-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+fxsr,+mmx,+sse,+sse2" "unsafe-fp-math"="false" "use-soft-float"="false" }
What I am doing wrong?
This is what clang++ is giving me:
; ModuleID = 'C:\Users\Owner\Documents\C++\SVN\prototypeInd\util\StaticBigInt.cpp'
target datalayout = "e-m:w-i64:64-f80:128-n8:16:32:64-S128"
target triple = "x86_64-pc-windows-msvc18.0.0"
; Function Attrs: norecurse nounwind readnone uwtable
define i32 #main() #0 {
entry:
ret i32 0
}
attributes #0 = { norecurse nounwind readnone uwtable "disable-tail-calls"="false" "less-precise-fpmad"="false" "no-frame-pointer-elim"="false" "no-infs-fp-math"="false" "no-nans-fp-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+fxsr,+mmx,+sse,+sse2" "unsafe-fp-math"="false" "use-soft-float"="false" }
!llvm.module.flags = !{!0}
!llvm.ident = !{!1}
!0 = !{i32 1, !"PIC Level", i32 2}
!1 = !{!"clang version 3.8.0 (branches/release_38)"}
Note:
I am using clang version 3.8 and llc version 3.4
When you run a command such as:
clang -S -emit-llvm ...
Then the compiler emits not an IR in a bitcode form, but human readable representation.
It makes sense if all tools you use have the same versions, or if you just want to inspect the output manually.
However, the human readable IR may be incompatible with old tools.
In this case I can recommend to use bitcode directly (note that there is no -S parameter anymore):
clang -emit-llvm
C backend in LLVM was removed several years ago. It seems that you're trying to feed LLVM IR from the recent LLVM version to llc from old LLVM. This is certainly not supported - the IR is not compatible between the versions.

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"%f\00", 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/

Understanding how memory allocation works (LLVM)

I'm making progress on a toy compiler (first time), and trying to understand how to allocate/construct an LLVM struct type.
The Kaleidoscope tutorial doesn't include or even mention this and I don't know what I'm looking for in the LLVM source/tests to find possible examples.
So I've written a simply C++ example, dumped the IR with clang in an effort to try to understand what it produces but to be honest I don't follow it all. The things obvious to me are the function definition/declarations and some function calls and a memset call so I get pieces of it but it doesn't all come together for me yet. (P.S my interpretation of the alloca instruction docs is that it anything created from that gets freed on return so I can't use that right, it's essentially only for local variables?)
What I've done is:
alloc.cpp
struct Alloc {
int age;
};
//Alloc allocCpy() {
// return *new Alloc();
//}
Alloc *allocPtr() {
return new Alloc();
}
int main() {
Alloc *ptr = allocPtr();
// ptr->name = "Courtney";
// Alloc cpy = allocCpy();
// cpy.name = "Robinson";
// std::cout << ptr->name << std::endl;
// std::cout << cpy.name << std::endl;
return 0;
}
Then run clang -S -emit-llvm alloc.cpp to produce alloc.ll
; ModuleID = 'alloc.cpp'
target datalayout = "e-m:o-i64:64-f80:128-n8:16:32:64-S128"
target triple = "x86_64-apple-macosx10.11.0"
%struct.Alloc = type { i32 }
; Function Attrs: ssp uwtable
define %struct.Alloc* #_Z8allocPtrv() #0 {
entry:
%call = call noalias i8* #_Znwm(i64 4) #3
%0 = bitcast i8* %call to %struct.Alloc*
%1 = bitcast %struct.Alloc* %0 to i8*
call void #llvm.memset.p0i8.i64(i8* %1, i8 0, i64 4, i32 4, i1 false)
ret %struct.Alloc* %0
}
; Function Attrs: nobuiltin
declare noalias i8* #_Znwm(i64) #1
; Function Attrs: nounwind
declare void #llvm.memset.p0i8.i64(i8* nocapture, i8, i64, i32, i1) #2
; Function Attrs: ssp uwtable
define i32 #main() #0 {
entry:
%retval = alloca i32, align 4
%ptr = alloca %struct.Alloc*, align 8
store i32 0, i32* %retval
%call = call %struct.Alloc* #_Z8allocPtrv()
store %struct.Alloc* %call, %struct.Alloc** %ptr, align 8
ret i32 0
}
attributes #0 = { ssp 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"="core2" "target-features"="+cx16,+sse,+sse2,+sse3,+ssse3" "unsafe-fp-math"="false" "use-soft-float"="false" }
attributes #1 = { nobuiltin "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"="core2" "target-features"="+cx16,+sse,+sse2,+sse3,+ssse3" "unsafe-fp-math"="false" "use-soft-float"="false" }
attributes #2 = { nounwind }
attributes #3 = { builtin }
!llvm.module.flags = !{!0}
!llvm.ident = !{!1}
!0 = !{i32 1, !"PIC Level", i32 2}
!1 = !{!"clang version 3.7.0 (tags/RELEASE_370/final)"}
Can someone explain what's happening in this IR and how it maps back to the C++? Or ignoring this specific example how one would/should go about allocating heap memory for an LLVM StructType that out lives the function within which it was created (and if you're feeling generous, how to later release the memory).
The bits I've commented out are from my original example but being a total novice the IR from that was even less insightful...
my interpretation of the alloca instruction docs is that it anything
created from that gets freed on return so I can't use that right, it's
essentially only for local variables?
Yes. Furthermore, the current advice on LLVM IR is that although alloca works as you expect it to, optimizations are another case. They advise that you alloca all of your locals in the entry block right away, even if you don't allow the user access to them or they don't always contain meaningful data.
Heap allocation is a library feature. It is not a feature of LLVM or the compiler. When you use new T(), the compiler simply calls operator new to get the memory and then constructs T there. There is no magic involved. Most of the junk that you see there is C++-ABI specific rather than any requirement of LLVM. It eventually lowers into something like void* p = malloc(size); new(p) T();. For pretty much all types T, this pretty much boils down to a series of stores into p or calling a user-defined function.
You can use the memory allocation function from the runtime library of your choice.
trying to understand how to allocate/construct an LLVM struct type
The LLVM type system does not include the notion of construction. That is a notion of the source language.
As far as LLVM is concerned, a struct is just a bunch of bits, and all memory locations are more-or-less the same. If you want the bits to be a particular thing, then store the bits you want to that location. If you want to put the bits on the heap, then call a runtime library heap allocation function and store the bits into that location.
Note that garbage collection, however, is a somewhat different story, as there is some awkward stuff going on w.r.t. finding locals on the stack for marking.
For the record, you will not get far trying to understand Clang's LLVM IR. I've been doing that for several years now and it is batshit crazy and will take you that long to start to get a grip, not to mention full of C++-specific ABI details that you don't want to know about. You will get a lot further asking in #llvm in their IRC channel or asking specific questions here than in trying to reverse-engineer that.
I don't recommend looking at unoptimized IR emitted by Clang - it's way too verbose. -O1 makes it a lot more readable - here's the -O1 version with comments annotating the lines (also I've reordered two lines to make it slightly more readable):
%struct.Alloc = type { i32 } ; Define the Alloc type.
define noalias %struct.Alloc* #_Z8allocPtrv() #0 {
%1 = tail call noalias i8* #_Znwj(i32 4) #2 ; Call _Znwj(4). This retuns i8*.
%3 = bitcast i8* %1 to i32* ; Cast the returned value to i32* (int*)...
store i32 0, i32* %3, align 4 ; ...and zero its content.
%2 = bitcast i8* %1 to %struct.Alloc* ; Cast the returned value to Alloc*...
ret %struct.Alloc* %2 ; ...and return it.
}
; Declare the _Znwj function. This doesn't need to be defined since it's already defined
; in libstdc++: this is 'operator new'. You can see this by passing this string through a
; C++ demangler, for example the one at http://demangler.com/.
declare noalias i8* #_Znwj(i32) #1
define i32 #main() #0 {
%1 = tail call %struct.Alloc* #_Z8allocPtrv() ; Call _Z8allocPtrv (Defined above).
ret i32 0
}
This is a new call, not a local allocation, so it will not be cleared when leaving #_Z8allocPtrv. Local allocations are indeed performed in LLVM IR with the alloca instruction, and not a new call.
If you're curious how new works, I believe its standard implementation uses malloc, which is translated by the compiler that compiled the library to some function that includes system call(s).

How to locate the function name in the llvm bytecode, using call and alias instruction?

I have the following C++ code:
class Date {
public:
Date(int, int, int);
private:
int year; int month; int day;
};
extern "C" int main(int argc, char *argv[])
{
Date today(1,9,2014);
//....
return 0;
}
Date::Date(int d, int m, int y) { day = d; month = m; year =y; }
The corresponding bytecode is:
#_ZN4DateC1Eiii = alias void (%class.Date*, i32, i32, i32)* #_ZN4DateC2Eiii
define i32 #main(i32 %argc, i8** %argv) {
entry:
%retval = alloca i32, align 4
%argc.addr = alloca i32, align 4
%argv.addr = alloca i8**, align 4
%today = alloca %class.Date, align 4
store i32 0, i32* %retval
store i32 %argc, i32* %argc.addr, align 4
call void #llvm.dbg.declare(metadata !{i32* %argc.addr}, metadata !922), !dbg !923
store i8** %argv, i8*** %argv.addr, align 4
call void #llvm.dbg.declare(metadata !{i8*** %argv.addr}, metadata !924), !dbg !923
call void #llvm.dbg.declare(metadata !{%class.Date* %today}, metadata !925), !dbg !927
call void #_ZN4DateC1Eiii(%class.Date* %today, i32 1, i32 9, i32 1999), !dbg !927
//...
ret i32 0, !dbg !930
}
//...
define void #_ZN4DateC2Eiii(%class.Date* %this, i32 %d, i32 %m, i32 %y) unnamed_addr nounwind align 2 {
entry:
//...
}
I'm doing a parse of this code and I need to know how to get to # _ZN4DateC2Eiii function, starting from the call ??
call void # _ZN4DateC1Eiii (class.Date% *% today, i32 1, i32 9, i32 1999)! dbg! 927.
The line
call void #_ZN4DateC1Eiii(class.Date%* %today, i32 1, i32 9, i32 1999), !dbg !927
is an instruction of type CallInst. If it was a direct function call, you could have used CallInst::getCalledFunction() to get the called function, and you can get a function's name via getName().
With indirect function calls, you need to invoke the instruction's GetCalledValue() method, which returns some value. You then have to manually check what that value is and handle it appropriately.
In your case, with an indirect call to an alias, it should be something like
(cast<GlobalAlias>(MyCallInst->getCalledValue()))->getAliasee()->getName();
// ^ ^ ^
// Declared type: CallInst Value Constant
// Actual type: CallInst GlobalAlias Function
(added annotations of what types are involved below, to help with understanding this complex line)
Noticed I have used cast, which assumes you know that the called value is in fact an alias. If you're not certain of that, use isa or dyn_cast instead.