Issue 61458
Summary `reassociate` creates loop dependent variables and defeats `licm`
Labels new issue
Assignees
Reporter qcolombet
    I stumbled on a case where the reassociate pass is actively making the generated code worse.
In a nutshell, reassociate turns loop invariant computations into loop variant ones and licm is not able to hoist them back.

I haven't dug why, maybe reassociate is tweaked to form cse'able expressions / reduce the total number of instructions but the overall runtime is going to be worse in this case.

To reproduce:
```
opt -S -passes='reassociate' repro_reassoc_defeats_licm.ll -o -
```

Result:
Before reassociate we have:
- 2 loop invariant adds
- 1 loop variant shift
- 3 loop variant adds

After reassociate we have:
- 0 loop invariant adds
- 1 loop variant shift
- 5 loop variant adds (of which 1 is cse'able)

So accounting for `cse` (`-passes=reassociate,early-cse`), we would trade 2 loop invariant adds + 3 loop variant adds with 4 loop variant adds.

Before:
```
define void @reassoc_defeats_licm(i64 %inv1, i64 %inv2, i64 %inv3) {
bb:
 %inv4 = add nuw nsw i64 %inv1, %inv2
  %inv5 = add nuw nsw i64 %inv2, %inv3
  br label %bb214

bb214: ; preds = %bb214, %bb
  %iv1 = phi i64 [ %iv2, %bb214 ], [ 0, %bb ]
  %iv2 = phi i64 [ %iv2_plus_1, %bb214 ], [ 1, %bb ]
 %loop_dependent = shl nuw nsw i64 %iv1, 13
  %loop_dependent2 = add nsw i64 %inv4, %loop_dependent
  call void @keep_alive(i64 %loop_dependent2)
  %loop_dependent3 = add i64 %inv5, %loop_dependent
 call void @keep_alive(i64 %loop_dependent3)
  %iv2_plus_1 = add i64 %iv2, 1
  br label %bb214
}

declare void @keep_alive(i64)
```

After (with cse):
```
define void @reassoc_defeats_licm(i64 %inv1, i64 %inv2, i64 %inv3) {
bb:
  br label %bb214

bb214:                                            ; preds = %bb214, %bb
  %iv1 = phi i64 [ %iv2, %bb214 ], [ 0, %bb ]
  %iv2 = phi i64 [ %iv2_plus_1, %bb214 ], [ 1, %bb ]
  %loop_dependent = shl nuw nsw i64 %iv1, 13
  %inv4 = add i64 %loop_dependent, %inv2
 %loop_dependent2 = add i64 %inv4, %inv1
  call void @keep_alive(i64 %loop_dependent2)
  %loop_dependent3 = add i64 %inv4, %inv3
  call void @keep_alive(i64 %loop_dependent3)
  %iv2_plus_1 = add i64 %iv2, 1
  br label %bb214
}

declare void @keep_alive(i64)
```

[repro_reassoc_defeats_licm.ll.txt](https://github.com/llvm/llvm-project/files/10994658/repro_reassoc_defeats_licm.ll.txt)
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to