MLIR ‘switch’ op to LLVM dialect

Hi,
I want to use mlir-opt pass and mlir-translate pass to convert a mlir dialect to LLVM IR,but there are some problems so I need your help.
In short,the problem is how to convert an op named ‘switch’ to llvm dialect.

the source code is:

func @switch(%flag : i32, %caseOperand : i32) {
  switch %flag : i32, [
    default: ^bb1(%caseOperand : i32),
    42: ^bb2(%caseOperand : i32),
    43: ^bb3(%caseOperand : i32)
  ]

  ^bb1(%bb1arg : i32):
    return
  ^bb2(%bb2arg : i32):
    return
  ^bb3(%bb3arg : i32):
    return
}

and I get it from llvm-project/mlir/test/Dialect/Standard.

So, I use ./mlir-opt --convert-std-to-llvm and I get:

module attributes {llvm.data_layout = ""}  {
  llvm.func @switch(%arg0: i32, %arg1: i32) {
    switch %arg0 : i32, [
      default: ^bb1(%arg1 : i32),
      42: ^bb2(%arg1 : i32),
      43: ^bb3(%arg1 : i32)
    ]
  ^bb1(%0: i32):  // pred: ^bb0
    llvm.return
  ^bb2(%1: i32):  // pred: ^bb0
    llvm.return
  ^bb3(%2: i32):  // pred: ^bb0
    llvm.return
  }
}

The ’switch’ op doesn’t change and I find it is llvm dialect op, but I don’t know which pass can I use.;(

I don’t know whether I missed a point here, but you can directly use mlir-translate on the llvm-dialect code to generate llvm IR.

Assuming the initial code that you gave is in test_std.mlir, I was able to run the following to generate llvm IR.

 ./bin/mlir-opt test_std.mlir --convert-std-to-llvm | ./bin/mlir-translate --mlir-to-llvmir

The switch statement gets converted to the llvm switch instruction. LLVM Language Reference Manual — LLVM 13 documentation

I don’t know what went wrong with the code you gave above. Also, I think the switch in llvm dialect should be llvm.switch and not switch. The llvm dialect that I get after running convert-std-to-llvm is the following. As you can see it has an llvm.switch.

builtin.module attributes {llvm.data_layout = ""}  {
  llvm.func @switch(%arg0: i32, %arg1: i32) {
    llvm.switch %arg0, ^bb1(%arg1 : i32) [
      42: ^bb2(%arg1 : i32),
      43: ^bb3(%arg1 : i32)
    ]
  ^bb1(%0: i32):  // pred: ^bb0
    llvm.return
  ^bb2(%1: i32):  // pred: ^bb0
    llvm.return
  ^bb3(%2: i32):  // pred: ^bb0
    llvm.return
  }
}

Are you using a latest build of mlir from GitHub - llvm/llvm-project: The LLVM Project is a collection of modular and reusable compiler and toolchai?

1 Like