GCC Generates Unexpected Assembly for Bitwise Operations in C++ on ARM Architecture
I'm stuck on something that should probably be simple. I'm migrating some code and I've searched everywhere and can't find a clear answer... This might be a silly question, but Quick question that's been bugging me - I'm working on a C++ application that heavily relies on bitwise operations for performance-critical sections of the code. I've recently switched from GCC 9 to GCC 11.2 on an ARM-based system, and I've noticed some unexpected behavior in the generated assembly code. Specifically, my simple function that performs bitwise AND operations is behaving differently. Here's a snippet of my code: ```cpp #include <iostream> int bitwiseAnd(int a, int b) { return a & b; } int main() { int result = bitwiseAnd(5, 3); std::cout << "Result: " << result << std::endl; // Should print 1 return 0; } ``` When I compile this with `g++ -O2 -S -o output.s main.cpp`, the assembly code generated seems to use a more complex instruction sequence than I expected. The relevant part of the assembly looks like this: ```asm ; ... movs r0, #5 movs r1, #3 and r0, r0, r1 ; ... ``` What surprises me is that the optimizer is not using the immediate values directly, and instead, it seems to be performing additional `movs` instructions before the `and` operation. I had expected a more straightforward optimization in this case. To debug, I tried compiling with `-O3` and `-fomit-frame-pointer`, but the output remains the same. I also checked with `-fverbose-asm` to see the optimization details, which didn't clarify why the optimizer chose this path. Is there something I'm missing, or is this a known scenario with GCC 11.2 on ARM? Any insights on why the optimizer behaves this way and how I might improve it would be really appreciated. What am I doing wrong? My development environment is Linux. Am I missing something obvious? This is happening in both development and production on Linux. Thanks for your help in advance! The project is a desktop app built with C++. What am I doing wrong?