3

Clang has different behaviors in different cases, when add padding to struct, and what's the rule?

For below c++ code:

struct CT1 {
  char   c1 = 'c';
  double d1;
  char   c2;
};

struct CT2 {
  char   c1;
  double d1;
  char   c2;
};
struct CT3 {
  char   c1 = 'c';
  double d1;
};

int main() {
  CT1 ct1;
  CT2 ct2;
  CT3 ct3;
  return 0;
}

Clang will generate IR code:

%struct.CT1 = type <{ i8, [7 x i8], double, i8, [7 x i8] }>
%struct.CT2 = type { i8, double, i8 }
%struct.CT3 = type { i8, double }

I have several questions:

  1. CT1 has padding, while CT2 has not. CT1 is only different with CT2 by having a initial value of c1. Why?
  2. CT3 hasn't padding, which is only different with CT1 by reduced a property named c2. Why?
  3. IR Code of CT2 doesn't add padding explicitly, but in log (using -Wpadded) it seems to have added padding already, is this true? And does it means that we can not add padding by hand?
warning: padding struct 'CT3' with 7 bytes to align 'd1' [-Wpadded]
  double d1;
  1. How to add padding to struct by IRBuilder of LLVM?

I need to generate IR code by hand, so i need to know when should i add padding to struct.

Really thanks for any reply.

Lanistor
  • 149
  • 8
  • 1
    CT1 has a custom constructor while CT2 does not. This makes CT1 non-POD, unlike CT2. It seems that these are treated differently: https://stackoverflow.com/questions/53837373/standard-layout-and-tail-padding As for 3: I think you simply add fake i8 fields manually? – freakish Aug 12 '20 at 07:34
  • Clang has C++ rules and target machine rules. The former is not my cup of tea. For the latter, LLVM's target layout declaration decides when pushing is/needs to be added. – arnt Aug 12 '20 at 07:57
  • @freakish Thanks for reply. i8 fields of CT3 is really added by mistake, had deleted it. – Lanistor Aug 13 '20 at 04:06
  • @arnt Thanks for reply. I really need to find out the rules clearly. – Lanistor Aug 13 '20 at 04:13
  • C++ is not known for simple rules. Making life simple for compiler authors is/was an explicit non-goal. Sorry. But at least you have the clang source and can read it. – arnt Aug 13 '20 at 16:39

0 Answers0