Book Image

LLVM Cookbook

Book Image

LLVM Cookbook

Overview of this book

Table of Contents (16 chapters)
LLVM Cookbook
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface
Index

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 such as associativity, commutativity, and distributivity to rearrange an expression to enable other optimizations, such as constant folding, LICM, and so on.

In the preceding example, we used the inverse property to eliminate patterns such...