c++11 - g++ faulty optimization with specialized template -


i'm having problem g++ (4.9.2) optimization produces faulty code puzzling me. , faulty, mean code output fundementally different between optimized (-o1, -o2 or -o3) , non-optimized (-o0) compilation. and, of course, optimized code wrong.

i have class similar <bitset>, info stored @ bit-level , instantiated number of bits, has specialized template bits <= 8 bits.

#include <iostream> using namespace std;  // generalized class bits, uses array of specialized, 1-byte bits template <unsigned int bits=8, bool _=(bits>8)> class bits {     bits<8,false> reg[(bits+7)>>3];  public:     void set(int pos)  { reg[pos>>3].set(pos%8);  };     void clr(int pos)  { reg[pos>>3].clr(pos%8);  };     bool get(int pos)  { reg[pos>>3].get(pos%8);  }; };  // specialized, 1-byte bits (flag stored in char) template <unsigned int bits> class bits<bits,false> {     char reg;  public:     bits() : reg(0) {};     bits(int r) : reg(r) {};      void set(int pos) { reg |=  mark(pos);        };     void clr(int pos) { reg &= ~mark(pos);        };     bool get(int pos) { return (reg & mark(pos)); };      static int mark(int pos) { return ( 1 << pos ); }; };     int main() {     bits<16> b;     bits<8> c;      b.set(1);     c.set(1);      cout << b.get(1) << endl;     cout << c.get(1) << endl;      return 0; }; 

the test simple, set bit , print said bit state stdout. done 16-bits bits object (the generalized templated) , 8-bit bits object (the specialized template). expected answer true either objects. , when compile no optimization (i.e. g++-4.9 -o0 main.cpp), get. output of ./a.out is:

1 1 

but when compile -o1 optimization (i.e. g++-4.9 -o1 main.cpp), results different , partially wrong:

0 1 

specifically, bits<8> tests correctly in both optimzation (-o0 , -o3), bits<16> test correctly -o0 , not -o1.

the optimizer (-o1, -o2, , -o3) optimizes out bits member functions , jumps final results, calculated @ compile-time. optimizer making error, don't know root cause. know should looking debug problem?

it helps when function returning bool has return statement:

    bool get(int pos)  { return reg[pos>>3].get(pos%8);  };                          ^^^^^^ 

with that:

$ g++ -o3 foo.cpp $ ./a.out 1 1 

Comments

Popular posts from this blog

java - Static nested class instance -

c# - Bluetooth LE CanUpdate Characteristic property -

JavaScript - Replace variable from string in all occurrences -