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>
13using namespace llvm;
14
15namespace {
16
17// Test fixture
18class PointerIntPairTest : public testing::Test {
19};
20
21TEST_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
39TEST_F(PointerIntPairTest, DefaultInitialize) {
40  PointerIntPair<PointerIntPairTest *, 2> Pair;
41  EXPECT_EQ(nullptr, Pair.getPointer());
42  EXPECT_EQ(0U, Pair.getInt());
43}
44
45TEST_F(PointerIntPairTest, ManyUnusedBits) {
46  // In real code this would be a word-sized integer limited to 31 bits.
47  struct Fixnum31 {
48    uintptr_t Value;
49  };
50  class FixnumPointerTraits {
51  public:
52    static inline void *getAsVoidPointer(Fixnum31 Num) {
53      return reinterpret_cast<void *>(Num.Value << NumLowBitsAvailable);
54    }
55    static inline Fixnum31 getFromVoidPointer(void *P) {
56      // In real code this would assert that the value is in range.
57      return { reinterpret_cast<uintptr_t>(P) >> NumLowBitsAvailable };
58    }
59    enum { NumLowBitsAvailable = std::numeric_limits<uintptr_t>::digits - 31 };
60  };
61
62  PointerIntPair<Fixnum31, 1, bool, FixnumPointerTraits> pair;
63  EXPECT_EQ((uintptr_t)0, pair.getPointer().Value);
64  EXPECT_FALSE(pair.getInt());
65
66  pair.setPointerAndInt({ 0x7FFFFFFF }, true );
67  EXPECT_EQ((uintptr_t)0x7FFFFFFF, pair.getPointer().Value);
68  EXPECT_TRUE(pair.getInt());
69
70  EXPECT_EQ(FixnumPointerTraits::NumLowBitsAvailable - 1,
71            PointerLikeTypeTraits<decltype(pair)>::NumLowBitsAvailable);
72}
73
74} // end anonymous namespace
75