LLVM SelectionDAG Image Generation

829 阅读1分钟

This post is to see how the visualize SelectionDAG looks like. Therefore we use a simple add function in c to depict this procedure. By the way, a SelectionDAG is an represnetation of a Basic Block not a function, if there are many basic block in a function, there will be many SelectionDAG as well. Readers can check by changing our example function with if-else branching execution path.

// add.c
int add( int a, int b) { int c = a + b; return c; }

Then turn it into LLVM IR.

$ clang -c -emit-llvm add.c
$ ls
add.c    add.bc
$ llvm-dis add.bc
$ ls
add.c    add.bc    add.ll
$ cat add.ll
; ModuleID = 'add.bc'
...
define i32 @add(i32 %0, i32 %1) #0 {
  %3 = alloca i32, align 4
  %4 = alloca i32, align 4
  %5 = alloca i32, align 4
  store i32 %0, i32* %3, align 4
  store i32 %1, i32* %4, align 4
  %6 = load i32, i32* %3, align 4
  %7 = load i32, i32* %4, align 4
  %8 = add nsw i32 %6, %7
  store i32 %8, i32* %5, align 4
  %9 = load i32, i32* %5, align 4
  ret i32 %9
}
...

Now we focus on the function part of LLVM IR.

define i32 @add(i32 %0, i32 %1) #0 {
  %3 = alloca i32, align 4
  %4 = alloca i32, align 4
  %5 = alloca i32, align 4
  store i32 %0, i32* %3, align 4
  store i32 %1, i32* %4, align 4
  %6 = load i32, i32* %3, align 4
  %7 = load i32, i32* %4, align 4
  %8 = add nsw i32 %6, %7
  store i32 %8, i32* %5, align 4
  %9 = load i32, i32* %5, align 4
  ret i32 %9
}

Use llc to view the DAG of this function.

llc -fast-isel=false -view-dag-combine1-dags add.ll

It will generate a dag.XXX.dot file in /tmp directory, which is an image. By the way, if you want llc to generate dot file in current directory, you need to modify the source code of LLVM, i.e. llvm::createGraphFilename at /llvm-project/llvm/lib/Support/GraphWriter.cpp.

This time, you need graphviz to generate an image from that .dot file.

brew install graphviz

 Afterward, just see the image by following command:

dot -Tpng dag.XXX.dot > dag.add.png

Then open the dag.add.png with your favourite image viewer.

There you go. By the way, there are different phases for SelectionDAG after different processes.