shift.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // RUN: %clang_cc1 -Wall -Wshift-sign-overflow -ffreestanding -fsyntax-only -verify %s
  2. #include <limits.h>
  3. #define WORD_BIT (sizeof(int) * CHAR_BIT)
  4. enum {
  5. X = 1 << 0,
  6. Y = 1 << 1,
  7. Z = 1 << 2
  8. };
  9. void test() {
  10. char c;
  11. c = 0 << 0;
  12. c = 0 << 1;
  13. c = 1 << 0;
  14. c = 1 << -0;
  15. c = 1 >> -0;
  16. c = 1 << -1; // expected-warning {{shift count is negative}}
  17. c = 1 >> -1; // expected-warning {{shift count is negative}}
  18. c = 1 << c;
  19. c <<= 0;
  20. c >>= 0;
  21. c <<= 1;
  22. c >>= 1;
  23. c <<= -1; // expected-warning {{shift count is negative}}
  24. c >>= -1; // expected-warning {{shift count is negative}}
  25. c <<= 999999; // expected-warning {{shift count >= width of type}}
  26. c >>= 999999; // expected-warning {{shift count >= width of type}}
  27. c <<= CHAR_BIT; // expected-warning {{shift count >= width of type}}
  28. c >>= CHAR_BIT; // expected-warning {{shift count >= width of type}}
  29. c <<= CHAR_BIT+1; // expected-warning {{shift count >= width of type}}
  30. c >>= CHAR_BIT+1; // expected-warning {{shift count >= width of type}}
  31. (void)((long)c << CHAR_BIT);
  32. int i;
  33. i = 1 << (WORD_BIT - 2);
  34. i = 2 << (WORD_BIT - 1); // expected-warning {{bits to represent, but 'int' only has}}
  35. i = 1 << (WORD_BIT - 1); // expected-warning {{sets the sign bit of the shift expression}}
  36. i = -1 << (WORD_BIT - 1); // expected-warning {{shifting a negative signed value is undefined}}
  37. i = -1 << 0; // expected-warning {{shifting a negative signed value is undefined}}
  38. i = 0 << (WORD_BIT - 1);
  39. i = (char)1 << (WORD_BIT - 2);
  40. unsigned u;
  41. u = 1U << (WORD_BIT - 1);
  42. u = 5U << (WORD_BIT - 1);
  43. long long int lli;
  44. lli = INT_MIN << 2; // expected-warning {{shifting a negative signed value is undefined}}
  45. lli = 1LL << (sizeof(long long) * CHAR_BIT - 2);
  46. }
  47. #define a 0
  48. #define ashift 8
  49. enum { b = (a << ashift) };
  50. // Don't warn for negative shifts in code that is unreachable.
  51. void test_pr5544() {
  52. (void) (((1) > 63 && (1) < 128 ? (((unsigned long long) 1)<<((1)-64)) : (unsigned long long) 0)); // no-warning
  53. }
  54. void test_shift_too_much(char x) {
  55. if (0)
  56. (void) (x >> 80); // no-warning
  57. (void) (x >> 80); // expected-warning {{shift count >= width of type}}
  58. }