[PATCH] D155940: [SimplifyCFG] Transform for merging the combination of phis in switch

Hongyu Chen via Phabricator via llvm-commits llvm-commits at lists.llvm.org
Fri Jul 21 04:10:46 PDT 2023


XChy created this revision.
XChy added reviewers: skatkov, DamonFool, nikic, kazu.
XChy added a project: LLVM.
Herald added subscribers: khei4, StephenFan, hiraditya.
Herald added a project: All.
XChy requested review of this revision.
Herald added a subscriber: llvm-commits.

This create a function **MergePhisInSwitch** to handle the similar cases below.

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

The phis here should be merged into one phi, so that we can better optimize it:

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

Proof:
normal <https://alive2.llvm.org/ce/z/vAWi88>
multiple stages <https://alive2.llvm.org/ce/z/DDBQqp>
multiple stages 2 <https://alive2.llvm.org/ce/z/nGkeqN>
multiple phi combinations <https://alive2.llvm.org/ce/z/VQeEdp>

And lookup table optimization should convert it into `add %arg 1`.
This patch just match similar CFG structure and merge the phis in different cases.

Maybe such transform can be applied to other situations besides switch,
but I'm not sure whether it's better than not merging. Therefore, I only try it in `switch`,

Related issue:
Switch not fully optimized #63876 <https://github.com/llvm/llvm-project/issues/63876>


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D155940

Files:
  llvm/lib/Transforms/Utils/SimplifyCFG.cpp
  llvm/test/Transforms/SimplifyCFG/merge-phis-in-switch.ll

-------------- next part --------------
A non-text attachment was scrubbed...
Name: D155940.542857.patch
Type: text/x-patch
Size: 9313 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/llvm-commits/attachments/20230721/2f31ff47/attachment.bin>


More information about the llvm-commits mailing list