Skip to content

Commit

Permalink
[CIR][LowerToLLVM] Fix ptrdiffs in face of !cir.void
Browse files Browse the repository at this point in the history
  • Loading branch information
bcardosolopes committed May 3, 2024
1 parent 1efee91 commit 795925f
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 8 deletions.
24 changes: 16 additions & 8 deletions clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2533,6 +2533,9 @@ class CIRPtrDiffOpLowering

uint64_t getTypeSize(mlir::Type type, mlir::Operation &op) const {
mlir::DataLayout layout(op.getParentOfType<mlir::ModuleOp>());
// For LLVM purposes we treat void as u8.
if (isa<mlir::cir::VoidType>(type))
type = mlir::cir::IntType::get(type.getContext(), 8, /*isSigned=*/false);
return llvm::divideCeil(layout.getTypeSizeInBits(type), 8);
}

Expand All @@ -2552,16 +2555,21 @@ class CIRPtrDiffOpLowering

auto ptrTy = op.getLhs().getType().cast<mlir::cir::PointerType>();
auto typeSize = getTypeSize(ptrTy.getPointee(), *op);
auto typeSizeVal = rewriter.create<mlir::LLVM::ConstantOp>(
op.getLoc(), llvmDstTy, mlir::IntegerAttr::get(llvmDstTy, typeSize));

if (dstTy.isUnsigned())
rewriter.replaceOpWithNewOp<mlir::LLVM::UDivOp>(op, llvmDstTy, diff,
typeSizeVal);
else
rewriter.replaceOpWithNewOp<mlir::LLVM::SDivOp>(op, llvmDstTy, diff,
typeSizeVal);
// Avoid silly division by 1.
auto resultVal = diff.getResult();
if (typeSize != 1) {
auto typeSizeVal = rewriter.create<mlir::LLVM::ConstantOp>(
op.getLoc(), llvmDstTy, mlir::IntegerAttr::get(llvmDstTy, typeSize));

if (dstTy.isUnsigned())
resultVal = rewriter.create<mlir::LLVM::UDivOp>(op.getLoc(), llvmDstTy,
diff, typeSizeVal);
else
resultVal = rewriter.create<mlir::LLVM::SDivOp>(op.getLoc(), llvmDstTy,
diff, typeSizeVal);
}
rewriter.replaceOp(op, resultVal);
return mlir::success();
}
};
Expand Down
18 changes: 18 additions & 0 deletions clang/test/CIR/CodeGen/ptrdiff.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -fclangir -emit-cir %s -o %t.cir
// RUN: FileCheck --check-prefix=CIR --input-file=%t.cir %s
// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -fclangir -emit-llvm %s -o %t.ll
// RUN: FileCheck --check-prefix=LLVM --input-file=%t.ll %s

int addrcmp(const void* a, const void* b) {
// CIR-LABEL: addrcmp
// CIR: %[[R:.*]] = cir.ptr_diff
// CIR: cir.cast(integral, %[[R]] : !s64i), !s32

// LLVM-LABEL: addrcmp
// LLVM: %[[PTR_A:.*]] = ptrtoint ptr {{.*}} to i64
// LLVM: %[[PTR_B:.*]] = ptrtoint ptr {{.*}} to i64
// LLVM: %[[SUB:.*]] = sub i64 %[[PTR_A]], %[[PTR_B]]
// LLVM-NOT: sdiv
// LLVM: trunc i64 %[[SUB]] to i32
return *(const void**)a - *(const void**)b;
}
File renamed without changes.

0 comments on commit 795925f

Please sign in to comment.