It would be convenient if gdb supported alignof like it supports sizeof for a type or expression. GCC has had an GNU extension for it: https://gcc.gnu.org/onlinedocs/gcc/Alignment.html C++11 has a keyword alignof and C11 has _Alignof (with alignof when including stdalign.h) both only work on a type, but as a GNU extension they also work on expressions. alignof has the same rules as sizeof, alignof on an array gives the alignment of the element type, on a c++ reference type it gives the alignment of the referenced type.
This can be especially valuable for pretty printers because sometimes alignof is used for layout. See: https://github.com/rust-lang/rust/blob/master/src/libstd/collections/hash/table.rs#L778
Actually implementing alignof in the expression parser is tricky, because normally the alignment is not specified in the debug info, and gdb doesn't know about the ABI rules here. Maybe mirroring DW_AT_alignment for pretty-printers would be good enough. At least rustc seems to emit this for many things -- at least all the structures I've looked at (though not pointer types or base types... so maybe not as useful as I thought).
You can see what I did so far, here: https://github.com/tromey/gdb/tree/submit/alignment This just reads DW_AT_alignment.
We discussed this on #gdb and came up with this idea: <tromey> so the current plan is something like: [13:08] <tromey> use DW_AT_alignment if it exists <tromey> else, for int/float/pointer types, use gdbarch, and update the arch_*_type calls <tromey> and for struct/union types, use the max alignment of the fields
Time to admit I'm doing this.
Submitted: https://sourceware.org/ml/gdb-patches/2018-04/msg00466.html
The master branch has been updated by Tom Tromey <tromey@sourceware.org>: https://sourceware.org/git/gitweb.cgi?p=binutils-gdb.git;h=007e1530347330d4dbba387c4e35aae05bc06498 commit 007e1530347330d4dbba387c4e35aae05bc06498 Author: Tom Tromey <tom@tromey.com> Date: Fri Apr 20 13:40:29 2018 -0600 Handle alignof and _Alignof This adds alignof and _Alignof to the C/C++ expression parser, and adds new tests to test the features. The tests are written to try to ensure that gdb's knowledge of alignment rules stays in sync with the compiler's. 2018-04-30 Tom Tromey <tom@tromey.com> PR exp/17095: * NEWS: Update. * std-operator.def (UNOP_ALIGNOF): New operator. * expprint.c (dump_subexp_body_standard) <case UNOP_ALIGNOF>: New. * eval.c (evaluate_subexp_standard) <case UNOP_ALIGNOF>: New. * c-lang.c (c_op_print_tab): Add alignof. * c-exp.y (ALIGNOF): New token. (exp): Add "ALIGNOF" production. (ident_tokens): Add _Alignof and alignof. 2018-04-30 Tom Tromey <tom@tromey.com> PR exp/17095: * gdb.dwarf2/dw2-align.exp: New file. * gdb.cp/align.exp: New file. * gdb.base/align.exp: New file. * lib/gdb.exp (gdb_int128_helper): New proc. (has_int128_c, has_int128_cxx): New caching procs.
Fixed.