[ADT] Use a nonce type with at least 4 byte alignment.
[oota-llvm.git] / unittests / ADT / PointerIntPairTest.cpp
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(PointerIntPairTest, GetSet) {
18   struct S {
19     int i;
20   };
21   S s;
22
23   PointerIntPair<S *, 2> Pair(&s, 1U);
24   EXPECT_EQ(&s, Pair.getPointer());
25   EXPECT_EQ(1U, Pair.getInt());
26
27   Pair.setInt(2);
28   EXPECT_EQ(&s, Pair.getPointer());
29   EXPECT_EQ(2U, Pair.getInt());
30
31   Pair.setPointer(nullptr);
32   EXPECT_EQ(nullptr, Pair.getPointer());
33   EXPECT_EQ(2U, Pair.getInt());
34
35   Pair.setPointerAndInt(&s, 3U);
36   EXPECT_EQ(&s, Pair.getPointer());
37   EXPECT_EQ(3U, Pair.getInt());
38 }
39
40 TEST(PointerIntPairTest, DefaultInitialize) {
41   PointerIntPair<float *, 2> Pair;
42   EXPECT_EQ(nullptr, Pair.getPointer());
43   EXPECT_EQ(0U, Pair.getInt());
44 }
45
46 TEST(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
75 } // end anonymous namespace