Skip to content

[clang] pointer subtraction should use ptrtoaddr rather than ptrtoint #159419

@bababuck

Description

@bababuck

Not sure this is an issue or not, but seems incorrect from what I was able to gather.

From the C-specification,

Pointer subtraction works by subtracting p1’s numeric value from p3’s, and dividing by target object size. The two pointer arguments should point into the same array.

My understanding is that pointer subtraction should return the number of elements between the two pointers. From this, it follows that the provenance of the pointer should not be considered, and thus a ptrtoaddr instruction should be used.

However, clang currently lowers pointer subtraction using ptrtoint.

#include <stdint.h>
#include <stddef.h>

ptrdiff_t foot(int8_t *a, int8_t *b) {
  return a - b;
}
./bin/clang -O2 -S -emit-llvm -o ptr.ll ptr.c
; Function Attrs: mustprogress nofree norecurse nosync nounwind willreturn memory(none)
define dso_local noundef i64 @foot(ptr noundef %a, ptr noundef %b) local_unnamed_addr #0 {
entry:
  %sub.ptr.lhs.cast = ptrtoint ptr %a to i64
  %sub.ptr.rhs.cast = ptrtoint ptr %b to i64
  %sub.ptr.sub = sub i64 %sub.ptr.lhs.cast, %sub.ptr.rhs.cast
  ret i64 %sub.ptr.sub
}  

Metadata

Metadata

Assignees

No one assigned

    Labels

    clang:codegenIR generation bugs: mangling, exceptions, etc.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions