Home | History | Annotate | Download | only in ADT
      1 //===- llvm/unittest/ADT/PointerIntPairTest.cpp - Unit tests --------------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 
     10 #include "gtest/gtest.h"
     11 #include "llvm/ADT/PointerIntPair.h"
     12 #include <limits>
     13 using namespace llvm;
     14 
     15 namespace {
     16 
     17 // Test fixture
     18 class PointerIntPairTest : public testing::Test {
     19 };
     20 
     21 TEST_F(PointerIntPairTest, GetSet) {
     22   PointerIntPair<PointerIntPairTest *, 2> Pair(this, 1U);
     23   EXPECT_EQ(this, Pair.getPointer());
     24   EXPECT_EQ(1U, Pair.getInt());
     25 
     26   Pair.setInt(2);
     27   EXPECT_EQ(this, Pair.getPointer());
     28   EXPECT_EQ(2U, Pair.getInt());
     29 
     30   Pair.setPointer(nullptr);
     31   EXPECT_EQ(nullptr, Pair.getPointer());
     32   EXPECT_EQ(2U, Pair.getInt());
     33 
     34   Pair.setPointerAndInt(this, 3U);
     35   EXPECT_EQ(this, Pair.getPointer());
     36   EXPECT_EQ(3U, Pair.getInt());
     37 }
     38 
     39 TEST_F(PointerIntPairTest, DefaultInitialize) {
     40   PointerIntPair<PointerIntPairTest *, 2> Pair;
     41   EXPECT_EQ(nullptr, Pair.getPointer());
     42   EXPECT_EQ(0U, Pair.getInt());
     43 }
     44 
     45 #if !(defined(_MSC_VER) && _MSC_VER==1700)
     46 TEST_F(PointerIntPairTest, ManyUnusedBits) {
     47   // In real code this would be a word-sized integer limited to 31 bits.
     48   struct Fixnum31 {
     49     uintptr_t Value;
     50   };
     51   class FixnumPointerTraits {
     52   public:
     53     static inline void *getAsVoidPointer(Fixnum31 Num) {
     54       return reinterpret_cast<void *>(Num.Value << NumLowBitsAvailable);
     55     }
     56     static inline Fixnum31 getFromVoidPointer(void *P) {
     57       // In real code this would assert that the value is in range.
     58       return { reinterpret_cast<uintptr_t>(P) >> NumLowBitsAvailable };
     59     }
     60     enum { NumLowBitsAvailable = std::numeric_limits<uintptr_t>::digits - 31 };
     61   };
     62 
     63   PointerIntPair<Fixnum31, 1, bool, FixnumPointerTraits> pair;
     64   EXPECT_EQ((uintptr_t)0, pair.getPointer().Value);
     65   EXPECT_FALSE(pair.getInt());
     66 
     67   pair.setPointerAndInt({ 0x7FFFFFFF }, true );
     68   EXPECT_EQ((uintptr_t)0x7FFFFFFF, pair.getPointer().Value);
     69   EXPECT_TRUE(pair.getInt());
     70 
     71   EXPECT_EQ(FixnumPointerTraits::NumLowBitsAvailable - 1,
     72             PointerLikeTypeTraits<decltype(pair)>::NumLowBitsAvailable);
     73 }
     74 #endif
     75 
     76 } // end anonymous namespace
     77