[llvm-bugs] [Bug 37243] New: Feature request: add sizeof extension for structs with flexible array member

via llvm-bugs llvm-bugs at lists.llvm.org
Wed Apr 25 14:32:05 PDT 2018


https://bugs.llvm.org/show_bug.cgi?id=37243

            Bug ID: 37243
           Summary: Feature request: add sizeof extension for structs with
                    flexible array member
           Product: clang
           Version: unspecified
          Hardware: Other
                OS: Linux
            Status: NEW
          Severity: enhancement
          Priority: P
         Component: Frontend
          Assignee: unassignedclangbugs at nondot.org
          Reporter: vicencb at gmail.com
                CC: llvm-bugs at lists.llvm.org

Hi
It would be nice to have an extension that reports the size of a struct with a
flexible array member.

Calculating the size of such an struct is a bit cumbersome if alignment is to
be taken into account.
Also, this feature nicely fits with other compiler built-ins like 'sizeof'.

Currently, writing some code like this is required:
#include <stdalign.h>
#include <stddef.h>

typedef struct strc {
  unsigned len;
  char     val[];
} strc;

static inline size_t strc_size(size_t length) {
  static const size_t   alignment                 = alignof(strc);
  static const size_t   offsetofmember            = offsetof(strc, val);
  static const size_t   sizeofmember0             = sizeof(((strc
*)0)->val[0]);
  static const unsigned offsetofmember_is_aligned = offsetofmember ==
((offsetofmember + alignment - 1) / alignment) * alignment;
  static const unsigned sizeofmember0_is_aligned  = sizeofmember0  ==
((sizeofmember0  + alignment - 1) / alignment) * alignment;
  static const unsigned always_aligned            = offsetofmember_is_aligned
&& sizeofmember0_is_aligned;
  size_t packed_size = offsetofmember + length * sizeofmember0;
  size_t padded_size = ((packed_size + alignment - 1) / alignment ) *
alignment;
  return always_aligned ? packed_size : padded_size;
}
// That function is generic enough that can be moved into a macro
//   for any struct with a flexible array member:
#define sizeof_struct(type, member) size_t type##_size(size_t length) {...}

This extension could be provided on top of the 'sizeof' operator as an extra
optional argument:
sizeof(strc, 7) == strc_size(7)
sizeof(strc)    == strc_size(0)
sizeof strc     == strc_size(0)

Regards,
  Vicente.

-- 
You are receiving this mail because:
You are on the CC list for the bug.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/llvm-bugs/attachments/20180425/d71405db/attachment.html>


More information about the llvm-bugs mailing list