llvm-project icon indicating copy to clipboard operation
llvm-project copied to clipboard

[SimplifyCFG] Missed lookup table optimization even for simple switch

Open XChy opened this issue 3 years ago • 2 comments

Shell: opt -S -passes='simplifycfg<switch-to-lookup>' src.ll. Lookup table optimization has no effect for examples below:

define i8 @src(i8 noundef %arg) {
start:
  switch i8 %arg, label %unreachable [
  i8 0, label %case0
  i8 1, label %case1
  i8 2, label %case2
  i8 3, label %case3
  ]
unreachable:
  unreachable
case0:
  br label %case3
case1:
  br label %case3
case2:
  br label %case3
case3:
  %phi = phi i8 [0, %case0], [ 1, %case1 ], [ 2, %case2 ], [3, %start]
  ret i8 %phi
}

This should be folded into ret i8 %arg with "SingleValue" lookup table, but NOT in fact.

Neither for %phi = phi i8 [1, %case0], [ 2, %case1 ], [ 3, %case2 ], [4, %start], which should be folded into ret(add %arg 1) with "LinearMapKind" lookup table.

To find the reason why the IR above do not fold under switch-to-lookup optimization, I debugged with these IR. Finally, I found that the function isTypeLegalForLookupTable determines that i8 is illegal for DataLayout (So are i16, i32, i64). Maybe this is because I do not specify DataLayout, but from my point of view, such SingleValue/LinearMap optimization should be machine-independent. #63876 provides a proof about transformation. It would be great if someone could explain whether it's a miscompilation and fix it if yes.

XChy avatar Jul 24 '23 07:07 XChy

pls add target info, like target datalayout = "e-m:e-p:64:64-i64:64-i128:128-n64-S128" target triple = "riscv64-unknown-elf"

LiqinWeng avatar Sep 05 '23 03:09 LiqinWeng

pls add target info, like target datalayout = "e-m:e-p:64:64-i64:64-i128:128-n64-S128" target triple = "riscv64-unknown-elf"

Thanks for you comment, but I'm afraid that such SingleValue/LinearMap optimization should be target-independent. Or you could show some reasons why it should depend on target info?

XChy avatar Sep 06 '23 09:09 XChy