the code below behaves differently at -O1 and -O2.   


#include <stdio.h>

static void swapcopy_int( int * target, char * source, int num_bytes )
{
    int * to = target ;
    int * from = (int *) source ;
    for(int count=0; count < num_bytes/sizeof(int); count++ ){
        int t2 ;
        int t1 = *from++ ;
        *(((char *)&t2)+3) = *(((char *)&t1)  ) ;
        *(((char *)&t2)+2) = *(((char *)&t1)+1) ;
        *(((char *)&t2)+1) = *(((char *)&t1)+2) ;
        *(((char *)&t2)  ) = *(((char *)&t1)+3) ;
        *to++ = t2 ;
    }
}

int main()
{
     int num_rows = 0;
     int num_cols = 0;
     num_rows = 0x10000000;
     num_cols = 0x20000000;
     swapcopy_int   ( &num_rows, (char *)&num_rows, sizeof( int    ) );
     swapcopy_int   ( &num_cols, (char *)&num_cols, sizeof( int    ) );
     printf (" rows = %d cols = %d \n", num_rows, num_cols );
     return 0;

}


$ g++ -O1 xx.c
$ ./a.out
the target is 0xbf8e3acc (10000000) the source is 0xbf8e3acc (10000000) bytes =
4
the target is 0xbf8e3ac8 (20000000) the source is 0xbf8e3ac8 (20000000) bytes =
4
 rows = -1740992833 cols = -1740992833

             ^
         These are wrong !!!!
$ g++ -O2 xx.c
$ ./a.out
the target is 0xbfe7985c (10000000) the source is 0xbfe7985c (10000000) bytes =
4
the target is 0xbfe79858 (20000000) the source is 0xbfe79858 (20000000) bytes =
4
 rows = 16 cols = 32

         ^
        These are right
$ g++ --version
g++ (GCC) 4.4.1
Copyright (C) 2009 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.


-- 
           Summary: Code does not work at -O1
           Product: gcc
           Version: 4.4.3
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c++
        AssignedTo: unassigned at gcc dot gnu dot org
        ReportedBy: bdavis at gcc dot gnu dot org
  GCC host triplet: i686/linux/gnu


http://gcc.gnu.org/bugzilla/show_bug.cgi?id=43240

Reply via email to