llvm.org GIT mirror llvm / 495097a
Add assertions checking SignExtend{32,64}'s bit width. Summary: The bit width must be greater than zero, otherwise we shift by the integer's width, which is UB. Also (more obviously) the width must be less than or equal to the integer's width, otherwise we shift by a negative number, which is also UB. Reviewers: rnk Subscribers: llvm-commits, dylanmckay Differential Revision: https://reviews.llvm.org/D22442 git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@275720 91177308-0d34-0410-b5e6-96231b3b80d8 Justin Lebar 4 years ago
1 changed file(s) with 19 addition(s) and 11 deletion(s). Raw diff Collapse all Expand all
671671 return alignTo(Value, Align) - Value;
672672 }
673673
674 /// SignExtend32 - Sign extend B-bit number x to 32-bit int.
675 /// Usage int32_t r = SignExtend32<5>(x);
676 template inline int32_t SignExtend32(uint32_t x) {
677 return int32_t(x << (32 - B)) >> (32 - B);
678 }
679
680 /// \brief Sign extend number in the bottom B bits of X to a 32-bit int.
674 /// Sign-extend the number in the bottom B bits of X to a 32-bit integer.
681675 /// Requires 0 < B <= 32.
676 template inline int32_t SignExtend32(uint32_t X) {
677 static_assert(B > 0, "Bit width can't be 0.");
678 static_assert(B <= 32, "Bit width out of range.");
679 return int32_t(X << (32 - B)) >> (32 - B);
680 }
681
682 /// Sign-extend the number in the bottom B bits of X to a 32-bit integer.
683 /// Requires 0 < B < 32.
682684 inline int32_t SignExtend32(uint32_t X, unsigned B) {
685 assert(B > 0 && "Bit width can't be 0.");
686 assert(B <= 32 && "Bit width out of range.");
683687 return int32_t(X << (32 - B)) >> (32 - B);
684688 }
685689
686 /// SignExtend64 - Sign extend B-bit number x to 64-bit int.
687 /// Usage int64_t r = SignExtend64<5>(x);
690 /// Sign-extend the number in the bottom B bits of X to a 64-bit integer.
691 /// Requires 0 < B < 64.
688692 template inline int64_t SignExtend64(uint64_t x) {
693 static_assert(B > 0, "Bit width can't be 0.");
694 static_assert(B <= 64, "Bit width out of range.");
689695 return int64_t(x << (64 - B)) >> (64 - B);
690696 }
691697
692 /// \brief Sign extend number in the bottom B bits of X to a 64-bit int.
693 /// Requires 0 < B <= 64.
698 /// Sign-extend the number in the bottom B bits of X to a 64-bit integer.
699 /// Requires 0 < B < 64.
694700 inline int64_t SignExtend64(uint64_t X, unsigned B) {
701 assert(B > 0 && "Bit width can't be 0.");
702 assert(B <= 64 && "Bit width out of range.");
695703 return int64_t(X << (64 - B)) >> (64 - B);
696704 }
697705