Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 22 additions & 1 deletion clang/lib/CIR/Lowering/ThroughMLIR/LowerCIRToMLIR.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -515,14 +515,35 @@ class CIRScopeOpLowering
}
};

struct CIRBrCondOpLowering
: public mlir::OpConversionPattern<mlir::cir::BrCondOp> {
using mlir::OpConversionPattern<mlir::cir::BrCondOp>::OpConversionPattern;

mlir::LogicalResult
matchAndRewrite(mlir::cir::BrCondOp brOp, OpAdaptor adaptor,
mlir::ConversionPatternRewriter &rewriter) const override {

auto condition = adaptor.getCond();
auto i1Condition = rewriter.create<mlir::arith::TruncIOp>(
brOp.getLoc(), rewriter.getI1Type(), condition);
rewriter.replaceOpWithNewOp<mlir::cf::CondBranchOp>(
brOp, i1Condition.getResult(), brOp.getDestTrue(),
adaptor.getDestOperandsTrue(), brOp.getDestFalse(),
adaptor.getDestOperandsFalse());

return mlir::success();
}
};

void populateCIRToMLIRConversionPatterns(mlir::RewritePatternSet &patterns,
mlir::TypeConverter &converter) {
patterns.add<CIRReturnLowering, CIRBrOpLowering>(patterns.getContext());

patterns.add<CIRCmpOpLowering, CIRCallLowering, CIRUnaryOpLowering,
CIRBinOpLowering, CIRLoadLowering, CIRConstantLowering,
CIRStoreLowering, CIRAllocaLowering, CIRFuncLowering,
CIRScopeOpLowering>(converter, patterns.getContext());
CIRScopeOpLowering, CIRBrCondOpLowering>(converter,
patterns.getContext());
}

static mlir::TypeConverter prepareTypeConverter() {
Expand Down
37 changes: 37 additions & 0 deletions clang/test/CIR/Lowering/ThroughMLIR/branch.cir
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
// RUN: cir-opt %s -cir-to-mlir | FileCheck %s -check-prefix=MLIR
// RUN: cir-opt %s -cir-to-mlir -cir-mlir-to-llvm | mlir-translate -mlir-to-llvmir | FileCheck %s -check-prefix=LLVM

!s32i = !cir.int<s, 32>
cir.func @foo(%arg0: !cir.bool) -> !s32i {
cir.brcond %arg0 ^bb1, ^bb2
^bb1:
%0 = cir.const(#cir.int<1>: !s32i) : !s32i
cir.return %0 : !s32i
^bb2:
%1 = cir.const(#cir.int<0>: !s32i) : !s32i
cir.return %1 : !s32i
}

// MLIR: module {
// MLIR-NEXT: func.func @foo(%arg0: i8) -> i32
// MLIR-NEXT: %0 = arith.trunci %arg0 : i8 to i1
// MLIR-NEXT: cf.cond_br %0, ^bb1, ^bb2
// MLIR-NEXT: ^bb1: // pred: ^bb0
// MLIR-NEXT: %c1_i32 = arith.constant 1 : i32
// MLIR-NEXT: return %c1_i32 : i32
// MLIR-NEXT: ^bb2: // pred: ^bb0
// MLIR-NEXT: %c0_i32 = arith.constant 0 : i32
// MLIR-NEXT: return %c0_i32 : i32
// MLIR-NEXT: }
// MLIR-NEXT: }

// LLVM: define i32 @foo(i8 %0)
// LLVM-NEXT: %2 = trunc i8 %0 to i1
// LLVM-NEXT: br i1 %2, label %3, label %4
// LLVM-EMPTY:
// LLVM-NEXT: 3: ; preds = %1
// LLVM-NEXT: ret i32 1
// LLVM-EMPTY:
// LLVM-NEXT: 4: ; preds = %1
// LLVM-NEXT: ret i32 0
// LLVM-NEXT: }