From bcbfc03bd6355523e8d82c2b77b1e451a3d48a19 Mon Sep 17 00:00:00 2001 From: Yury Gribov Date: Thu, 21 Dec 2023 17:44:11 +0300 Subject: [PATCH] [CIR][CodeGen] Use signed type for result of ptrdiff operation. (#355) Before this fix attached test case has been failing due to type mismatch (signed vs unsigned). --- clang/lib/CIR/CodeGen/CIRGenModule.cpp | 4 ++++ clang/lib/CIR/CodeGen/CIRGenTypeCache.h | 3 ++- clang/test/CIR/CodeGen/ptr_diff.cpp | 15 +++++++++++++-- 3 files changed, 19 insertions(+), 3 deletions(-) diff --git a/clang/lib/CIR/CodeGen/CIRGenModule.cpp b/clang/lib/CIR/CodeGen/CIRGenModule.cpp index e7717e57e8b4..a2b2e2277a9b 100644 --- a/clang/lib/CIR/CodeGen/CIRGenModule.cpp +++ b/clang/lib/CIR/CodeGen/CIRGenModule.cpp @@ -162,6 +162,10 @@ CIRGenModule::CIRGenModule(mlir::MLIRContext &context, // TODO: ConstGlobalsPtrTy // TODO: ASTAllocaAddressSpace + PtrDiffTy = ::mlir::cir::IntType::get( + builder.getContext(), astCtx.getTargetInfo().getMaxPointerWidth(), + /*isSigned=*/true); + mlir::cir::sob::SignedOverflowBehavior sob; switch (langOpts.getSignedOverflowBehavior()) { case clang::LangOptions::SignedOverflowBehaviorTy::SOB_Defined: diff --git a/clang/lib/CIR/CodeGen/CIRGenTypeCache.h b/clang/lib/CIR/CodeGen/CIRGenTypeCache.h index cea3f07922e0..ac3442626ca8 100644 --- a/clang/lib/CIR/CodeGen/CIRGenTypeCache.h +++ b/clang/lib/CIR/CodeGen/CIRGenTypeCache.h @@ -49,9 +49,10 @@ struct CIRGenTypeCache { union { mlir::Type UIntPtrTy; mlir::Type SizeTy; - mlir::Type PtrDiffTy; }; + mlir::Type PtrDiffTy; + /// void* in address space 0 mlir::cir::PointerType VoidPtrTy; mlir::cir::PointerType UInt8PtrTy; diff --git a/clang/test/CIR/CodeGen/ptr_diff.cpp b/clang/test/CIR/CodeGen/ptr_diff.cpp index 924162d3c790..ebaa5ec6bfac 100644 --- a/clang/test/CIR/CodeGen/ptr_diff.cpp +++ b/clang/test/CIR/CodeGen/ptr_diff.cpp @@ -9,5 +9,16 @@ size_type size(unsigned long *_start, unsigned long *_finish) { // CHECK: cir.func @_Z4sizePmS_(%arg0: !cir.ptr // CHECK: %3 = cir.load %1 : cir.ptr >, !cir.ptr // CHECK: %4 = cir.load %0 : cir.ptr >, !cir.ptr -// CHECK: %5 = cir.ptr_diff(%3, %4) : !cir.ptr -> !u64i - \ No newline at end of file +// CHECK: %5 = cir.ptr_diff(%3, %4) : !cir.ptr -> !s64i +// CHECK: %6 = cir.cast(integral, %5 : !s64i), !u64i + +long add(char *a, char *b) { + return a - b + 1; +} + +// CHECK: cir.func @_Z3addPcS_(%arg0: !cir.ptr +// %5 = cir.ptr_diff(%3, %4) : !cir.ptr -> !s64i +// %6 = cir.const(#cir.int<1> : !s32i) : !s32i +// %7 = cir.cast(integral, %6 : !s32i), !s64i +// %8 = cir.binop(add, %5, %7) : !s64i +