OrenIshShalom
OrenIshShalom

Reputation: 7172

Source to source transformations with llvm opt

I'm compiling the following code:

#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv)
{
    unsigned int i=atoi(argv[1]);
    unsigned int n=atoi(argv[2]);
    unsigned int r=0;
    unsigned int iter=0;

    while(i<n)
    {
        iter++;
        if (r>0) { i=0; r--; }
        else     { i++;      }
    }
    return iter;
}

with

$ clang -O3 -c -emit-llvm file.c -o file.bc
$ llvm-dis file.bc -o file.ll

And when I inspect the resulting *.ll file I'm pleasantly surprised, because the entire code shrinks down to:

; Function Attrs: nounwind uwtable
define dso_local i32 @main(i32 %argc, i8** nocapture readonly %argv) local_unnamed_addr #0 {
entry:
  %arrayidx = getelementptr inbounds i8*, i8** %argv, i64 1
  %0 = load i8*, i8** %arrayidx, align 8, !tbaa !2
  %call.i = tail call i64 @strtol(i8* nocapture nonnull %0, i8** null, i32 10) #2
  %conv.i = trunc i64 %call.i to i32
  %arrayidx1 = getelementptr inbounds i8*, i8** %argv, i64 2
  %1 = load i8*, i8** %arrayidx1, align 8, !tbaa !2
  %call.i12 = tail call i64 @strtol(i8* nocapture nonnull %1, i8** null, i32 10) #2
  %conv.i13 = trunc i64 %call.i12 to i32
  %2 = icmp ugt i32 %conv.i13, %conv.i
  %3 = select i1 %2, i32 %conv.i13, i32 %conv.i
  %4 = sub i32 %3, %conv.i
  ret i32 %4
}

Which essentially means: return (n>i)?(n-i):0 Is there anyway I can translate optimized bitcode back to C source?

Upvotes: 1

Views: 150

Answers (1)

You can try llvm-cbe. Maybe it will be suitable for you.

Anyway, llvm-cbe was removed from llvm upstream, due it was not working good as I know :D

Maybe retdec is usable somehow, due it is based on llvm, but not sure.

Upvotes: 1

Related Questions