Incorrect shift optimization - by YamaA

Status : 

  Fixed<br /><br />
		This item has been fixed in the current or upcoming version of this product.<br /><br />
		A more detailed explanation for the resolution of this particular item may have been provided in the comments section.

Sign in
to vote
ID 653501 Comments
Status Closed Workarounds
Type Bug Repros 1
Opened 3/25/2011 12:11:10 AM
Access Restriction Public


The following code has problem when only VC10(SP1) Release build. I think the code "codeNum = 1 << leadingZeroBits" is broken by optimization. It has no problem on VC9.

#include <stdio.h>
#include <stdlib.h>

__forceinline int func(unsigned int& bs)
	int leadingZeroBits = -1;
	for (int b = 0; !b && leadingZeroBits < 32; leadingZeroBits++){
		b = bs >> (32 - 1);
		bs <<= 1;
	if (leadingZeroBits == 0)
		return 0;
	int codeNum = 1 << leadingZeroBits;
	codeNum = codeNum - 1 + (bs >> (32 - leadingZeroBits));
	bs <<= leadingZeroBits;
	return codeNum;

int main(int argc, char* argv[])
	unsigned int val = argc >= 2 ? atoi(argv[1]) : 690262112;
	for (int j = 0; j < 16; j++){
		printf("%d ", func(val));
Sign in to post a comment.
Posted by Microsoft on 3/29/2011 at 11:40 AM
We have investigated the issue and will fix it in a future release. This is actually the same issue as reported at

As a workaround, you can avoid initializing the induction variable leadingZeroBits as a negative number. In your code, you would change the initialization of leadingZeroBits from -1 to 0, change the for-loop test to be "leadingZeroBits <= 32" and then adjust leadingZeroBits with leadingZeroBits-- to get the desired behavior.

Mark Levine
Visual C++

Posted by Microsoft on 3/25/2011 at 2:18 AM
Thank you for submitting feedback on Visual Studio 2010 and .NET Framework. Your issue has been routed to the appropriate VS development team for review. We will contact you if we require any additional information.
Posted by Microsoft on 3/25/2011 at 12:12 AM
Thank you for your feedback, we are currently reviewing the issue you have submitted. If this issue is urgent, please contact support directly(