Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enabling strict aliasing warnings in g++

What is the correct way to enable strict aliasing warnings in g++? Does VC++ 10 implement those rules?

like image 393
user1086635 Avatar asked Dec 18 '11 15:12

user1086635


People also ask

How do you get around strict aliasing?

The answer typically is to type pun, often the methods used violate strict aliasing rules. Sometimes we want to circumvent the type system and interpret an object as a different type. This is called type punning, to reinterpret a segment of memory as another type.

What is the strict aliasing rule and why do we care?

GCC compiler makes an assumption that pointers of different types will never point to the same memory location i.e., alias of each other. Strict aliasing rule helps the compiler to optimize the code.

What is C++ aliasing?

In C, C++, and some other programming languages, the term aliasing refers to a situation where two different expressions or symbols refer to the same object.

What is strict C++?

"Strict aliasing is an assumption, made by the C (or C++) compiler, that dereferencing pointers to objects of different types will never refer to the same memory location (i.e. alias each other.)"


3 Answers

Use -fstrict-aliasing for g++. I also use -Wstrict-aliasing=2 to see warnings related to possible violations of strict aliasing rules.

like image 184
Sergey Kalinichenko Avatar answered Sep 18 '22 11:09

Sergey Kalinichenko


They're enabled automatically by -O2 because it needs to use them to do some of the optimizations. Definitely combine it with the warning (-Wall does the trick) to make sure you aren't building potentially buggy code. Otherwise you can use -fstrict-aliasing as seen in another answer to enable them.

I'm not sure about VC++10 however.

like image 38
Mark B Avatar answered Sep 21 '22 11:09

Mark B


VC++ 10 enables the strict aliasing rule with /O1 and above. I use the test program(with count value 6) in chapter 'BENEFITS TO THE STRICT ALIASING RULE' of here. And get following asm code. You can see the load of b is done only once.

00A910AE  movzx       edx,word ptr [edx+2]  //Load of b
00A910B2  xor         eax,eax  
00A910B4  xor         ecx,ecx  
00A910B6  add         dword ptr [esp+eax*4+34h],edx  //Loop start
00A910BA  add         eax,1  
00A910BD  adc         ecx,edi  
00A910BF  jne         main+76h (0A910C6h)  
00A910C1  cmp         eax,6  
00A910C4  jb          main+66h (0A910B6h)  //Loop end

But looks like there isn't a way to enable the warning for breaking this rule.

like image 45
Shawnone Avatar answered Sep 22 '22 11:09

Shawnone