diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp --- a/clang/lib/Sema/SemaChecking.cpp +++ b/clang/lib/Sema/SemaChecking.cpp @@ -16020,16 +16020,21 @@ llvm::APInt size = ArrayTy->getSize(); if (BaseType != EffectiveType) { - // Make sure we're comparing apples to apples when comparing index to size + // Make sure we're comparing apples to apples when comparing index to + // size. uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); uint64_t array_typesize = Context.getTypeSize(BaseType); - // Handle ptrarith_typesize being zero, such as when casting to void* - if (!ptrarith_typesize) ptrarith_typesize = 1; + + // Handle ptrarith_typesize being zero, such as when casting to void*. + if (!ptrarith_typesize) + ptrarith_typesize = Context.getCharWidth(); + if (ptrarith_typesize != array_typesize) { - // There's a cast to a different size type involved + // There's a cast to a different size type involved. uint64_t ratio = array_typesize / ptrarith_typesize; + // TODO: Be smarter about handling cases where array_typesize is not a - // multiple of ptrarith_typesize + // multiple of ptrarith_typesize. if (ptrarith_typesize * ratio == array_typesize) size *= llvm::APInt(size.getBitWidth(), ratio); } diff --git a/clang/test/Sema/array-bounds-ptr-arith.c b/clang/test/Sema/array-bounds-ptr-arith.c --- a/clang/test/Sema/array-bounds-ptr-arith.c +++ b/clang/test/Sema/array-bounds-ptr-arith.c @@ -6,13 +6,12 @@ struct ext2_super_block{ unsigned char s_uuid[8]; // expected-note {{declared here}} }; -void* ext2_statfs (struct ext2_super_block *es,int a) -{ - return (void *)es->s_uuid + sizeof(int); // no-warning + +void* ext2_statfs (struct ext2_super_block *es,int a) { + return (void *)es->s_uuid + sizeof(int); // no-warning } -void* broken (struct ext2_super_block *es,int a) -{ - return (void *)es->s_uuid + 80; // expected-warning {{refers past the end of the array (that contains 8 elements)}} +void* broken (struct ext2_super_block *es,int a) { + return (void *)es->s_uuid + 9; // expected-warning {{the pointer incremented by 9 refers past the end of the array (that contains 8 elements)}} } // Test case reduced from PR11594