Reassociating expressions

In this recipe, you will learn about reassociating expressions and how it helps in optimization.

Getting Ready

The opt tool should be installed for this recipe to work.

How to do it…

  1. Write the test case for a simple reassociate transformation:
    $ cat testreassociate.ll
    define i32 @test(i32 %b, i32 %a) {
      %tmp.1 = add i32 %a, 1234
      %tmp.2 = add i32 %b, %tmp.1
      %tmp.4 = xor i32 %a, -1
      ; (b+(a+1234))+~a -> b+1233
      %tmp.5 = add i32 %tmp.2, %tmp.4
      ret i32 %tmp.5
    }
    
  2. Run the reassociate pass on this test case to see how the code is modified:
    $ opt testreassociate.ll  –reassociate –die –S
    define i32 @test(i32 %b, i32 %a) {
    %tmp.5 = add i32 %b, 1233
    ret i32 %tmp.5
    }
    

How it works …

By reassociation, we mean applying algebraic properties ...

Get LLVM Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.