Unnamed: 0
int64
0
0
repo_id
stringlengths
5
186
file_path
stringlengths
15
223
content
stringlengths
1
32.8M
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/Support/formatted_raw_ostream_test.cpp
//===- llvm/unittest/Support/formatted_raw_ostream_test.cpp ---------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/Support/FormattedStream.h" #include "llvm/ADT/SmallString.h" #include "llvm/Support/raw_ostream.h" #include "gtest/gtest.h" using namespace llvm; namespace { TEST(formatted_raw_ostreamTest, Test_Tell) { // Check offset when underlying stream has buffer contents. SmallString<128> A; raw_svector_ostream B(A); formatted_raw_ostream C(B); char tmp[100] = ""; for (unsigned i = 0; i != 3; ++i) { C.write(tmp, 100); EXPECT_EQ(100*(i+1), (unsigned) C.tell()); } } }
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/Support/SwapByteOrderTest.cpp
//===- unittests/Support/SwapByteOrderTest.cpp - swap byte order test -----===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "gtest/gtest.h" #include "llvm/Support/SwapByteOrder.h" #include <cstdlib> #include <ctime> using namespace llvm; #undef max namespace { // In these first two tests all of the original_uintx values are truncated // except for 64. We could avoid this, but there's really no point. TEST(getSwappedBytes, UnsignedRoundTrip) { // The point of the bit twiddling of magic is to test with and without bits // in every byte. uint64_t value = 1; for (std::size_t i = 0; i <= sizeof(value); ++i) { uint8_t original_uint8 = static_cast<uint8_t>(value); EXPECT_EQ(original_uint8, sys::getSwappedBytes(sys::getSwappedBytes(original_uint8))); uint16_t original_uint16 = static_cast<uint16_t>(value); EXPECT_EQ(original_uint16, sys::getSwappedBytes(sys::getSwappedBytes(original_uint16))); uint32_t original_uint32 = static_cast<uint32_t>(value); EXPECT_EQ(original_uint32, sys::getSwappedBytes(sys::getSwappedBytes(original_uint32))); uint64_t original_uint64 = static_cast<uint64_t>(value); EXPECT_EQ(original_uint64, sys::getSwappedBytes(sys::getSwappedBytes(original_uint64))); value = (value << 8) | 0x55; // binary 0101 0101. } } TEST(getSwappedBytes, SignedRoundTrip) { // The point of the bit twiddling of magic is to test with and without bits // in every byte. uint64_t value = 1; for (std::size_t i = 0; i <= sizeof(value); ++i) { int8_t original_int8 = static_cast<int8_t>(value); EXPECT_EQ(original_int8, sys::getSwappedBytes(sys::getSwappedBytes(original_int8))); int16_t original_int16 = static_cast<int16_t>(value); EXPECT_EQ(original_int16, sys::getSwappedBytes(sys::getSwappedBytes(original_int16))); int32_t original_int32 = static_cast<int32_t>(value); EXPECT_EQ(original_int32, sys::getSwappedBytes(sys::getSwappedBytes(original_int32))); int64_t original_int64 = static_cast<int64_t>(value); EXPECT_EQ(original_int64, sys::getSwappedBytes(sys::getSwappedBytes(original_int64))); // Test other sign. value *= -1; original_int8 = static_cast<int8_t>(value); EXPECT_EQ(original_int8, sys::getSwappedBytes(sys::getSwappedBytes(original_int8))); original_int16 = static_cast<int16_t>(value); EXPECT_EQ(original_int16, sys::getSwappedBytes(sys::getSwappedBytes(original_int16))); original_int32 = static_cast<int32_t>(value); EXPECT_EQ(original_int32, sys::getSwappedBytes(sys::getSwappedBytes(original_int32))); original_int64 = static_cast<int64_t>(value); EXPECT_EQ(original_int64, sys::getSwappedBytes(sys::getSwappedBytes(original_int64))); // Return to normal sign and twiddle. value *= -1; value = (value << 8) | 0x55; // binary 0101 0101. } } TEST(getSwappedBytes, uint8_t) { EXPECT_EQ(uint8_t(0x11), sys::getSwappedBytes(uint8_t(0x11))); } TEST(getSwappedBytes, uint16_t) { EXPECT_EQ(uint16_t(0x1122), sys::getSwappedBytes(uint16_t(0x2211))); } TEST(getSwappedBytes, uint32_t) { EXPECT_EQ(uint32_t(0x11223344), sys::getSwappedBytes(uint32_t(0x44332211))); } TEST(getSwappedBytes, uint64_t) { EXPECT_EQ(uint64_t(0x1122334455667788ULL), sys::getSwappedBytes(uint64_t(0x8877665544332211ULL))); } TEST(getSwappedBytes, int8_t) { EXPECT_EQ(int8_t(0x11), sys::getSwappedBytes(int8_t(0x11))); } TEST(getSwappedBytes, int16_t) { EXPECT_EQ(int16_t(0x1122), sys::getSwappedBytes(int16_t(0x2211))); } TEST(getSwappedBytes, int32_t) { EXPECT_EQ(int32_t(0x11223344), sys::getSwappedBytes(int32_t(0x44332211))); } TEST(getSwappedBytes, int64_t) { EXPECT_EQ(int64_t(0x1122334455667788LL), sys::getSwappedBytes(int64_t(0x8877665544332211LL))); } TEST(getSwappedBytes, float) { EXPECT_EQ(1.79366203433576585078237386661e-43f, sys::getSwappedBytes(-0.0f)); // 0x11223344 EXPECT_EQ(7.1653228759765625e2f, sys::getSwappedBytes(1.2795344e-28f)); } TEST(getSwappedBytes, double) { EXPECT_EQ(6.32404026676795576546008054871e-322, sys::getSwappedBytes(-0.0)); // 0x1122334455667788 EXPECT_EQ(-7.08687663657301358331704585496e-268, sys::getSwappedBytes(3.84141202447173065923064450234e-226)); } TEST(swapByteOrder, uint8_t) { uint8_t value = 0x11; sys::swapByteOrder(value); EXPECT_EQ(uint8_t(0x11), value); } TEST(swapByteOrder, uint16_t) { uint16_t value = 0x2211; sys::swapByteOrder(value); EXPECT_EQ(uint16_t(0x1122), value); } TEST(swapByteOrder, uint32_t) { uint32_t value = 0x44332211; sys::swapByteOrder(value); EXPECT_EQ(uint32_t(0x11223344), value); } TEST(swapByteOrder, uint64_t) { uint64_t value = 0x8877665544332211ULL; sys::swapByteOrder(value); EXPECT_EQ(uint64_t(0x1122334455667788ULL), value); } TEST(swapByteOrder, int8_t) { int8_t value = 0x11; sys::swapByteOrder(value); EXPECT_EQ(int8_t(0x11), value); } TEST(swapByteOrder, int16_t) { int16_t value = 0x2211; sys::swapByteOrder(value); EXPECT_EQ(int16_t(0x1122), value); } TEST(swapByteOrder, int32_t) { int32_t value = 0x44332211; sys::swapByteOrder(value); EXPECT_EQ(int32_t(0x11223344), value); } TEST(swapByteOrder, int64_t) { int64_t value = 0x8877665544332211LL; sys::swapByteOrder(value); EXPECT_EQ(int64_t(0x1122334455667788LL), value); } TEST(swapByteOrder, float) { float value = 7.1653228759765625e2f; // 0x44332211 sys::swapByteOrder(value); EXPECT_EQ(1.2795344e-28f, value); } TEST(swapByteOrder, double) { double value = -7.08687663657301358331704585496e-268; // 0x8877665544332211 sys::swapByteOrder(value); EXPECT_EQ(3.84141202447173065923064450234e-226, value); } }
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/Support/TimeValueTest.cpp
//===- llvm/unittest/Support/TimeValueTest.cpp - Time Value tests ---------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "gtest/gtest.h" #include "llvm/Support/TimeValue.h" #include <time.h> using namespace llvm; namespace { TEST(TimeValue, time_t) { sys::TimeValue now = sys::TimeValue::now(); time_t now_t = time(nullptr); EXPECT_TRUE(std::abs(static_cast<long>(now_t - now.toEpochTime())) < 2); } TEST(TimeValue, Win32FILETIME) { uint64_t epoch_as_filetime = 0x19DB1DED53E8000ULL; uint32_t ns = 765432100; sys::TimeValue epoch; // FILETIME has 100ns of intervals. uint64_t ft1970 = epoch_as_filetime + ns / 100; epoch.fromWin32Time(ft1970); // The "seconds" part in Posix time may be expected as zero. EXPECT_EQ(0u, epoch.toEpochTime()); EXPECT_EQ(ns, static_cast<uint32_t>(epoch.nanoseconds())); // Confirm it reversible. EXPECT_EQ(ft1970, epoch.toWin32Time()); } }
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/Support/MemoryTest.cpp
//===- llvm/unittest/Support/AllocatorTest.cpp - BumpPtrAllocator tests ---===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/Support/Memory.h" #include "llvm/Support/Process.h" #include "gtest/gtest.h" #include <cstdlib> using namespace llvm; using namespace sys; namespace { class MappedMemoryTest : public ::testing::TestWithParam<unsigned> { public: MappedMemoryTest() { Flags = GetParam(); PageSize = sys::Process::getPageSize(); } protected: // Adds RW flags to permit testing of the resulting memory unsigned getTestableEquivalent(unsigned RequestedFlags) { switch (RequestedFlags) { case Memory::MF_READ: case Memory::MF_WRITE: case Memory::MF_READ|Memory::MF_WRITE: return Memory::MF_READ|Memory::MF_WRITE; case Memory::MF_READ|Memory::MF_EXEC: case Memory::MF_READ|Memory::MF_WRITE|Memory::MF_EXEC: case Memory::MF_EXEC: return Memory::MF_READ|Memory::MF_WRITE|Memory::MF_EXEC; } // Default in case values are added to the enum, as required by some compilers return Memory::MF_READ|Memory::MF_WRITE; } // Returns true if the memory blocks overlap bool doesOverlap(MemoryBlock M1, MemoryBlock M2) { if (M1.base() == M2.base()) return true; if (M1.base() > M2.base()) return (unsigned char *)M2.base() + M2.size() > M1.base(); return (unsigned char *)M1.base() + M1.size() > M2.base(); } unsigned Flags; size_t PageSize; }; TEST_P(MappedMemoryTest, AllocAndRelease) { std::error_code EC; MemoryBlock M1 = Memory::allocateMappedMemory(sizeof(int), nullptr, Flags,EC); EXPECT_EQ(std::error_code(), EC); EXPECT_NE((void*)nullptr, M1.base()); EXPECT_LE(sizeof(int), M1.size()); EXPECT_FALSE(Memory::releaseMappedMemory(M1)); } TEST_P(MappedMemoryTest, MultipleAllocAndRelease) { std::error_code EC; MemoryBlock M1 = Memory::allocateMappedMemory(16, nullptr, Flags, EC); EXPECT_EQ(std::error_code(), EC); MemoryBlock M2 = Memory::allocateMappedMemory(64, nullptr, Flags, EC); EXPECT_EQ(std::error_code(), EC); MemoryBlock M3 = Memory::allocateMappedMemory(32, nullptr, Flags, EC); EXPECT_EQ(std::error_code(), EC); EXPECT_NE((void*)nullptr, M1.base()); EXPECT_LE(16U, M1.size()); EXPECT_NE((void*)nullptr, M2.base()); EXPECT_LE(64U, M2.size()); EXPECT_NE((void*)nullptr, M3.base()); EXPECT_LE(32U, M3.size()); EXPECT_FALSE(doesOverlap(M1, M2)); EXPECT_FALSE(doesOverlap(M2, M3)); EXPECT_FALSE(doesOverlap(M1, M3)); EXPECT_FALSE(Memory::releaseMappedMemory(M1)); EXPECT_FALSE(Memory::releaseMappedMemory(M3)); MemoryBlock M4 = Memory::allocateMappedMemory(16, nullptr, Flags, EC); EXPECT_EQ(std::error_code(), EC); EXPECT_NE((void*)nullptr, M4.base()); EXPECT_LE(16U, M4.size()); EXPECT_FALSE(Memory::releaseMappedMemory(M4)); EXPECT_FALSE(Memory::releaseMappedMemory(M2)); } TEST_P(MappedMemoryTest, BasicWrite) { // This test applies only to readable and writeable combinations if (Flags && !((Flags & Memory::MF_READ) && (Flags & Memory::MF_WRITE))) return; std::error_code EC; MemoryBlock M1 = Memory::allocateMappedMemory(sizeof(int), nullptr, Flags,EC); EXPECT_EQ(std::error_code(), EC); EXPECT_NE((void*)nullptr, M1.base()); EXPECT_LE(sizeof(int), M1.size()); int *a = (int*)M1.base(); *a = 1; EXPECT_EQ(1, *a); EXPECT_FALSE(Memory::releaseMappedMemory(M1)); } TEST_P(MappedMemoryTest, MultipleWrite) { // This test applies only to readable and writeable combinations if (Flags && !((Flags & Memory::MF_READ) && (Flags & Memory::MF_WRITE))) return; std::error_code EC; MemoryBlock M1 = Memory::allocateMappedMemory(sizeof(int), nullptr, Flags, EC); EXPECT_EQ(std::error_code(), EC); MemoryBlock M2 = Memory::allocateMappedMemory(8 * sizeof(int), nullptr, Flags, EC); EXPECT_EQ(std::error_code(), EC); MemoryBlock M3 = Memory::allocateMappedMemory(4 * sizeof(int), nullptr, Flags, EC); EXPECT_EQ(std::error_code(), EC); EXPECT_FALSE(doesOverlap(M1, M2)); EXPECT_FALSE(doesOverlap(M2, M3)); EXPECT_FALSE(doesOverlap(M1, M3)); EXPECT_NE((void*)nullptr, M1.base()); EXPECT_LE(1U * sizeof(int), M1.size()); EXPECT_NE((void*)nullptr, M2.base()); EXPECT_LE(8U * sizeof(int), M2.size()); EXPECT_NE((void*)nullptr, M3.base()); EXPECT_LE(4U * sizeof(int), M3.size()); int *x = (int*)M1.base(); *x = 1; int *y = (int*)M2.base(); for (int i = 0; i < 8; i++) { y[i] = i; } int *z = (int*)M3.base(); *z = 42; EXPECT_EQ(1, *x); EXPECT_EQ(7, y[7]); EXPECT_EQ(42, *z); EXPECT_FALSE(Memory::releaseMappedMemory(M1)); EXPECT_FALSE(Memory::releaseMappedMemory(M3)); MemoryBlock M4 = Memory::allocateMappedMemory(64 * sizeof(int), nullptr, Flags, EC); EXPECT_EQ(std::error_code(), EC); EXPECT_NE((void*)nullptr, M4.base()); EXPECT_LE(64U * sizeof(int), M4.size()); x = (int*)M4.base(); *x = 4; EXPECT_EQ(4, *x); EXPECT_FALSE(Memory::releaseMappedMemory(M4)); // Verify that M2 remains unaffected by other activity for (int i = 0; i < 8; i++) { EXPECT_EQ(i, y[i]); } EXPECT_FALSE(Memory::releaseMappedMemory(M2)); } TEST_P(MappedMemoryTest, EnabledWrite) { std::error_code EC; MemoryBlock M1 = Memory::allocateMappedMemory(2 * sizeof(int), nullptr, Flags, EC); EXPECT_EQ(std::error_code(), EC); MemoryBlock M2 = Memory::allocateMappedMemory(8 * sizeof(int), nullptr, Flags, EC); EXPECT_EQ(std::error_code(), EC); MemoryBlock M3 = Memory::allocateMappedMemory(4 * sizeof(int), nullptr, Flags, EC); EXPECT_EQ(std::error_code(), EC); EXPECT_NE((void*)nullptr, M1.base()); EXPECT_LE(2U * sizeof(int), M1.size()); EXPECT_NE((void*)nullptr, M2.base()); EXPECT_LE(8U * sizeof(int), M2.size()); EXPECT_NE((void*)nullptr, M3.base()); EXPECT_LE(4U * sizeof(int), M3.size()); EXPECT_FALSE(Memory::protectMappedMemory(M1, getTestableEquivalent(Flags))); EXPECT_FALSE(Memory::protectMappedMemory(M2, getTestableEquivalent(Flags))); EXPECT_FALSE(Memory::protectMappedMemory(M3, getTestableEquivalent(Flags))); EXPECT_FALSE(doesOverlap(M1, M2)); EXPECT_FALSE(doesOverlap(M2, M3)); EXPECT_FALSE(doesOverlap(M1, M3)); int *x = (int*)M1.base(); *x = 1; int *y = (int*)M2.base(); for (unsigned int i = 0; i < 8; i++) { y[i] = i; } int *z = (int*)M3.base(); *z = 42; EXPECT_EQ(1, *x); EXPECT_EQ(7, y[7]); EXPECT_EQ(42, *z); EXPECT_FALSE(Memory::releaseMappedMemory(M1)); EXPECT_FALSE(Memory::releaseMappedMemory(M3)); EXPECT_EQ(6, y[6]); MemoryBlock M4 = Memory::allocateMappedMemory(16, nullptr, Flags, EC); EXPECT_EQ(std::error_code(), EC); EXPECT_NE((void*)nullptr, M4.base()); EXPECT_LE(16U, M4.size()); EXPECT_EQ(std::error_code(), Memory::protectMappedMemory(M4, getTestableEquivalent(Flags))); x = (int*)M4.base(); *x = 4; EXPECT_EQ(4, *x); EXPECT_FALSE(Memory::releaseMappedMemory(M4)); EXPECT_FALSE(Memory::releaseMappedMemory(M2)); } TEST_P(MappedMemoryTest, SuccessiveNear) { std::error_code EC; MemoryBlock M1 = Memory::allocateMappedMemory(16, nullptr, Flags, EC); EXPECT_EQ(std::error_code(), EC); MemoryBlock M2 = Memory::allocateMappedMemory(64, &M1, Flags, EC); EXPECT_EQ(std::error_code(), EC); MemoryBlock M3 = Memory::allocateMappedMemory(32, &M2, Flags, EC); EXPECT_EQ(std::error_code(), EC); EXPECT_NE((void*)nullptr, M1.base()); EXPECT_LE(16U, M1.size()); EXPECT_NE((void*)nullptr, M2.base()); EXPECT_LE(64U, M2.size()); EXPECT_NE((void*)nullptr, M3.base()); EXPECT_LE(32U, M3.size()); EXPECT_FALSE(doesOverlap(M1, M2)); EXPECT_FALSE(doesOverlap(M2, M3)); EXPECT_FALSE(doesOverlap(M1, M3)); EXPECT_FALSE(Memory::releaseMappedMemory(M1)); EXPECT_FALSE(Memory::releaseMappedMemory(M3)); EXPECT_FALSE(Memory::releaseMappedMemory(M2)); } TEST_P(MappedMemoryTest, DuplicateNear) { std::error_code EC; MemoryBlock Near((void*)(3*PageSize), 16); MemoryBlock M1 = Memory::allocateMappedMemory(16, &Near, Flags, EC); EXPECT_EQ(std::error_code(), EC); MemoryBlock M2 = Memory::allocateMappedMemory(64, &Near, Flags, EC); EXPECT_EQ(std::error_code(), EC); MemoryBlock M3 = Memory::allocateMappedMemory(32, &Near, Flags, EC); EXPECT_EQ(std::error_code(), EC); EXPECT_NE((void*)nullptr, M1.base()); EXPECT_LE(16U, M1.size()); EXPECT_NE((void*)nullptr, M2.base()); EXPECT_LE(64U, M2.size()); EXPECT_NE((void*)nullptr, M3.base()); EXPECT_LE(32U, M3.size()); EXPECT_FALSE(Memory::releaseMappedMemory(M1)); EXPECT_FALSE(Memory::releaseMappedMemory(M3)); EXPECT_FALSE(Memory::releaseMappedMemory(M2)); } TEST_P(MappedMemoryTest, ZeroNear) { std::error_code EC; MemoryBlock Near(nullptr, 0); MemoryBlock M1 = Memory::allocateMappedMemory(16, &Near, Flags, EC); EXPECT_EQ(std::error_code(), EC); MemoryBlock M2 = Memory::allocateMappedMemory(64, &Near, Flags, EC); EXPECT_EQ(std::error_code(), EC); MemoryBlock M3 = Memory::allocateMappedMemory(32, &Near, Flags, EC); EXPECT_EQ(std::error_code(), EC); EXPECT_NE((void*)nullptr, M1.base()); EXPECT_LE(16U, M1.size()); EXPECT_NE((void*)nullptr, M2.base()); EXPECT_LE(64U, M2.size()); EXPECT_NE((void*)nullptr, M3.base()); EXPECT_LE(32U, M3.size()); EXPECT_FALSE(doesOverlap(M1, M2)); EXPECT_FALSE(doesOverlap(M2, M3)); EXPECT_FALSE(doesOverlap(M1, M3)); EXPECT_FALSE(Memory::releaseMappedMemory(M1)); EXPECT_FALSE(Memory::releaseMappedMemory(M3)); EXPECT_FALSE(Memory::releaseMappedMemory(M2)); } TEST_P(MappedMemoryTest, ZeroSizeNear) { std::error_code EC; MemoryBlock Near((void*)(4*PageSize), 0); MemoryBlock M1 = Memory::allocateMappedMemory(16, &Near, Flags, EC); EXPECT_EQ(std::error_code(), EC); MemoryBlock M2 = Memory::allocateMappedMemory(64, &Near, Flags, EC); EXPECT_EQ(std::error_code(), EC); MemoryBlock M3 = Memory::allocateMappedMemory(32, &Near, Flags, EC); EXPECT_EQ(std::error_code(), EC); EXPECT_NE((void*)nullptr, M1.base()); EXPECT_LE(16U, M1.size()); EXPECT_NE((void*)nullptr, M2.base()); EXPECT_LE(64U, M2.size()); EXPECT_NE((void*)nullptr, M3.base()); EXPECT_LE(32U, M3.size()); EXPECT_FALSE(doesOverlap(M1, M2)); EXPECT_FALSE(doesOverlap(M2, M3)); EXPECT_FALSE(doesOverlap(M1, M3)); EXPECT_FALSE(Memory::releaseMappedMemory(M1)); EXPECT_FALSE(Memory::releaseMappedMemory(M3)); EXPECT_FALSE(Memory::releaseMappedMemory(M2)); } TEST_P(MappedMemoryTest, UnalignedNear) { std::error_code EC; MemoryBlock Near((void*)(2*PageSize+5), 0); MemoryBlock M1 = Memory::allocateMappedMemory(15, &Near, Flags, EC); EXPECT_EQ(std::error_code(), EC); EXPECT_NE((void*)nullptr, M1.base()); EXPECT_LE(sizeof(int), M1.size()); EXPECT_FALSE(Memory::releaseMappedMemory(M1)); } // Note that Memory::MF_WRITE is not supported exclusively across // operating systems and architectures and can imply MF_READ|MF_WRITE unsigned MemoryFlags[] = { Memory::MF_READ, Memory::MF_WRITE, Memory::MF_READ|Memory::MF_WRITE, Memory::MF_EXEC, Memory::MF_READ|Memory::MF_EXEC, Memory::MF_READ|Memory::MF_WRITE|Memory::MF_EXEC }; INSTANTIATE_TEST_CASE_P(AllocationTests, MappedMemoryTest, ::testing::ValuesIn(MemoryFlags)); } // anonymous namespace
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/Support/CompressionTest.cpp
//===- llvm/unittest/Support/CompressionTest.cpp - Compression tests ------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements unit tests for the Compression functions. // //===----------------------------------------------------------------------===// #include "llvm/Support/Compression.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringRef.h" #include "llvm/Config/config.h" #include "gtest/gtest.h" using namespace llvm; namespace { #if LLVM_ENABLE_ZLIB == 1 && HAVE_LIBZ void TestZlibCompression(StringRef Input, zlib::CompressionLevel Level) { SmallString<32> Compressed; SmallString<32> Uncompressed; EXPECT_EQ(zlib::StatusOK, zlib::compress(Input, Compressed, Level)); // Check that uncompressed buffer is the same as original. EXPECT_EQ(zlib::StatusOK, zlib::uncompress(Compressed, Uncompressed, Input.size())); EXPECT_EQ(Input, Uncompressed); if (Input.size() > 0) { // Uncompression fails if expected length is too short. EXPECT_EQ(zlib::StatusBufferTooShort, zlib::uncompress(Compressed, Uncompressed, Input.size() - 1)); } } TEST(CompressionTest, Zlib) { TestZlibCompression("", zlib::DefaultCompression); TestZlibCompression("hello, world!", zlib::NoCompression); TestZlibCompression("hello, world!", zlib::BestSizeCompression); TestZlibCompression("hello, world!", zlib::BestSpeedCompression); TestZlibCompression("hello, world!", zlib::DefaultCompression); const size_t kSize = 1024; char BinaryData[kSize]; for (size_t i = 0; i < kSize; ++i) { BinaryData[i] = i & 255; } StringRef BinaryDataStr(BinaryData, kSize); TestZlibCompression(BinaryDataStr, zlib::NoCompression); TestZlibCompression(BinaryDataStr, zlib::BestSizeCompression); TestZlibCompression(BinaryDataStr, zlib::BestSpeedCompression); TestZlibCompression(BinaryDataStr, zlib::DefaultCompression); } TEST(CompressionTest, ZlibCRC32) { EXPECT_EQ( 0x414FA339U, zlib::crc32(StringRef("The quick brown fox jumps over the lazy dog"))); } #endif }
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/Support/FileOutputBufferTest.cpp
//===- llvm/unittest/Support/FileOutputBuffer.cpp - unit tests ------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/Support/Errc.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/FileOutputBuffer.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Path.h" #include "llvm/Support/raw_ostream.h" #include "gtest/gtest.h" using namespace llvm; using namespace llvm::sys; #define ASSERT_NO_ERROR(x) \ if (std::error_code ASSERT_NO_ERROR_ec = x) { \ errs() << #x ": did not return errc::success.\n" \ << "error number: " << ASSERT_NO_ERROR_ec.value() << "\n" \ << "error message: " << ASSERT_NO_ERROR_ec.message() << "\n"; \ } else { \ } namespace { TEST(FileOutputBuffer, Test) { // Create unique temporary directory for these tests SmallString<128> TestDirectory; { ASSERT_NO_ERROR( fs::createUniqueDirectory("FileOutputBuffer-test", TestDirectory)); } // TEST 1: Verify commit case. SmallString<128> File1(TestDirectory); File1.append("/file1"); { std::unique_ptr<FileOutputBuffer> Buffer; ASSERT_NO_ERROR(FileOutputBuffer::create(File1, 8192, Buffer)); // Start buffer with special header. memcpy(Buffer->getBufferStart(), "AABBCCDDEEFFGGHHIIJJ", 20); // Write to end of buffer to verify it is writable. memcpy(Buffer->getBufferEnd() - 20, "AABBCCDDEEFFGGHHIIJJ", 20); // Commit buffer. ASSERT_NO_ERROR(Buffer->commit()); } // Verify file is correct size. uint64_t File1Size; ASSERT_NO_ERROR(fs::file_size(Twine(File1), File1Size)); ASSERT_EQ(File1Size, 8192ULL); ASSERT_NO_ERROR(fs::remove(File1.str())); // TEST 2: Verify abort case. SmallString<128> File2(TestDirectory); File2.append("/file2"); { std::unique_ptr<FileOutputBuffer> Buffer2; ASSERT_NO_ERROR(FileOutputBuffer::create(File2, 8192, Buffer2)); // Fill buffer with special header. memcpy(Buffer2->getBufferStart(), "AABBCCDDEEFFGGHHIIJJ", 20); // Do *not* commit buffer. } // Verify file does not exist (because buffer not committed). ASSERT_EQ(fs::access(Twine(File2), fs::AccessMode::Exist), errc::no_such_file_or_directory); ASSERT_NO_ERROR(fs::remove(File2.str())); // TEST 3: Verify sizing down case. SmallString<128> File3(TestDirectory); File3.append("/file3"); { std::unique_ptr<FileOutputBuffer> Buffer; ASSERT_NO_ERROR(FileOutputBuffer::create(File3, 8192000, Buffer)); // Start buffer with special header. memcpy(Buffer->getBufferStart(), "AABBCCDDEEFFGGHHIIJJ", 20); // Write to end of buffer to verify it is writable. memcpy(Buffer->getBufferEnd() - 20, "AABBCCDDEEFFGGHHIIJJ", 20); ASSERT_NO_ERROR(Buffer->commit()); } // Verify file is correct size. uint64_t File3Size; ASSERT_NO_ERROR(fs::file_size(Twine(File3), File3Size)); ASSERT_EQ(File3Size, 8192000ULL); ASSERT_NO_ERROR(fs::remove(File3.str())); // TEST 4: Verify file can be made executable. SmallString<128> File4(TestDirectory); File4.append("/file4"); { std::unique_ptr<FileOutputBuffer> Buffer; ASSERT_NO_ERROR(FileOutputBuffer::create(File4, 8192, Buffer, FileOutputBuffer::F_executable)); // Start buffer with special header. memcpy(Buffer->getBufferStart(), "AABBCCDDEEFFGGHHIIJJ", 20); // Commit buffer. ASSERT_NO_ERROR(Buffer->commit()); } // Verify file exists and is executable. fs::file_status Status; ASSERT_NO_ERROR(fs::status(Twine(File4), Status)); bool IsExecutable = (Status.permissions() & fs::owner_exe); EXPECT_TRUE(IsExecutable); ASSERT_NO_ERROR(fs::remove(File4.str())); // Clean up. ASSERT_NO_ERROR(fs::remove(TestDirectory.str())); } } // anonymous namespace
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/Support/ProcessTest.cpp
//===- unittest/Support/ProcessTest.cpp -----------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/Support/Process.h" #include "gtest/gtest.h" #ifdef LLVM_ON_WIN32 #include <windows.h> #endif namespace { using namespace llvm; using namespace sys; TEST(ProcessTest, GetRandomNumberTest) { const unsigned r1 = Process::GetRandomNumber(); const unsigned r2 = Process::GetRandomNumber(); // It should be extremely unlikely that both r1 and r2 are 0. EXPECT_NE((r1 | r2), 0u); } #ifdef _MSC_VER #define setenv(name, var, ignore) _putenv_s(name, var) #endif #if HAVE_SETENV || _MSC_VER TEST(ProcessTest, Basic) { setenv("__LLVM_TEST_ENVIRON_VAR__", "abc", true); Optional<std::string> val(Process::GetEnv("__LLVM_TEST_ENVIRON_VAR__")); EXPECT_TRUE(val.hasValue()); EXPECT_STREQ("abc", val->c_str()); } TEST(ProcessTest, None) { Optional<std::string> val( Process::GetEnv("__LLVM_TEST_ENVIRON_NO_SUCH_VAR__")); EXPECT_FALSE(val.hasValue()); } #endif #ifdef LLVM_ON_WIN32 TEST(ProcessTest, Wchar) { SetEnvironmentVariableW(L"__LLVM_TEST_ENVIRON_VAR__", L"abcdefghijklmnopqrs"); Optional<std::string> val(Process::GetEnv("__LLVM_TEST_ENVIRON_VAR__")); EXPECT_TRUE(val.hasValue()); EXPECT_STREQ("abcdefghijklmnopqrs", val->c_str()); } #endif } // end anonymous namespace
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/Support/LineIteratorTest.cpp
//===- LineIterator.cpp - Unit tests --------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/Support/LineIterator.h" #include "llvm/Support/MemoryBuffer.h" #include "gtest/gtest.h" using namespace llvm; using namespace llvm::sys; namespace { TEST(LineIteratorTest, Basic) { std::unique_ptr<MemoryBuffer> Buffer = MemoryBuffer::getMemBuffer("line 1\n" "line 2\n" "line 3"); line_iterator I = line_iterator(*Buffer), E; EXPECT_FALSE(I.is_at_eof()); EXPECT_NE(E, I); EXPECT_EQ("line 1", *I); EXPECT_EQ(1, I.line_number()); ++I; EXPECT_EQ("line 2", *I); EXPECT_EQ(2, I.line_number()); ++I; EXPECT_EQ("line 3", *I); EXPECT_EQ(3, I.line_number()); ++I; EXPECT_TRUE(I.is_at_eof()); EXPECT_EQ(E, I); } TEST(LineIteratorTest, CommentAndBlankSkipping) { std::unique_ptr<MemoryBuffer> Buffer( MemoryBuffer::getMemBuffer("line 1\n" "line 2\n" "# Comment 1\n" "\n" "line 5\n" "\n" "# Comment 2")); line_iterator I = line_iterator(*Buffer, true, '#'), E; EXPECT_FALSE(I.is_at_eof()); EXPECT_NE(E, I); EXPECT_EQ("line 1", *I); EXPECT_EQ(1, I.line_number()); ++I; EXPECT_EQ("line 2", *I); EXPECT_EQ(2, I.line_number()); ++I; EXPECT_EQ("line 5", *I); EXPECT_EQ(5, I.line_number()); ++I; EXPECT_TRUE(I.is_at_eof()); EXPECT_EQ(E, I); } TEST(LineIteratorTest, CommentSkippingKeepBlanks) { std::unique_ptr<MemoryBuffer> Buffer( MemoryBuffer::getMemBuffer("line 1\n" "line 2\n" "# Comment 1\n" "# Comment 2\n" "\n" "line 6\n" "\n" "# Comment 3")); line_iterator I = line_iterator(*Buffer, false, '#'), E; EXPECT_FALSE(I.is_at_eof()); EXPECT_NE(E, I); EXPECT_EQ("line 1", *I); EXPECT_EQ(1, I.line_number()); ++I; EXPECT_EQ("line 2", *I); EXPECT_EQ(2, I.line_number()); ++I; EXPECT_EQ("", *I); EXPECT_EQ(5, I.line_number()); ++I; EXPECT_EQ("line 6", *I); EXPECT_EQ(6, I.line_number()); ++I; EXPECT_EQ("", *I); EXPECT_EQ(7, I.line_number()); ++I; EXPECT_TRUE(I.is_at_eof()); EXPECT_EQ(E, I); } TEST(LineIteratorTest, BlankSkipping) { std::unique_ptr<MemoryBuffer> Buffer = MemoryBuffer::getMemBuffer("\n\n\n" "line 1\n" "\n\n\n" "line 2\n" "\n\n\n"); line_iterator I = line_iterator(*Buffer), E; EXPECT_FALSE(I.is_at_eof()); EXPECT_NE(E, I); EXPECT_EQ("line 1", *I); EXPECT_EQ(4, I.line_number()); ++I; EXPECT_EQ("line 2", *I); EXPECT_EQ(8, I.line_number()); ++I; EXPECT_TRUE(I.is_at_eof()); EXPECT_EQ(E, I); } TEST(LineIteratorTest, BlankKeeping) { std::unique_ptr<MemoryBuffer> Buffer = MemoryBuffer::getMemBuffer("\n\n" "line 3\n" "\n" "line 5\n" "\n\n"); line_iterator I = line_iterator(*Buffer, false), E; EXPECT_FALSE(I.is_at_eof()); EXPECT_NE(E, I); EXPECT_EQ("", *I); EXPECT_EQ(1, I.line_number()); ++I; EXPECT_EQ("", *I); EXPECT_EQ(2, I.line_number()); ++I; EXPECT_EQ("line 3", *I); EXPECT_EQ(3, I.line_number()); ++I; EXPECT_EQ("", *I); EXPECT_EQ(4, I.line_number()); ++I; EXPECT_EQ("line 5", *I); EXPECT_EQ(5, I.line_number()); ++I; EXPECT_EQ("", *I); EXPECT_EQ(6, I.line_number()); ++I; EXPECT_EQ("", *I); EXPECT_EQ(7, I.line_number()); ++I; EXPECT_TRUE(I.is_at_eof()); EXPECT_EQ(E, I); } TEST(LineIteratorTest, EmptyBuffers) { std::unique_ptr<MemoryBuffer> Buffer = MemoryBuffer::getMemBuffer(""); EXPECT_TRUE(line_iterator(*Buffer).is_at_eof()); EXPECT_EQ(line_iterator(), line_iterator(*Buffer)); EXPECT_TRUE(line_iterator(*Buffer, false).is_at_eof()); EXPECT_EQ(line_iterator(), line_iterator(*Buffer, false)); Buffer = MemoryBuffer::getMemBuffer("\n\n\n"); EXPECT_TRUE(line_iterator(*Buffer).is_at_eof()); EXPECT_EQ(line_iterator(), line_iterator(*Buffer)); Buffer = MemoryBuffer::getMemBuffer("# foo\n" "\n" "# bar"); EXPECT_TRUE(line_iterator(*Buffer, true, '#').is_at_eof()); EXPECT_EQ(line_iterator(), line_iterator(*Buffer, true, '#')); Buffer = MemoryBuffer::getMemBuffer("\n" "# baz\n" "\n"); EXPECT_TRUE(line_iterator(*Buffer, true, '#').is_at_eof()); EXPECT_EQ(line_iterator(), line_iterator(*Buffer, true, '#')); } } // anonymous namespace
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/Support/raw_ostream_test.cpp
//===- llvm/unittest/Support/raw_ostream_test.cpp - raw_ostream tests -----===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "gtest/gtest.h" #include "llvm/ADT/SmallString.h" #include "llvm/Support/Format.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; namespace { template<typename T> std::string printToString(const T &Value) { std::string res; llvm::raw_string_ostream(res) << Value; return res; } /// printToString - Print the given value to a stream which only has \arg /// BytesLeftInBuffer bytes left in the buffer. This is useful for testing edge /// cases in the buffer handling logic. template<typename T> std::string printToString(const T &Value, unsigned BytesLeftInBuffer) { // FIXME: This is relying on internal knowledge of how raw_ostream works to // get the buffer position right. SmallString<256> SVec; assert(BytesLeftInBuffer < 256 && "Invalid buffer count!"); llvm::raw_svector_ostream OS(SVec); unsigned StartIndex = 256 - BytesLeftInBuffer; for (unsigned i = 0; i != StartIndex; ++i) OS << '?'; OS << Value; return OS.str().substr(StartIndex); } template<typename T> std::string printToStringUnbuffered(const T &Value) { std::string res; llvm::raw_string_ostream OS(res); OS.SetUnbuffered(); OS << Value; return res; } TEST(raw_ostreamTest, Types_Buffered) { // Char EXPECT_EQ("c", printToString('c')); // String EXPECT_EQ("hello", printToString("hello")); EXPECT_EQ("hello", printToString(std::string("hello"))); // Int EXPECT_EQ("0", printToString(0)); EXPECT_EQ("2425", printToString(2425)); EXPECT_EQ("-2425", printToString(-2425)); // Long long EXPECT_EQ("0", printToString(0LL)); EXPECT_EQ("257257257235709", printToString(257257257235709LL)); EXPECT_EQ("-257257257235709", printToString(-257257257235709LL)); // Double EXPECT_EQ("1.100000e+00", printToString(1.1)); // void* EXPECT_EQ("0x0", printToString((void*) nullptr)); EXPECT_EQ("0xbeef", printToString((void*) 0xbeef)); // HLSL Change - fix conversion EXPECT_EQ("0xdeadbeef", printToString((void*) 0xdeadbeefull)); // Min and max. EXPECT_EQ("18446744073709551615", printToString(UINT64_MAX)); EXPECT_EQ("-9223372036854775808", printToString(INT64_MIN)); } TEST(raw_ostreamTest, Types_Unbuffered) { // Char EXPECT_EQ("c", printToStringUnbuffered('c')); // String EXPECT_EQ("hello", printToStringUnbuffered("hello")); EXPECT_EQ("hello", printToStringUnbuffered(std::string("hello"))); // Int EXPECT_EQ("0", printToStringUnbuffered(0)); EXPECT_EQ("2425", printToStringUnbuffered(2425)); EXPECT_EQ("-2425", printToStringUnbuffered(-2425)); // Long long EXPECT_EQ("0", printToStringUnbuffered(0LL)); EXPECT_EQ("257257257235709", printToStringUnbuffered(257257257235709LL)); EXPECT_EQ("-257257257235709", printToStringUnbuffered(-257257257235709LL)); // Double EXPECT_EQ("1.100000e+00", printToStringUnbuffered(1.1)); // void* EXPECT_EQ("0x0", printToStringUnbuffered((void*) nullptr)); EXPECT_EQ("0xbeef", printToStringUnbuffered((void*) 0xbeef)); // HLSL Change - fix conversion EXPECT_EQ("0xdeadbeef", printToStringUnbuffered((void*) 0xdeadbeefull)); // Min and max. EXPECT_EQ("18446744073709551615", printToStringUnbuffered(UINT64_MAX)); EXPECT_EQ("-9223372036854775808", printToStringUnbuffered(INT64_MIN)); } TEST(raw_ostreamTest, BufferEdge) { EXPECT_EQ("1.20", printToString(format("%.2f", 1.2), 1)); EXPECT_EQ("1.20", printToString(format("%.2f", 1.2), 2)); EXPECT_EQ("1.20", printToString(format("%.2f", 1.2), 3)); EXPECT_EQ("1.20", printToString(format("%.2f", 1.2), 4)); EXPECT_EQ("1.20", printToString(format("%.2f", 1.2), 10)); } TEST(raw_ostreamTest, TinyBuffer) { std::string Str; raw_string_ostream OS(Str); OS.SetBufferSize(1); OS << "hello"; OS << 1; OS << 'w' << 'o' << 'r' << 'l' << 'd'; EXPECT_EQ("hello1world", OS.str()); } TEST(raw_ostreamTest, WriteEscaped) { std::string Str; Str = ""; raw_string_ostream(Str).write_escaped("hi"); EXPECT_EQ("hi", Str); Str = ""; raw_string_ostream(Str).write_escaped("\\\t\n\""); EXPECT_EQ("\\\\\\t\\n\\\"", Str); Str = ""; raw_string_ostream(Str).write_escaped("\1\10\200"); EXPECT_EQ("\\001\\010\\200", Str); } TEST(raw_ostreamTest, Justify) { EXPECT_EQ("xyz ", printToString(left_justify("xyz", 6), 6)); EXPECT_EQ("abc", printToString(left_justify("abc", 3), 3)); EXPECT_EQ("big", printToString(left_justify("big", 1), 3)); EXPECT_EQ(" xyz", printToString(right_justify("xyz", 6), 6)); EXPECT_EQ("abc", printToString(right_justify("abc", 3), 3)); EXPECT_EQ("big", printToString(right_justify("big", 1), 3)); } TEST(raw_ostreamTest, FormatHex) { EXPECT_EQ("0x1234", printToString(format_hex(0x1234, 6), 6)); EXPECT_EQ("0x001234", printToString(format_hex(0x1234, 8), 8)); EXPECT_EQ("0x00001234", printToString(format_hex(0x1234, 10), 10)); EXPECT_EQ("0x1234", printToString(format_hex(0x1234, 4), 6)); EXPECT_EQ("0xff", printToString(format_hex(255, 4), 4)); EXPECT_EQ("0xFF", printToString(format_hex(255, 4, true), 4)); EXPECT_EQ("0x1", printToString(format_hex(1, 3), 3)); EXPECT_EQ("0x12", printToString(format_hex(0x12, 3), 4)); EXPECT_EQ("0x123", printToString(format_hex(0x123, 3), 5)); EXPECT_EQ("FF", printToString(format_hex_no_prefix(0xFF, 2, true), 4)); EXPECT_EQ("ABCD", printToString(format_hex_no_prefix(0xABCD, 2, true), 4)); EXPECT_EQ("0xffffffffffffffff", printToString(format_hex(UINT64_MAX, 18), 18)); EXPECT_EQ("0x8000000000000000", printToString(format_hex((INT64_MIN), 18), 18)); } TEST(raw_ostreamTest, FormatDecimal) { EXPECT_EQ(" 0", printToString(format_decimal(0, 4), 4)); EXPECT_EQ(" -1", printToString(format_decimal(-1, 4), 4)); EXPECT_EQ(" -1", printToString(format_decimal(-1, 6), 6)); EXPECT_EQ("1234567890", printToString(format_decimal(1234567890, 10), 10)); EXPECT_EQ(" 9223372036854775807", printToString(format_decimal(INT64_MAX, 21), 21)); EXPECT_EQ(" -9223372036854775808", printToString(format_decimal(INT64_MIN, 21), 21)); } }
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/Support/StreamingMemoryObject.cpp
//===- llvm/unittest/Support/StreamingMemoryObject.cpp - unit tests -------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/ADT/STLExtras.h" #include "llvm/Support/StreamingMemoryObject.h" #include "gtest/gtest.h" #include <string.h> using namespace llvm; namespace { class NullDataStreamer : public DataStreamer { size_t GetBytes(unsigned char *buf, size_t len) override { memset(buf, 0, len); return len; } }; } TEST(StreamingMemoryObject, Test) { auto DS = make_unique<NullDataStreamer>(); StreamingMemoryObject O(std::move(DS)); EXPECT_TRUE(O.isValidAddress(32 * 1024)); } TEST(StreamingMemoryObject, TestSetKnownObjectSize) { auto DS = make_unique<NullDataStreamer>(); StreamingMemoryObject O(std::move(DS)); uint8_t Buf[32]; EXPECT_EQ((uint64_t) 16, O.readBytes(Buf, 16, 0)); O.setKnownObjectSize(24); EXPECT_EQ((uint64_t) 8, O.readBytes(Buf, 16, 16)); }
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/Support/ErrorOrTest.cpp
//===- unittests/ErrorOrTest.cpp - ErrorOr.h tests ------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/Support/ErrorOr.h" #include "llvm/Support/Errc.h" #include "gtest/gtest.h" #include <memory> using namespace llvm; namespace { ErrorOr<int> t1() {return 1;} ErrorOr<int> t2() { return errc::invalid_argument; } TEST(ErrorOr, SimpleValue) { ErrorOr<int> a = t1(); // FIXME: This is probably a bug in gtest. EXPECT_TRUE should expand to // include the !! to make it friendly to explicit bool operators. EXPECT_TRUE(!!a); EXPECT_EQ(1, *a); ErrorOr<int> b = a; EXPECT_EQ(1, *b); a = t2(); EXPECT_FALSE(a); EXPECT_EQ(a.getError(), errc::invalid_argument); #ifdef EXPECT_DEBUG_DEATH EXPECT_DEBUG_DEATH(*a, "Cannot get value when an error exists"); #endif } ErrorOr<std::unique_ptr<int> > t3() { return std::unique_ptr<int>(new int(3)); } TEST(ErrorOr, Types) { int x; ErrorOr<int&> a(x); *a = 42; EXPECT_EQ(42, x); // Move only types. EXPECT_EQ(3, **t3()); } struct B {}; struct D : B {}; TEST(ErrorOr, Covariant) { ErrorOr<B*> b(ErrorOr<D*>(nullptr)); b = ErrorOr<D*>(nullptr); ErrorOr<std::unique_ptr<B> > b1(ErrorOr<std::unique_ptr<D> >(nullptr)); b1 = ErrorOr<std::unique_ptr<D> >(nullptr); ErrorOr<std::unique_ptr<int>> b2(ErrorOr<int *>(nullptr)); ErrorOr<int *> b3(nullptr); ErrorOr<std::unique_ptr<int>> b4(b3); } TEST(ErrorOr, Comparison) { ErrorOr<int> x(errc::no_such_file_or_directory); EXPECT_EQ(x, errc::no_such_file_or_directory); } // ErrorOr<int*> x(nullptr); // ErrorOr<std::unique_ptr<int>> y = x; // invalid conversion static_assert( !std::is_convertible<const ErrorOr<int *> &, ErrorOr<std::unique_ptr<int>>>::value, "do not invoke explicit ctors in implicit conversion from lvalue"); // ErrorOr<std::unique_ptr<int>> y = ErrorOr<int*>(nullptr); // invalid // // conversion static_assert( !std::is_convertible<ErrorOr<int *> &&, ErrorOr<std::unique_ptr<int>>>::value, "do not invoke explicit ctors in implicit conversion from rvalue"); // ErrorOr<int*> x(nullptr); // ErrorOr<std::unique_ptr<int>> y; // y = x; // invalid conversion static_assert(!std::is_assignable<ErrorOr<std::unique_ptr<int>>, const ErrorOr<int *> &>::value, "do not invoke explicit ctors in assignment"); // ErrorOr<std::unique_ptr<int>> x; // x = ErrorOr<int*>(nullptr); // invalid conversion static_assert(!std::is_assignable<ErrorOr<std::unique_ptr<int>>, ErrorOr<int *> &&>::value, "do not invoke explicit ctors in assignment"); } // end anon namespace
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/Support/ProgramTest.cpp
//===- unittest/Support/ProgramTest.cpp -----------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/Support/CommandLine.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Path.h" #include "llvm/Support/Program.h" #include "gtest/gtest.h" #include <stdlib.h> #if defined(__APPLE__) # include <crt_externs.h> #elif !defined(_MSC_VER) // Forward declare environ in case it's not provided by stdlib.h. extern char **environ; #endif #if defined(LLVM_ON_UNIX) #include <unistd.h> void sleep_for(unsigned int seconds) { sleep(seconds); } #elif defined(LLVM_ON_WIN32) #include <windows.h> void sleep_for(unsigned int seconds) { Sleep(seconds * 1000); } #else #error sleep_for is not implemented on your platform. #endif #define ASSERT_NO_ERROR(x) \ if (std::error_code ASSERT_NO_ERROR_ec = x) { \ SmallString<128> MessageStorage; \ raw_svector_ostream Message(MessageStorage); \ Message << #x ": did not return errc::success.\n" \ << "error number: " << ASSERT_NO_ERROR_ec.value() << "\n" \ << "error message: " << ASSERT_NO_ERROR_ec.message() << "\n"; \ GTEST_FATAL_FAILURE_(MessageStorage.c_str()); \ } else { \ } // From TestMain.cpp. extern const char *TestMainArgv0; namespace { using namespace llvm; using namespace sys; static cl::opt<std::string> ProgramTestStringArg1("program-test-string-arg1"); static cl::opt<std::string> ProgramTestStringArg2("program-test-string-arg2"); static void CopyEnvironment(std::vector<const char *> &out) { #ifdef __APPLE__ char **envp = *_NSGetEnviron(); #else // environ seems to work for Windows and most other Unices. char **envp = environ; #endif while (*envp != nullptr) { out.push_back(*envp); ++envp; } } #ifdef LLVM_ON_WIN32 TEST(ProgramTest, CreateProcessLongPath) { if (getenv("LLVM_PROGRAM_TEST_LONG_PATH")) exit(0); // getMainExecutable returns an absolute path; prepend the long-path prefix. std::string MyAbsExe = sys::fs::getMainExecutable(TestMainArgv0, &ProgramTestStringArg1); std::string MyExe; if (!StringRef(MyAbsExe).startswith("\\\\?\\")) MyExe.append("\\\\?\\"); MyExe.append(MyAbsExe); const char *ArgV[] = { MyExe.c_str(), "--gtest_filter=ProgramTest.CreateProcessLongPath", nullptr }; // Add LLVM_PROGRAM_TEST_LONG_PATH to the environment of the child. std::vector<const char *> EnvP; CopyEnvironment(EnvP); EnvP.push_back("LLVM_PROGRAM_TEST_LONG_PATH=1"); EnvP.push_back(nullptr); // Redirect stdout to a long path. SmallString<128> TestDirectory; ASSERT_NO_ERROR( fs::createUniqueDirectory("program-redirect-test", TestDirectory)); SmallString<256> LongPath(TestDirectory); LongPath.push_back('\\'); // MAX_PATH = 260 LongPath.append(260 - TestDirectory.size(), 'a'); StringRef LongPathRef(LongPath); std::string Error; bool ExecutionFailed; const StringRef *Redirects[] = { nullptr, &LongPathRef, nullptr }; int RC = ExecuteAndWait(MyExe, ArgV, &EnvP[0], Redirects, /*secondsToWait=*/ 10, /*memoryLimit=*/ 0, &Error, &ExecutionFailed); EXPECT_FALSE(ExecutionFailed) << Error; EXPECT_EQ(0, RC); // Remove the long stdout. ASSERT_NO_ERROR(fs::remove(Twine(LongPath))); ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory))); } #endif TEST(ProgramTest, CreateProcessTrailingSlash) { if (getenv("LLVM_PROGRAM_TEST_CHILD")) { if (ProgramTestStringArg1 == "has\\\\ trailing\\" && ProgramTestStringArg2 == "has\\\\ trailing\\") { exit(0); // Success! The arguments were passed and parsed. } exit(1); } std::string my_exe = sys::fs::getMainExecutable(TestMainArgv0, &ProgramTestStringArg1); const char *argv[] = { my_exe.c_str(), "--gtest_filter=ProgramTest.CreateProcessTrailingSlash", "-program-test-string-arg1", "has\\\\ trailing\\", "-program-test-string-arg2", "has\\\\ trailing\\", nullptr }; // Add LLVM_PROGRAM_TEST_CHILD to the environment of the child. std::vector<const char *> envp; CopyEnvironment(envp); envp.push_back("LLVM_PROGRAM_TEST_CHILD=1"); envp.push_back(nullptr); std::string error; bool ExecutionFailed; // Redirect stdout and stdin to NUL, but let stderr through. #ifdef LLVM_ON_WIN32 StringRef nul("NUL"); #else StringRef nul("/dev/null"); #endif const StringRef *redirects[] = { &nul, &nul, nullptr }; int rc = ExecuteAndWait(my_exe, argv, &envp[0], redirects, /*secondsToWait=*/ 10, /*memoryLimit=*/ 0, &error, &ExecutionFailed); EXPECT_FALSE(ExecutionFailed) << error; EXPECT_EQ(0, rc); } TEST(ProgramTest, TestExecuteNoWait) { using namespace llvm::sys; if (getenv("LLVM_PROGRAM_TEST_EXECUTE_NO_WAIT")) { sleep_for(/*seconds*/ 1); exit(0); } std::string Executable = sys::fs::getMainExecutable(TestMainArgv0, &ProgramTestStringArg1); const char *argv[] = { Executable.c_str(), "--gtest_filter=ProgramTest.TestExecuteNoWait", nullptr }; // Add LLVM_PROGRAM_TEST_EXECUTE_NO_WAIT to the environment of the child. std::vector<const char *> envp; CopyEnvironment(envp); envp.push_back("LLVM_PROGRAM_TEST_EXECUTE_NO_WAIT=1"); envp.push_back(nullptr); std::string Error; bool ExecutionFailed; ProcessInfo PI1 = ExecuteNoWait(Executable, argv, &envp[0], nullptr, 0, &Error, &ExecutionFailed); ASSERT_FALSE(ExecutionFailed) << Error; ASSERT_NE(PI1.Pid, ProcessInfo::InvalidPid) << "Invalid process id"; unsigned LoopCount = 0; // Test that Wait() with WaitUntilTerminates=true works. In this case, // LoopCount should only be incremented once. while (true) { ++LoopCount; ProcessInfo WaitResult = Wait(PI1, 0, true, &Error); ASSERT_TRUE(Error.empty()); if (WaitResult.Pid == PI1.Pid) break; } EXPECT_EQ(LoopCount, 1u) << "LoopCount should be 1"; ProcessInfo PI2 = ExecuteNoWait(Executable, argv, &envp[0], nullptr, 0, &Error, &ExecutionFailed); ASSERT_FALSE(ExecutionFailed) << Error; ASSERT_NE(PI2.Pid, ProcessInfo::InvalidPid) << "Invalid process id"; // Test that Wait() with SecondsToWait=0 performs a non-blocking wait. In this // cse, LoopCount should be greater than 1 (more than one increment occurs). while (true) { ++LoopCount; ProcessInfo WaitResult = Wait(PI2, 0, false, &Error); ASSERT_TRUE(Error.empty()); if (WaitResult.Pid == PI2.Pid) break; } ASSERT_GT(LoopCount, 1u) << "LoopCount should be >1"; } TEST(ProgramTest, TestExecuteAndWaitTimeout) { using namespace llvm::sys; if (getenv("LLVM_PROGRAM_TEST_TIMEOUT")) { sleep_for(/*seconds*/ 10); exit(0); } std::string Executable = sys::fs::getMainExecutable(TestMainArgv0, &ProgramTestStringArg1); const char *argv[] = { Executable.c_str(), "--gtest_filter=ProgramTest.TestExecuteAndWaitTimeout", nullptr }; // Add LLVM_PROGRAM_TEST_TIMEOUT to the environment of the child. std::vector<const char *> envp; CopyEnvironment(envp); envp.push_back("LLVM_PROGRAM_TEST_TIMEOUT=1"); envp.push_back(nullptr); std::string Error; bool ExecutionFailed; int RetCode = ExecuteAndWait(Executable, argv, &envp[0], nullptr, /*secondsToWait=*/1, 0, &Error, &ExecutionFailed); ASSERT_EQ(-2, RetCode); } TEST(ProgramTest, TestExecuteNegative) { std::string Executable = "i_dont_exist"; const char *argv[] = { Executable.c_str(), nullptr }; { std::string Error; bool ExecutionFailed; int RetCode = ExecuteAndWait(Executable, argv, nullptr, nullptr, 0, 0, &Error, &ExecutionFailed); ASSERT_TRUE(RetCode < 0) << "On error ExecuteAndWait should return 0 or " "positive value indicating the result code"; ASSERT_TRUE(ExecutionFailed); ASSERT_FALSE(Error.empty()); } { std::string Error; bool ExecutionFailed; ProcessInfo PI = ExecuteNoWait(Executable, argv, nullptr, nullptr, 0, &Error, &ExecutionFailed); ASSERT_EQ(PI.Pid, ProcessInfo::InvalidPid) << "On error ExecuteNoWait should return an invalid ProcessInfo"; ASSERT_TRUE(ExecutionFailed); ASSERT_FALSE(Error.empty()); } } #ifdef LLVM_ON_WIN32 const char utf16le_text[] = "\x6c\x00\x69\x00\x6e\x00\x67\x00\xfc\x00\x69\x00\xe7\x00\x61\x00"; const char utf16be_text[] = "\x00\x6c\x00\x69\x00\x6e\x00\x67\x00\xfc\x00\x69\x00\xe7\x00\x61"; #endif const char utf8_text[] = "\x6c\x69\x6e\x67\xc3\xbc\x69\xc3\xa7\x61"; TEST(ProgramTest, TestWriteWithSystemEncoding) { SmallString<128> TestDirectory; ASSERT_NO_ERROR(fs::createUniqueDirectory("program-test", TestDirectory)); errs() << "Test Directory: " << TestDirectory << '\n'; errs().flush(); SmallString<128> file_pathname(TestDirectory); path::append(file_pathname, "international-file.txt"); // Only on Windows we should encode in UTF16. For other systems, use UTF8 ASSERT_NO_ERROR(sys::writeFileWithEncoding(file_pathname.c_str(), utf8_text, sys::WEM_UTF16)); int fd = 0; ASSERT_NO_ERROR(fs::openFileForRead(file_pathname.c_str(), fd)); #if defined(LLVM_ON_WIN32) char buf[18]; ASSERT_EQ(::read(fd, buf, 18), 18); if (strncmp(buf, "\xfe\xff", 2) == 0) { // UTF16-BE ASSERT_EQ(strncmp(&buf[2], utf16be_text, 16), 0); } else if (strncmp(buf, "\xff\xfe", 2) == 0) { // UTF16-LE ASSERT_EQ(strncmp(&buf[2], utf16le_text, 16), 0); } else { FAIL() << "Invalid BOM in UTF-16 file"; } #else char buf[10]; ASSERT_EQ(::read(fd, buf, 10), 10); ASSERT_EQ(strncmp(buf, utf8_text, 10), 0); #endif ::close(fd); ASSERT_NO_ERROR(fs::remove(file_pathname.str())); ASSERT_NO_ERROR(fs::remove(TestDirectory.str())); } } // end anonymous namespace
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/Support/YAMLIOTest.cpp
//===- unittest/Support/YAMLIOTest.cpp ------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/ADT/SmallString.h" #include "llvm/ADT/Twine.h" #include "llvm/Support/Casting.h" #include "llvm/Support/Format.h" #include "llvm/Support/YAMLTraits.h" #include "gtest/gtest.h" using llvm::yaml::Input; using llvm::yaml::Output; using llvm::yaml::IO; using llvm::yaml::MappingTraits; using llvm::yaml::MappingNormalization; using llvm::yaml::ScalarTraits; using llvm::yaml::Hex8; using llvm::yaml::Hex16; using llvm::yaml::Hex32; using llvm::yaml::Hex64; static void suppressErrorMessages(const llvm::SMDiagnostic &, void *) { } //===----------------------------------------------------------------------===// // Test MappingTraits //===----------------------------------------------------------------------===// struct FooBar { int foo; int bar; }; typedef std::vector<FooBar> FooBarSequence; LLVM_YAML_IS_SEQUENCE_VECTOR(FooBar) struct FooBarContainer { FooBarSequence fbs; }; namespace llvm { namespace yaml { template <> struct MappingTraits<FooBar> { static void mapping(IO &io, FooBar& fb) { io.mapRequired("foo", fb.foo); io.mapRequired("bar", fb.bar); } }; template <> struct MappingTraits<FooBarContainer> { static void mapping(IO &io, FooBarContainer &fb) { io.mapRequired("fbs", fb.fbs); } }; } } // // Test the reading of a yaml mapping // TEST(YAMLIO, TestMapRead) { FooBar doc; { Input yin("---\nfoo: 3\nbar: 5\n...\n"); yin >> doc; EXPECT_FALSE(yin.error()); EXPECT_EQ(doc.foo, 3); EXPECT_EQ(doc.bar, 5); } { Input yin("{foo: 3, bar: 5}"); yin >> doc; EXPECT_FALSE(yin.error()); EXPECT_EQ(doc.foo, 3); EXPECT_EQ(doc.bar, 5); } } TEST(YAMLIO, TestMalformedMapRead) { FooBar doc; Input yin("{foo: 3; bar: 5}", nullptr, suppressErrorMessages); yin >> doc; EXPECT_TRUE(!!yin.error()); } // // Test the reading of a yaml sequence of mappings // TEST(YAMLIO, TestSequenceMapRead) { FooBarSequence seq; Input yin("---\n - foo: 3\n bar: 5\n - foo: 7\n bar: 9\n...\n"); yin >> seq; EXPECT_FALSE(yin.error()); EXPECT_EQ(seq.size(), 2UL); FooBar& map1 = seq[0]; FooBar& map2 = seq[1]; EXPECT_EQ(map1.foo, 3); EXPECT_EQ(map1.bar, 5); EXPECT_EQ(map2.foo, 7); EXPECT_EQ(map2.bar, 9); } // // Test the reading of a map containing a yaml sequence of mappings // TEST(YAMLIO, TestContainerSequenceMapRead) { { FooBarContainer cont; Input yin2("---\nfbs:\n - foo: 3\n bar: 5\n - foo: 7\n bar: 9\n...\n"); yin2 >> cont; EXPECT_FALSE(yin2.error()); EXPECT_EQ(cont.fbs.size(), 2UL); EXPECT_EQ(cont.fbs[0].foo, 3); EXPECT_EQ(cont.fbs[0].bar, 5); EXPECT_EQ(cont.fbs[1].foo, 7); EXPECT_EQ(cont.fbs[1].bar, 9); } { FooBarContainer cont; Input yin("---\nfbs:\n...\n"); yin >> cont; // Okay: Empty node represents an empty array. EXPECT_FALSE(yin.error()); EXPECT_EQ(cont.fbs.size(), 0UL); } { FooBarContainer cont; Input yin("---\nfbs: !!null null\n...\n"); yin >> cont; // Okay: null represents an empty array. EXPECT_FALSE(yin.error()); EXPECT_EQ(cont.fbs.size(), 0UL); } { FooBarContainer cont; Input yin("---\nfbs: ~\n...\n"); yin >> cont; // Okay: null represents an empty array. EXPECT_FALSE(yin.error()); EXPECT_EQ(cont.fbs.size(), 0UL); } { FooBarContainer cont; Input yin("---\nfbs: null\n...\n"); yin >> cont; // Okay: null represents an empty array. EXPECT_FALSE(yin.error()); EXPECT_EQ(cont.fbs.size(), 0UL); } } // // Test the reading of a map containing a malformed yaml sequence // TEST(YAMLIO, TestMalformedContainerSequenceMapRead) { { FooBarContainer cont; Input yin("---\nfbs:\n foo: 3\n bar: 5\n...\n", nullptr, suppressErrorMessages); yin >> cont; // Error: fbs is not a sequence. EXPECT_TRUE(!!yin.error()); EXPECT_EQ(cont.fbs.size(), 0UL); } { FooBarContainer cont; Input yin("---\nfbs: 'scalar'\n...\n", nullptr, suppressErrorMessages); yin >> cont; // This should be an error. EXPECT_TRUE(!!yin.error()); EXPECT_EQ(cont.fbs.size(), 0UL); } } // // Test writing then reading back a sequence of mappings // TEST(YAMLIO, TestSequenceMapWriteAndRead) { std::string intermediate; { FooBar entry1; entry1.foo = 10; entry1.bar = -3; FooBar entry2; entry2.foo = 257; entry2.bar = 0; FooBarSequence seq; seq.push_back(entry1); seq.push_back(entry2); llvm::raw_string_ostream ostr(intermediate); Output yout(ostr); yout << seq; } { Input yin(intermediate); FooBarSequence seq2; yin >> seq2; EXPECT_FALSE(yin.error()); EXPECT_EQ(seq2.size(), 2UL); FooBar& map1 = seq2[0]; FooBar& map2 = seq2[1]; EXPECT_EQ(map1.foo, 10); EXPECT_EQ(map1.bar, -3); EXPECT_EQ(map2.foo, 257); EXPECT_EQ(map2.bar, 0); } } //===----------------------------------------------------------------------===// // Test built-in types //===----------------------------------------------------------------------===// struct BuiltInTypes { llvm::StringRef str; std::string stdstr; uint64_t u64; uint32_t u32; uint16_t u16; uint8_t u8; bool b; int64_t s64; int32_t s32; int16_t s16; int8_t s8; float f; double d; Hex8 h8; Hex16 h16; Hex32 h32; Hex64 h64; }; namespace llvm { namespace yaml { template <> struct MappingTraits<BuiltInTypes> { static void mapping(IO &io, BuiltInTypes& bt) { io.mapRequired("str", bt.str); io.mapRequired("stdstr", bt.stdstr); io.mapRequired("u64", bt.u64); io.mapRequired("u32", bt.u32); io.mapRequired("u16", bt.u16); io.mapRequired("u8", bt.u8); io.mapRequired("b", bt.b); io.mapRequired("s64", bt.s64); io.mapRequired("s32", bt.s32); io.mapRequired("s16", bt.s16); io.mapRequired("s8", bt.s8); io.mapRequired("f", bt.f); io.mapRequired("d", bt.d); io.mapRequired("h8", bt.h8); io.mapRequired("h16", bt.h16); io.mapRequired("h32", bt.h32); io.mapRequired("h64", bt.h64); } }; } } // // Test the reading of all built-in scalar conversions // TEST(YAMLIO, TestReadBuiltInTypes) { BuiltInTypes map; Input yin("---\n" "str: hello there\n" "stdstr: hello where?\n" "u64: 5000000000\n" "u32: 4000000000\n" "u16: 65000\n" "u8: 255\n" "b: false\n" "s64: -5000000000\n" "s32: -2000000000\n" "s16: -32000\n" "s8: -127\n" "f: 137.125\n" "d: -2.8625\n" "h8: 0xFF\n" "h16: 0x8765\n" "h32: 0xFEDCBA98\n" "h64: 0xFEDCBA9876543210\n" "...\n"); yin >> map; EXPECT_FALSE(yin.error()); EXPECT_TRUE(map.str.equals("hello there")); EXPECT_TRUE(map.stdstr == "hello where?"); EXPECT_EQ(map.u64, 5000000000ULL); EXPECT_EQ(map.u32, 4000000000U); EXPECT_EQ(map.u16, 65000); EXPECT_EQ(map.u8, 255); EXPECT_EQ(map.b, false); EXPECT_EQ(map.s64, -5000000000LL); EXPECT_EQ(map.s32, -2000000000L); EXPECT_EQ(map.s16, -32000); EXPECT_EQ(map.s8, -127); EXPECT_EQ(map.f, 137.125); EXPECT_EQ(map.d, -2.8625); EXPECT_EQ(map.h8, Hex8(255)); EXPECT_EQ(map.h16, Hex16(0x8765)); EXPECT_EQ(map.h32, Hex32(0xFEDCBA98)); EXPECT_EQ(map.h64, Hex64(0xFEDCBA9876543210LL)); } // // Test writing then reading back all built-in scalar types // TEST(YAMLIO, TestReadWriteBuiltInTypes) { std::string intermediate; { BuiltInTypes map; map.str = "one two"; map.stdstr = "three four"; map.u64 = 6000000000ULL; map.u32 = 3000000000U; map.u16 = 50000; map.u8 = 254; map.b = true; map.s64 = -6000000000LL; map.s32 = -2000000000; map.s16 = -32000; map.s8 = -128; map.f = 3.25; map.d = -2.8625; map.h8 = 254; map.h16 = 50000; map.h32 = 3000000000U; map.h64 = 6000000000LL; llvm::raw_string_ostream ostr(intermediate); Output yout(ostr); yout << map; } { Input yin(intermediate); BuiltInTypes map; yin >> map; EXPECT_FALSE(yin.error()); EXPECT_TRUE(map.str.equals("one two")); EXPECT_TRUE(map.stdstr == "three four"); EXPECT_EQ(map.u64, 6000000000ULL); EXPECT_EQ(map.u32, 3000000000U); EXPECT_EQ(map.u16, 50000); EXPECT_EQ(map.u8, 254); EXPECT_EQ(map.b, true); EXPECT_EQ(map.s64, -6000000000LL); EXPECT_EQ(map.s32, -2000000000L); EXPECT_EQ(map.s16, -32000); EXPECT_EQ(map.s8, -128); EXPECT_EQ(map.f, 3.25); EXPECT_EQ(map.d, -2.8625); EXPECT_EQ(map.h8, Hex8(254)); EXPECT_EQ(map.h16, Hex16(50000)); EXPECT_EQ(map.h32, Hex32(3000000000U)); EXPECT_EQ(map.h64, Hex64(6000000000LL)); } } struct StringTypes { llvm::StringRef str1; llvm::StringRef str2; llvm::StringRef str3; llvm::StringRef str4; llvm::StringRef str5; llvm::StringRef str6; llvm::StringRef str7; llvm::StringRef str8; llvm::StringRef str9; llvm::StringRef str10; llvm::StringRef str11; std::string stdstr1; std::string stdstr2; std::string stdstr3; std::string stdstr4; std::string stdstr5; std::string stdstr6; std::string stdstr7; std::string stdstr8; std::string stdstr9; std::string stdstr10; std::string stdstr11; }; namespace llvm { namespace yaml { template <> struct MappingTraits<StringTypes> { static void mapping(IO &io, StringTypes& st) { io.mapRequired("str1", st.str1); io.mapRequired("str2", st.str2); io.mapRequired("str3", st.str3); io.mapRequired("str4", st.str4); io.mapRequired("str5", st.str5); io.mapRequired("str6", st.str6); io.mapRequired("str7", st.str7); io.mapRequired("str8", st.str8); io.mapRequired("str9", st.str9); io.mapRequired("str10", st.str10); io.mapRequired("str11", st.str11); io.mapRequired("stdstr1", st.stdstr1); io.mapRequired("stdstr2", st.stdstr2); io.mapRequired("stdstr3", st.stdstr3); io.mapRequired("stdstr4", st.stdstr4); io.mapRequired("stdstr5", st.stdstr5); io.mapRequired("stdstr6", st.stdstr6); io.mapRequired("stdstr7", st.stdstr7); io.mapRequired("stdstr8", st.stdstr8); io.mapRequired("stdstr9", st.stdstr9); io.mapRequired("stdstr10", st.stdstr10); io.mapRequired("stdstr11", st.stdstr11); } }; } } TEST(YAMLIO, TestReadWriteStringTypes) { std::string intermediate; { StringTypes map; map.str1 = "'aaa"; map.str2 = "\"bbb"; map.str3 = "`ccc"; map.str4 = "@ddd"; map.str5 = ""; map.str6 = "0000000004000000"; map.str7 = "true"; map.str8 = "FALSE"; map.str9 = "~"; map.str10 = "0.2e20"; map.str11 = "0x30"; map.stdstr1 = "'eee"; map.stdstr2 = "\"fff"; map.stdstr3 = "`ggg"; map.stdstr4 = "@hhh"; map.stdstr5 = ""; map.stdstr6 = "0000000004000000"; map.stdstr7 = "true"; map.stdstr8 = "FALSE"; map.stdstr9 = "~"; map.stdstr10 = "0.2e20"; map.stdstr11 = "0x30"; llvm::raw_string_ostream ostr(intermediate); Output yout(ostr); yout << map; } llvm::StringRef flowOut(intermediate); EXPECT_NE(llvm::StringRef::npos, flowOut.find("'''aaa")); EXPECT_NE(llvm::StringRef::npos, flowOut.find("'\"bbb'")); EXPECT_NE(llvm::StringRef::npos, flowOut.find("'`ccc'")); EXPECT_NE(llvm::StringRef::npos, flowOut.find("'@ddd'")); EXPECT_NE(llvm::StringRef::npos, flowOut.find("''\n")); EXPECT_NE(llvm::StringRef::npos, flowOut.find("'0000000004000000'\n")); EXPECT_NE(llvm::StringRef::npos, flowOut.find("'true'\n")); EXPECT_NE(llvm::StringRef::npos, flowOut.find("'FALSE'\n")); EXPECT_NE(llvm::StringRef::npos, flowOut.find("'~'\n")); EXPECT_NE(llvm::StringRef::npos, flowOut.find("'0.2e20'\n")); EXPECT_NE(llvm::StringRef::npos, flowOut.find("'0x30'\n")); EXPECT_NE(std::string::npos, flowOut.find("'''eee")); EXPECT_NE(std::string::npos, flowOut.find("'\"fff'")); EXPECT_NE(std::string::npos, flowOut.find("'`ggg'")); EXPECT_NE(std::string::npos, flowOut.find("'@hhh'")); EXPECT_NE(std::string::npos, flowOut.find("''\n")); EXPECT_NE(std::string::npos, flowOut.find("'0000000004000000'\n")); { Input yin(intermediate); StringTypes map; yin >> map; EXPECT_FALSE(yin.error()); EXPECT_TRUE(map.str1.equals("'aaa")); EXPECT_TRUE(map.str2.equals("\"bbb")); EXPECT_TRUE(map.str3.equals("`ccc")); EXPECT_TRUE(map.str4.equals("@ddd")); EXPECT_TRUE(map.str5.equals("")); EXPECT_TRUE(map.str6.equals("0000000004000000")); EXPECT_TRUE(map.stdstr1 == "'eee"); EXPECT_TRUE(map.stdstr2 == "\"fff"); EXPECT_TRUE(map.stdstr3 == "`ggg"); EXPECT_TRUE(map.stdstr4 == "@hhh"); EXPECT_TRUE(map.stdstr5 == ""); EXPECT_TRUE(map.stdstr6 == "0000000004000000"); } } //===----------------------------------------------------------------------===// // Test ScalarEnumerationTraits //===----------------------------------------------------------------------===// enum Colors { cRed, cBlue, cGreen, cYellow }; struct ColorMap { Colors c1; Colors c2; Colors c3; Colors c4; Colors c5; Colors c6; }; namespace llvm { namespace yaml { template <> struct ScalarEnumerationTraits<Colors> { static void enumeration(IO &io, Colors &value) { io.enumCase(value, "red", cRed); io.enumCase(value, "blue", cBlue); io.enumCase(value, "green", cGreen); io.enumCase(value, "yellow",cYellow); } }; template <> struct MappingTraits<ColorMap> { static void mapping(IO &io, ColorMap& c) { io.mapRequired("c1", c.c1); io.mapRequired("c2", c.c2); io.mapRequired("c3", c.c3); io.mapOptional("c4", c.c4, cBlue); // supplies default io.mapOptional("c5", c.c5, cYellow); // supplies default io.mapOptional("c6", c.c6, cRed); // supplies default } }; } } // // Test reading enumerated scalars // TEST(YAMLIO, TestEnumRead) { ColorMap map; Input yin("---\n" "c1: blue\n" "c2: red\n" "c3: green\n" "c5: yellow\n" "...\n"); yin >> map; EXPECT_FALSE(yin.error()); EXPECT_EQ(cBlue, map.c1); EXPECT_EQ(cRed, map.c2); EXPECT_EQ(cGreen, map.c3); EXPECT_EQ(cBlue, map.c4); // tests default EXPECT_EQ(cYellow,map.c5); // tests overridden EXPECT_EQ(cRed, map.c6); // tests default } //===----------------------------------------------------------------------===// // Test ScalarBitSetTraits //===----------------------------------------------------------------------===// enum MyFlags { flagNone = 0, flagBig = 1 << 0, flagFlat = 1 << 1, flagRound = 1 << 2, flagPointy = 1 << 3 }; inline MyFlags operator|(MyFlags a, MyFlags b) { return static_cast<MyFlags>( static_cast<uint32_t>(a) | static_cast<uint32_t>(b)); } struct FlagsMap { MyFlags f1; MyFlags f2; MyFlags f3; MyFlags f4; }; namespace llvm { namespace yaml { template <> struct ScalarBitSetTraits<MyFlags> { static void bitset(IO &io, MyFlags &value) { io.bitSetCase(value, "big", flagBig); io.bitSetCase(value, "flat", flagFlat); io.bitSetCase(value, "round", flagRound); io.bitSetCase(value, "pointy",flagPointy); } }; template <> struct MappingTraits<FlagsMap> { static void mapping(IO &io, FlagsMap& c) { io.mapRequired("f1", c.f1); io.mapRequired("f2", c.f2); io.mapRequired("f3", c.f3); io.mapOptional("f4", c.f4, MyFlags(flagRound)); } }; } } // // Test reading flow sequence representing bit-mask values // TEST(YAMLIO, TestFlagsRead) { FlagsMap map; Input yin("---\n" "f1: [ big ]\n" "f2: [ round, flat ]\n" "f3: []\n" "...\n"); yin >> map; EXPECT_FALSE(yin.error()); EXPECT_EQ(flagBig, map.f1); EXPECT_EQ(flagRound|flagFlat, map.f2); EXPECT_EQ(flagNone, map.f3); // check empty set EXPECT_EQ(flagRound, map.f4); // check optional key } // // Test writing then reading back bit-mask values // TEST(YAMLIO, TestReadWriteFlags) { std::string intermediate; { FlagsMap map; map.f1 = flagBig; map.f2 = flagRound | flagFlat; map.f3 = flagNone; map.f4 = flagNone; llvm::raw_string_ostream ostr(intermediate); Output yout(ostr); yout << map; } { Input yin(intermediate); FlagsMap map2; yin >> map2; EXPECT_FALSE(yin.error()); EXPECT_EQ(flagBig, map2.f1); EXPECT_EQ(flagRound|flagFlat, map2.f2); EXPECT_EQ(flagNone, map2.f3); //EXPECT_EQ(flagRound, map2.f4); // check optional key } } //===----------------------------------------------------------------------===// // Test ScalarTraits //===----------------------------------------------------------------------===// struct MyCustomType { int length; int width; }; struct MyCustomTypeMap { MyCustomType f1; MyCustomType f2; int f3; }; namespace llvm { namespace yaml { template <> struct MappingTraits<MyCustomTypeMap> { static void mapping(IO &io, MyCustomTypeMap& s) { io.mapRequired("f1", s.f1); io.mapRequired("f2", s.f2); io.mapRequired("f3", s.f3); } }; // MyCustomType is formatted as a yaml scalar. A value of // {length=3, width=4} would be represented in yaml as "3 by 4". template<> struct ScalarTraits<MyCustomType> { static void output(const MyCustomType &value, void* ctxt, llvm::raw_ostream &out) { out << llvm::format("%d by %d", value.length, value.width); } static StringRef input(StringRef scalar, void* ctxt, MyCustomType &value) { size_t byStart = scalar.find("by"); if ( byStart != StringRef::npos ) { StringRef lenStr = scalar.slice(0, byStart); lenStr = lenStr.rtrim(); if ( lenStr.getAsInteger(0, value.length) ) { return "malformed length"; } StringRef widthStr = scalar.drop_front(byStart+2); widthStr = widthStr.ltrim(); if ( widthStr.getAsInteger(0, value.width) ) { return "malformed width"; } return StringRef(); } else { return "malformed by"; } } static bool mustQuote(StringRef) { return true; } }; } } // // Test writing then reading back custom values // TEST(YAMLIO, TestReadWriteMyCustomType) { std::string intermediate; { MyCustomTypeMap map; map.f1.length = 1; map.f1.width = 4; map.f2.length = 100; map.f2.width = 400; map.f3 = 10; llvm::raw_string_ostream ostr(intermediate); Output yout(ostr); yout << map; } { Input yin(intermediate); MyCustomTypeMap map2; yin >> map2; EXPECT_FALSE(yin.error()); EXPECT_EQ(1, map2.f1.length); EXPECT_EQ(4, map2.f1.width); EXPECT_EQ(100, map2.f2.length); EXPECT_EQ(400, map2.f2.width); EXPECT_EQ(10, map2.f3); } } //===----------------------------------------------------------------------===// // Test BlockScalarTraits //===----------------------------------------------------------------------===// struct MultilineStringType { std::string str; }; struct MultilineStringTypeMap { MultilineStringType name; MultilineStringType description; MultilineStringType ingredients; MultilineStringType recipes; MultilineStringType warningLabels; MultilineStringType documentation; int price; }; namespace llvm { namespace yaml { template <> struct MappingTraits<MultilineStringTypeMap> { static void mapping(IO &io, MultilineStringTypeMap& s) { io.mapRequired("name", s.name); io.mapRequired("description", s.description); io.mapRequired("ingredients", s.ingredients); io.mapRequired("recipes", s.recipes); io.mapRequired("warningLabels", s.warningLabels); io.mapRequired("documentation", s.documentation); io.mapRequired("price", s.price); } }; // MultilineStringType is formatted as a yaml block literal scalar. A value of // "Hello\nWorld" would be represented in yaml as // | // Hello // World template <> struct BlockScalarTraits<MultilineStringType> { static void output(const MultilineStringType &value, void *ctxt, llvm::raw_ostream &out) { out << value.str; } static StringRef input(StringRef scalar, void *ctxt, MultilineStringType &value) { value.str = scalar.str(); return StringRef(); } }; } } LLVM_YAML_IS_DOCUMENT_LIST_VECTOR(MultilineStringType) // // Test writing then reading back custom values // TEST(YAMLIO, TestReadWriteMultilineStringType) { std::string intermediate; { MultilineStringTypeMap map; map.name.str = "An Item"; map.description.str = "Hello\nWorld"; map.ingredients.str = "SubItem 1\nSub Item 2\n\nSub Item 3\n"; map.recipes.str = "\n\nTest 1\n\n\n"; map.warningLabels.str = ""; map.documentation.str = "\n\n"; map.price = 350; llvm::raw_string_ostream ostr(intermediate); Output yout(ostr); yout << map; } { Input yin(intermediate); MultilineStringTypeMap map2; yin >> map2; EXPECT_FALSE(yin.error()); EXPECT_EQ(map2.name.str, "An Item\n"); EXPECT_EQ(map2.description.str, "Hello\nWorld\n"); EXPECT_EQ(map2.ingredients.str, "SubItem 1\nSub Item 2\n\nSub Item 3\n"); EXPECT_EQ(map2.recipes.str, "\n\nTest 1\n"); EXPECT_TRUE(map2.warningLabels.str.empty()); EXPECT_TRUE(map2.documentation.str.empty()); EXPECT_EQ(map2.price, 350); } } // // Test writing then reading back custom values // TEST(YAMLIO, TestReadWriteBlockScalarDocuments) { std::string intermediate; { std::vector<MultilineStringType> documents; MultilineStringType doc; doc.str = "Hello\nWorld"; documents.push_back(doc); llvm::raw_string_ostream ostr(intermediate); Output yout(ostr); yout << documents; // Verify that the block scalar header was written out on the same line // as the document marker. EXPECT_NE(llvm::StringRef::npos, llvm::StringRef(ostr.str()).find("--- |")); } { Input yin(intermediate); std::vector<MultilineStringType> documents2; yin >> documents2; EXPECT_FALSE(yin.error()); EXPECT_EQ(documents2.size(), size_t(1)); EXPECT_EQ(documents2[0].str, "Hello\nWorld\n"); } } TEST(YAMLIO, TestReadWriteBlockScalarValue) { std::string intermediate; { MultilineStringType doc; doc.str = "Just a block\nscalar doc"; llvm::raw_string_ostream ostr(intermediate); Output yout(ostr); yout << doc; } { Input yin(intermediate); MultilineStringType doc; yin >> doc; EXPECT_FALSE(yin.error()); EXPECT_EQ(doc.str, "Just a block\nscalar doc\n"); } } //===----------------------------------------------------------------------===// // Test flow sequences //===----------------------------------------------------------------------===// LLVM_YAML_STRONG_TYPEDEF(int, MyNumber) LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(MyNumber) LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(llvm::StringRef) namespace llvm { namespace yaml { template<> struct ScalarTraits<MyNumber> { static void output(const MyNumber &value, void *, llvm::raw_ostream &out) { out << value; } static StringRef input(StringRef scalar, void *, MyNumber &value) { long long n; if ( getAsSignedInteger(scalar, 0, n) ) return "invalid number"; value = n; return StringRef(); } static bool mustQuote(StringRef) { return false; } }; } } struct NameAndNumbers { llvm::StringRef name; std::vector<llvm::StringRef> strings; std::vector<MyNumber> single; std::vector<MyNumber> numbers; }; namespace llvm { namespace yaml { template <> struct MappingTraits<NameAndNumbers> { static void mapping(IO &io, NameAndNumbers& nn) { io.mapRequired("name", nn.name); io.mapRequired("strings", nn.strings); io.mapRequired("single", nn.single); io.mapRequired("numbers", nn.numbers); } }; } } typedef std::vector<MyNumber> MyNumberFlowSequence; LLVM_YAML_IS_SEQUENCE_VECTOR(MyNumberFlowSequence) struct NameAndNumbersFlow { llvm::StringRef name; std::vector<MyNumberFlowSequence> sequenceOfNumbers; }; namespace llvm { namespace yaml { template <> struct MappingTraits<NameAndNumbersFlow> { static void mapping(IO &io, NameAndNumbersFlow& nn) { io.mapRequired("name", nn.name); io.mapRequired("sequenceOfNumbers", nn.sequenceOfNumbers); } }; } } // // Test writing then reading back custom values // TEST(YAMLIO, TestReadWriteMyFlowSequence) { std::string intermediate; { NameAndNumbers map; map.name = "hello"; map.strings.push_back(llvm::StringRef("one")); map.strings.push_back(llvm::StringRef("two")); map.single.push_back(1); map.numbers.push_back(10); map.numbers.push_back(-30); map.numbers.push_back(1024); llvm::raw_string_ostream ostr(intermediate); Output yout(ostr); yout << map; // Verify sequences were written in flow style ostr.flush(); llvm::StringRef flowOut(intermediate); EXPECT_NE(llvm::StringRef::npos, flowOut.find("one, two")); EXPECT_NE(llvm::StringRef::npos, flowOut.find("10, -30, 1024")); } { Input yin(intermediate); NameAndNumbers map2; yin >> map2; EXPECT_FALSE(yin.error()); EXPECT_TRUE(map2.name.equals("hello")); EXPECT_EQ(map2.strings.size(), 2UL); EXPECT_TRUE(map2.strings[0].equals("one")); EXPECT_TRUE(map2.strings[1].equals("two")); EXPECT_EQ(map2.single.size(), 1UL); EXPECT_EQ(1, map2.single[0]); EXPECT_EQ(map2.numbers.size(), 3UL); EXPECT_EQ(10, map2.numbers[0]); EXPECT_EQ(-30, map2.numbers[1]); EXPECT_EQ(1024, map2.numbers[2]); } } // // Test writing then reading back a sequence of flow sequences. // TEST(YAMLIO, TestReadWriteSequenceOfMyFlowSequence) { std::string intermediate; { NameAndNumbersFlow map; map.name = "hello"; MyNumberFlowSequence single = { 0 }; MyNumberFlowSequence numbers = { 12, 1, -512 }; map.sequenceOfNumbers.push_back(single); map.sequenceOfNumbers.push_back(numbers); map.sequenceOfNumbers.push_back(MyNumberFlowSequence()); llvm::raw_string_ostream ostr(intermediate); Output yout(ostr); yout << map; // Verify sequences were written in flow style // and that the parent sequence used '-'. ostr.flush(); llvm::StringRef flowOut(intermediate); EXPECT_NE(llvm::StringRef::npos, flowOut.find("- [ 0 ]")); EXPECT_NE(llvm::StringRef::npos, flowOut.find("- [ 12, 1, -512 ]")); EXPECT_NE(llvm::StringRef::npos, flowOut.find("- [ ]")); } { Input yin(intermediate); NameAndNumbersFlow map2; yin >> map2; EXPECT_FALSE(yin.error()); EXPECT_TRUE(map2.name.equals("hello")); EXPECT_EQ(map2.sequenceOfNumbers.size(), 3UL); EXPECT_EQ(map2.sequenceOfNumbers[0].size(), 1UL); EXPECT_EQ(0, map2.sequenceOfNumbers[0][0]); EXPECT_EQ(map2.sequenceOfNumbers[1].size(), 3UL); EXPECT_EQ(12, map2.sequenceOfNumbers[1][0]); EXPECT_EQ(1, map2.sequenceOfNumbers[1][1]); EXPECT_EQ(-512, map2.sequenceOfNumbers[1][2]); EXPECT_TRUE(map2.sequenceOfNumbers[2].empty()); } } //===----------------------------------------------------------------------===// // Test normalizing/denormalizing //===----------------------------------------------------------------------===// LLVM_YAML_STRONG_TYPEDEF(uint32_t, TotalSeconds) typedef std::vector<TotalSeconds> SecondsSequence; LLVM_YAML_IS_SEQUENCE_VECTOR(TotalSeconds) namespace llvm { namespace yaml { template <> struct MappingTraits<TotalSeconds> { class NormalizedSeconds { public: NormalizedSeconds(IO &io) : hours(0), minutes(0), seconds(0) { } NormalizedSeconds(IO &, TotalSeconds &secs) : hours(secs/3600), minutes((secs - (hours*3600))/60), seconds(secs % 60) { } TotalSeconds denormalize(IO &) { return TotalSeconds(hours*3600 + minutes*60 + seconds); } uint32_t hours; uint8_t minutes; uint8_t seconds; }; static void mapping(IO &io, TotalSeconds &secs) { MappingNormalization<NormalizedSeconds, TotalSeconds> keys(io, secs); io.mapOptional("hours", keys->hours, (uint32_t)0); io.mapOptional("minutes", keys->minutes, (uint8_t)0); io.mapRequired("seconds", keys->seconds); } }; } } // // Test the reading of a yaml sequence of mappings // TEST(YAMLIO, TestReadMySecondsSequence) { SecondsSequence seq; Input yin("---\n - hours: 1\n seconds: 5\n - seconds: 59\n...\n"); yin >> seq; EXPECT_FALSE(yin.error()); EXPECT_EQ(seq.size(), 2UL); EXPECT_EQ(seq[0], 3605U); EXPECT_EQ(seq[1], 59U); } // // Test writing then reading back custom values // TEST(YAMLIO, TestReadWriteMySecondsSequence) { std::string intermediate; { SecondsSequence seq; seq.push_back(4000); seq.push_back(500); seq.push_back(59); llvm::raw_string_ostream ostr(intermediate); Output yout(ostr); yout << seq; } { Input yin(intermediate); SecondsSequence seq2; yin >> seq2; EXPECT_FALSE(yin.error()); EXPECT_EQ(seq2.size(), 3UL); EXPECT_EQ(seq2[0], 4000U); EXPECT_EQ(seq2[1], 500U); EXPECT_EQ(seq2[2], 59U); } } //===----------------------------------------------------------------------===// // Test dynamic typing //===----------------------------------------------------------------------===// enum AFlags { a1, a2, a3 }; enum BFlags { b1, b2, b3 }; enum Kind { kindA, kindB }; struct KindAndFlags { KindAndFlags() : kind(kindA), flags(0) { } KindAndFlags(Kind k, uint32_t f) : kind(k), flags(f) { } Kind kind; uint32_t flags; }; typedef std::vector<KindAndFlags> KindAndFlagsSequence; LLVM_YAML_IS_SEQUENCE_VECTOR(KindAndFlags) namespace llvm { namespace yaml { template <> struct ScalarEnumerationTraits<AFlags> { static void enumeration(IO &io, AFlags &value) { io.enumCase(value, "a1", a1); io.enumCase(value, "a2", a2); io.enumCase(value, "a3", a3); } }; template <> struct ScalarEnumerationTraits<BFlags> { static void enumeration(IO &io, BFlags &value) { io.enumCase(value, "b1", b1); io.enumCase(value, "b2", b2); io.enumCase(value, "b3", b3); } }; template <> struct ScalarEnumerationTraits<Kind> { static void enumeration(IO &io, Kind &value) { io.enumCase(value, "A", kindA); io.enumCase(value, "B", kindB); } }; template <> struct MappingTraits<KindAndFlags> { static void mapping(IO &io, KindAndFlags& kf) { io.mapRequired("kind", kf.kind); // Type of "flags" field varies depending on "kind" field. // Use memcpy here to avoid breaking strict aliasing rules. if (kf.kind == kindA) { AFlags aflags = static_cast<AFlags>(kf.flags); io.mapRequired("flags", aflags); kf.flags = aflags; } else { BFlags bflags = static_cast<BFlags>(kf.flags); io.mapRequired("flags", bflags); kf.flags = bflags; } } }; } } // // Test the reading of a yaml sequence dynamic types // TEST(YAMLIO, TestReadKindAndFlagsSequence) { KindAndFlagsSequence seq; Input yin("---\n - kind: A\n flags: a2\n - kind: B\n flags: b1\n...\n"); yin >> seq; EXPECT_FALSE(yin.error()); EXPECT_EQ(seq.size(), 2UL); EXPECT_EQ(seq[0].kind, kindA); EXPECT_EQ(seq[0].flags, (uint32_t)a2); EXPECT_EQ(seq[1].kind, kindB); EXPECT_EQ(seq[1].flags, (uint32_t)b1); } // // Test writing then reading back dynamic types // TEST(YAMLIO, TestReadWriteKindAndFlagsSequence) { std::string intermediate; { KindAndFlagsSequence seq; seq.push_back(KindAndFlags(kindA,a1)); seq.push_back(KindAndFlags(kindB,b1)); seq.push_back(KindAndFlags(kindA,a2)); seq.push_back(KindAndFlags(kindB,b2)); seq.push_back(KindAndFlags(kindA,a3)); llvm::raw_string_ostream ostr(intermediate); Output yout(ostr); yout << seq; } { Input yin(intermediate); KindAndFlagsSequence seq2; yin >> seq2; EXPECT_FALSE(yin.error()); EXPECT_EQ(seq2.size(), 5UL); EXPECT_EQ(seq2[0].kind, kindA); EXPECT_EQ(seq2[0].flags, (uint32_t)a1); EXPECT_EQ(seq2[1].kind, kindB); EXPECT_EQ(seq2[1].flags, (uint32_t)b1); EXPECT_EQ(seq2[2].kind, kindA); EXPECT_EQ(seq2[2].flags, (uint32_t)a2); EXPECT_EQ(seq2[3].kind, kindB); EXPECT_EQ(seq2[3].flags, (uint32_t)b2); EXPECT_EQ(seq2[4].kind, kindA); EXPECT_EQ(seq2[4].flags, (uint32_t)a3); } } //===----------------------------------------------------------------------===// // Test document list //===----------------------------------------------------------------------===// struct FooBarMap { int foo; int bar; }; typedef std::vector<FooBarMap> FooBarMapDocumentList; LLVM_YAML_IS_DOCUMENT_LIST_VECTOR(FooBarMap) namespace llvm { namespace yaml { template <> struct MappingTraits<FooBarMap> { static void mapping(IO &io, FooBarMap& fb) { io.mapRequired("foo", fb.foo); io.mapRequired("bar", fb.bar); } }; } } // // Test the reading of a yaml mapping // TEST(YAMLIO, TestDocRead) { FooBarMap doc; Input yin("---\nfoo: 3\nbar: 5\n...\n"); yin >> doc; EXPECT_FALSE(yin.error()); EXPECT_EQ(doc.foo, 3); EXPECT_EQ(doc.bar,5); } // // Test writing then reading back a sequence of mappings // TEST(YAMLIO, TestSequenceDocListWriteAndRead) { std::string intermediate; { FooBarMap doc1; doc1.foo = 10; doc1.bar = -3; FooBarMap doc2; doc2.foo = 257; doc2.bar = 0; std::vector<FooBarMap> docList; docList.push_back(doc1); docList.push_back(doc2); llvm::raw_string_ostream ostr(intermediate); Output yout(ostr); yout << docList; } { Input yin(intermediate); std::vector<FooBarMap> docList2; yin >> docList2; EXPECT_FALSE(yin.error()); EXPECT_EQ(docList2.size(), 2UL); FooBarMap& map1 = docList2[0]; FooBarMap& map2 = docList2[1]; EXPECT_EQ(map1.foo, 10); EXPECT_EQ(map1.bar, -3); EXPECT_EQ(map2.foo, 257); EXPECT_EQ(map2.bar, 0); } } //===----------------------------------------------------------------------===// // Test document tags //===----------------------------------------------------------------------===// struct MyDouble { MyDouble() : value(0.0) { } MyDouble(double x) : value(x) { } double value; }; LLVM_YAML_IS_DOCUMENT_LIST_VECTOR(MyDouble) namespace llvm { namespace yaml { template <> struct MappingTraits<MyDouble> { static void mapping(IO &io, MyDouble &d) { if (io.mapTag("!decimal", true)) { mappingDecimal(io, d); } else if (io.mapTag("!fraction")) { mappingFraction(io, d); } } static void mappingDecimal(IO &io, MyDouble &d) { io.mapRequired("value", d.value); } static void mappingFraction(IO &io, MyDouble &d) { double num, denom; io.mapRequired("numerator", num); io.mapRequired("denominator", denom); // convert fraction to double d.value = num/denom; } }; } } // // Test the reading of two different tagged yaml documents. // TEST(YAMLIO, TestTaggedDocuments) { std::vector<MyDouble> docList; Input yin("--- !decimal\nvalue: 3.0\n" "--- !fraction\nnumerator: 9.0\ndenominator: 2\n...\n"); yin >> docList; EXPECT_FALSE(yin.error()); EXPECT_EQ(docList.size(), 2UL); EXPECT_EQ(docList[0].value, 3.0); EXPECT_EQ(docList[1].value, 4.5); } // // Test writing then reading back tagged documents // TEST(YAMLIO, TestTaggedDocumentsWriteAndRead) { std::string intermediate; { MyDouble a(10.25); MyDouble b(-3.75); std::vector<MyDouble> docList; docList.push_back(a); docList.push_back(b); llvm::raw_string_ostream ostr(intermediate); Output yout(ostr); yout << docList; } { Input yin(intermediate); std::vector<MyDouble> docList2; yin >> docList2; EXPECT_FALSE(yin.error()); EXPECT_EQ(docList2.size(), 2UL); EXPECT_EQ(docList2[0].value, 10.25); EXPECT_EQ(docList2[1].value, -3.75); } } //===----------------------------------------------------------------------===// // Test mapping validation //===----------------------------------------------------------------------===// struct MyValidation { double value; }; LLVM_YAML_IS_DOCUMENT_LIST_VECTOR(MyValidation) namespace llvm { namespace yaml { template <> struct MappingTraits<MyValidation> { static void mapping(IO &io, MyValidation &d) { io.mapRequired("value", d.value); } static StringRef validate(IO &io, MyValidation &d) { if (d.value < 0) return "negative value"; return StringRef(); } }; } } // // Test that validate() is called and complains about the negative value. // TEST(YAMLIO, TestValidatingInput) { std::vector<MyValidation> docList; Input yin("--- \nvalue: 3.0\n" "--- \nvalue: -1.0\n...\n", nullptr, suppressErrorMessages); yin >> docList; EXPECT_TRUE(!!yin.error()); } //===----------------------------------------------------------------------===// // Test flow mapping //===----------------------------------------------------------------------===// struct FlowFooBar { int foo; int bar; FlowFooBar() : foo(0), bar(0) {} FlowFooBar(int foo, int bar) : foo(foo), bar(bar) {} }; typedef std::vector<FlowFooBar> FlowFooBarSequence; LLVM_YAML_IS_SEQUENCE_VECTOR(FlowFooBar) struct FlowFooBarDoc { FlowFooBar attribute; FlowFooBarSequence seq; }; namespace llvm { namespace yaml { template <> struct MappingTraits<FlowFooBar> { static void mapping(IO &io, FlowFooBar &fb) { io.mapRequired("foo", fb.foo); io.mapRequired("bar", fb.bar); } static const bool flow = true; }; template <> struct MappingTraits<FlowFooBarDoc> { static void mapping(IO &io, FlowFooBarDoc &fb) { io.mapRequired("attribute", fb.attribute); io.mapRequired("seq", fb.seq); } }; } } // // Test writing then reading back custom mappings // TEST(YAMLIO, TestReadWriteMyFlowMapping) { std::string intermediate; { FlowFooBarDoc doc; doc.attribute = FlowFooBar(42, 907); doc.seq.push_back(FlowFooBar(1, 2)); doc.seq.push_back(FlowFooBar(0, 0)); doc.seq.push_back(FlowFooBar(-1, 1024)); llvm::raw_string_ostream ostr(intermediate); Output yout(ostr); yout << doc; // Verify that mappings were written in flow style ostr.flush(); llvm::StringRef flowOut(intermediate); EXPECT_NE(llvm::StringRef::npos, flowOut.find("{ foo: 42, bar: 907 }")); EXPECT_NE(llvm::StringRef::npos, flowOut.find("- { foo: 1, bar: 2 }")); EXPECT_NE(llvm::StringRef::npos, flowOut.find("- { foo: 0, bar: 0 }")); EXPECT_NE(llvm::StringRef::npos, flowOut.find("- { foo: -1, bar: 1024 }")); } { Input yin(intermediate); FlowFooBarDoc doc2; yin >> doc2; EXPECT_FALSE(yin.error()); EXPECT_EQ(doc2.attribute.foo, 42); EXPECT_EQ(doc2.attribute.bar, 907); EXPECT_EQ(doc2.seq.size(), 3UL); EXPECT_EQ(doc2.seq[0].foo, 1); EXPECT_EQ(doc2.seq[0].bar, 2); EXPECT_EQ(doc2.seq[1].foo, 0); EXPECT_EQ(doc2.seq[1].bar, 0); EXPECT_EQ(doc2.seq[2].foo, -1); EXPECT_EQ(doc2.seq[2].bar, 1024); } } //===----------------------------------------------------------------------===// // Test error handling //===----------------------------------------------------------------------===// // // Test error handling of unknown enumerated scalar // TEST(YAMLIO, TestColorsReadError) { ColorMap map; Input yin("---\n" "c1: blue\n" "c2: purple\n" "c3: green\n" "...\n", /*Ctxt=*/nullptr, suppressErrorMessages); yin >> map; EXPECT_TRUE(!!yin.error()); } // // Test error handling of flow sequence with unknown value // TEST(YAMLIO, TestFlagsReadError) { FlagsMap map; Input yin("---\n" "f1: [ big ]\n" "f2: [ round, hollow ]\n" "f3: []\n" "...\n", /*Ctxt=*/nullptr, suppressErrorMessages); yin >> map; EXPECT_TRUE(!!yin.error()); } // // Test error handling reading built-in uint8_t type // LLVM_YAML_IS_SEQUENCE_VECTOR(uint8_t) TEST(YAMLIO, TestReadBuiltInTypesUint8Error) { std::vector<uint8_t> seq; Input yin("---\n" "- 255\n" "- 0\n" "- 257\n" "...\n", /*Ctxt=*/nullptr, suppressErrorMessages); yin >> seq; EXPECT_TRUE(!!yin.error()); } // // Test error handling reading built-in uint16_t type // LLVM_YAML_IS_SEQUENCE_VECTOR(uint16_t) TEST(YAMLIO, TestReadBuiltInTypesUint16Error) { std::vector<uint16_t> seq; Input yin("---\n" "- 65535\n" "- 0\n" "- 66000\n" "...\n", /*Ctxt=*/nullptr, suppressErrorMessages); yin >> seq; EXPECT_TRUE(!!yin.error()); } // // Test error handling reading built-in uint32_t type // LLVM_YAML_IS_SEQUENCE_VECTOR(uint32_t) TEST(YAMLIO, TestReadBuiltInTypesUint32Error) { std::vector<uint32_t> seq; Input yin("---\n" "- 4000000000\n" "- 0\n" "- 5000000000\n" "...\n", /*Ctxt=*/nullptr, suppressErrorMessages); yin >> seq; EXPECT_TRUE(!!yin.error()); } // // Test error handling reading built-in uint64_t type // LLVM_YAML_IS_SEQUENCE_VECTOR(uint64_t) TEST(YAMLIO, TestReadBuiltInTypesUint64Error) { std::vector<uint64_t> seq; Input yin("---\n" "- 18446744073709551615\n" "- 0\n" "- 19446744073709551615\n" "...\n", /*Ctxt=*/nullptr, suppressErrorMessages); yin >> seq; EXPECT_TRUE(!!yin.error()); } // // Test error handling reading built-in int8_t type // LLVM_YAML_IS_SEQUENCE_VECTOR(int8_t) TEST(YAMLIO, TestReadBuiltInTypesint8OverError) { std::vector<int8_t> seq; Input yin("---\n" "- -128\n" "- 0\n" "- 127\n" "- 128\n" "...\n", /*Ctxt=*/nullptr, suppressErrorMessages); yin >> seq; EXPECT_TRUE(!!yin.error()); } // // Test error handling reading built-in int8_t type // TEST(YAMLIO, TestReadBuiltInTypesint8UnderError) { std::vector<int8_t> seq; Input yin("---\n" "- -128\n" "- 0\n" "- 127\n" "- -129\n" "...\n", /*Ctxt=*/nullptr, suppressErrorMessages); yin >> seq; EXPECT_TRUE(!!yin.error()); } // // Test error handling reading built-in int16_t type // LLVM_YAML_IS_SEQUENCE_VECTOR(int16_t) TEST(YAMLIO, TestReadBuiltInTypesint16UnderError) { std::vector<int16_t> seq; Input yin("---\n" "- 32767\n" "- 0\n" "- -32768\n" "- -32769\n" "...\n", /*Ctxt=*/nullptr, suppressErrorMessages); yin >> seq; EXPECT_TRUE(!!yin.error()); } // // Test error handling reading built-in int16_t type // TEST(YAMLIO, TestReadBuiltInTypesint16OverError) { std::vector<int16_t> seq; Input yin("---\n" "- 32767\n" "- 0\n" "- -32768\n" "- 32768\n" "...\n", /*Ctxt=*/nullptr, suppressErrorMessages); yin >> seq; EXPECT_TRUE(!!yin.error()); } // // Test error handling reading built-in int32_t type // LLVM_YAML_IS_SEQUENCE_VECTOR(int32_t) TEST(YAMLIO, TestReadBuiltInTypesint32UnderError) { std::vector<int32_t> seq; Input yin("---\n" "- 2147483647\n" "- 0\n" "- -2147483648\n" "- -2147483649\n" "...\n", /*Ctxt=*/nullptr, suppressErrorMessages); yin >> seq; EXPECT_TRUE(!!yin.error()); } // // Test error handling reading built-in int32_t type // TEST(YAMLIO, TestReadBuiltInTypesint32OverError) { std::vector<int32_t> seq; Input yin("---\n" "- 2147483647\n" "- 0\n" "- -2147483648\n" "- 2147483649\n" "...\n", /*Ctxt=*/nullptr, suppressErrorMessages); yin >> seq; EXPECT_TRUE(!!yin.error()); } // // Test error handling reading built-in int64_t type // LLVM_YAML_IS_SEQUENCE_VECTOR(int64_t) TEST(YAMLIO, TestReadBuiltInTypesint64UnderError) { std::vector<int64_t> seq; Input yin("---\n" "- -9223372036854775808\n" "- 0\n" "- 9223372036854775807\n" "- -9223372036854775809\n" "...\n", /*Ctxt=*/nullptr, suppressErrorMessages); yin >> seq; EXPECT_TRUE(!!yin.error()); } // // Test error handling reading built-in int64_t type // TEST(YAMLIO, TestReadBuiltInTypesint64OverError) { std::vector<int64_t> seq; Input yin("---\n" "- -9223372036854775808\n" "- 0\n" "- 9223372036854775807\n" "- 9223372036854775809\n" "...\n", /*Ctxt=*/nullptr, suppressErrorMessages); yin >> seq; EXPECT_TRUE(!!yin.error()); } // // Test error handling reading built-in float type // LLVM_YAML_IS_SEQUENCE_VECTOR(float) TEST(YAMLIO, TestReadBuiltInTypesFloatError) { std::vector<float> seq; Input yin("---\n" "- 0.0\n" "- 1000.1\n" "- -123.456\n" "- 1.2.3\n" "...\n", /*Ctxt=*/nullptr, suppressErrorMessages); yin >> seq; EXPECT_TRUE(!!yin.error()); } // // Test error handling reading built-in float type // LLVM_YAML_IS_SEQUENCE_VECTOR(double) TEST(YAMLIO, TestReadBuiltInTypesDoubleError) { std::vector<double> seq; Input yin("---\n" "- 0.0\n" "- 1000.1\n" "- -123.456\n" "- 1.2.3\n" "...\n", /*Ctxt=*/nullptr, suppressErrorMessages); yin >> seq; EXPECT_TRUE(!!yin.error()); } // // Test error handling reading built-in Hex8 type // LLVM_YAML_IS_SEQUENCE_VECTOR(Hex8) TEST(YAMLIO, TestReadBuiltInTypesHex8Error) { std::vector<Hex8> seq; Input yin("---\n" "- 0x12\n" "- 0xFE\n" "- 0x123\n" "...\n", /*Ctxt=*/nullptr, suppressErrorMessages); yin >> seq; EXPECT_TRUE(!!yin.error()); } // // Test error handling reading built-in Hex16 type // LLVM_YAML_IS_SEQUENCE_VECTOR(Hex16) TEST(YAMLIO, TestReadBuiltInTypesHex16Error) { std::vector<Hex16> seq; Input yin("---\n" "- 0x0012\n" "- 0xFEFF\n" "- 0x12345\n" "...\n", /*Ctxt=*/nullptr, suppressErrorMessages); yin >> seq; EXPECT_TRUE(!!yin.error()); } // // Test error handling reading built-in Hex32 type // LLVM_YAML_IS_SEQUENCE_VECTOR(Hex32) TEST(YAMLIO, TestReadBuiltInTypesHex32Error) { std::vector<Hex32> seq; Input yin("---\n" "- 0x0012\n" "- 0xFEFF0000\n" "- 0x1234556789\n" "...\n", /*Ctxt=*/nullptr, suppressErrorMessages); yin >> seq; EXPECT_TRUE(!!yin.error()); } // // Test error handling reading built-in Hex64 type // LLVM_YAML_IS_SEQUENCE_VECTOR(Hex64) TEST(YAMLIO, TestReadBuiltInTypesHex64Error) { std::vector<Hex64> seq; Input yin("---\n" "- 0x0012\n" "- 0xFFEEDDCCBBAA9988\n" "- 0x12345567890ABCDEF0\n" "...\n", /*Ctxt=*/nullptr, suppressErrorMessages); yin >> seq; EXPECT_TRUE(!!yin.error()); } TEST(YAMLIO, TestMalformedMapFailsGracefully) { FooBar doc; { // We pass the suppressErrorMessages handler to handle the error // message generated in the constructor of Input. Input yin("{foo:3, bar: 5}", /*Ctxt=*/nullptr, suppressErrorMessages); yin >> doc; EXPECT_TRUE(!!yin.error()); } { Input yin("---\nfoo:3\nbar: 5\n...\n", /*Ctxt=*/nullptr, suppressErrorMessages); yin >> doc; EXPECT_TRUE(!!yin.error()); } } struct OptionalTest { std::vector<int> Numbers; }; struct OptionalTestSeq { std::vector<OptionalTest> Tests; }; LLVM_YAML_IS_SEQUENCE_VECTOR(OptionalTest) namespace llvm { namespace yaml { template <> struct MappingTraits<OptionalTest> { static void mapping(IO& IO, OptionalTest &OT) { IO.mapOptional("Numbers", OT.Numbers); } }; template <> struct MappingTraits<OptionalTestSeq> { static void mapping(IO &IO, OptionalTestSeq &OTS) { IO.mapOptional("Tests", OTS.Tests); } }; } } TEST(YAMLIO, SequenceElideTest) { // Test that writing out a purely optional structure with its fields set to // default followed by other data is properly read back in. OptionalTestSeq Seq; OptionalTest One, Two, Three, Four; int N[] = {1, 2, 3}; Three.Numbers.assign(N, N + 3); Seq.Tests.push_back(One); Seq.Tests.push_back(Two); Seq.Tests.push_back(Three); Seq.Tests.push_back(Four); std::string intermediate; { llvm::raw_string_ostream ostr(intermediate); Output yout(ostr); yout << Seq; } Input yin(intermediate); OptionalTestSeq Seq2; yin >> Seq2; EXPECT_FALSE(yin.error()); EXPECT_EQ(4UL, Seq2.Tests.size()); EXPECT_TRUE(Seq2.Tests[0].Numbers.empty()); EXPECT_TRUE(Seq2.Tests[1].Numbers.empty()); EXPECT_EQ(1, Seq2.Tests[2].Numbers[0]); EXPECT_EQ(2, Seq2.Tests[2].Numbers[1]); EXPECT_EQ(3, Seq2.Tests[2].Numbers[2]); EXPECT_TRUE(Seq2.Tests[3].Numbers.empty()); } TEST(YAMLIO, TestEmptyStringFailsForMapWithRequiredFields) { FooBar doc; Input yin(""); yin >> doc; EXPECT_TRUE(!!yin.error()); } TEST(YAMLIO, TestEmptyStringSucceedsForMapWithOptionalFields) { OptionalTest doc; Input yin(""); yin >> doc; EXPECT_FALSE(yin.error()); } TEST(YAMLIO, TestEmptyStringSucceedsForSequence) { std::vector<uint8_t> seq; Input yin("", /*Ctxt=*/nullptr, suppressErrorMessages); yin >> seq; EXPECT_FALSE(yin.error()); EXPECT_TRUE(seq.empty()); } struct FlowMap { llvm::StringRef str1, str2, str3; FlowMap(llvm::StringRef str1, llvm::StringRef str2, llvm::StringRef str3) : str1(str1), str2(str2), str3(str3) {} }; struct FlowSeq { llvm::StringRef str; FlowSeq(llvm::StringRef S) : str(S) {} FlowSeq() = default; }; namespace llvm { namespace yaml { template <> struct MappingTraits<FlowMap> { static void mapping(IO &io, FlowMap &fm) { io.mapRequired("str1", fm.str1); io.mapRequired("str2", fm.str2); io.mapRequired("str3", fm.str3); } static const bool flow = true; }; template <> struct ScalarTraits<FlowSeq> { static void output(const FlowSeq &value, void*, llvm::raw_ostream &out) { out << value.str; } static StringRef input(StringRef scalar, void*, FlowSeq &value) { value.str = scalar; return ""; } static bool mustQuote(StringRef S) { return false; } }; } } LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(FlowSeq) TEST(YAMLIO, TestWrapFlow) { std::string out; llvm::raw_string_ostream ostr(out); FlowMap Map("This is str1", "This is str2", "This is str3"); std::vector<FlowSeq> Seq; Seq.emplace_back("This is str1"); Seq.emplace_back("This is str2"); Seq.emplace_back("This is str3"); { // 20 is just bellow the total length of the first mapping field. // We should wreap at every element. Output yout(ostr, nullptr, 15); yout << Map; ostr.flush(); EXPECT_EQ(out, "---\n" "{ str1: This is str1, \n" " str2: This is str2, \n" " str3: This is str3 }\n" "...\n"); out.clear(); yout << Seq; ostr.flush(); EXPECT_EQ(out, "---\n" "[ This is str1, \n" " This is str2, \n" " This is str3 ]\n" "...\n"); out.clear(); } { // 25 will allow the second field to be output on the first line. Output yout(ostr, nullptr, 25); yout << Map; ostr.flush(); EXPECT_EQ(out, "---\n" "{ str1: This is str1, str2: This is str2, \n" " str3: This is str3 }\n" "...\n"); out.clear(); yout << Seq; ostr.flush(); EXPECT_EQ(out, "---\n" "[ This is str1, This is str2, \n" " This is str3 ]\n" "...\n"); out.clear(); } { // 0 means no wrapping. Output yout(ostr, nullptr, 0); yout << Map; ostr.flush(); EXPECT_EQ(out, "---\n" "{ str1: This is str1, str2: This is str2, str3: This is str3 }\n" "...\n"); out.clear(); yout << Seq; ostr.flush(); EXPECT_EQ(out, "---\n" "[ This is str1, This is str2, This is str3 ]\n" "...\n"); out.clear(); } }
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/Support/RegexTest.cpp
//===- llvm/unittest/Support/RegexTest.cpp - Regex tests --===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/Support/Regex.h" #include "llvm/ADT/SmallVector.h" #include "gtest/gtest.h" #include <cstring> using namespace llvm; namespace { class RegexTest : public ::testing::Test { }; TEST_F(RegexTest, Basics) { Regex r1("^[0-9]+$"); EXPECT_TRUE(r1.match("916")); EXPECT_TRUE(r1.match("9")); EXPECT_FALSE(r1.match("9a")); SmallVector<StringRef, 1> Matches; Regex r2("[0-9]+"); EXPECT_TRUE(r2.match("aa216b", &Matches)); EXPECT_EQ(1u, Matches.size()); EXPECT_EQ("216", Matches[0].str()); Regex r3("[0-9]+([a-f])?:([0-9]+)"); EXPECT_TRUE(r3.match("9a:513b", &Matches)); EXPECT_EQ(3u, Matches.size()); EXPECT_EQ("9a:513", Matches[0].str()); EXPECT_EQ("a", Matches[1].str()); EXPECT_EQ("513", Matches[2].str()); EXPECT_TRUE(r3.match("9:513b", &Matches)); EXPECT_EQ(3u, Matches.size()); EXPECT_EQ("9:513", Matches[0].str()); EXPECT_EQ("", Matches[1].str()); EXPECT_EQ("513", Matches[2].str()); Regex r4("a[^b]+b"); std::string String="axxb"; String[2] = '\0'; EXPECT_FALSE(r4.match("abb")); EXPECT_TRUE(r4.match(String, &Matches)); EXPECT_EQ(1u, Matches.size()); EXPECT_EQ(String, Matches[0].str()); std::string NulPattern="X[0-9]+X([a-f])?:([0-9]+)"; String="YX99a:513b"; NulPattern[7] = '\0'; Regex r5(NulPattern); EXPECT_FALSE(r5.match(String)); EXPECT_FALSE(r5.match("X9")); String[3]='\0'; EXPECT_TRUE(r5.match(String)); } TEST_F(RegexTest, Backreferences) { Regex r1("([a-z]+)_\\1"); SmallVector<StringRef, 4> Matches; EXPECT_TRUE(r1.match("abc_abc", &Matches)); EXPECT_EQ(2u, Matches.size()); EXPECT_FALSE(r1.match("abc_ab", &Matches)); Regex r2("a([0-9])b\\1c\\1"); EXPECT_TRUE(r2.match("a4b4c4", &Matches)); EXPECT_EQ(2u, Matches.size()); EXPECT_EQ("4", Matches[1].str()); EXPECT_FALSE(r2.match("a2b2c3")); Regex r3("a([0-9])([a-z])b\\1\\2"); EXPECT_TRUE(r3.match("a6zb6z", &Matches)); EXPECT_EQ(3u, Matches.size()); EXPECT_EQ("6", Matches[1].str()); EXPECT_EQ("z", Matches[2].str()); EXPECT_FALSE(r3.match("a6zb6y")); EXPECT_FALSE(r3.match("a6zb7z")); } TEST_F(RegexTest, Substitution) { std::string Error; EXPECT_EQ("aNUMber", Regex("[0-9]+").sub("NUM", "a1234ber")); // Standard Escapes EXPECT_EQ("a\\ber", Regex("[0-9]+").sub("\\\\", "a1234ber", &Error)); EXPECT_EQ("", Error); EXPECT_EQ("a\nber", Regex("[0-9]+").sub("\\n", "a1234ber", &Error)); EXPECT_EQ("", Error); EXPECT_EQ("a\tber", Regex("[0-9]+").sub("\\t", "a1234ber", &Error)); EXPECT_EQ("", Error); EXPECT_EQ("ajber", Regex("[0-9]+").sub("\\j", "a1234ber", &Error)); EXPECT_EQ("", Error); EXPECT_EQ("aber", Regex("[0-9]+").sub("\\", "a1234ber", &Error)); EXPECT_EQ(Error, "replacement string contained trailing backslash"); // Backreferences EXPECT_EQ("aa1234bber", Regex("a[0-9]+b").sub("a\\0b", "a1234ber", &Error)); EXPECT_EQ("", Error); EXPECT_EQ("a1234ber", Regex("a([0-9]+)b").sub("a\\1b", "a1234ber", &Error)); EXPECT_EQ("", Error); EXPECT_EQ("aber", Regex("a[0-9]+b").sub("a\\100b", "a1234ber", &Error)); EXPECT_EQ(Error, "invalid backreference string '100'"); } TEST_F(RegexTest, IsLiteralERE) { EXPECT_TRUE(Regex::isLiteralERE("abc")); EXPECT_FALSE(Regex::isLiteralERE("a(bc)")); EXPECT_FALSE(Regex::isLiteralERE("^abc")); EXPECT_FALSE(Regex::isLiteralERE("abc$")); EXPECT_FALSE(Regex::isLiteralERE("a|bc")); EXPECT_FALSE(Regex::isLiteralERE("abc*")); EXPECT_FALSE(Regex::isLiteralERE("abc+")); EXPECT_FALSE(Regex::isLiteralERE("abc?")); EXPECT_FALSE(Regex::isLiteralERE("abc.")); EXPECT_FALSE(Regex::isLiteralERE("a[bc]")); EXPECT_FALSE(Regex::isLiteralERE("abc\\1")); EXPECT_FALSE(Regex::isLiteralERE("abc{1,2}")); } TEST_F(RegexTest, Escape) { EXPECT_EQ("a\\[bc\\]", Regex::escape("a[bc]")); EXPECT_EQ("abc\\{1\\\\,2\\}", Regex::escape("abc{1\\,2}")); } TEST_F(RegexTest, IsValid) { std::string Error; EXPECT_FALSE(Regex("(foo").isValid(Error)); EXPECT_EQ("parentheses not balanced", Error); EXPECT_FALSE(Regex("a[b-").isValid(Error)); EXPECT_EQ("invalid character range", Error); } TEST_F(RegexTest, MoveConstruct) { Regex r1("^[0-9]+$"); Regex r2(std::move(r1)); EXPECT_TRUE(r2.match("916")); } TEST_F(RegexTest, MoveAssign) { Regex r1("^[0-9]+$"); Regex r2("abc"); r2 = std::move(r1); EXPECT_TRUE(r2.match("916")); } }
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/Support/MemoryBufferTest.cpp
//===- llvm/unittest/Support/MemoryBufferTest.cpp - MemoryBuffer tests ----===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements unit tests for the MemoryBuffer support class. // //===----------------------------------------------------------------------===// #include "llvm/Support/FileSystem.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/raw_ostream.h" #include "gtest/gtest.h" using namespace llvm; namespace { class MemoryBufferTest : public testing::Test { protected: MemoryBufferTest() : data("this is some data") { } void SetUp() override {} /// Common testing for different modes of getOpenFileSlice. /// Creates a temporary file with known contents, and uses /// MemoryBuffer::getOpenFileSlice to map it. /// If \p Reopen is true, the file is closed after creating and reopened /// anew before using MemoryBuffer. void testGetOpenFileSlice(bool Reopen); typedef std::unique_ptr<MemoryBuffer> OwningBuffer; std::string data; }; TEST_F(MemoryBufferTest, get) { // Default name and null-terminator flag OwningBuffer MB1(MemoryBuffer::getMemBuffer(data)); EXPECT_TRUE(nullptr != MB1.get()); // RequiresNullTerminator = false OwningBuffer MB2(MemoryBuffer::getMemBuffer(data, "one", false)); EXPECT_TRUE(nullptr != MB2.get()); // RequiresNullTerminator = true OwningBuffer MB3(MemoryBuffer::getMemBuffer(data, "two", true)); EXPECT_TRUE(nullptr != MB3.get()); // verify all 3 buffers point to the same address EXPECT_EQ(MB1->getBufferStart(), MB2->getBufferStart()); EXPECT_EQ(MB2->getBufferStart(), MB3->getBufferStart()); // verify the original data is unmodified after deleting the buffers MB1.reset(); MB2.reset(); MB3.reset(); EXPECT_EQ("this is some data", data); } TEST_F(MemoryBufferTest, NullTerminator4K) { // Test that a file with size that is a multiple of the page size can be null // terminated correctly by MemoryBuffer. int TestFD; SmallString<64> TestPath; sys::fs::createTemporaryFile("MemoryBufferTest_NullTerminator4K", "temp", TestFD, TestPath); raw_fd_ostream OF(TestFD, true, /*unbuffered=*/true); for (unsigned i = 0; i < 4096 / 16; ++i) { OF << "0123456789abcdef"; } OF.close(); ErrorOr<OwningBuffer> MB = MemoryBuffer::getFile(TestPath.c_str()); std::error_code EC = MB.getError(); ASSERT_FALSE(EC); const char *BufData = MB.get()->getBufferStart(); EXPECT_EQ('f', BufData[4095]); EXPECT_EQ('\0', BufData[4096]); } TEST_F(MemoryBufferTest, copy) { // copy with no name OwningBuffer MBC1(MemoryBuffer::getMemBufferCopy(data)); EXPECT_TRUE(nullptr != MBC1.get()); // copy with a name OwningBuffer MBC2(MemoryBuffer::getMemBufferCopy(data, "copy")); EXPECT_TRUE(nullptr != MBC2.get()); // verify the two copies do not point to the same place EXPECT_NE(MBC1->getBufferStart(), MBC2->getBufferStart()); } TEST_F(MemoryBufferTest, make_new) { // 0-sized buffer OwningBuffer Zero(MemoryBuffer::getNewUninitMemBuffer(0)); EXPECT_TRUE(nullptr != Zero.get()); // uninitialized buffer with no name OwningBuffer One(MemoryBuffer::getNewUninitMemBuffer(321)); EXPECT_TRUE(nullptr != One.get()); // uninitialized buffer with name OwningBuffer Two(MemoryBuffer::getNewUninitMemBuffer(123, "bla")); EXPECT_TRUE(nullptr != Two.get()); // 0-initialized buffer with no name OwningBuffer Three(MemoryBuffer::getNewMemBuffer(321, data)); EXPECT_TRUE(nullptr != Three.get()); for (size_t i = 0; i < 321; ++i) EXPECT_EQ(0, Three->getBufferStart()[0]); // 0-initialized buffer with name OwningBuffer Four(MemoryBuffer::getNewMemBuffer(123, "zeros")); EXPECT_TRUE(nullptr != Four.get()); for (size_t i = 0; i < 123; ++i) EXPECT_EQ(0, Four->getBufferStart()[0]); } void MemoryBufferTest::testGetOpenFileSlice(bool Reopen) { // Test that MemoryBuffer::getOpenFile works properly when no null // terminator is requested and the size is large enough to trigger // the usage of memory mapping. int TestFD; SmallString<64> TestPath; // Create a temporary file and write data into it. sys::fs::createTemporaryFile("prefix", "temp", TestFD, TestPath); // OF is responsible for closing the file; If the file is not // reopened, it will be unbuffered so that the results are // immediately visible through the fd. raw_fd_ostream OF(TestFD, true, !Reopen); for (int i = 0; i < 60000; ++i) { OF << "0123456789"; } if (Reopen) { OF.close(); EXPECT_FALSE(sys::fs::openFileForRead(TestPath.c_str(), TestFD)); } ErrorOr<OwningBuffer> Buf = MemoryBuffer::getOpenFileSlice(TestFD, TestPath.c_str(), 40000, // Size 80000 // Offset ); std::error_code EC = Buf.getError(); EXPECT_FALSE(EC); StringRef BufData = Buf.get()->getBuffer(); EXPECT_EQ(BufData.size(), 40000U); EXPECT_EQ(BufData[0], '0'); EXPECT_EQ(BufData[9], '9'); } // HLSL Change Begin // The MS filesystem breaks loading file slices on Windows unless you are // reopening the file, so we disable this test case. #if LLVM_ON_WIN32 TEST_F(MemoryBufferTest, DISABLED_getOpenFileNoReopen) { #else TEST_F(MemoryBufferTest, getOpenFileNoReopen) { #endif // HLSL Change End testGetOpenFileSlice(false); } TEST_F(MemoryBufferTest, getOpenFileReopened) { testGetOpenFileSlice(true); } TEST_F(MemoryBufferTest, slice) { // Create a file that is six pages long with different data on each page. int FD; SmallString<64> TestPath; sys::fs::createTemporaryFile("MemoryBufferTest_Slice", "temp", FD, TestPath); raw_fd_ostream OF(FD, true, /*unbuffered=*/true); for (unsigned i = 0; i < 0x2000 / 8; ++i) { OF << "12345678"; } for (unsigned i = 0; i < 0x2000 / 8; ++i) { OF << "abcdefgh"; } for (unsigned i = 0; i < 0x2000 / 8; ++i) { OF << "ABCDEFGH"; } OF.close(); // Try offset of one page. ErrorOr<OwningBuffer> MB = MemoryBuffer::getFileSlice(TestPath.str(), 0x4000, 0x1000); std::error_code EC = MB.getError(); ASSERT_FALSE(EC); EXPECT_EQ(0x4000UL, MB.get()->getBufferSize()); StringRef BufData = MB.get()->getBuffer(); EXPECT_TRUE(BufData.substr(0x0000,8).equals("12345678")); EXPECT_TRUE(BufData.substr(0x0FF8,8).equals("12345678")); EXPECT_TRUE(BufData.substr(0x1000,8).equals("abcdefgh")); EXPECT_TRUE(BufData.substr(0x2FF8,8).equals("abcdefgh")); EXPECT_TRUE(BufData.substr(0x3000,8).equals("ABCDEFGH")); EXPECT_TRUE(BufData.substr(0x3FF8,8).equals("ABCDEFGH")); // Try non-page aligned. ErrorOr<OwningBuffer> MB2 = MemoryBuffer::getFileSlice(TestPath.str(), 0x3000, 0x0800); EC = MB2.getError(); ASSERT_FALSE(EC); EXPECT_EQ(0x3000UL, MB2.get()->getBufferSize()); StringRef BufData2 = MB2.get()->getBuffer(); EXPECT_TRUE(BufData2.substr(0x0000,8).equals("12345678")); EXPECT_TRUE(BufData2.substr(0x17F8,8).equals("12345678")); EXPECT_TRUE(BufData2.substr(0x1800,8).equals("abcdefgh")); EXPECT_TRUE(BufData2.substr(0x2FF8,8).equals("abcdefgh")); } }
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/Support/ArrayRecyclerTest.cpp
//===--- unittest/Support/ArrayRecyclerTest.cpp ---------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/Support/ArrayRecycler.h" #include "llvm/Support/Allocator.h" #include "gtest/gtest.h" #include <cstdlib> using namespace llvm; namespace { struct Object { int Num; Object *Other; }; typedef ArrayRecycler<Object> ARO; TEST(ArrayRecyclerTest, Capacity) { // Capacity size should never be 0. ARO::Capacity Cap = ARO::Capacity::get(0); EXPECT_LT(0u, Cap.getSize()); size_t PrevSize = Cap.getSize(); for (unsigned N = 1; N != 100; ++N) { Cap = ARO::Capacity::get(N); EXPECT_LE(N, Cap.getSize()); if (PrevSize >= N) EXPECT_EQ(PrevSize, Cap.getSize()); else EXPECT_LT(PrevSize, Cap.getSize()); PrevSize = Cap.getSize(); } // Check that the buckets are monotonically increasing. Cap = ARO::Capacity::get(0); PrevSize = Cap.getSize(); for (unsigned N = 0; N != 20; ++N) { Cap = Cap.getNext(); EXPECT_LT(PrevSize, Cap.getSize()); PrevSize = Cap.getSize(); } } TEST(ArrayRecyclerTest, Basics) { BumpPtrAllocator Allocator; ArrayRecycler<Object> DUT; ARO::Capacity Cap = ARO::Capacity::get(8); Object *A1 = DUT.allocate(Cap, Allocator); A1[0].Num = 21; A1[7].Num = 17; Object *A2 = DUT.allocate(Cap, Allocator); A2[0].Num = 121; A2[7].Num = 117; Object *A3 = DUT.allocate(Cap, Allocator); A3[0].Num = 221; A3[7].Num = 217; EXPECT_EQ(21, A1[0].Num); EXPECT_EQ(17, A1[7].Num); EXPECT_EQ(121, A2[0].Num); EXPECT_EQ(117, A2[7].Num); EXPECT_EQ(221, A3[0].Num); EXPECT_EQ(217, A3[7].Num); DUT.deallocate(Cap, A2); // Check that deallocation didn't clobber anything. EXPECT_EQ(21, A1[0].Num); EXPECT_EQ(17, A1[7].Num); EXPECT_EQ(221, A3[0].Num); EXPECT_EQ(217, A3[7].Num); // Verify recycling. Object *A2x = DUT.allocate(Cap, Allocator); EXPECT_EQ(A2, A2x); DUT.deallocate(Cap, A2x); DUT.deallocate(Cap, A1); DUT.deallocate(Cap, A3); // Objects are not required to be recycled in reverse deallocation order, but // that is what the current implementation does. Object *A3x = DUT.allocate(Cap, Allocator); EXPECT_EQ(A3, A3x); Object *A1x = DUT.allocate(Cap, Allocator); EXPECT_EQ(A1, A1x); Object *A2y = DUT.allocate(Cap, Allocator); EXPECT_EQ(A2, A2y); // Back to allocation from the BumpPtrAllocator. Object *A4 = DUT.allocate(Cap, Allocator); EXPECT_NE(A1, A4); EXPECT_NE(A2, A4); EXPECT_NE(A3, A4); DUT.clear(Allocator); } } // end anonymous namespace
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/Support/YAMLParserTest.cpp
//===- unittest/Support/YAMLParserTest ------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/ADT/SmallString.h" #include "llvm/ADT/Twine.h" #include "llvm/Support/Casting.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/YAMLParser.h" #include "gtest/gtest.h" namespace llvm { static void SuppressDiagnosticsOutput(const SMDiagnostic &, void *) { // Prevent SourceMgr from writing errors to stderr // to reduce noise in unit test runs. } // Assumes Ctx is an SMDiagnostic where Diag can be stored. static void CollectDiagnosticsOutput(const SMDiagnostic &Diag, void *Ctx) { SMDiagnostic* DiagOut = static_cast<SMDiagnostic*>(Ctx); *DiagOut = Diag; } // Checks that the given input gives a parse error. Makes sure that an error // text is available and the parse fails. static void ExpectParseError(StringRef Message, StringRef Input) { SourceMgr SM; yaml::Stream Stream(Input, SM); SM.setDiagHandler(SuppressDiagnosticsOutput); EXPECT_FALSE(Stream.validate()) << Message << ": " << Input; EXPECT_TRUE(Stream.failed()) << Message << ": " << Input; } // Checks that the given input can be parsed without error. static void ExpectParseSuccess(StringRef Message, StringRef Input) { SourceMgr SM; yaml::Stream Stream(Input, SM); EXPECT_TRUE(Stream.validate()) << Message << ": " << Input; } TEST(YAMLParser, ParsesEmptyArray) { ExpectParseSuccess("Empty array", "[]"); } TEST(YAMLParser, FailsIfNotClosingArray) { ExpectParseError("Not closing array", "["); ExpectParseError("Not closing array", " [ "); ExpectParseError("Not closing array", " [x"); } TEST(YAMLParser, ParsesEmptyArrayWithWhitespace) { ExpectParseSuccess("Array with spaces", " [ ] "); ExpectParseSuccess("All whitespaces", "\t\r\n[\t\n \t\r ]\t\r \n\n"); } TEST(YAMLParser, ParsesEmptyObject) { ExpectParseSuccess("Empty object", "[{}]"); } TEST(YAMLParser, ParsesObject) { ExpectParseSuccess("Object with an entry", "[{\"a\":\"/b\"}]"); } TEST(YAMLParser, ParsesMultipleKeyValuePairsInObject) { ExpectParseSuccess("Multiple key, value pairs", "[{\"a\":\"/b\",\"c\":\"d\",\"e\":\"f\"}]"); } TEST(YAMLParser, FailsIfNotClosingObject) { ExpectParseError("Missing close on empty", "[{]"); ExpectParseError("Missing close after pair", "[{\"a\":\"b\"]"); } TEST(YAMLParser, FailsIfMissingColon) { ExpectParseError("Missing colon between key and value", "[{\"a\"\"/b\"}]"); ExpectParseError("Missing colon between key and value", "[{\"a\" \"b\"}]"); } TEST(YAMLParser, FailsOnMissingQuote) { ExpectParseError("Missing open quote", "[{a\":\"b\"}]"); ExpectParseError("Missing closing quote", "[{\"a\":\"b}]"); } TEST(YAMLParser, ParsesEscapedQuotes) { ExpectParseSuccess("Parses escaped string in key and value", "[{\"a\":\"\\\"b\\\" \\\" \\\"\"}]"); } TEST(YAMLParser, ParsesEmptyString) { ExpectParseSuccess("Parses empty string in value", "[{\"a\":\"\"}]"); } TEST(YAMLParser, ParsesMultipleObjects) { ExpectParseSuccess( "Multiple objects in array", "[" " { \"a\" : \"b\" }," " { \"a\" : \"b\" }," " { \"a\" : \"b\" }" "]"); } TEST(YAMLParser, FailsOnMissingComma) { ExpectParseError( "Missing comma", "[" " { \"a\" : \"b\" }" " { \"a\" : \"b\" }" "]"); } TEST(YAMLParser, ParsesSpacesInBetweenTokens) { ExpectParseSuccess( "Various whitespace between tokens", " \t \n\n \r [ \t \n\n \r" " \t \n\n \r { \t \n\n \r\"a\"\t \n\n \r :" " \t \n\n \r \"b\"\t \n\n \r } \t \n\n \r,\t \n\n \r" " \t \n\n \r { \t \n\n \r\"a\"\t \n\n \r :" " \t \n\n \r \"b\"\t \n\n \r } \t \n\n \r]\t \n\n \r"); } TEST(YAMLParser, ParsesArrayOfArrays) { ExpectParseSuccess("Array of arrays", "[[]]"); } TEST(YAMLParser, ParsesBlockLiteralScalars) { ExpectParseSuccess("Block literal scalar", "test: |\n Hello\n World\n"); ExpectParseSuccess("Block literal scalar EOF", "test: |\n Hello\n World"); ExpectParseSuccess("Empty block literal scalar header EOF", "test: | "); ExpectParseSuccess("Empty block literal scalar", "test: |\ntest2: 20"); ExpectParseSuccess("Empty block literal scalar 2", "- | \n \n\n \n- 42"); ExpectParseSuccess("Block literal scalar in sequence", "- |\n Testing\n Out\n\n- 22"); ExpectParseSuccess("Block literal scalar in document", "--- |\n Document\n..."); ExpectParseSuccess("Empty non indented lines still count", "- |\n First line\n \n\n Another line\n\n- 2"); ExpectParseSuccess("Comment in block literal scalar header", "test: | # Comment \n No Comment\ntest 2: | # Void"); ExpectParseSuccess("Chomping indicators in block literal scalar header", "test: |- \n Hello\n\ntest 2: |+ \n\n World\n\n\n"); ExpectParseSuccess("Indent indicators in block literal scalar header", "test: |1 \n \n Hello \n World\n"); ExpectParseSuccess("Chomping and indent indicators in block literals", "test: |-1\n Hello\ntest 2: |9+\n World"); ExpectParseSuccess("Trailing comments in block literals", "test: |\n Content\n # Trailing\n #Comment\ntest 2: 3"); ExpectParseError("Invalid block scalar header", "test: | failure"); ExpectParseError("Invalid line indentation", "test: |\n First line\n Error"); ExpectParseError("Long leading space line", "test: |\n \n Test\n"); } TEST(YAMLParser, NullTerminatedBlockScalars) { SourceMgr SM; yaml::Stream Stream("test: |\n Hello\n World\n", SM); yaml::Document &Doc = *Stream.begin(); yaml::MappingNode *Map = cast<yaml::MappingNode>(Doc.getRoot()); StringRef Value = cast<yaml::BlockScalarNode>(Map->begin()->getValue())->getValue(); EXPECT_EQ(Value, "Hello\nWorld\n"); EXPECT_EQ(Value.data()[Value.size()], '\0'); } TEST(YAMLParser, HandlesEndOfFileGracefully) { ExpectParseError("In string starting with EOF", "[\""); ExpectParseError("In string hitting EOF", "[\" "); ExpectParseError("In string escaping EOF", "[\" \\"); ExpectParseError("In array starting with EOF", "["); ExpectParseError("In array element starting with EOF", "[[], "); ExpectParseError("In array hitting EOF", "[[] "); ExpectParseError("In array hitting EOF", "[[]"); ExpectParseError("In object hitting EOF", "{\"\""); } TEST(YAMLParser, HandlesNullValuesInKeyValueNodesGracefully) { ExpectParseError("KeyValueNode with null value", "test: '"); } // Checks that the given string can be parsed into an identical string inside // of an array. static void ExpectCanParseString(StringRef String) { std::string StringInArray = (llvm::Twine("[\"") + String + "\"]").str(); SourceMgr SM; yaml::Stream Stream(StringInArray, SM); yaml::SequenceNode *ParsedSequence = dyn_cast<yaml::SequenceNode>(Stream.begin()->getRoot()); StringRef ParsedString = dyn_cast<yaml::ScalarNode>( static_cast<yaml::Node*>(ParsedSequence->begin()))->getRawValue(); ParsedString = ParsedString.substr(1, ParsedString.size() - 2); EXPECT_EQ(String, ParsedString.str()); } // Checks that parsing the given string inside an array fails. static void ExpectCannotParseString(StringRef String) { std::string StringInArray = (llvm::Twine("[\"") + String + "\"]").str(); ExpectParseError((Twine("When parsing string \"") + String + "\"").str(), StringInArray); } TEST(YAMLParser, ParsesStrings) { ExpectCanParseString(""); ExpectCannotParseString("\\"); ExpectCannotParseString("\""); ExpectCanParseString(" "); ExpectCanParseString("\\ "); ExpectCanParseString("\\\""); ExpectCannotParseString("\"\\"); ExpectCannotParseString(" \\"); ExpectCanParseString("\\\\"); ExpectCannotParseString("\\\\\\"); ExpectCanParseString("\\\\\\\\"); ExpectCanParseString("\\\" "); ExpectCannotParseString("\\\\\" "); ExpectCanParseString("\\\\\\\" "); ExpectCanParseString(" \\\\ \\\" \\\\\\\" "); } TEST(YAMLParser, WorksWithIteratorAlgorithms) { SourceMgr SM; yaml::Stream Stream("[\"1\", \"2\", \"3\", \"4\", \"5\", \"6\"]", SM); yaml::SequenceNode *Array = dyn_cast<yaml::SequenceNode>(Stream.begin()->getRoot()); EXPECT_EQ(6, std::distance(Array->begin(), Array->end())); } TEST(YAMLParser, DefaultDiagnosticFilename) { SourceMgr SM; SMDiagnostic GeneratedDiag; SM.setDiagHandler(CollectDiagnosticsOutput, &GeneratedDiag); // When we construct a YAML stream over an unnamed string, // the filename is hard-coded as "YAML". yaml::Stream UnnamedStream("[]", SM); UnnamedStream.printError(UnnamedStream.begin()->getRoot(), "Hello, World!"); EXPECT_EQ("YAML", GeneratedDiag.getFilename()); } TEST(YAMLParser, DiagnosticFilenameFromBufferID) { SourceMgr SM; SMDiagnostic GeneratedDiag; SM.setDiagHandler(CollectDiagnosticsOutput, &GeneratedDiag); // When we construct a YAML stream over a named buffer, // we get its ID as filename in diagnostics. std::unique_ptr<MemoryBuffer> Buffer = MemoryBuffer::getMemBuffer("[]", "buffername.yaml"); yaml::Stream Stream(Buffer->getMemBufferRef(), SM); Stream.printError(Stream.begin()->getRoot(), "Hello, World!"); EXPECT_EQ("buffername.yaml", GeneratedDiag.getFilename()); } } // end namespace llvm
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/Support/ThreadLocalTest.cpp
//===- llvm/unittest/Support/ThreadLocalTest.cpp - ThreadLocal tests ------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/Support/ThreadLocal.h" #include "gtest/gtest.h" #include <type_traits> using namespace llvm; using namespace sys; namespace { class ThreadLocalTest : public ::testing::Test { }; struct S { int i; }; TEST_F(ThreadLocalTest, Basics) { ThreadLocal<const S> x; static_assert( std::is_const<std::remove_pointer<decltype(x.get())>::type>::value, "ThreadLocal::get didn't return a pointer to const object"); EXPECT_EQ(nullptr, x.get()); S s; x.set(&s); EXPECT_EQ(&s, x.get()); x.erase(); EXPECT_EQ(nullptr, x.get()); ThreadLocal<S> y; static_assert( !std::is_const<std::remove_pointer<decltype(y.get())>::type>::value, "ThreadLocal::get returned a pointer to const object"); EXPECT_EQ(nullptr, y.get()); y.set(&s); EXPECT_EQ(&s, y.get()); y.erase(); EXPECT_EQ(nullptr, y.get()); } }
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/Support/StringPool.cpp
//===- llvm/unittest/Support/StringPoiil.cpp - StringPool tests -----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/Support/StringPool.h" #include "gtest/gtest.h" using namespace llvm; namespace { TEST(PooledStringPtrTest, OperatorEquals) { StringPool pool; const PooledStringPtr a = pool.intern("a"); const PooledStringPtr b = pool.intern("b"); EXPECT_FALSE(a == b); } TEST(PooledStringPtrTest, OperatorNotEquals) { StringPool pool; const PooledStringPtr a = pool.intern("a"); const PooledStringPtr b = pool.intern("b"); EXPECT_TRUE(a != b); } }
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/Support/CMakeLists.txt
set(LLVM_LINK_COMPONENTS ${LLVM_TARGETS_TO_BUILD} Support ) # HLSL Change Begin # Disable filesystem tests because the HLSL compiler file system abstractions # don't work the same way LLVM's do. set(HLSL_IGNORE_SOURCES FileOutputBufferTest.cpp LockFileManagerTest.cpp MemoryTest.cpp Path.cpp raw_pwrite_stream_test.cpp # HLSL compiler doesn't support building targets... TargetRegistry.cpp ) # HLSL Change End add_llvm_unittest(SupportTests AlignOfTest.cpp AllocatorTest.cpp ArrayRecyclerTest.cpp BlockFrequencyTest.cpp BranchProbabilityTest.cpp Casting.cpp CommandLineTest.cpp CompressionTest.cpp ConvertUTFTest.cpp DataExtractorTest.cpp DwarfTest.cpp EndianStreamTest.cpp EndianTest.cpp ErrorOrTest.cpp #FileOutputBufferTest.cpp # HLSL Change LEB128Test.cpp LineIteratorTest.cpp #LockFileManagerTest.cpp # HLSL Change MD5Test.cpp ManagedStatic.cpp MathExtrasTest.cpp MemoryBufferTest.cpp #MemoryTest.cpp # HLSL Change #Path.cpp # HLSL Change ProcessTest.cpp ProgramTest.cpp RegexTest.cpp ScaledNumberTest.cpp SourceMgrTest.cpp SpecialCaseListTest.cpp StreamingMemoryObject.cpp StringPool.cpp SwapByteOrderTest.cpp #TargetRegistry.cpp # HLSL Change ThreadLocalTest.cpp TimeValueTest.cpp UnicodeTest.cpp YAMLIOTest.cpp YAMLParserTest.cpp formatted_raw_ostream_test.cpp raw_ostream_test.cpp #raw_pwrite_stream_test.cpp # HLSL Change ) # ManagedStatic.cpp uses <pthread>. if(LLVM_ENABLE_THREADS AND HAVE_LIBPTHREAD) target_link_libraries(SupportTests pthread) endif()
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/Support/BlockFrequencyTest.cpp
//===- unittests/Support/BlockFrequencyTest.cpp - BlockFrequency tests ----===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/Support/BlockFrequency.h" #include "llvm/Support/BranchProbability.h" #include "llvm/Support/DataTypes.h" #include "gtest/gtest.h" #include <climits> using namespace llvm; namespace { TEST(BlockFrequencyTest, OneToZero) { BlockFrequency Freq(1); BranchProbability Prob(UINT32_MAX - 1, UINT32_MAX); Freq *= Prob; EXPECT_EQ(Freq.getFrequency(), 0u); Freq = BlockFrequency(1); Freq *= Prob; EXPECT_EQ(Freq.getFrequency(), 0u); } TEST(BlockFrequencyTest, OneToOne) { BlockFrequency Freq(1); BranchProbability Prob(UINT32_MAX, UINT32_MAX); Freq *= Prob; EXPECT_EQ(Freq.getFrequency(), 1u); Freq = BlockFrequency(1); Freq *= Prob; EXPECT_EQ(Freq.getFrequency(), 1u); } TEST(BlockFrequencyTest, ThreeToOne) { BlockFrequency Freq(3); BranchProbability Prob(3000000, 9000000); Freq *= Prob; EXPECT_EQ(Freq.getFrequency(), 1u); Freq = BlockFrequency(3); Freq *= Prob; EXPECT_EQ(Freq.getFrequency(), 1u); } TEST(BlockFrequencyTest, MaxToHalfMax) { BlockFrequency Freq(UINT64_MAX); BranchProbability Prob(UINT32_MAX / 2, UINT32_MAX); Freq *= Prob; EXPECT_EQ(Freq.getFrequency(), 9223372034707292159ULL); Freq = BlockFrequency(UINT64_MAX); Freq *= Prob; EXPECT_EQ(Freq.getFrequency(), 9223372034707292159ULL); } TEST(BlockFrequencyTest, BigToBig) { const uint64_t Big = 387246523487234346LL; const uint32_t P = 123456789; BlockFrequency Freq(Big); BranchProbability Prob(P, P); Freq *= Prob; EXPECT_EQ(Freq.getFrequency(), Big); Freq = BlockFrequency(Big); Freq *= Prob; EXPECT_EQ(Freq.getFrequency(), Big); } TEST(BlockFrequencyTest, MaxToMax) { BlockFrequency Freq(UINT64_MAX); BranchProbability Prob(UINT32_MAX, UINT32_MAX); Freq *= Prob; EXPECT_EQ(Freq.getFrequency(), UINT64_MAX); // This additionally makes sure if we have a value equal to our saturating // value, we do not signal saturation if the result equals said value, but // saturating does not occur. Freq = BlockFrequency(UINT64_MAX); Freq *= Prob; EXPECT_EQ(Freq.getFrequency(), UINT64_MAX); } TEST(BlockFrequency, Divide) { BlockFrequency Freq(0x3333333333333333ULL); Freq /= BranchProbability(1, 2); EXPECT_EQ(Freq.getFrequency(), 0x6666666666666666ULL); } TEST(BlockFrequencyTest, Saturate) { BlockFrequency Freq(0x3333333333333333ULL); Freq /= BranchProbability(100, 300); EXPECT_EQ(Freq.getFrequency(), 0x9999999999999999ULL); Freq /= BranchProbability(1, 2); EXPECT_EQ(Freq.getFrequency(), UINT64_MAX); Freq = 0x1000000000000000ULL; Freq /= BranchProbability(10000, 160000); EXPECT_EQ(Freq.getFrequency(), UINT64_MAX); // Try to cheat the multiplication overflow check. Freq = 0x00000001f0000001ull; Freq /= BranchProbability(1000, 0xf000000f); EXPECT_EQ(33506781356485509ULL, Freq.getFrequency()); } TEST(BlockFrequencyTest, SaturatingRightShift) { BlockFrequency Freq(0x10080ULL); Freq >>= 2; EXPECT_EQ(Freq.getFrequency(), 0x4020ULL); Freq >>= 20; EXPECT_EQ(Freq.getFrequency(), 0x1ULL); } }
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/Support/SourceMgrTest.cpp
//===- unittests/Support/SourceMgrTest.cpp - SourceMgr tests --------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/Support/SourceMgr.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/raw_ostream.h" #include "gtest/gtest.h" using namespace llvm; namespace { class SourceMgrTest : public testing::Test { public: SourceMgr SM; unsigned MainBufferID; std::string Output; void setMainBuffer(StringRef Text, StringRef BufferName) { std::unique_ptr<MemoryBuffer> MainBuffer = MemoryBuffer::getMemBuffer(Text, BufferName); MainBufferID = SM.AddNewSourceBuffer(std::move(MainBuffer), llvm::SMLoc()); } SMLoc getLoc(unsigned Offset) { return SMLoc::getFromPointer( SM.getMemoryBuffer(MainBufferID)->getBufferStart() + Offset); } SMRange getRange(unsigned Offset, unsigned Length) { return SMRange(getLoc(Offset), getLoc(Offset + Length)); } void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg, ArrayRef<SMRange> Ranges, ArrayRef<SMFixIt> FixIts) { raw_string_ostream OS(Output); SM.PrintMessage(OS, Loc, Kind, Msg, Ranges, FixIts); } }; } // unnamed namespace TEST_F(SourceMgrTest, BasicError) { setMainBuffer("aaa bbb\nccc ddd\n", "file.in"); printMessage(getLoc(4), SourceMgr::DK_Error, "message", None, None); EXPECT_EQ("file.in:1:5: error: message\n" "aaa bbb\n" " ^\n", Output); } TEST_F(SourceMgrTest, BasicWarning) { setMainBuffer("aaa bbb\nccc ddd\n", "file.in"); printMessage(getLoc(4), SourceMgr::DK_Warning, "message", None, None); EXPECT_EQ("file.in:1:5: warning: message\n" "aaa bbb\n" " ^\n", Output); } TEST_F(SourceMgrTest, BasicNote) { setMainBuffer("aaa bbb\nccc ddd\n", "file.in"); printMessage(getLoc(4), SourceMgr::DK_Note, "message", None, None); EXPECT_EQ("file.in:1:5: note: message\n" "aaa bbb\n" " ^\n", Output); } TEST_F(SourceMgrTest, LocationAtEndOfLine) { setMainBuffer("aaa bbb\nccc ddd\n", "file.in"); printMessage(getLoc(6), SourceMgr::DK_Error, "message", None, None); EXPECT_EQ("file.in:1:7: error: message\n" "aaa bbb\n" " ^\n", Output); } TEST_F(SourceMgrTest, LocationAtNewline) { setMainBuffer("aaa bbb\nccc ddd\n", "file.in"); printMessage(getLoc(7), SourceMgr::DK_Error, "message", None, None); EXPECT_EQ("file.in:1:8: error: message\n" "aaa bbb\n" " ^\n", Output); } TEST_F(SourceMgrTest, BasicRange) { setMainBuffer("aaa bbb\nccc ddd\n", "file.in"); printMessage(getLoc(4), SourceMgr::DK_Error, "message", getRange(4, 3), None); EXPECT_EQ("file.in:1:5: error: message\n" "aaa bbb\n" " ^~~\n", Output); } TEST_F(SourceMgrTest, RangeWithTab) { setMainBuffer("aaa\tbbb\nccc ddd\n", "file.in"); printMessage(getLoc(4), SourceMgr::DK_Error, "message", getRange(3, 3), None); EXPECT_EQ("file.in:1:5: error: message\n" "aaa bbb\n" " ~~~~~^~\n", Output); } TEST_F(SourceMgrTest, MultiLineRange) { setMainBuffer("aaa bbb\nccc ddd\n", "file.in"); printMessage(getLoc(4), SourceMgr::DK_Error, "message", getRange(4, 7), None); EXPECT_EQ("file.in:1:5: error: message\n" "aaa bbb\n" " ^~~\n", Output); } TEST_F(SourceMgrTest, MultipleRanges) { setMainBuffer("aaa bbb\nccc ddd\n", "file.in"); SMRange Ranges[] = { getRange(0, 3), getRange(4, 3) }; printMessage(getLoc(4), SourceMgr::DK_Error, "message", Ranges, None); EXPECT_EQ("file.in:1:5: error: message\n" "aaa bbb\n" "~~~ ^~~\n", Output); } TEST_F(SourceMgrTest, OverlappingRanges) { setMainBuffer("aaa bbb\nccc ddd\n", "file.in"); SMRange Ranges[] = { getRange(0, 3), getRange(2, 4) }; printMessage(getLoc(4), SourceMgr::DK_Error, "message", Ranges, None); EXPECT_EQ("file.in:1:5: error: message\n" "aaa bbb\n" "~~~~^~\n", Output); } TEST_F(SourceMgrTest, BasicFixit) { setMainBuffer("aaa bbb\nccc ddd\n", "file.in"); printMessage(getLoc(4), SourceMgr::DK_Error, "message", None, makeArrayRef(SMFixIt(getRange(4, 3), "zzz"))); EXPECT_EQ("file.in:1:5: error: message\n" "aaa bbb\n" " ^~~\n" " zzz\n", Output); } TEST_F(SourceMgrTest, FixitForTab) { setMainBuffer("aaa\tbbb\nccc ddd\n", "file.in"); printMessage(getLoc(3), SourceMgr::DK_Error, "message", None, makeArrayRef(SMFixIt(getRange(3, 1), "zzz"))); EXPECT_EQ("file.in:1:4: error: message\n" "aaa bbb\n" " ^^^^^\n" " zzz\n", Output); }
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/Support/UnicodeTest.cpp
//===- unittests/Support/UnicodeTest.cpp - Unicode.h tests ----------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/Support/Unicode.h" #include "gtest/gtest.h" namespace llvm { namespace sys { namespace unicode { namespace { TEST(Unicode, columnWidthUTF8) { EXPECT_EQ(0, columnWidthUTF8("")); EXPECT_EQ(1, columnWidthUTF8(" ")); EXPECT_EQ(1, columnWidthUTF8("a")); EXPECT_EQ(1, columnWidthUTF8("~")); EXPECT_EQ(6, columnWidthUTF8("abcdef")); EXPECT_EQ(-1, columnWidthUTF8("\x01")); EXPECT_EQ(-1, columnWidthUTF8("aaaaaaaaaa\x01")); EXPECT_EQ(-1, columnWidthUTF8("\342\200\213")); // 200B ZERO WIDTH SPACE // 00AD SOFT HYPHEN is displayed on most terminals as a space or a dash. Some // text editors display it only when a line is broken at it, some use it as a // line-break hint, but don't display. We choose terminal-oriented // interpretation. EXPECT_EQ(1, columnWidthUTF8("\302\255")); EXPECT_EQ(0, columnWidthUTF8("\314\200")); // 0300 COMBINING GRAVE ACCENT EXPECT_EQ(1, columnWidthUTF8("\340\270\201")); // 0E01 THAI CHARACTER KO KAI EXPECT_EQ(2, columnWidthUTF8("\344\270\200")); // CJK UNIFIED IDEOGRAPH-4E00 EXPECT_EQ(4, columnWidthUTF8("\344\270\200\344\270\200")); EXPECT_EQ(3, columnWidthUTF8("q\344\270\200")); EXPECT_EQ(3, columnWidthUTF8("\314\200\340\270\201\344\270\200")); // Invalid UTF-8 strings, columnWidthUTF8 should error out. EXPECT_EQ(-2, columnWidthUTF8("\344")); EXPECT_EQ(-2, columnWidthUTF8("\344\270")); EXPECT_EQ(-2, columnWidthUTF8("\344\270\033")); EXPECT_EQ(-2, columnWidthUTF8("\344\270\300")); EXPECT_EQ(-2, columnWidthUTF8("\377\366\355")); EXPECT_EQ(-2, columnWidthUTF8("qwer\344")); EXPECT_EQ(-2, columnWidthUTF8("qwer\344\270")); EXPECT_EQ(-2, columnWidthUTF8("qwer\344\270\033")); EXPECT_EQ(-2, columnWidthUTF8("qwer\344\270\300")); EXPECT_EQ(-2, columnWidthUTF8("qwer\377\366\355")); // UTF-8 sequences longer than 4 bytes correspond to unallocated Unicode // characters. EXPECT_EQ(-2, columnWidthUTF8("\370\200\200\200\200")); // U+200000 EXPECT_EQ(-2, columnWidthUTF8("\374\200\200\200\200\200")); // U+4000000 } TEST(Unicode, isPrintable) { EXPECT_FALSE(isPrintable(0)); // <control-0000>-<control-001F> EXPECT_FALSE(isPrintable(0x01)); EXPECT_FALSE(isPrintable(0x1F)); EXPECT_TRUE(isPrintable(' ')); EXPECT_TRUE(isPrintable('A')); EXPECT_TRUE(isPrintable('~')); EXPECT_FALSE(isPrintable(0x7F)); // <control-007F>..<control-009F> EXPECT_FALSE(isPrintable(0x90)); EXPECT_FALSE(isPrintable(0x9F)); EXPECT_TRUE(isPrintable(0xAC)); EXPECT_TRUE(isPrintable(0xAD)); // SOFT HYPHEN is displayed on most terminals // as either a space or a dash. EXPECT_TRUE(isPrintable(0xAE)); EXPECT_TRUE(isPrintable(0x0377)); // GREEK SMALL LETTER PAMPHYLIAN DIGAMMA EXPECT_FALSE(isPrintable(0x0378)); // <reserved-0378>..<reserved-0379> EXPECT_FALSE(isPrintable(0x0600)); // ARABIC NUMBER SIGN EXPECT_FALSE(isPrintable(0x1FFFF)); // <reserved-1F774>..<noncharacter-1FFFF> EXPECT_TRUE(isPrintable(0x20000)); // CJK UNIFIED IDEOGRAPH-20000 EXPECT_FALSE(isPrintable(0x10FFFF)); // noncharacter } } // namespace } // namespace unicode } // namespace sys } // namespace llvm
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/Support/raw_pwrite_stream_test.cpp
//===- raw_pwrite_stream_test.cpp - raw_pwrite_stream tests ---------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "gtest/gtest.h" #include "llvm/ADT/SmallString.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; namespace { TEST(raw_pwrite_ostreamTest, TestSVector) { SmallVector<char, 0> Buffer; raw_svector_ostream OS(Buffer); OS << "abcd"; StringRef Test = "test"; OS.pwrite(Test.data(), Test.size(), 0); EXPECT_EQ(Test, OS.str()); #ifdef GTEST_HAS_DEATH_TEST #ifndef NDEBUG EXPECT_DEATH(OS.pwrite("12345", 5, 0), "We don't support extending the stream"); #endif #endif } TEST(raw_pwrite_ostreamTest, TestFD) { SmallString<64> Path; int FD; sys::fs::createTemporaryFile("foo", "bar", FD, Path); raw_fd_ostream OS(FD, true); OS << "abcd"; StringRef Test = "test"; OS.pwrite(Test.data(), Test.size(), 0); OS.pwrite(Test.data(), Test.size(), 0); #ifdef GTEST_HAS_DEATH_TEST #ifndef NDEBUG EXPECT_DEATH(OS.pwrite("12345", 5, 0), "We don't support extending the stream"); #endif #endif } #ifdef LLVM_ON_UNIX TEST(raw_pwrite_ostreamTest, TestDevNull) { int FD; sys::fs::openFileForWrite("/dev/null", FD, sys::fs::F_None); raw_fd_ostream OS(FD, true); OS << "abcd"; StringRef Test = "test"; OS.pwrite(Test.data(), Test.size(), 0); OS.pwrite(Test.data(), Test.size(), 0); } #endif }
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/Support/ManagedStatic.cpp
//===- llvm/unittest/Support/ManagedStatic.cpp - ManagedStatic tests ------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/Support/ManagedStatic.h" #include "llvm/Config/config.h" #include "llvm/Support/Threading.h" #ifdef HAVE_PTHREAD_H #include <pthread.h> #endif // // /////////////////////////////////////////////////////////////////////////////// #include "gtest/gtest.h" using namespace llvm; namespace { #if LLVM_ENABLE_THREADS != 0 && defined(HAVE_PTHREAD_H) && \ !__has_feature(memory_sanitizer) namespace test1 { llvm::ManagedStatic<int> ms; void *helper(void*) { *ms; return nullptr; } // Valgrind's leak checker complains glibc's stack allocation. // To appease valgrind, we provide our own stack for each thread. void *allocate_stack(pthread_attr_t &a, size_t n = 65536) { void *stack = malloc(n); pthread_attr_init(&a); #if defined(__linux__) pthread_attr_setstack(&a, stack, n); #endif return stack; } } TEST(Initialize, MultipleThreads) { // Run this test under tsan: http://code.google.com/p/data-race-test/ pthread_attr_t a1, a2; void *p1 = test1::allocate_stack(a1); void *p2 = test1::allocate_stack(a2); pthread_t t1, t2; pthread_create(&t1, &a1, test1::helper, nullptr); pthread_create(&t2, &a2, test1::helper, nullptr); pthread_join(t1, nullptr); pthread_join(t2, nullptr); free(p1); free(p2); } #endif } // anonymous namespace
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/Support/MD5Test.cpp
//===- llvm/unittest/Support/MD5Test.cpp - MD5 tests ----------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements unit tests for the MD5 functions. // //===----------------------------------------------------------------------===// #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/SmallString.h" #include "llvm/Support/MD5.h" #include "gtest/gtest.h" using namespace llvm; namespace { /// \brief Tests an arbitrary set of bytes passed as \p Input. void TestMD5Sum(ArrayRef<uint8_t> Input, StringRef Final) { MD5 Hash; Hash.update(Input); MD5::MD5Result MD5Res; Hash.final(MD5Res); SmallString<32> Res; MD5::stringifyResult(MD5Res, Res); EXPECT_EQ(Res, Final); } void TestMD5Sum(StringRef Input, StringRef Final) { MD5 Hash; Hash.update(Input); MD5::MD5Result MD5Res; Hash.final(MD5Res); SmallString<32> Res; MD5::stringifyResult(MD5Res, Res); EXPECT_EQ(Res, Final); } TEST(MD5Test, MD5) { TestMD5Sum(makeArrayRef((const uint8_t *)"", (size_t) 0), "d41d8cd98f00b204e9800998ecf8427e"); TestMD5Sum(makeArrayRef((const uint8_t *)"a", (size_t) 1), "0cc175b9c0f1b6a831c399e269772661"); TestMD5Sum(makeArrayRef((const uint8_t *)"abcdefghijklmnopqrstuvwxyz", (size_t) 26), "c3fcd3d76192e4007dfb496cca67e13b"); TestMD5Sum(makeArrayRef((const uint8_t *)"\0", (size_t) 1), "93b885adfe0da089cdf634904fd59f71"); TestMD5Sum(makeArrayRef((const uint8_t *)"a\0", (size_t) 2), "4144e195f46de78a3623da7364d04f11"); TestMD5Sum(makeArrayRef((const uint8_t *)"abcdefghijklmnopqrstuvwxyz\0", (size_t) 27), "81948d1f1554f58cd1a56ebb01f808cb"); TestMD5Sum("abcdefghijklmnopqrstuvwxyz", "c3fcd3d76192e4007dfb496cca67e13b"); } }
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/Support/AllocatorTest.cpp
//===- llvm/unittest/Support/AllocatorTest.cpp - BumpPtrAllocator tests ---===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/Support/Allocator.h" #include "gtest/gtest.h" #include <cstdlib> using namespace llvm; namespace { TEST(AllocatorTest, Basics) { BumpPtrAllocator Alloc; int *a = (int*)Alloc.Allocate(sizeof(int), 1); int *b = (int*)Alloc.Allocate(sizeof(int) * 10, 1); int *c = (int*)Alloc.Allocate(sizeof(int), 1); *a = 1; b[0] = 2; b[9] = 2; *c = 3; EXPECT_EQ(1, *a); EXPECT_EQ(2, b[0]); EXPECT_EQ(2, b[9]); EXPECT_EQ(3, *c); EXPECT_EQ(1U, Alloc.GetNumSlabs()); BumpPtrAllocator Alloc2 = std::move(Alloc); EXPECT_EQ(0U, Alloc.GetNumSlabs()); EXPECT_EQ(1U, Alloc2.GetNumSlabs()); // Make sure the old pointers still work. These are especially interesting // under ASan or Valgrind. EXPECT_EQ(1, *a); EXPECT_EQ(2, b[0]); EXPECT_EQ(2, b[9]); EXPECT_EQ(3, *c); Alloc = std::move(Alloc2); EXPECT_EQ(0U, Alloc2.GetNumSlabs()); EXPECT_EQ(1U, Alloc.GetNumSlabs()); } // Allocate enough bytes to create three slabs. TEST(AllocatorTest, ThreeSlabs) { BumpPtrAllocator Alloc; Alloc.Allocate(3000, 1); EXPECT_EQ(1U, Alloc.GetNumSlabs()); Alloc.Allocate(3000, 1); EXPECT_EQ(2U, Alloc.GetNumSlabs()); Alloc.Allocate(3000, 1); EXPECT_EQ(3U, Alloc.GetNumSlabs()); } // Allocate enough bytes to create two slabs, reset the allocator, and do it // again. TEST(AllocatorTest, TestReset) { BumpPtrAllocator Alloc; // Allocate something larger than the SizeThreshold=4096. (void)Alloc.Allocate(5000, 1); Alloc.Reset(); // Calling Reset should free all CustomSizedSlabs. EXPECT_EQ(0u, Alloc.GetNumSlabs()); Alloc.Allocate(3000, 1); EXPECT_EQ(1U, Alloc.GetNumSlabs()); Alloc.Allocate(3000, 1); EXPECT_EQ(2U, Alloc.GetNumSlabs()); Alloc.Reset(); EXPECT_EQ(1U, Alloc.GetNumSlabs()); Alloc.Allocate(3000, 1); EXPECT_EQ(1U, Alloc.GetNumSlabs()); Alloc.Allocate(3000, 1); EXPECT_EQ(2U, Alloc.GetNumSlabs()); } // Test some allocations at varying alignments. TEST(AllocatorTest, TestAlignment) { BumpPtrAllocator Alloc; uintptr_t a; a = (uintptr_t)Alloc.Allocate(1, 2); EXPECT_EQ(0U, a & 1); a = (uintptr_t)Alloc.Allocate(1, 4); EXPECT_EQ(0U, a & 3); a = (uintptr_t)Alloc.Allocate(1, 8); EXPECT_EQ(0U, a & 7); a = (uintptr_t)Alloc.Allocate(1, 16); EXPECT_EQ(0U, a & 15); a = (uintptr_t)Alloc.Allocate(1, 32); EXPECT_EQ(0U, a & 31); a = (uintptr_t)Alloc.Allocate(1, 64); EXPECT_EQ(0U, a & 63); a = (uintptr_t)Alloc.Allocate(1, 128); EXPECT_EQ(0U, a & 127); } // Test allocating just over the slab size. This tests a bug where before the // allocator incorrectly calculated the buffer end pointer. TEST(AllocatorTest, TestOverflow) { BumpPtrAllocator Alloc; // Fill the slab right up until the end pointer. Alloc.Allocate(4096, 1); EXPECT_EQ(1U, Alloc.GetNumSlabs()); // If we don't allocate a new slab, then we will have overflowed. Alloc.Allocate(1, 1); EXPECT_EQ(2U, Alloc.GetNumSlabs()); } // Test allocating with a size larger than the initial slab size. TEST(AllocatorTest, TestSmallSlabSize) { BumpPtrAllocator Alloc; Alloc.Allocate(8000, 1); EXPECT_EQ(1U, Alloc.GetNumSlabs()); } // Test requesting alignment that goes past the end of the current slab. TEST(AllocatorTest, TestAlignmentPastSlab) { BumpPtrAllocator Alloc; Alloc.Allocate(4095, 1); // Aligning the current slab pointer is likely to move it past the end of the // slab, which would confuse any unsigned comparisons with the difference of // the end pointer and the aligned pointer. Alloc.Allocate(1024, 8192); EXPECT_EQ(2U, Alloc.GetNumSlabs()); } // Mock slab allocator that returns slabs aligned on 4096 bytes. There is no // easy portable way to do this, so this is kind of a hack. class MockSlabAllocator { static size_t LastSlabSize; public: ~MockSlabAllocator() { } void *Allocate(size_t Size, size_t /*Alignment*/) { // Allocate space for the alignment, the slab, and a void* that goes right // before the slab. size_t Alignment = 4096; void *MemBase = malloc(Size + Alignment - 1 + sizeof(void*)); // Find the slab start. void *Slab = (void *)alignAddr((char*)MemBase + sizeof(void *), Alignment); // Hold a pointer to the base so we can free the whole malloced block. ((void**)Slab)[-1] = MemBase; LastSlabSize = Size; return Slab; } void Deallocate(void *Slab, size_t Size) { free(((void**)Slab)[-1]); } static size_t GetLastSlabSize() { return LastSlabSize; } }; size_t MockSlabAllocator::LastSlabSize = 0; // Allocate a large-ish block with a really large alignment so that the // allocator will think that it has space, but after it does the alignment it // will not. TEST(AllocatorTest, TestBigAlignment) { BumpPtrAllocatorImpl<MockSlabAllocator> Alloc; // First allocate a tiny bit to ensure we have to re-align things. (void)Alloc.Allocate(1, 1); // Now the big chunk with a big alignment. (void)Alloc.Allocate(3000, 2048); // We test that the last slab size is not the default 4096 byte slab, but // rather a custom sized slab that is larger. EXPECT_GT(MockSlabAllocator::GetLastSlabSize(), 4096u); } } // anonymous namespace
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/Support/LockFileManagerTest.cpp
//===- unittests/LockFileManagerTest.cpp - LockFileManager tests ----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/Support/LockFileManager.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Path.h" #include "gtest/gtest.h" #include <memory> using namespace llvm; namespace { TEST(LockFileManagerTest, Basic) { SmallString<64> TmpDir; std::error_code EC; EC = sys::fs::createUniqueDirectory("LockFileManagerTestDir", TmpDir); ASSERT_FALSE(EC); SmallString<64> LockedFile(TmpDir); sys::path::append(LockedFile, "file.lock"); { // The lock file should not exist, so we should successfully acquire it. LockFileManager Locked1(LockedFile); EXPECT_EQ(LockFileManager::LFS_Owned, Locked1.getState()); // Attempting to reacquire the lock should fail. Waiting on it would cause // deadlock, so don't try that. LockFileManager Locked2(LockedFile); EXPECT_NE(LockFileManager::LFS_Owned, Locked2.getState()); } // Now that the lock is out of scope, the file should be gone. EXPECT_FALSE(sys::fs::exists(StringRef(LockedFile))); EC = sys::fs::remove(StringRef(TmpDir)); ASSERT_FALSE(EC); } TEST(LockFileManagerTest, LinkLockExists) { SmallString<64> TmpDir; std::error_code EC; EC = sys::fs::createUniqueDirectory("LockFileManagerTestDir", TmpDir); ASSERT_FALSE(EC); SmallString<64> LockedFile(TmpDir); sys::path::append(LockedFile, "file"); SmallString<64> FileLocK(TmpDir); sys::path::append(FileLocK, "file.lock"); SmallString<64> TmpFileLock(TmpDir); sys::path::append(TmpFileLock, "file.lock-000"); int FD; EC = sys::fs::openFileForWrite(StringRef(TmpFileLock), FD, sys::fs::F_None); ASSERT_FALSE(EC); int Ret = close(FD); ASSERT_EQ(Ret, 0); EC = sys::fs::create_link(TmpFileLock.str(), FileLocK.str()); ASSERT_FALSE(EC); EC = sys::fs::remove(StringRef(TmpFileLock)); ASSERT_FALSE(EC); { // The lock file doesn't point to a real file, so we should successfully // acquire it. LockFileManager Locked(LockedFile); EXPECT_EQ(LockFileManager::LFS_Owned, Locked.getState()); } // Now that the lock is out of scope, the file should be gone. EXPECT_FALSE(sys::fs::exists(StringRef(LockedFile))); EC = sys::fs::remove(StringRef(TmpDir)); ASSERT_FALSE(EC); } TEST(LockFileManagerTest, RelativePath) { SmallString<64> TmpDir; std::error_code EC; EC = sys::fs::createUniqueDirectory("LockFileManagerTestDir", TmpDir); ASSERT_FALSE(EC); char PathBuf[1024]; const char *OrigPath = getcwd(PathBuf, 1024); ASSERT_FALSE(chdir(TmpDir.c_str())); sys::fs::create_directory("inner"); SmallString<64> LockedFile("inner"); sys::path::append(LockedFile, "file"); SmallString<64> FileLock(LockedFile); FileLock += ".lock"; { // The lock file should not exist, so we should successfully acquire it. LockFileManager Locked(LockedFile); EXPECT_EQ(LockFileManager::LFS_Owned, Locked.getState()); EXPECT_TRUE(sys::fs::exists(FileLock.str())); } // Now that the lock is out of scope, the file should be gone. EXPECT_FALSE(sys::fs::exists(LockedFile.str())); EXPECT_FALSE(sys::fs::exists(FileLock.str())); EC = sys::fs::remove("inner"); ASSERT_FALSE(EC); ASSERT_FALSE(chdir(OrigPath)); EC = sys::fs::remove(StringRef(TmpDir)); ASSERT_FALSE(EC); } } // end anonymous namespace
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/Support/BranchProbabilityTest.cpp
//===- unittest/Support/BranchProbabilityTest.cpp - BranchProbability tests -=// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/Support/BranchProbability.h" #include "llvm/Support/raw_ostream.h" #include "gtest/gtest.h" using namespace llvm; namespace llvm { void PrintTo(const BranchProbability &P, ::std::ostream *os) { *os << P.getNumerator() << "/" << P.getDenominator(); } } namespace { typedef BranchProbability BP; TEST(BranchProbabilityTest, Accessors) { EXPECT_EQ(1u, BP(1, 7).getNumerator()); EXPECT_EQ(7u, BP(1, 7).getDenominator()); EXPECT_EQ(0u, BP::getZero().getNumerator()); EXPECT_EQ(1u, BP::getZero().getDenominator()); EXPECT_EQ(1u, BP::getOne().getNumerator()); EXPECT_EQ(1u, BP::getOne().getDenominator()); } TEST(BranchProbabilityTest, Operators) { EXPECT_TRUE(BP(1, 7) < BP(2, 7)); EXPECT_TRUE(BP(1, 7) < BP(1, 4)); EXPECT_TRUE(BP(5, 7) < BP(3, 4)); EXPECT_FALSE(BP(1, 7) < BP(1, 7)); EXPECT_FALSE(BP(1, 7) < BP(2, 14)); EXPECT_FALSE(BP(4, 7) < BP(1, 2)); EXPECT_FALSE(BP(4, 7) < BP(3, 7)); EXPECT_FALSE(BP(1, 7) > BP(2, 7)); EXPECT_FALSE(BP(1, 7) > BP(1, 4)); EXPECT_FALSE(BP(5, 7) > BP(3, 4)); EXPECT_FALSE(BP(1, 7) > BP(1, 7)); EXPECT_FALSE(BP(1, 7) > BP(2, 14)); EXPECT_TRUE(BP(4, 7) > BP(1, 2)); EXPECT_TRUE(BP(4, 7) > BP(3, 7)); EXPECT_TRUE(BP(1, 7) <= BP(2, 7)); EXPECT_TRUE(BP(1, 7) <= BP(1, 4)); EXPECT_TRUE(BP(5, 7) <= BP(3, 4)); EXPECT_TRUE(BP(1, 7) <= BP(1, 7)); EXPECT_TRUE(BP(1, 7) <= BP(2, 14)); EXPECT_FALSE(BP(4, 7) <= BP(1, 2)); EXPECT_FALSE(BP(4, 7) <= BP(3, 7)); EXPECT_FALSE(BP(1, 7) >= BP(2, 7)); EXPECT_FALSE(BP(1, 7) >= BP(1, 4)); EXPECT_FALSE(BP(5, 7) >= BP(3, 4)); EXPECT_TRUE(BP(1, 7) >= BP(1, 7)); EXPECT_TRUE(BP(1, 7) >= BP(2, 14)); EXPECT_TRUE(BP(4, 7) >= BP(1, 2)); EXPECT_TRUE(BP(4, 7) >= BP(3, 7)); EXPECT_FALSE(BP(1, 7) == BP(2, 7)); EXPECT_FALSE(BP(1, 7) == BP(1, 4)); EXPECT_FALSE(BP(5, 7) == BP(3, 4)); EXPECT_TRUE(BP(1, 7) == BP(1, 7)); EXPECT_TRUE(BP(1, 7) == BP(2, 14)); EXPECT_FALSE(BP(4, 7) == BP(1, 2)); EXPECT_FALSE(BP(4, 7) == BP(3, 7)); EXPECT_TRUE(BP(1, 7) != BP(2, 7)); EXPECT_TRUE(BP(1, 7) != BP(1, 4)); EXPECT_TRUE(BP(5, 7) != BP(3, 4)); EXPECT_FALSE(BP(1, 7) != BP(1, 7)); EXPECT_FALSE(BP(1, 7) != BP(2, 14)); EXPECT_TRUE(BP(4, 7) != BP(1, 2)); EXPECT_TRUE(BP(4, 7) != BP(3, 7)); } TEST(BranchProbabilityTest, MoreOperators) { BP A(4, 5); BP B(4U << 29, 5U << 29); BP C(3, 4); EXPECT_TRUE(A == B); EXPECT_FALSE(A != B); EXPECT_FALSE(A < B); EXPECT_FALSE(A > B); EXPECT_TRUE(A <= B); EXPECT_TRUE(A >= B); EXPECT_FALSE(B == C); EXPECT_TRUE(B != C); EXPECT_FALSE(B < C); EXPECT_TRUE(B > C); EXPECT_FALSE(B <= C); EXPECT_TRUE(B >= C); BP BigZero(0, UINT32_MAX); BP BigOne(UINT32_MAX, UINT32_MAX); EXPECT_FALSE(BigZero == BigOne); EXPECT_TRUE(BigZero != BigOne); EXPECT_TRUE(BigZero < BigOne); EXPECT_FALSE(BigZero > BigOne); EXPECT_TRUE(BigZero <= BigOne); EXPECT_FALSE(BigZero >= BigOne); } TEST(BranchProbabilityTest, getCompl) { EXPECT_EQ(BP(5, 7), BP(2, 7).getCompl()); EXPECT_EQ(BP(2, 7), BP(5, 7).getCompl()); EXPECT_EQ(BP::getZero(), BP(7, 7).getCompl()); EXPECT_EQ(BP::getOne(), BP(0, 7).getCompl()); } TEST(BranchProbabilityTest, scale) { // Multiply by 1.0. EXPECT_EQ(UINT64_MAX, BP(1, 1).scale(UINT64_MAX)); EXPECT_EQ(UINT64_MAX, BP(7, 7).scale(UINT64_MAX)); EXPECT_EQ(UINT32_MAX, BP(1, 1).scale(UINT32_MAX)); EXPECT_EQ(UINT32_MAX, BP(7, 7).scale(UINT32_MAX)); EXPECT_EQ(0u, BP(1, 1).scale(0)); EXPECT_EQ(0u, BP(7, 7).scale(0)); // Multiply by 0.0. EXPECT_EQ(0u, BP(0, 1).scale(UINT64_MAX)); EXPECT_EQ(0u, BP(0, 1).scale(UINT64_MAX)); EXPECT_EQ(0u, BP(0, 1).scale(0)); auto Two63 = UINT64_C(1) << 63; auto Two31 = UINT64_C(1) << 31; // Multiply by 0.5. EXPECT_EQ(Two63 - 1, BP(1, 2).scale(UINT64_MAX)); // Big fractions. EXPECT_EQ(1u, BP(Two31, UINT32_MAX).scale(2)); EXPECT_EQ(Two31, BP(Two31, UINT32_MAX).scale(Two31 * 2)); EXPECT_EQ(Two63 + Two31, BP(Two31, UINT32_MAX).scale(UINT64_MAX)); // High precision. EXPECT_EQ(UINT64_C(9223372047592194055), BP(Two31 + 1, UINT32_MAX - 2).scale(UINT64_MAX)); } TEST(BranchProbabilityTest, scaleByInverse) { // Divide by 1.0. EXPECT_EQ(UINT64_MAX, BP(1, 1).scaleByInverse(UINT64_MAX)); EXPECT_EQ(UINT64_MAX, BP(7, 7).scaleByInverse(UINT64_MAX)); EXPECT_EQ(UINT32_MAX, BP(1, 1).scaleByInverse(UINT32_MAX)); EXPECT_EQ(UINT32_MAX, BP(7, 7).scaleByInverse(UINT32_MAX)); EXPECT_EQ(0u, BP(1, 1).scaleByInverse(0)); EXPECT_EQ(0u, BP(7, 7).scaleByInverse(0)); // Divide by something very small. EXPECT_EQ(UINT64_MAX, BP(1, UINT32_MAX).scaleByInverse(UINT64_MAX)); EXPECT_EQ(uint64_t(UINT32_MAX) * UINT32_MAX, BP(1, UINT32_MAX).scaleByInverse(UINT32_MAX)); EXPECT_EQ(UINT32_MAX, BP(1, UINT32_MAX).scaleByInverse(1)); auto Two63 = UINT64_C(1) << 63; auto Two31 = UINT64_C(1) << 31; // Divide by 0.5. EXPECT_EQ(UINT64_MAX - 1, BP(1, 2).scaleByInverse(Two63 - 1)); EXPECT_EQ(UINT64_MAX, BP(1, 2).scaleByInverse(Two63)); // Big fractions. EXPECT_EQ(1u, BP(Two31, UINT32_MAX).scaleByInverse(1)); EXPECT_EQ(2u, BP(Two31 - 1, UINT32_MAX).scaleByInverse(1)); EXPECT_EQ(Two31 * 2 - 1, BP(Two31, UINT32_MAX).scaleByInverse(Two31)); EXPECT_EQ(Two31 * 2 + 1, BP(Two31 - 1, UINT32_MAX).scaleByInverse(Two31)); EXPECT_EQ(UINT64_MAX, BP(Two31, UINT32_MAX).scaleByInverse(Two63 + Two31)); // High precision. The exact answers to these are close to the successors of // the floor. If we were rounding, these would round up. EXPECT_EQ(UINT64_C(18446744065119617030), BP(Two31 + 2, UINT32_MAX - 2) .scaleByInverse(UINT64_C(9223372047592194055))); EXPECT_EQ(UINT64_C(18446744065119617026), BP(Two31 + 1, UINT32_MAX).scaleByInverse(Two63 + Two31)); } TEST(BranchProbabilityTest, scaleBruteForce) { struct { uint64_t Num; uint32_t Prob[2]; uint64_t Result; } Tests[] = { // Data for scaling that results in <= 64 bit division. { 0x1423e2a50ULL, { 0x64819521, 0x7765dd13 }, 0x10f418889ULL }, { 0x35ef14ceULL, { 0x28ade3c7, 0x304532ae }, 0x2d73c33aULL }, { 0xd03dbfbe24ULL, { 0x790079, 0xe419f3 }, 0x6e776fc1fdULL }, { 0x21d67410bULL, { 0x302a9dc2, 0x3ddb4442 }, 0x1a5948fd6ULL }, { 0x8664aeadULL, { 0x3d523513, 0x403523b1 }, 0x805a04cfULL }, { 0x201db0cf4ULL, { 0x35112a7b, 0x79fc0c74 }, 0xdf8b07f6ULL }, { 0x13f1e4430aULL, { 0x21c92bf, 0x21e63aae }, 0x13e0cba15ULL }, { 0x16c83229ULL, { 0x3793f66f, 0x53180dea }, 0xf3ce7b6ULL }, { 0xc62415be8ULL, { 0x9cc4a63, 0x4327ae9b }, 0x1ce8b71caULL }, { 0x6fac5e434ULL, { 0xe5f9170, 0x1115e10b }, 0x5df23dd4cULL }, { 0x1929375f2ULL, { 0x3a851375, 0x76c08456 }, 0xc662b082ULL }, { 0x243c89db6ULL, { 0x354ebfc0, 0x450ef197 }, 0x1bf8c1661ULL }, { 0x310e9b31aULL, { 0x1b1b8acf, 0x2d3629f0 }, 0x1d69c93f9ULL }, { 0xa1fae921dULL, { 0xa7a098c, 0x10469f44 }, 0x684413d6cULL }, { 0xc1582d957ULL, { 0x498e061, 0x59856bc }, 0x9edc5f4e7ULL }, { 0x57cfee75ULL, { 0x1d061dc3, 0x7c8bfc17 }, 0x1476a220ULL }, { 0x139220080ULL, { 0x294a6c71, 0x2a2b07c9 }, 0x1329e1c76ULL }, { 0x1665d353cULL, { 0x7080db5, 0xde0d75c }, 0xb590d9fbULL }, { 0xe8f14541ULL, { 0x5188e8b2, 0x736527ef }, 0xa4971be5ULL }, { 0x2f4775f29ULL, { 0x254ef0fe, 0x435fcf50 }, 0x1a2e449c1ULL }, { 0x27b85d8d7ULL, { 0x304c8220, 0x5de678f2 }, 0x146e3bef9ULL }, { 0x1d362e36bULL, { 0x36c85b12, 0x37a66f55 }, 0x1cc19b8e6ULL }, { 0x155fd48c7ULL, { 0xf5894d, 0x1256108 }, 0x11e383602ULL }, { 0xb5db2d15ULL, { 0x39bb26c5, 0x5bdcda3e }, 0x72499259ULL }, { 0x153990298ULL, { 0x48921c09, 0x706eb817 }, 0xdb3268e8ULL }, { 0x28a7c3ed7ULL, { 0x1f776fd7, 0x349f7a70 }, 0x184f73ae1ULL }, { 0x724dbeabULL, { 0x1bd149f5, 0x253a085e }, 0x5569c0b3ULL }, { 0xd8f0c513ULL, { 0x18c8cc4c, 0x1b72bad0 }, 0xc3e30643ULL }, { 0x17ce3dcbULL, { 0x1e4c6260, 0x233b359e }, 0x1478f4afULL }, { 0x1ce036ce0ULL, { 0x29e3c8af, 0x5318dd4a }, 0xe8e76196ULL }, { 0x1473ae2aULL, { 0x29b897ba, 0x2be29378 }, 0x13718185ULL }, { 0x1dd41aa68ULL, { 0x3d0a4441, 0x5a0e8f12 }, 0x1437b6bbfULL }, { 0x1b49e4a53ULL, { 0x3430c1fe, 0x5a204aed }, 0xfcd6852fULL }, { 0x217941b19ULL, { 0x12ced2bd, 0x21b68310 }, 0x12aca65b1ULL }, { 0xac6a4dc8ULL, { 0x3ed68da8, 0x6fdca34c }, 0x60da926dULL }, { 0x1c503a4e7ULL, { 0xfcbbd32, 0x11e48d17 }, 0x18fec7d38ULL }, { 0x1c885855ULL, { 0x213e919d, 0x25941897 }, 0x193de743ULL }, { 0x29b9c168eULL, { 0x2b644aea, 0x45725ee7 }, 0x1a122e5d5ULL }, { 0x806a33f2ULL, { 0x30a80a23, 0x5063733a }, 0x4db9a264ULL }, { 0x282afc96bULL, { 0x143ae554, 0x1a9863ff }, 0x1e8de5204ULL }, // Data for scaling that results in > 64 bit division. { 0x23ca5f2f672ca41cULL, { 0xecbc641, 0x111373f7 }, 0x1f0301e5e8295ab5ULL }, { 0x5e4f2468142265e3ULL, { 0x1ddf5837, 0x32189233 }, 0x383ca7ba9fdd2c8cULL }, { 0x277a1a6f6b266bf6ULL, { 0x415d81a8, 0x61eb5e1e }, 0x1a5a3e1d41b30c0fULL }, { 0x1bdbb49a237035cbULL, { 0xea5bf17, 0x1d25ffb3 }, 0xdffc51c53d44b93ULL }, { 0x2bce6d29b64fb8ULL, { 0x3bfd5631, 0x7525c9bb }, 0x166ebedda7ac57ULL }, { 0x3a02116103df5013ULL, { 0x2ee18a83, 0x3299aea8 }, 0x35be8922ab1e2a84ULL }, { 0x7b5762390799b18cULL, { 0x12f8e5b9, 0x2563bcd4 }, 0x3e960077aca01209ULL }, { 0x69cfd72537021579ULL, { 0x4c35f468, 0x6a40feee }, 0x4be4cb3848be98a3ULL }, { 0x49dfdf835120f1c1ULL, { 0x8cb3759, 0x559eb891 }, 0x79663f7120edadeULL }, { 0x74b5be5c27676381ULL, { 0x47e4c5e0, 0x7c7b19ff }, 0x4367d2dff36a1028ULL }, { 0x4f50f97075e7f431ULL, { 0x9a50a17, 0x11cd1185 }, 0x2af952b34c032df4ULL }, { 0x2f8b0d712e393be4ULL, { 0x1487e386, 0x15aa356e }, 0x2d0df36478a776aaULL }, { 0x224c1c75999d3deULL, { 0x3b2df0ea, 0x4523b100 }, 0x1d5b481d145f08aULL }, { 0x2bcbcea22a399a76ULL, { 0x28b58212, 0x48dd013e }, 0x187814d084c47cabULL }, { 0x1dbfca91257cb2d1ULL, { 0x1a8c04d9, 0x5e92502c }, 0x859cf7d00f77545ULL }, { 0x7f20039b57cda935ULL, { 0xeccf651, 0x323f476e }, 0x25720cd976461a77ULL }, { 0x40512c6a586aa087ULL, { 0x113b0423, 0x398c9eab }, 0x1341c03de8696a7eULL }, { 0x63d802693f050a11ULL, { 0xf50cdd6, 0xfce2a44 }, 0x60c0177bb5e46846ULL }, { 0x2d956b422838de77ULL, { 0xb2d345b, 0x1321e557 }, 0x1aa0ed16b6aa5319ULL }, { 0x5a1cdf0c1657bc91ULL, { 0x1d77bb0c, 0x1f991ff1 }, 0x54097ee94ff87560ULL }, { 0x3801b26d7e00176bULL, { 0xeed25da, 0x1a819d8b }, 0x1f89e96a3a639526ULL }, { 0x37655e74338e1e45ULL, { 0x300e170a, 0x5a1595fe }, 0x1d8cfb55fddc0441ULL }, { 0x7b38703f2a84e6ULL, { 0x66d9053, 0xc79b6b9 }, 0x3f7d4c91774094ULL }, { 0x2245063c0acb3215ULL, { 0x30ce2f5b, 0x610e7271 }, 0x113b916468389235ULL }, { 0x6bc195877b7b8a7eULL, { 0x392004aa, 0x4a24e60c }, 0x530594fb17db6ba5ULL }, { 0x40a3fde23c7b43dbULL, { 0x4e712195, 0x6553e56e }, 0x320a799bc76a466aULL }, { 0x1d3dfc2866fbccbaULL, { 0x5075b517, 0x5fc42245 }, 0x18917f0061595bc3ULL }, { 0x19aeb14045a61121ULL, { 0x1bf6edec, 0x707e2f4b }, 0x6626672a070bcc7ULL }, { 0x44ff90486c531e9fULL, { 0x66598a, 0x8a90dc }, 0x32f6f2b0525199b0ULL }, { 0x3f3e7121092c5bcbULL, { 0x1c754df7, 0x5951a1b9 }, 0x14267f50b7ef375dULL }, { 0x60e2dafb7e50a67eULL, { 0x4d96c66e, 0x65bd878d }, 0x49e31715ac393f8bULL }, { 0x656286667e0e6e29ULL, { 0x9d971a2, 0xacda23b }, 0x5c6ee315ead6cb4fULL }, { 0x1114e0974255d507ULL, { 0x1c693, 0x2d6ff }, 0xaae42e4b35f6e60ULL }, { 0x508c8baf3a70ff5aULL, { 0x3b26b779, 0x6ad78745 }, 0x2c98387636c4b365ULL }, { 0x5b47bc666bf1f9cfULL, { 0x10a87ed6, 0x187d358a }, 0x3e1767155848368bULL }, { 0x50954e3744460395ULL, { 0x7a42263, 0xcdaa048 }, 0x2fe739f0aee1fee1ULL }, { 0x20020b406550dd8fULL, { 0x3318539, 0x42eead0 }, 0x186f326325fa346bULL }, { 0x5bcb0b872439ffd5ULL, { 0x6f61fb2, 0x9af7344 }, 0x41fa1e3bec3c1b30ULL }, { 0x7a670f365db87a53ULL, { 0x417e102, 0x3bb54c67 }, 0x8642a558304fd9eULL }, { 0x1ef0db1e7bab1cd0ULL, { 0x2b60cf38, 0x4188f78f }, 0x147ae0d6226b2ee6ULL } }; for (const auto &T : Tests) { EXPECT_EQ(T.Result, BP(T.Prob[0], T.Prob[1]).scale(T.Num)); } } }
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/Support/CommandLineTest.cpp
//===- llvm/unittest/Support/CommandLineTest.cpp - CommandLine tests ------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/ADT/STLExtras.h" #include "llvm/Config/config.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/StringSaver.h" #include "gtest/gtest.h" #include <stdlib.h> #include <string> using namespace llvm; namespace { class TempEnvVar { public: TempEnvVar(const char *name, const char *value) : name(name) { const char *old_value = getenv(name); EXPECT_EQ(nullptr, old_value) << old_value; #if HAVE_SETENV setenv(name, value, true); #else # define SKIP_ENVIRONMENT_TESTS #endif } ~TempEnvVar() { #if HAVE_SETENV // Assume setenv and unsetenv come together. unsetenv(name); #else (void)name; // Suppress -Wunused-private-field. #endif } private: const char *const name; }; template <typename T> class StackOption : public cl::opt<T> { typedef cl::opt<T> Base; public: // One option... template<class M0t> explicit StackOption(const M0t &M0) : Base(M0) {} // Two options... template<class M0t, class M1t> StackOption(const M0t &M0, const M1t &M1) : Base(M0, M1) {} // Three options... template<class M0t, class M1t, class M2t> StackOption(const M0t &M0, const M1t &M1, const M2t &M2) : Base(M0, M1, M2) {} // Four options... template<class M0t, class M1t, class M2t, class M3t> StackOption(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3) : Base(M0, M1, M2, M3) {} ~StackOption() override { this->removeArgument(); } }; cl::OptionCategory TestCategory("Test Options", "Description"); TEST(CommandLineTest, ModifyExisitingOption) { // HLSL Change begin const char Description[] = "New description"; const char ArgString[] = "new-test-option"; const char ValueString[] = "Integer"; StackOption<int> TestOption("test-option", cl::desc("old description")); // HLSL Change end StringMap<cl::Option *> &Map = cl::getRegisteredOptions(); ASSERT_TRUE(Map.count("test-option") == 1) << "Could not find option in map."; cl::Option *Retrieved = Map["test-option"]; ASSERT_EQ(&TestOption, Retrieved) << "Retrieved wrong option."; // HLSL - Change begin // No context here but HLSL changed GeneralCategory to a pointer. ASSERT_EQ(cl::GeneralCategory,Retrieved->Category) << "Incorrect default option category."; // HLSL - Change end Retrieved->setCategory(TestCategory); ASSERT_EQ(&TestCategory,Retrieved->Category) << "Failed to modify option's option category."; Retrieved->setDescription(Description); ASSERT_STREQ(Retrieved->HelpStr, Description) << "Changing option description failed."; Retrieved->setArgStr(ArgString); ASSERT_STREQ(ArgString, Retrieved->ArgStr) << "Failed to modify option's Argument string."; Retrieved->setValueStr(ValueString); ASSERT_STREQ(Retrieved->ValueStr, ValueString) << "Failed to modify option's Value string."; Retrieved->setHiddenFlag(cl::Hidden); ASSERT_EQ(cl::Hidden, TestOption.getOptionHiddenFlag()) << "Failed to modify option's hidden flag."; } #ifndef SKIP_ENVIRONMENT_TESTS const char test_env_var[] = "LLVM_TEST_COMMAND_LINE_FLAGS"; cl::opt<std::string> EnvironmentTestOption("env-test-opt"); TEST(CommandLineTest, ParseEnvironment) { TempEnvVar TEV(test_env_var, "-env-test-opt=hello"); EXPECT_EQ("", EnvironmentTestOption); cl::ParseEnvironmentOptions("CommandLineTest", test_env_var); EXPECT_EQ("hello", EnvironmentTestOption); } // This test used to make valgrind complain // ("Conditional jump or move depends on uninitialised value(s)") // // Warning: Do not run any tests after this one that try to gain access to // registered command line options because this will likely result in a // SEGFAULT. This can occur because the cl::opt in the test below is declared // on the stack which will be destroyed after the test completes but the // command line system will still hold a pointer to a deallocated cl::Option. TEST(CommandLineTest, ParseEnvironmentToLocalVar) { // Put cl::opt on stack to check for proper initialization of fields. StackOption<std::string> EnvironmentTestOptionLocal("env-test-opt-local"); TempEnvVar TEV(test_env_var, "-env-test-opt-local=hello-local"); EXPECT_EQ("", EnvironmentTestOptionLocal); cl::ParseEnvironmentOptions("CommandLineTest", test_env_var); EXPECT_EQ("hello-local", EnvironmentTestOptionLocal); } #endif // SKIP_ENVIRONMENT_TESTS TEST(CommandLineTest, UseOptionCategory) { StackOption<int> TestOption2("test-option", cl::cat(TestCategory)); ASSERT_EQ(&TestCategory,TestOption2.Category) << "Failed to assign Option " "Category."; } typedef void ParserFunction(StringRef Source, StringSaver &Saver, SmallVectorImpl<const char *> &NewArgv, bool MarkEOLs); void testCommandLineTokenizer(ParserFunction *parse, const char *Input, const char *const Output[], size_t OutputSize) { SmallVector<const char *, 0> Actual; BumpPtrAllocator A; BumpPtrStringSaver Saver(A); parse(Input, Saver, Actual, /*MarkEOLs=*/false); EXPECT_EQ(OutputSize, Actual.size()); for (unsigned I = 0, E = Actual.size(); I != E; ++I) { if (I < OutputSize) EXPECT_STREQ(Output[I], Actual[I]); } } TEST(CommandLineTest, TokenizeGNUCommandLine) { const char *Input = "foo\\ bar \"foo bar\" \'foo bar\' 'foo\\\\bar' " "foo\"bar\"baz C:\\src\\foo.cpp \"C:\\src\\foo.cpp\""; const char *const Output[] = { "foo bar", "foo bar", "foo bar", "foo\\bar", "foobarbaz", "C:\\src\\foo.cpp", "C:\\src\\foo.cpp" }; testCommandLineTokenizer(cl::TokenizeGNUCommandLine, Input, Output, array_lengthof(Output)); } TEST(CommandLineTest, TokenizeWindowsCommandLine) { const char *Input = "a\\b c\\\\d e\\\\\"f g\" h\\\"i j\\\\\\\"k \"lmn\" o pqr " "\"st \\\"u\" \\v"; const char *const Output[] = { "a\\b", "c\\\\d", "e\\f g", "h\"i", "j\\\"k", "lmn", "o", "pqr", "st \"u", "\\v" }; testCommandLineTokenizer(cl::TokenizeWindowsCommandLine, Input, Output, array_lengthof(Output)); } TEST(CommandLineTest, AliasesWithArguments) { static const size_t ARGC = 3; const char *const Inputs[][ARGC] = { { "-tool", "-actual=x", "-extra" }, { "-tool", "-actual", "x" }, { "-tool", "-alias=x", "-extra" }, { "-tool", "-alias", "x" } }; for (size_t i = 0, e = array_lengthof(Inputs); i < e; ++i) { StackOption<std::string> Actual("actual"); StackOption<bool> Extra("extra"); StackOption<std::string> Input(cl::Positional); cl::alias Alias("alias", llvm::cl::aliasopt(Actual)); cl::ParseCommandLineOptions(ARGC, Inputs[i]); EXPECT_EQ("x", Actual); EXPECT_EQ(0, Input.getNumOccurrences()); Alias.removeArgument(); } } void testAliasRequired(int argc, const char *const *argv) { StackOption<std::string> Option("option", cl::Required); cl::alias Alias("o", llvm::cl::aliasopt(Option)); cl::ParseCommandLineOptions(argc, argv); EXPECT_EQ("x", Option); EXPECT_EQ(1, Option.getNumOccurrences()); Alias.removeArgument(); } TEST(CommandLineTest, AliasRequired) { const char *opts1[] = { "-tool", "-option=x" }; const char *opts2[] = { "-tool", "-o", "x" }; testAliasRequired(array_lengthof(opts1), opts1); testAliasRequired(array_lengthof(opts2), opts2); } /* HLSL Change begin TEST(CommandLineTest, HideUnrelatedOptions) { StackOption<int> TestOption1("hide-option-1"); StackOption<int> TestOption2("hide-option-2", cl::cat(TestCategory)); cl::HideUnrelatedOptions(TestCategory); ASSERT_EQ(cl::ReallyHidden, TestOption1.getOptionHiddenFlag()) << "Failed to hide extra option."; ASSERT_EQ(cl::NotHidden, TestOption2.getOptionHiddenFlag()) << "Hid extra option that should be visable."; StringMap<cl::Option *> &Map = cl::getRegisteredOptions(); ASSERT_EQ(cl::NotHidden, Map["help"]->getOptionHiddenFlag()) << "Hid default option that should be visable."; } cl::OptionCategory TestCategory2("Test Options set 2", "Description"); TEST(CommandLineTest, HideUnrelatedOptionsMulti) { StackOption<int> TestOption1("multi-hide-option-1"); StackOption<int> TestOption2("multi-hide-option-2", cl::cat(TestCategory)); StackOption<int> TestOption3("multi-hide-option-3", cl::cat(TestCategory2)); const cl::OptionCategory *VisibleCategories[] = {&TestCategory, &TestCategory2}; cl::HideUnrelatedOptions(makeArrayRef(VisibleCategories)); ASSERT_EQ(cl::ReallyHidden, TestOption1.getOptionHiddenFlag()) << "Failed to hide extra option."; ASSERT_EQ(cl::NotHidden, TestOption2.getOptionHiddenFlag()) << "Hid extra option that should be visable."; ASSERT_EQ(cl::NotHidden, TestOption3.getOptionHiddenFlag()) << "Hid extra option that should be visable."; StringMap<cl::Option *> &Map = cl::getRegisteredOptions(); ASSERT_EQ(cl::NotHidden, Map["help"]->getOptionHiddenFlag()) << "Hid default option that should be visable."; } HLSL Change End */ } // anonymous namespace
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/Support/DwarfTest.cpp
//===- unittest/Support/DwarfTest.cpp - Dwarf support tests ---------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/Support/Dwarf.h" #include "gtest/gtest.h" using namespace llvm; using namespace llvm::dwarf; namespace { TEST(DwarfTest, TagStringOnInvalid) { // This is invalid, so it shouldn't be stringified. EXPECT_EQ(nullptr, TagString(DW_TAG_invalid)); // These aren't really tags: they describe ranges within tags. They // shouldn't be stringified either. EXPECT_EQ(nullptr, TagString(DW_TAG_lo_user)); EXPECT_EQ(nullptr, TagString(DW_TAG_hi_user)); EXPECT_EQ(nullptr, TagString(DW_TAG_user_base)); } TEST(DwarfTest, getTag) { // A couple of valid tags. EXPECT_EQ(DW_TAG_array_type, getTag("DW_TAG_array_type")); EXPECT_EQ(DW_TAG_module, getTag("DW_TAG_module")); // Invalid tags. EXPECT_EQ(DW_TAG_invalid, getTag("DW_TAG_invalid")); EXPECT_EQ(DW_TAG_invalid, getTag("DW_TAG_madeuptag")); EXPECT_EQ(DW_TAG_invalid, getTag("something else")); // Tag range markers should not be recognized. EXPECT_EQ(DW_TAG_invalid, getTag("DW_TAG_lo_user")); EXPECT_EQ(DW_TAG_invalid, getTag("DW_TAG_hi_user")); EXPECT_EQ(DW_TAG_invalid, getTag("DW_TAG_user_base")); } TEST(DwarfTest, getOperationEncoding) { // Some valid ops. EXPECT_EQ(DW_OP_deref, getOperationEncoding("DW_OP_deref")); EXPECT_EQ(DW_OP_bit_piece, getOperationEncoding("DW_OP_bit_piece")); // Invalid ops. EXPECT_EQ(0u, getOperationEncoding("DW_OP_otherthings")); EXPECT_EQ(0u, getOperationEncoding("other")); // Markers shouldn't be recognized. EXPECT_EQ(0u, getOperationEncoding("DW_OP_lo_user")); EXPECT_EQ(0u, getOperationEncoding("DW_OP_hi_user")); } TEST(DwarfTest, LanguageStringOnInvalid) { // This is invalid, so it shouldn't be stringified. EXPECT_EQ(nullptr, LanguageString(0)); // These aren't really tags: they describe ranges within tags. They // shouldn't be stringified either. EXPECT_EQ(nullptr, LanguageString(DW_LANG_lo_user)); EXPECT_EQ(nullptr, LanguageString(DW_LANG_hi_user)); } TEST(DwarfTest, getLanguage) { // A couple of valid languages. EXPECT_EQ(DW_LANG_C89, getLanguage("DW_LANG_C89")); EXPECT_EQ(DW_LANG_C_plus_plus_11, getLanguage("DW_LANG_C_plus_plus_11")); EXPECT_EQ(DW_LANG_OCaml, getLanguage("DW_LANG_OCaml")); EXPECT_EQ(DW_LANG_Mips_Assembler, getLanguage("DW_LANG_Mips_Assembler")); // Invalid languages. EXPECT_EQ(0u, getLanguage("DW_LANG_invalid")); EXPECT_EQ(0u, getLanguage("DW_TAG_array_type")); EXPECT_EQ(0u, getLanguage("something else")); // Language range markers should not be recognized. EXPECT_EQ(0u, getLanguage("DW_LANG_lo_user")); EXPECT_EQ(0u, getLanguage("DW_LANG_hi_user")); } TEST(DwarfTest, AttributeEncodingStringOnInvalid) { // This is invalid, so it shouldn't be stringified. EXPECT_EQ(nullptr, AttributeEncodingString(0)); // These aren't really tags: they describe ranges within tags. They // shouldn't be stringified either. EXPECT_EQ(nullptr, AttributeEncodingString(DW_ATE_lo_user)); EXPECT_EQ(nullptr, AttributeEncodingString(DW_ATE_hi_user)); } TEST(DwarfTest, getAttributeEncoding) { // A couple of valid languages. EXPECT_EQ(DW_ATE_boolean, getAttributeEncoding("DW_ATE_boolean")); EXPECT_EQ(DW_ATE_imaginary_float, getAttributeEncoding("DW_ATE_imaginary_float")); // Invalid languages. EXPECT_EQ(0u, getAttributeEncoding("DW_ATE_invalid")); EXPECT_EQ(0u, getAttributeEncoding("DW_TAG_array_type")); EXPECT_EQ(0u, getAttributeEncoding("something else")); // AttributeEncoding range markers should not be recognized. EXPECT_EQ(0u, getAttributeEncoding("DW_ATE_lo_user")); EXPECT_EQ(0u, getAttributeEncoding("DW_ATE_hi_user")); } TEST(DwarfTest, VirtualityString) { EXPECT_EQ(StringRef("DW_VIRTUALITY_none"), VirtualityString(DW_VIRTUALITY_none)); EXPECT_EQ(StringRef("DW_VIRTUALITY_virtual"), VirtualityString(DW_VIRTUALITY_virtual)); EXPECT_EQ(StringRef("DW_VIRTUALITY_pure_virtual"), VirtualityString(DW_VIRTUALITY_pure_virtual)); // DW_VIRTUALITY_max should be pure virtual. EXPECT_EQ(StringRef("DW_VIRTUALITY_pure_virtual"), VirtualityString(DW_VIRTUALITY_max)); // Invalid numbers shouldn't be stringified. EXPECT_EQ(nullptr, VirtualityString(DW_VIRTUALITY_max + 1)); EXPECT_EQ(nullptr, VirtualityString(DW_VIRTUALITY_max + 77)); } TEST(DwarfTest, getVirtuality) { EXPECT_EQ(DW_VIRTUALITY_none, getVirtuality("DW_VIRTUALITY_none")); EXPECT_EQ(DW_VIRTUALITY_virtual, getVirtuality("DW_VIRTUALITY_virtual")); EXPECT_EQ(DW_VIRTUALITY_pure_virtual, getVirtuality("DW_VIRTUALITY_pure_virtual")); // Invalid strings. EXPECT_EQ(DW_VIRTUALITY_invalid, getVirtuality("DW_VIRTUALITY_invalid")); EXPECT_EQ(DW_VIRTUALITY_invalid, getVirtuality("DW_VIRTUALITY_max")); EXPECT_EQ(DW_VIRTUALITY_invalid, getVirtuality("something else")); } } // end namespace
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/Support/ConvertUTFTest.cpp
//===- llvm/unittest/Support/ConvertUTFTest.cpp - ConvertUTF tests --------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/Support/ConvertUTF.h" #include "llvm/Support/Format.h" #include "gtest/gtest.h" #include <string> #include <utility> #include <vector> using namespace llvm; TEST(ConvertUTFTest, ConvertUTF16LittleEndianToUTF8String) { // Src is the look of disapproval. static const char Src[] = "\xff\xfe\xa0\x0c_\x00\xa0\x0c"; ArrayRef<char> Ref(Src, sizeof(Src) - 1); std::string Result; bool Success = convertUTF16ToUTF8String(Ref, Result); EXPECT_TRUE(Success); std::string Expected("\xe0\xb2\xa0_\xe0\xb2\xa0"); EXPECT_EQ(Expected, Result); } TEST(ConvertUTFTest, ConvertUTF16BigEndianToUTF8String) { // Src is the look of disapproval. static const char Src[] = "\xfe\xff\x0c\xa0\x00_\x0c\xa0"; ArrayRef<char> Ref(Src, sizeof(Src) - 1); std::string Result; bool Success = convertUTF16ToUTF8String(Ref, Result); EXPECT_TRUE(Success); std::string Expected("\xe0\xb2\xa0_\xe0\xb2\xa0"); EXPECT_EQ(Expected, Result); } TEST(ConvertUTFTest, ConvertUTF8ToUTF16String) { // Src is the look of disapproval. static const char Src[] = "\xe0\xb2\xa0_\xe0\xb2\xa0"; StringRef Ref(Src, sizeof(Src) - 1); SmallVector<UTF16, 5> Result; bool Success = convertUTF8ToUTF16String(Ref, Result); EXPECT_TRUE(Success); static const UTF16 Expected[] = {0x0CA0, 0x005f, 0x0CA0, 0}; ASSERT_EQ(3u, Result.size()); for (int I = 0, E = 3; I != E; ++I) EXPECT_EQ(Expected[I], Result[I]); } TEST(ConvertUTFTest, OddLengthInput) { std::string Result; bool Success = convertUTF16ToUTF8String(makeArrayRef("xxxxx", 5), Result); EXPECT_FALSE(Success); } TEST(ConvertUTFTest, Empty) { std::string Result; bool Success = convertUTF16ToUTF8String(None, Result); EXPECT_TRUE(Success); EXPECT_TRUE(Result.empty()); } TEST(ConvertUTFTest, HasUTF16BOM) { bool HasBOM = hasUTF16ByteOrderMark(makeArrayRef("\xff\xfe", 2)); EXPECT_TRUE(HasBOM); HasBOM = hasUTF16ByteOrderMark(makeArrayRef("\xfe\xff", 2)); EXPECT_TRUE(HasBOM); HasBOM = hasUTF16ByteOrderMark(makeArrayRef("\xfe\xff ", 3)); EXPECT_TRUE(HasBOM); // Don't care about odd lengths. HasBOM = hasUTF16ByteOrderMark(makeArrayRef("\xfe\xff\x00asdf", 6)); EXPECT_TRUE(HasBOM); HasBOM = hasUTF16ByteOrderMark(None); EXPECT_FALSE(HasBOM); HasBOM = hasUTF16ByteOrderMark(makeArrayRef("\xfe", 1)); EXPECT_FALSE(HasBOM); } struct ConvertUTFResultContainer { ConversionResult ErrorCode; std::vector<unsigned> UnicodeScalars; ConvertUTFResultContainer(ConversionResult ErrorCode) : ErrorCode(ErrorCode) {} ConvertUTFResultContainer withScalars(unsigned US0 = 0x110000, unsigned US1 = 0x110000, unsigned US2 = 0x110000, unsigned US3 = 0x110000, unsigned US4 = 0x110000, unsigned US5 = 0x110000, unsigned US6 = 0x110000, unsigned US7 = 0x110000) { ConvertUTFResultContainer Result(*this); if (US0 != 0x110000) Result.UnicodeScalars.push_back(US0); if (US1 != 0x110000) Result.UnicodeScalars.push_back(US1); if (US2 != 0x110000) Result.UnicodeScalars.push_back(US2); if (US3 != 0x110000) Result.UnicodeScalars.push_back(US3); if (US4 != 0x110000) Result.UnicodeScalars.push_back(US4); if (US5 != 0x110000) Result.UnicodeScalars.push_back(US5); if (US6 != 0x110000) Result.UnicodeScalars.push_back(US6); if (US7 != 0x110000) Result.UnicodeScalars.push_back(US7); return Result; } }; std::pair<ConversionResult, std::vector<unsigned>> ConvertUTF8ToUnicodeScalarsLenient(StringRef S) { const UTF8 *SourceStart = reinterpret_cast<const UTF8 *>(S.data()); const UTF8 *SourceNext = SourceStart; std::vector<UTF32> Decoded(S.size(), 0); UTF32 *TargetStart = Decoded.data(); auto ErrorCode = ConvertUTF8toUTF32(&SourceNext, SourceStart + S.size(), &TargetStart, Decoded.data() + Decoded.size(), lenientConversion); Decoded.resize(TargetStart - Decoded.data()); return std::make_pair(ErrorCode, Decoded); } std::pair<ConversionResult, std::vector<unsigned>> ConvertUTF8ToUnicodeScalarsPartialLenient(StringRef S) { const UTF8 *SourceStart = reinterpret_cast<const UTF8 *>(S.data()); const UTF8 *SourceNext = SourceStart; std::vector<UTF32> Decoded(S.size(), 0); UTF32 *TargetStart = Decoded.data(); auto ErrorCode = ConvertUTF8toUTF32Partial( &SourceNext, SourceStart + S.size(), &TargetStart, Decoded.data() + Decoded.size(), lenientConversion); Decoded.resize(TargetStart - Decoded.data()); return std::make_pair(ErrorCode, Decoded); } ::testing::AssertionResult CheckConvertUTF8ToUnicodeScalars(ConvertUTFResultContainer Expected, StringRef S, bool Partial = false) { ConversionResult ErrorCode; std::vector<unsigned> Decoded; if (!Partial) std::tie(ErrorCode, Decoded) = ConvertUTF8ToUnicodeScalarsLenient(S); else std::tie(ErrorCode, Decoded) = ConvertUTF8ToUnicodeScalarsPartialLenient(S); if (Expected.ErrorCode != ErrorCode) return ::testing::AssertionFailure() << "Expected error code " << Expected.ErrorCode << ", actual " << ErrorCode; if (Expected.UnicodeScalars != Decoded) return ::testing::AssertionFailure() << "Expected lenient decoded result:\n" << ::testing::PrintToString(Expected.UnicodeScalars) << "\n" << "Actual result:\n" << ::testing::PrintToString(Decoded); return ::testing::AssertionSuccess(); } TEST(ConvertUTFTest, UTF8ToUTF32Lenient) { // // 1-byte sequences // // U+0041 LATIN CAPITAL LETTER A EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0x0041), "\x41")); // // 2-byte sequences // // U+0283 LATIN SMALL LETTER ESH EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0x0283), "\xca\x83")); // U+03BA GREEK SMALL LETTER KAPPA // U+1F79 GREEK SMALL LETTER OMICRON WITH OXIA // U+03C3 GREEK SMALL LETTER SIGMA // U+03BC GREEK SMALL LETTER MU // U+03B5 GREEK SMALL LETTER EPSILON EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK) .withScalars(0x03ba, 0x1f79, 0x03c3, 0x03bc, 0x03b5), "\xce\xba\xe1\xbd\xb9\xcf\x83\xce\xbc\xce\xb5")); // // 3-byte sequences // // U+4F8B CJK UNIFIED IDEOGRAPH-4F8B // U+6587 CJK UNIFIED IDEOGRAPH-6587 EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0x4f8b, 0x6587), "\xe4\xbe\x8b\xe6\x96\x87")); // U+D55C HANGUL SYLLABLE HAN // U+AE00 HANGUL SYLLABLE GEUL EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0xd55c, 0xae00), "\xed\x95\x9c\xea\xb8\x80")); // U+1112 HANGUL CHOSEONG HIEUH // U+1161 HANGUL JUNGSEONG A // U+11AB HANGUL JONGSEONG NIEUN // U+1100 HANGUL CHOSEONG KIYEOK // U+1173 HANGUL JUNGSEONG EU // U+11AF HANGUL JONGSEONG RIEUL EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK) .withScalars(0x1112, 0x1161, 0x11ab, 0x1100, 0x1173, 0x11af), "\xe1\x84\x92\xe1\x85\xa1\xe1\x86\xab\xe1\x84\x80\xe1\x85\xb3" "\xe1\x86\xaf")); // // 4-byte sequences // // U+E0100 VARIATION SELECTOR-17 EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0x000E0100), "\xf3\xa0\x84\x80")); // // First possible sequence of a certain length // // U+0000 NULL EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0x0000), StringRef("\x00", 1))); // U+0080 PADDING CHARACTER EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0x0080), "\xc2\x80")); // U+0800 SAMARITAN LETTER ALAF EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0x0800), "\xe0\xa0\x80")); // U+10000 LINEAR B SYLLABLE B008 A EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0x10000), "\xf0\x90\x80\x80")); // U+200000 (invalid) EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd), "\xf8\x88\x80\x80\x80")); // U+4000000 (invalid) EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd), "\xfc\x84\x80\x80\x80\x80")); // // Last possible sequence of a certain length // // U+007F DELETE EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0x007f), "\x7f")); // U+07FF (unassigned) EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0x07ff), "\xdf\xbf")); // U+FFFF (noncharacter) EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0xffff), "\xef\xbf\xbf")); // U+1FFFFF (invalid) EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd), "\xf7\xbf\xbf\xbf")); // U+3FFFFFF (invalid) EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd), "\xfb\xbf\xbf\xbf\xbf")); // U+7FFFFFFF (invalid) EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd), "\xfd\xbf\xbf\xbf\xbf\xbf")); // // Other boundary conditions // // U+D7FF (unassigned) EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0xd7ff), "\xed\x9f\xbf")); // U+E000 (private use) EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0xe000), "\xee\x80\x80")); // U+FFFD REPLACEMENT CHARACTER EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0xfffd), "\xef\xbf\xbd")); // U+10FFFF (noncharacter) EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0x10ffff), "\xf4\x8f\xbf\xbf")); // U+110000 (invalid) EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd), "\xf4\x90\x80\x80")); // // Unexpected continuation bytes // // A sequence of unexpected continuation bytes that don't follow a first // byte, every byte is a maximal subpart. EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd), "\x80")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd), "\xbf")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd, 0xfffd), "\x80\x80")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd, 0xfffd), "\x80\xbf")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd, 0xfffd), "\xbf\x80")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd), "\x80\xbf\x80")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd), "\x80\xbf\x80\xbf")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd), "\x80\xbf\x82\xbf\xaa")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd), "\xaa\xb0\xbb\xbf\xaa\xa0")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd), "\xaa\xb0\xbb\xbf\xaa\xa0\x8f")); // All continuation bytes (0x80--0xbf). EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd) .withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd) .withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd) .withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd) .withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd) .withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd) .withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd) .withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd), "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f" "\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f" "\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf" "\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf")); // // Lonely start bytes // // Start bytes of 2-byte sequences (0xc0--0xdf). EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd) .withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd) .withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd) .withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd), "\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf" "\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020) .withScalars(0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020) .withScalars(0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020) .withScalars(0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020) .withScalars(0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020) .withScalars(0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020) .withScalars(0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020) .withScalars(0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020), "\xc0\x20\xc1\x20\xc2\x20\xc3\x20\xc4\x20\xc5\x20\xc6\x20\xc7\x20" "\xc8\x20\xc9\x20\xca\x20\xcb\x20\xcc\x20\xcd\x20\xce\x20\xcf\x20" "\xd0\x20\xd1\x20\xd2\x20\xd3\x20\xd4\x20\xd5\x20\xd6\x20\xd7\x20" "\xd8\x20\xd9\x20\xda\x20\xdb\x20\xdc\x20\xdd\x20\xde\x20\xdf\x20")); // Start bytes of 3-byte sequences (0xe0--0xef). EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd) .withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd), "\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020) .withScalars(0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020) .withScalars(0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020) .withScalars(0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020), "\xe0\x20\xe1\x20\xe2\x20\xe3\x20\xe4\x20\xe5\x20\xe6\x20\xe7\x20" "\xe8\x20\xe9\x20\xea\x20\xeb\x20\xec\x20\xed\x20\xee\x20\xef\x20")); // Start bytes of 4-byte sequences (0xf0--0xf7). EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd), "\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020) .withScalars(0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020), "\xf0\x20\xf1\x20\xf2\x20\xf3\x20\xf4\x20\xf5\x20\xf6\x20\xf7\x20")); // Start bytes of 5-byte sequences (0xf8--0xfb). EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd), "\xf8\xf9\xfa\xfb")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020), "\xf8\x20\xf9\x20\xfa\x20\xfb\x20")); // Start bytes of 6-byte sequences (0xfc--0xfd). EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd, 0xfffd), "\xfc\xfd")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0x0020, 0xfffd, 0x0020), "\xfc\x20\xfd\x20")); // // Other bytes (0xc0--0xc1, 0xfe--0xff). // EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd), "\xc0")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd), "\xc1")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd), "\xfe")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd), "\xff")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd), "\xc0\xc1\xfe\xff")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd), "\xfe\xfe\xff\xff")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd), "\xfe\x80\x80\x80\x80\x80")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd), "\xff\x80\x80\x80\x80\x80")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020, 0xfffd, 0x0020), "\xc0\x20\xc1\x20\xfe\x20\xff\x20")); // // Sequences with one continuation byte missing // EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd), "\xc2")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd), "\xdf")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd), "\xe0\xa0")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd), "\xe0\xbf")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd), "\xe1\x80")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd), "\xec\xbf")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd), "\xed\x80")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd), "\xed\x9f")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd), "\xee\x80")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd), "\xef\xbf")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd), "\xf0\x90\x80")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd), "\xf0\xbf\xbf")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd), "\xf1\x80\x80")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd), "\xf3\xbf\xbf")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd), "\xf4\x80\x80")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd), "\xf4\x8f\xbf")); // Overlong sequences with one trailing byte missing. EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd), "\xc0")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd), "\xc1")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd, 0xfffd), "\xe0\x80")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd, 0xfffd), "\xe0\x9f")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd), "\xf0\x80\x80")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd), "\xf0\x8f\x80")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd), "\xf8\x80\x80\x80")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd), "\xfc\x80\x80\x80\x80")); // Sequences that represent surrogates with one trailing byte missing. // High surrogates EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd, 0xfffd), "\xed\xa0")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd, 0xfffd), "\xed\xac")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd, 0xfffd), "\xed\xaf")); // Low surrogates EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd, 0xfffd), "\xed\xb0")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd, 0xfffd), "\xed\xb4")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd, 0xfffd), "\xed\xbf")); // Ill-formed 4-byte sequences. // 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx // U+1100xx (invalid) EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd), "\xf4\x90\x80")); // U+13FBxx (invalid) EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd), "\xf4\xbf\xbf")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd), "\xf5\x80\x80")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd), "\xf6\x80\x80")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd), "\xf7\x80\x80")); // U+1FFBxx (invalid) EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd), "\xf7\xbf\xbf")); // Ill-formed 5-byte sequences. // 111110uu 10zzzzzz 10zzyyyy 10yyyyxx 10xxxxxx // U+2000xx (invalid) EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd), "\xf8\x88\x80\x80")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd), "\xf8\xbf\xbf\xbf")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd), "\xf9\x80\x80\x80")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd), "\xfa\x80\x80\x80")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd), "\xfb\x80\x80\x80")); // U+3FFFFxx (invalid) EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd), "\xfb\xbf\xbf\xbf")); // Ill-formed 6-byte sequences. // 1111110u 10uuuuuu 10uzzzzz 10zzzyyyy 10yyyyxx 10xxxxxx // U+40000xx (invalid) EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd), "\xfc\x84\x80\x80\x80")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd), "\xfc\xbf\xbf\xbf\xbf")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd), "\xfd\x80\x80\x80\x80")); // U+7FFFFFxx (invalid) EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd), "\xfd\xbf\xbf\xbf\xbf")); // // Sequences with two continuation bytes missing // EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd), "\xf0\x90")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd), "\xf0\xbf")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd), "\xf1\x80")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd), "\xf3\xbf")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd), "\xf4\x80")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd), "\xf4\x8f")); // Overlong sequences with two trailing byte missing. EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd), "\xe0")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd, 0xfffd), "\xf0\x80")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd, 0xfffd), "\xf0\x8f")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd), "\xf8\x80\x80")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd), "\xfc\x80\x80\x80")); // Sequences that represent surrogates with two trailing bytes missing. EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd), "\xed")); // Ill-formed 4-byte sequences. // 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx // U+110yxx (invalid) EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd, 0xfffd), "\xf4\x90")); // U+13Fyxx (invalid) EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd, 0xfffd), "\xf4\xbf")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd, 0xfffd), "\xf5\x80")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd, 0xfffd), "\xf6\x80")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd, 0xfffd), "\xf7\x80")); // U+1FFyxx (invalid) EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd, 0xfffd), "\xf7\xbf")); // Ill-formed 5-byte sequences. // 111110uu 10zzzzzz 10zzyyyy 10yyyyxx 10xxxxxx // U+200yxx (invalid) EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd, 0xfffd, 0xfffd), "\xf8\x88\x80")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd, 0xfffd, 0xfffd), "\xf8\xbf\xbf")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd, 0xfffd, 0xfffd), "\xf9\x80\x80")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd, 0xfffd, 0xfffd), "\xfa\x80\x80")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd, 0xfffd, 0xfffd), "\xfb\x80\x80")); // U+3FFFyxx (invalid) EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd, 0xfffd, 0xfffd), "\xfb\xbf\xbf")); // Ill-formed 6-byte sequences. // 1111110u 10uuuuuu 10zzzzzz 10zzyyyy 10yyyyxx 10xxxxxx // U+4000yxx (invalid) EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd), "\xfc\x84\x80\x80")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd), "\xfc\xbf\xbf\xbf")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd), "\xfd\x80\x80\x80")); // U+7FFFFyxx (invalid) EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd), "\xfd\xbf\xbf\xbf")); // // Sequences with three continuation bytes missing // EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd), "\xf0")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd), "\xf1")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd), "\xf2")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd), "\xf3")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd), "\xf4")); // Broken overlong sequences. EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd), "\xf0")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd, 0xfffd), "\xf8\x80")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd, 0xfffd, 0xfffd), "\xfc\x80\x80")); // Ill-formed 4-byte sequences. // 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx // U+14yyxx (invalid) EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd), "\xf5")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd), "\xf6")); // U+1Cyyxx (invalid) EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd), "\xf7")); // Ill-formed 5-byte sequences. // 111110uu 10zzzzzz 10zzyyyy 10yyyyxx 10xxxxxx // U+20yyxx (invalid) EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd, 0xfffd), "\xf8\x88")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd, 0xfffd), "\xf8\xbf")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd, 0xfffd), "\xf9\x80")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd, 0xfffd), "\xfa\x80")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd, 0xfffd), "\xfb\x80")); // U+3FCyyxx (invalid) EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd, 0xfffd), "\xfb\xbf")); // Ill-formed 6-byte sequences. // 1111110u 10uuuuuu 10zzzzzz 10zzyyyy 10yyyyxx 10xxxxxx // U+400yyxx (invalid) EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd, 0xfffd, 0xfffd), "\xfc\x84\x80")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd, 0xfffd, 0xfffd), "\xfc\xbf\xbf")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd, 0xfffd, 0xfffd), "\xfd\x80\x80")); // U+7FFCyyxx (invalid) EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd, 0xfffd, 0xfffd), "\xfd\xbf\xbf")); // // Sequences with four continuation bytes missing // // Ill-formed 5-byte sequences. // 111110uu 10zzzzzz 10zzyyyy 10yyyyxx 10xxxxxx // U+uzyyxx (invalid) EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd), "\xf8")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd), "\xf9")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd), "\xfa")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd), "\xfb")); // U+3zyyxx (invalid) EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd), "\xfb")); // Broken overlong sequences. EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd), "\xf8")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd, 0xfffd), "\xfc\x80")); // Ill-formed 6-byte sequences. // 1111110u 10uuuuuu 10zzzzzz 10zzyyyy 10yyyyxx 10xxxxxx // U+uzzyyxx (invalid) EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd, 0xfffd), "\xfc\x84")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd, 0xfffd), "\xfc\xbf")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd, 0xfffd), "\xfd\x80")); // U+7Fzzyyxx (invalid) EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd, 0xfffd), "\xfd\xbf")); // // Sequences with five continuation bytes missing // // Ill-formed 6-byte sequences. // 1111110u 10uuuuuu 10zzzzzz 10zzyyyy 10yyyyxx 10xxxxxx // U+uzzyyxx (invalid) EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd), "\xfc")); // U+uuzzyyxx (invalid) EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd), "\xfd")); // // Consecutive sequences with trailing bytes missing // EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, /**/ 0xfffd, 0xfffd, /**/ 0xfffd, 0xfffd, 0xfffd) .withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd) .withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd) .withScalars(0xfffd, /**/ 0xfffd, /**/ 0xfffd, 0xfffd, 0xfffd) .withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd) .withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd), "\xc0" "\xe0\x80" "\xf0\x80\x80" "\xf8\x80\x80\x80" "\xfc\x80\x80\x80\x80" "\xdf" "\xef\xbf" "\xf7\xbf\xbf" "\xfb\xbf\xbf\xbf" "\xfd\xbf\xbf\xbf\xbf")); // // Overlong UTF-8 sequences // // U+002F SOLIDUS EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0x002f), "\x2f")); // Overlong sequences of the above. EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd, 0xfffd), "\xc0\xaf")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd), "\xe0\x80\xaf")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd), "\xf0\x80\x80\xaf")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd), "\xf8\x80\x80\x80\xaf")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd), "\xfc\x80\x80\x80\x80\xaf")); // U+0000 NULL EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0x0000), StringRef("\x00", 1))); // Overlong sequences of the above. EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd, 0xfffd), "\xc0\x80")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd), "\xe0\x80\x80")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd), "\xf0\x80\x80\x80")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd), "\xf8\x80\x80\x80\x80")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd), "\xfc\x80\x80\x80\x80\x80")); // Other overlong sequences. EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd, 0xfffd), "\xc0\xbf")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd, 0xfffd), "\xc1\x80")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal).withScalars(0xfffd, 0xfffd), "\xc1\xbf")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd), "\xe0\x9f\xbf")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd), "\xed\xa0\x80")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd), "\xed\xbf\xbf")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd), "\xf0\x8f\x80\x80")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd), "\xf0\x8f\xbf\xbf")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd), "\xf8\x87\xbf\xbf\xbf")); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd), "\xfc\x83\xbf\xbf\xbf\xbf")); // // Isolated surrogates // // Unicode 6.3.0: // // D71. High-surrogate code point: A Unicode code point in the range // U+D800 to U+DBFF. // // D73. Low-surrogate code point: A Unicode code point in the range // U+DC00 to U+DFFF. // Note: U+E0100 is <DB40 DD00> in UTF16. // High surrogates // U+D800 EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd), "\xed\xa0\x80")); // U+DB40 EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd), "\xed\xac\xa0")); // U+DBFF EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd), "\xed\xaf\xbf")); // Low surrogates // U+DC00 EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd), "\xed\xb0\x80")); // U+DD00 EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd), "\xed\xb4\x80")); // U+DFFF EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd), "\xed\xbf\xbf")); // Surrogate pairs // U+D800 U+DC00 EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd), "\xed\xa0\x80\xed\xb0\x80")); // U+D800 U+DD00 EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd), "\xed\xa0\x80\xed\xb4\x80")); // U+D800 U+DFFF EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd), "\xed\xa0\x80\xed\xbf\xbf")); // U+DB40 U+DC00 EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd), "\xed\xac\xa0\xed\xb0\x80")); // U+DB40 U+DD00 EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd), "\xed\xac\xa0\xed\xb4\x80")); // U+DB40 U+DFFF EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd), "\xed\xac\xa0\xed\xbf\xbf")); // U+DBFF U+DC00 EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd), "\xed\xaf\xbf\xed\xb0\x80")); // U+DBFF U+DD00 EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd), "\xed\xaf\xbf\xed\xb4\x80")); // U+DBFF U+DFFF EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceIllegal) .withScalars(0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd), "\xed\xaf\xbf\xed\xbf\xbf")); // // Noncharacters // // Unicode 6.3.0: // // D14. Noncharacter: A code point that is permanently reserved for // internal use and that should never be interchanged. Noncharacters // consist of the values U+nFFFE and U+nFFFF (where n is from 0 to 1016) // and the values U+FDD0..U+FDEF. // U+FFFE EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0xfffe), "\xef\xbf\xbe")); // U+FFFF EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0xffff), "\xef\xbf\xbf")); // U+1FFFE EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0x1fffe), "\xf0\x9f\xbf\xbe")); // U+1FFFF EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0x1ffff), "\xf0\x9f\xbf\xbf")); // U+2FFFE EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0x2fffe), "\xf0\xaf\xbf\xbe")); // U+2FFFF EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0x2ffff), "\xf0\xaf\xbf\xbf")); // U+3FFFE EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0x3fffe), "\xf0\xbf\xbf\xbe")); // U+3FFFF EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0x3ffff), "\xf0\xbf\xbf\xbf")); // U+4FFFE EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0x4fffe), "\xf1\x8f\xbf\xbe")); // U+4FFFF EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0x4ffff), "\xf1\x8f\xbf\xbf")); // U+5FFFE EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0x5fffe), "\xf1\x9f\xbf\xbe")); // U+5FFFF EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0x5ffff), "\xf1\x9f\xbf\xbf")); // U+6FFFE EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0x6fffe), "\xf1\xaf\xbf\xbe")); // U+6FFFF EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0x6ffff), "\xf1\xaf\xbf\xbf")); // U+7FFFE EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0x7fffe), "\xf1\xbf\xbf\xbe")); // U+7FFFF EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0x7ffff), "\xf1\xbf\xbf\xbf")); // U+8FFFE EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0x8fffe), "\xf2\x8f\xbf\xbe")); // U+8FFFF EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0x8ffff), "\xf2\x8f\xbf\xbf")); // U+9FFFE EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0x9fffe), "\xf2\x9f\xbf\xbe")); // U+9FFFF EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0x9ffff), "\xf2\x9f\xbf\xbf")); // U+AFFFE EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0xafffe), "\xf2\xaf\xbf\xbe")); // U+AFFFF EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0xaffff), "\xf2\xaf\xbf\xbf")); // U+BFFFE EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0xbfffe), "\xf2\xbf\xbf\xbe")); // U+BFFFF EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0xbffff), "\xf2\xbf\xbf\xbf")); // U+CFFFE EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0xcfffe), "\xf3\x8f\xbf\xbe")); // U+CFFFF EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0xcfffF), "\xf3\x8f\xbf\xbf")); // U+DFFFE EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0xdfffe), "\xf3\x9f\xbf\xbe")); // U+DFFFF EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0xdffff), "\xf3\x9f\xbf\xbf")); // U+EFFFE EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0xefffe), "\xf3\xaf\xbf\xbe")); // U+EFFFF EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0xeffff), "\xf3\xaf\xbf\xbf")); // U+FFFFE EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0xffffe), "\xf3\xbf\xbf\xbe")); // U+FFFFF EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0xfffff), "\xf3\xbf\xbf\xbf")); // U+10FFFE EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0x10fffe), "\xf4\x8f\xbf\xbe")); // U+10FFFF EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0x10ffff), "\xf4\x8f\xbf\xbf")); // U+FDD0 EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0xfdd0), "\xef\xb7\x90")); // U+FDD1 EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0xfdd1), "\xef\xb7\x91")); // U+FDD2 EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0xfdd2), "\xef\xb7\x92")); // U+FDD3 EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0xfdd3), "\xef\xb7\x93")); // U+FDD4 EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0xfdd4), "\xef\xb7\x94")); // U+FDD5 EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0xfdd5), "\xef\xb7\x95")); // U+FDD6 EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0xfdd6), "\xef\xb7\x96")); // U+FDD7 EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0xfdd7), "\xef\xb7\x97")); // U+FDD8 EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0xfdd8), "\xef\xb7\x98")); // U+FDD9 EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0xfdd9), "\xef\xb7\x99")); // U+FDDA EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0xfdda), "\xef\xb7\x9a")); // U+FDDB EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0xfddb), "\xef\xb7\x9b")); // U+FDDC EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0xfddc), "\xef\xb7\x9c")); // U+FDDD EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0xfddd), "\xef\xb7\x9d")); // U+FDDE EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0xfdde), "\xef\xb7\x9e")); // U+FDDF EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0xfddf), "\xef\xb7\x9f")); // U+FDE0 EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0xfde0), "\xef\xb7\xa0")); // U+FDE1 EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0xfde1), "\xef\xb7\xa1")); // U+FDE2 EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0xfde2), "\xef\xb7\xa2")); // U+FDE3 EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0xfde3), "\xef\xb7\xa3")); // U+FDE4 EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0xfde4), "\xef\xb7\xa4")); // U+FDE5 EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0xfde5), "\xef\xb7\xa5")); // U+FDE6 EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0xfde6), "\xef\xb7\xa6")); // U+FDE7 EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0xfde7), "\xef\xb7\xa7")); // U+FDE8 EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0xfde8), "\xef\xb7\xa8")); // U+FDE9 EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0xfde9), "\xef\xb7\xa9")); // U+FDEA EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0xfdea), "\xef\xb7\xaa")); // U+FDEB EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0xfdeb), "\xef\xb7\xab")); // U+FDEC EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0xfdec), "\xef\xb7\xac")); // U+FDED EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0xfded), "\xef\xb7\xad")); // U+FDEE EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0xfdee), "\xef\xb7\xae")); // U+FDEF EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0xfdef), "\xef\xb7\xaf")); // U+FDF0 EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0xfdf0), "\xef\xb7\xb0")); // U+FDF1 EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0xfdf1), "\xef\xb7\xb1")); // U+FDF2 EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0xfdf2), "\xef\xb7\xb2")); // U+FDF3 EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0xfdf3), "\xef\xb7\xb3")); // U+FDF4 EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0xfdf4), "\xef\xb7\xb4")); // U+FDF5 EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0xfdf5), "\xef\xb7\xb5")); // U+FDF6 EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0xfdf6), "\xef\xb7\xb6")); // U+FDF7 EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0xfdf7), "\xef\xb7\xb7")); // U+FDF8 EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0xfdf8), "\xef\xb7\xb8")); // U+FDF9 EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0xfdf9), "\xef\xb7\xb9")); // U+FDFA EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0xfdfa), "\xef\xb7\xba")); // U+FDFB EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0xfdfb), "\xef\xb7\xbb")); // U+FDFC EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0xfdfc), "\xef\xb7\xbc")); // U+FDFD EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0xfdfd), "\xef\xb7\xbd")); // U+FDFE EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0xfdfe), "\xef\xb7\xbe")); // U+FDFF EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0xfdff), "\xef\xb7\xbf")); } TEST(ConvertUTFTest, UTF8ToUTF32PartialLenient) { // U+0041 LATIN CAPITAL LETTER A EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(conversionOK).withScalars(0x0041), "\x41", true)); // // Sequences with one continuation byte missing // EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceExhausted), "\xc2", true)); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceExhausted), "\xdf", true)); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceExhausted), "\xe0\xa0", true)); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceExhausted), "\xe0\xbf", true)); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceExhausted), "\xe1\x80", true)); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceExhausted), "\xec\xbf", true)); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceExhausted), "\xed\x80", true)); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceExhausted), "\xed\x9f", true)); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceExhausted), "\xee\x80", true)); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceExhausted), "\xef\xbf", true)); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceExhausted), "\xf0\x90\x80", true)); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceExhausted), "\xf0\xbf\xbf", true)); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceExhausted), "\xf1\x80\x80", true)); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceExhausted), "\xf3\xbf\xbf", true)); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceExhausted), "\xf4\x80\x80", true)); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceExhausted), "\xf4\x8f\xbf", true)); EXPECT_TRUE(CheckConvertUTF8ToUnicodeScalars( ConvertUTFResultContainer(sourceExhausted).withScalars(0x0041), "\x41\xc2", true)); }
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/Support/Path.cpp
//===- llvm/unittest/Support/Path.cpp - Path tests ------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/Support/Path.h" #include "llvm/Support/Errc.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/raw_ostream.h" #include "gtest/gtest.h" #ifdef LLVM_ON_WIN32 #include <windows.h> #include <winerror.h> #endif using namespace llvm; using namespace llvm::sys; #define ASSERT_NO_ERROR(x) \ if (std::error_code ASSERT_NO_ERROR_ec = x) { \ SmallString<128> MessageStorage; \ raw_svector_ostream Message(MessageStorage); \ Message << #x ": did not return errc::success.\n" \ << "error number: " << ASSERT_NO_ERROR_ec.value() << "\n" \ << "error message: " << ASSERT_NO_ERROR_ec.message() << "\n"; \ GTEST_FATAL_FAILURE_(MessageStorage.c_str()); \ } else { \ } namespace { TEST(is_separator, Works) { EXPECT_TRUE(path::is_separator('/')); EXPECT_FALSE(path::is_separator('\0')); EXPECT_FALSE(path::is_separator('-')); EXPECT_FALSE(path::is_separator(' ')); #ifdef LLVM_ON_WIN32 EXPECT_TRUE(path::is_separator('\\')); #else EXPECT_FALSE(path::is_separator('\\')); #endif } TEST(Support, Path) { SmallVector<StringRef, 40> paths; paths.push_back(""); paths.push_back("."); paths.push_back(".."); paths.push_back("foo"); paths.push_back("/"); paths.push_back("/foo"); paths.push_back("foo/"); paths.push_back("/foo/"); paths.push_back("foo/bar"); paths.push_back("/foo/bar"); paths.push_back("//net"); paths.push_back("//net/foo"); paths.push_back("///foo///"); paths.push_back("///foo///bar"); paths.push_back("/."); paths.push_back("./"); paths.push_back("/.."); paths.push_back("../"); paths.push_back("foo/."); paths.push_back("foo/.."); paths.push_back("foo/./"); paths.push_back("foo/./bar"); paths.push_back("foo/.."); paths.push_back("foo/../"); paths.push_back("foo/../bar"); paths.push_back("c:"); paths.push_back("c:/"); paths.push_back("c:foo"); paths.push_back("c:/foo"); paths.push_back("c:foo/"); paths.push_back("c:/foo/"); paths.push_back("c:/foo/bar"); paths.push_back("prn:"); paths.push_back("c:\\"); paths.push_back("c:foo"); paths.push_back("c:\\foo"); paths.push_back("c:foo\\"); paths.push_back("c:\\foo\\"); paths.push_back("c:\\foo/"); paths.push_back("c:/foo\\bar"); SmallVector<StringRef, 5> ComponentStack; for (SmallVector<StringRef, 40>::const_iterator i = paths.begin(), e = paths.end(); i != e; ++i) { for (sys::path::const_iterator ci = sys::path::begin(*i), ce = sys::path::end(*i); ci != ce; ++ci) { ASSERT_FALSE(ci->empty()); ComponentStack.push_back(*ci); } for (sys::path::reverse_iterator ci = sys::path::rbegin(*i), ce = sys::path::rend(*i); ci != ce; ++ci) { ASSERT_TRUE(*ci == ComponentStack.back()); ComponentStack.pop_back(); } ASSERT_TRUE(ComponentStack.empty()); path::has_root_path(*i); path::root_path(*i); path::has_root_name(*i); path::root_name(*i); path::has_root_directory(*i); path::root_directory(*i); path::has_parent_path(*i); path::parent_path(*i); path::has_filename(*i); path::filename(*i); path::has_stem(*i); path::stem(*i); path::has_extension(*i); path::extension(*i); path::is_absolute(*i); path::is_relative(*i); SmallString<128> temp_store; temp_store = *i; ASSERT_NO_ERROR(fs::make_absolute(temp_store)); temp_store = *i; path::remove_filename(temp_store); temp_store = *i; path::replace_extension(temp_store, "ext"); StringRef filename(temp_store.begin(), temp_store.size()), stem, ext; stem = path::stem(filename); ext = path::extension(filename); EXPECT_EQ(*sys::path::rbegin(filename), (stem + ext).str()); path::native(*i, temp_store); } } TEST(Support, RelativePathIterator) { SmallString<64> Path(StringRef("c/d/e/foo.txt")); typedef SmallVector<StringRef, 4> PathComponents; PathComponents ExpectedPathComponents; PathComponents ActualPathComponents; StringRef(Path).split(ExpectedPathComponents, "/"); for (path::const_iterator I = path::begin(Path), E = path::end(Path); I != E; ++I) { ActualPathComponents.push_back(*I); } ASSERT_EQ(ExpectedPathComponents.size(), ActualPathComponents.size()); for (size_t i = 0; i <ExpectedPathComponents.size(); ++i) { EXPECT_EQ(ExpectedPathComponents[i].str(), ActualPathComponents[i].str()); } } TEST(Support, RelativePathDotIterator) { SmallString<64> Path(StringRef(".c/.d/../.")); typedef SmallVector<StringRef, 4> PathComponents; PathComponents ExpectedPathComponents; PathComponents ActualPathComponents; StringRef(Path).split(ExpectedPathComponents, "/"); for (path::const_iterator I = path::begin(Path), E = path::end(Path); I != E; ++I) { ActualPathComponents.push_back(*I); } ASSERT_EQ(ExpectedPathComponents.size(), ActualPathComponents.size()); for (size_t i = 0; i <ExpectedPathComponents.size(); ++i) { EXPECT_EQ(ExpectedPathComponents[i].str(), ActualPathComponents[i].str()); } } TEST(Support, AbsolutePathIterator) { SmallString<64> Path(StringRef("/c/d/e/foo.txt")); typedef SmallVector<StringRef, 4> PathComponents; PathComponents ExpectedPathComponents; PathComponents ActualPathComponents; StringRef(Path).split(ExpectedPathComponents, "/"); // The root path will also be a component when iterating ExpectedPathComponents[0] = "/"; for (path::const_iterator I = path::begin(Path), E = path::end(Path); I != E; ++I) { ActualPathComponents.push_back(*I); } ASSERT_EQ(ExpectedPathComponents.size(), ActualPathComponents.size()); for (size_t i = 0; i <ExpectedPathComponents.size(); ++i) { EXPECT_EQ(ExpectedPathComponents[i].str(), ActualPathComponents[i].str()); } } TEST(Support, AbsolutePathDotIterator) { SmallString<64> Path(StringRef("/.c/.d/../.")); typedef SmallVector<StringRef, 4> PathComponents; PathComponents ExpectedPathComponents; PathComponents ActualPathComponents; StringRef(Path).split(ExpectedPathComponents, "/"); // The root path will also be a component when iterating ExpectedPathComponents[0] = "/"; for (path::const_iterator I = path::begin(Path), E = path::end(Path); I != E; ++I) { ActualPathComponents.push_back(*I); } ASSERT_EQ(ExpectedPathComponents.size(), ActualPathComponents.size()); for (size_t i = 0; i <ExpectedPathComponents.size(); ++i) { EXPECT_EQ(ExpectedPathComponents[i].str(), ActualPathComponents[i].str()); } } #ifdef LLVM_ON_WIN32 TEST(Support, AbsolutePathIteratorWin32) { SmallString<64> Path(StringRef("c:\\c\\e\\foo.txt")); typedef SmallVector<StringRef, 4> PathComponents; PathComponents ExpectedPathComponents; PathComponents ActualPathComponents; StringRef(Path).split(ExpectedPathComponents, "\\"); // The root path (which comes after the drive name) will also be a component // when iterating. ExpectedPathComponents.insert(ExpectedPathComponents.begin()+1, "\\"); for (path::const_iterator I = path::begin(Path), E = path::end(Path); I != E; ++I) { ActualPathComponents.push_back(*I); } ASSERT_EQ(ExpectedPathComponents.size(), ActualPathComponents.size()); for (size_t i = 0; i <ExpectedPathComponents.size(); ++i) { EXPECT_EQ(ExpectedPathComponents[i].str(), ActualPathComponents[i].str()); } } #endif // LLVM_ON_WIN32 TEST(Support, AbsolutePathIteratorEnd) { // Trailing slashes are converted to '.' unless they are part of the root path. SmallVector<StringRef, 4> Paths; Paths.push_back("/foo/"); Paths.push_back("/foo//"); Paths.push_back("//net//"); #ifdef LLVM_ON_WIN32 Paths.push_back("c:\\\\"); #endif for (StringRef Path : Paths) { StringRef LastComponent = *path::rbegin(Path); EXPECT_EQ(".", LastComponent); } SmallVector<StringRef, 3> RootPaths; RootPaths.push_back("/"); RootPaths.push_back("//net/"); #ifdef LLVM_ON_WIN32 RootPaths.push_back("c:\\"); #endif for (StringRef Path : RootPaths) { StringRef LastComponent = *path::rbegin(Path); EXPECT_EQ(1u, LastComponent.size()); EXPECT_TRUE(path::is_separator(LastComponent[0])); } } TEST(Support, HomeDirectory) { #ifdef LLVM_ON_UNIX // This test only makes sense on Unix if $HOME is set. if (::getenv("HOME")) { #endif SmallString<128> HomeDir; EXPECT_TRUE(path::home_directory(HomeDir)); EXPECT_FALSE(HomeDir.empty()); #ifdef LLVM_ON_UNIX } #endif } class FileSystemTest : public testing::Test { protected: /// Unique temporary directory in which all created filesystem entities must /// be placed. It is removed at the end of each test (must be empty). SmallString<128> TestDirectory; void SetUp() override { ASSERT_NO_ERROR( fs::createUniqueDirectory("file-system-test", TestDirectory)); // We don't care about this specific file. errs() << "Test Directory: " << TestDirectory << '\n'; errs().flush(); } void TearDown() override { ASSERT_NO_ERROR(fs::remove(TestDirectory.str())); } }; TEST_F(FileSystemTest, Unique) { // Create a temp file. int FileDescriptor; SmallString<64> TempPath; ASSERT_NO_ERROR( fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath)); // The same file should return an identical unique id. fs::UniqueID F1, F2; ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath), F1)); ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath), F2)); ASSERT_EQ(F1, F2); // Different files should return different unique ids. int FileDescriptor2; SmallString<64> TempPath2; ASSERT_NO_ERROR( fs::createTemporaryFile("prefix", "temp", FileDescriptor2, TempPath2)); fs::UniqueID D; ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath2), D)); ASSERT_NE(D, F1); ::close(FileDescriptor2); ASSERT_NO_ERROR(fs::remove(Twine(TempPath2))); // Two paths representing the same file on disk should still provide the // same unique id. We can test this by making a hard link. ASSERT_NO_ERROR(fs::create_link(Twine(TempPath), Twine(TempPath2))); fs::UniqueID D2; ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath2), D2)); ASSERT_EQ(D2, F1); ::close(FileDescriptor); SmallString<128> Dir1; ASSERT_NO_ERROR( fs::createUniqueDirectory("dir1", Dir1)); ASSERT_NO_ERROR(fs::getUniqueID(Dir1.c_str(), F1)); ASSERT_NO_ERROR(fs::getUniqueID(Dir1.c_str(), F2)); ASSERT_EQ(F1, F2); SmallString<128> Dir2; ASSERT_NO_ERROR( fs::createUniqueDirectory("dir2", Dir2)); ASSERT_NO_ERROR(fs::getUniqueID(Dir2.c_str(), F2)); ASSERT_NE(F1, F2); } TEST_F(FileSystemTest, TempFiles) { // Create a temp file. int FileDescriptor; SmallString<64> TempPath; ASSERT_NO_ERROR( fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath)); // Make sure it exists. ASSERT_TRUE(sys::fs::exists(Twine(TempPath))); // Create another temp tile. int FD2; SmallString<64> TempPath2; ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD2, TempPath2)); ASSERT_TRUE(TempPath2.endswith(".temp")); ASSERT_NE(TempPath.str(), TempPath2.str()); fs::file_status A, B; ASSERT_NO_ERROR(fs::status(Twine(TempPath), A)); ASSERT_NO_ERROR(fs::status(Twine(TempPath2), B)); EXPECT_FALSE(fs::equivalent(A, B)); ::close(FD2); // Remove Temp2. ASSERT_NO_ERROR(fs::remove(Twine(TempPath2))); ASSERT_NO_ERROR(fs::remove(Twine(TempPath2))); ASSERT_EQ(fs::remove(Twine(TempPath2), false), errc::no_such_file_or_directory); std::error_code EC = fs::status(TempPath2.c_str(), B); EXPECT_EQ(EC, errc::no_such_file_or_directory); EXPECT_EQ(B.type(), fs::file_type::file_not_found); // Make sure Temp2 doesn't exist. ASSERT_EQ(fs::access(Twine(TempPath2), sys::fs::AccessMode::Exist), errc::no_such_file_or_directory); SmallString<64> TempPath3; ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "", TempPath3)); ASSERT_FALSE(TempPath3.endswith(".")); // Create a hard link to Temp1. ASSERT_NO_ERROR(fs::create_link(Twine(TempPath), Twine(TempPath2))); bool equal; ASSERT_NO_ERROR(fs::equivalent(Twine(TempPath), Twine(TempPath2), equal)); EXPECT_TRUE(equal); ASSERT_NO_ERROR(fs::status(Twine(TempPath), A)); ASSERT_NO_ERROR(fs::status(Twine(TempPath2), B)); EXPECT_TRUE(fs::equivalent(A, B)); // Remove Temp1. ::close(FileDescriptor); ASSERT_NO_ERROR(fs::remove(Twine(TempPath))); // Remove the hard link. ASSERT_NO_ERROR(fs::remove(Twine(TempPath2))); // Make sure Temp1 doesn't exist. ASSERT_EQ(fs::access(Twine(TempPath), sys::fs::AccessMode::Exist), errc::no_such_file_or_directory); #ifdef LLVM_ON_WIN32 // Path name > 260 chars should get an error. const char *Path270 = "abcdefghijklmnopqrstuvwxyz9abcdefghijklmnopqrstuvwxyz8" "abcdefghijklmnopqrstuvwxyz7abcdefghijklmnopqrstuvwxyz6" "abcdefghijklmnopqrstuvwxyz5abcdefghijklmnopqrstuvwxyz4" "abcdefghijklmnopqrstuvwxyz3abcdefghijklmnopqrstuvwxyz2" "abcdefghijklmnopqrstuvwxyz1abcdefghijklmnopqrstuvwxyz0"; EXPECT_EQ(fs::createUniqueFile(Path270, FileDescriptor, TempPath), errc::invalid_argument); // Relative path < 247 chars, no problem. const char *Path216 = "abcdefghijklmnopqrstuvwxyz7abcdefghijklmnopqrstuvwxyz6" "abcdefghijklmnopqrstuvwxyz5abcdefghijklmnopqrstuvwxyz4" "abcdefghijklmnopqrstuvwxyz3abcdefghijklmnopqrstuvwxyz2" "abcdefghijklmnopqrstuvwxyz1abcdefghijklmnopqrstuvwxyz0"; ASSERT_NO_ERROR(fs::createTemporaryFile(Path216, "", TempPath)); ASSERT_NO_ERROR(fs::remove(Twine(TempPath))); #endif } TEST_F(FileSystemTest, CreateDir) { ASSERT_NO_ERROR(fs::create_directory(Twine(TestDirectory) + "foo")); ASSERT_NO_ERROR(fs::create_directory(Twine(TestDirectory) + "foo")); ASSERT_EQ(fs::create_directory(Twine(TestDirectory) + "foo", false), errc::file_exists); ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "foo")); #ifdef LLVM_ON_WIN32 // Prove that create_directories() can handle a pathname > 248 characters, // which is the documented limit for CreateDirectory(). // (248 is MAX_PATH subtracting room for an 8.3 filename.) // Generate a directory path guaranteed to fall into that range. size_t TmpLen = TestDirectory.size(); const char *OneDir = "\\123456789"; size_t OneDirLen = strlen(OneDir); ASSERT_LT(OneDirLen, 12U); size_t NLevels = ((248 - TmpLen) / OneDirLen) + 1; SmallString<260> LongDir(TestDirectory); for (size_t I = 0; I < NLevels; ++I) LongDir.append(OneDir); ASSERT_NO_ERROR(fs::create_directories(Twine(LongDir))); ASSERT_NO_ERROR(fs::create_directories(Twine(LongDir))); ASSERT_EQ(fs::create_directories(Twine(LongDir), false), errc::file_exists); // Tidy up, "recursively" removing the directories. StringRef ThisDir(LongDir); for (size_t J = 0; J < NLevels; ++J) { ASSERT_NO_ERROR(fs::remove(ThisDir)); ThisDir = path::parent_path(ThisDir); } // Similarly for a relative pathname. Need to set the current directory to // TestDirectory so that the one we create ends up in the right place. char PreviousDir[260]; size_t PreviousDirLen = ::GetCurrentDirectoryA(260, PreviousDir); ASSERT_GT(PreviousDirLen, 0U); ASSERT_LT(PreviousDirLen, 260U); ASSERT_NE(::SetCurrentDirectoryA(TestDirectory.c_str()), 0); LongDir.clear(); // Generate a relative directory name with absolute length > 248. size_t LongDirLen = 249 - TestDirectory.size(); LongDir.assign(LongDirLen, 'a'); ASSERT_NO_ERROR(fs::create_directory(Twine(LongDir))); // While we're here, prove that .. and . handling works in these long paths. const char *DotDotDirs = "\\..\\.\\b"; LongDir.append(DotDotDirs); ASSERT_NO_ERROR(fs::create_directory("b")); ASSERT_EQ(fs::create_directory(Twine(LongDir), false), errc::file_exists); // And clean up. ASSERT_NO_ERROR(fs::remove("b")); ASSERT_NO_ERROR(fs::remove( Twine(LongDir.substr(0, LongDir.size() - strlen(DotDotDirs))))); ASSERT_NE(::SetCurrentDirectoryA(PreviousDir), 0); #endif } TEST_F(FileSystemTest, DirectoryIteration) { std::error_code ec; for (fs::directory_iterator i(".", ec), e; i != e; i.increment(ec)) ASSERT_NO_ERROR(ec); // Create a known hierarchy to recurse over. ASSERT_NO_ERROR( fs::create_directories(Twine(TestDirectory) + "/recursive/a0/aa1")); ASSERT_NO_ERROR( fs::create_directories(Twine(TestDirectory) + "/recursive/a0/ab1")); ASSERT_NO_ERROR(fs::create_directories(Twine(TestDirectory) + "/recursive/dontlookhere/da1")); ASSERT_NO_ERROR( fs::create_directories(Twine(TestDirectory) + "/recursive/z0/za1")); ASSERT_NO_ERROR( fs::create_directories(Twine(TestDirectory) + "/recursive/pop/p1")); typedef std::vector<std::string> v_t; v_t visited; for (fs::recursive_directory_iterator i(Twine(TestDirectory) + "/recursive", ec), e; i != e; i.increment(ec)){ ASSERT_NO_ERROR(ec); if (path::filename(i->path()) == "p1") { i.pop(); // FIXME: recursive_directory_iterator should be more robust. if (i == e) break; } if (path::filename(i->path()) == "dontlookhere") i.no_push(); visited.push_back(path::filename(i->path())); } v_t::const_iterator a0 = std::find(visited.begin(), visited.end(), "a0"); v_t::const_iterator aa1 = std::find(visited.begin(), visited.end(), "aa1"); v_t::const_iterator ab1 = std::find(visited.begin(), visited.end(), "ab1"); v_t::const_iterator dontlookhere = std::find(visited.begin(), visited.end(), "dontlookhere"); v_t::const_iterator da1 = std::find(visited.begin(), visited.end(), "da1"); v_t::const_iterator z0 = std::find(visited.begin(), visited.end(), "z0"); v_t::const_iterator za1 = std::find(visited.begin(), visited.end(), "za1"); v_t::const_iterator pop = std::find(visited.begin(), visited.end(), "pop"); v_t::const_iterator p1 = std::find(visited.begin(), visited.end(), "p1"); // Make sure that each path was visited correctly. ASSERT_NE(a0, visited.end()); ASSERT_NE(aa1, visited.end()); ASSERT_NE(ab1, visited.end()); ASSERT_NE(dontlookhere, visited.end()); ASSERT_EQ(da1, visited.end()); // Not visited. ASSERT_NE(z0, visited.end()); ASSERT_NE(za1, visited.end()); ASSERT_NE(pop, visited.end()); ASSERT_EQ(p1, visited.end()); // Not visited. // Make sure that parents were visited before children. No other ordering // guarantees can be made across siblings. ASSERT_LT(a0, aa1); ASSERT_LT(a0, ab1); ASSERT_LT(z0, za1); ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/a0/aa1")); ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/a0/ab1")); ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/a0")); ASSERT_NO_ERROR( fs::remove(Twine(TestDirectory) + "/recursive/dontlookhere/da1")); ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/dontlookhere")); ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/pop/p1")); ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/pop")); ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/z0/za1")); ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/z0")); ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive")); } const char archive[] = "!<arch>\x0A"; const char bitcode[] = "\xde\xc0\x17\x0b"; const char coff_object[] = "\x00\x00......"; const char coff_bigobj[] = "\x00\x00\xff\xff\x00\x02......" "\xc7\xa1\xba\xd1\xee\xba\xa9\x4b\xaf\x20\xfa\xf6\x6a\xa4\xdc\xb8"; const char coff_import_library[] = "\x00\x00\xff\xff...."; const char elf_relocatable[] = { 0x7f, 'E', 'L', 'F', 1, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 }; const char macho_universal_binary[] = "\xca\xfe\xba\xbe...\0x00"; const char macho_object[] = "\xfe\xed\xfa\xce..........\x00\x01"; const char macho_executable[] = "\xfe\xed\xfa\xce..........\x00\x02"; const char macho_fixed_virtual_memory_shared_lib[] = "\xfe\xed\xfa\xce..........\x00\x03"; const char macho_core[] = "\xfe\xed\xfa\xce..........\x00\x04"; const char macho_preload_executable[] = "\xfe\xed\xfa\xce..........\x00\x05"; const char macho_dynamically_linked_shared_lib[] = "\xfe\xed\xfa\xce..........\x00\x06"; const char macho_dynamic_linker[] = "\xfe\xed\xfa\xce..........\x00\x07"; const char macho_bundle[] = "\xfe\xed\xfa\xce..........\x00\x08"; const char macho_dsym_companion[] = "\xfe\xed\xfa\xce..........\x00\x0a"; const char macho_kext_bundle[] = "\xfe\xed\xfa\xce..........\x00\x0b"; const char windows_resource[] = "\x00\x00\x00\x00\x020\x00\x00\x00\xff"; const char macho_dynamically_linked_shared_lib_stub[] = "\xfe\xed\xfa\xce..........\x00\x09"; TEST_F(FileSystemTest, Magic) { struct type { const char *filename; const char *magic_str; size_t magic_str_len; fs::file_magic magic; } types[] = { #define DEFINE(magic) \ { #magic, magic, sizeof(magic), fs::file_magic::magic } DEFINE(archive), DEFINE(bitcode), DEFINE(coff_object), { "coff_bigobj", coff_bigobj, sizeof(coff_bigobj), fs::file_magic::coff_object }, DEFINE(coff_import_library), DEFINE(elf_relocatable), DEFINE(macho_universal_binary), DEFINE(macho_object), DEFINE(macho_executable), DEFINE(macho_fixed_virtual_memory_shared_lib), DEFINE(macho_core), DEFINE(macho_preload_executable), DEFINE(macho_dynamically_linked_shared_lib), DEFINE(macho_dynamic_linker), DEFINE(macho_bundle), DEFINE(macho_dynamically_linked_shared_lib_stub), DEFINE(macho_dsym_companion), DEFINE(macho_kext_bundle), DEFINE(windows_resource) #undef DEFINE }; // Create some files filled with magic. for (type *i = types, *e = types + (sizeof(types) / sizeof(type)); i != e; ++i) { SmallString<128> file_pathname(TestDirectory); path::append(file_pathname, i->filename); std::error_code EC; raw_fd_ostream file(file_pathname, EC, sys::fs::F_None); ASSERT_FALSE(file.has_error()); StringRef magic(i->magic_str, i->magic_str_len); file << magic; file.close(); EXPECT_EQ(i->magic, fs::identify_magic(magic)); ASSERT_NO_ERROR(fs::remove(Twine(file_pathname))); } } #ifdef LLVM_ON_WIN32 TEST_F(FileSystemTest, CarriageReturn) { SmallString<128> FilePathname(TestDirectory); std::error_code EC; path::append(FilePathname, "test"); { raw_fd_ostream File(FilePathname, EC, sys::fs::F_Text); ASSERT_NO_ERROR(EC); File << '\n'; } { auto Buf = MemoryBuffer::getFile(FilePathname.str()); EXPECT_TRUE((bool)Buf); EXPECT_EQ(Buf.get()->getBuffer(), "\r\n"); } { raw_fd_ostream File(FilePathname, EC, sys::fs::F_None); ASSERT_NO_ERROR(EC); File << '\n'; } { auto Buf = MemoryBuffer::getFile(FilePathname.str()); EXPECT_TRUE((bool)Buf); EXPECT_EQ(Buf.get()->getBuffer(), "\n"); } ASSERT_NO_ERROR(fs::remove(Twine(FilePathname))); } #endif TEST_F(FileSystemTest, Resize) { int FD; SmallString<64> TempPath; ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD, TempPath)); ASSERT_NO_ERROR(fs::resize_file(FD, 123)); fs::file_status Status; ASSERT_NO_ERROR(fs::status(FD, Status)); ASSERT_EQ(Status.getSize(), 123U); } TEST_F(FileSystemTest, FileMapping) { // Create a temp file. int FileDescriptor; SmallString<64> TempPath; ASSERT_NO_ERROR( fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath)); unsigned Size = 4096; ASSERT_NO_ERROR(fs::resize_file(FileDescriptor, Size)); // Map in temp file and add some content std::error_code EC; StringRef Val("hello there"); { fs::mapped_file_region mfr(FileDescriptor, fs::mapped_file_region::readwrite, Size, 0, EC); ASSERT_NO_ERROR(EC); std::copy(Val.begin(), Val.end(), mfr.data()); // Explicitly add a 0. mfr.data()[Val.size()] = 0; // Unmap temp file } // Map it back in read-only int FD; EC = fs::openFileForRead(Twine(TempPath), FD); ASSERT_NO_ERROR(EC); fs::mapped_file_region mfr(FD, fs::mapped_file_region::readonly, Size, 0, EC); ASSERT_NO_ERROR(EC); // Verify content EXPECT_EQ(StringRef(mfr.const_data()), Val); // Unmap temp file fs::mapped_file_region m(FD, fs::mapped_file_region::readonly, Size, 0, EC); ASSERT_NO_ERROR(EC); ASSERT_EQ(close(FD), 0); } TEST(Support, NormalizePath) { #if defined(LLVM_ON_WIN32) #define EXPECT_PATH_IS(path__, windows__, not_windows__) \ EXPECT_EQ(path__, windows__); #else #define EXPECT_PATH_IS(path__, windows__, not_windows__) \ EXPECT_EQ(path__, not_windows__); #endif SmallString<64> Path1("a"); SmallString<64> Path2("a/b"); SmallString<64> Path3("a\\b"); SmallString<64> Path4("a\\\\b"); SmallString<64> Path5("\\a"); SmallString<64> Path6("a\\"); path::native(Path1); EXPECT_PATH_IS(Path1, "a", "a"); path::native(Path2); EXPECT_PATH_IS(Path2, "a\\b", "a/b"); path::native(Path3); EXPECT_PATH_IS(Path3, "a\\b", "a/b"); path::native(Path4); EXPECT_PATH_IS(Path4, "a\\\\b", "a\\\\b"); path::native(Path5); EXPECT_PATH_IS(Path5, "\\a", "/a"); path::native(Path6); EXPECT_PATH_IS(Path6, "a\\", "a/"); #undef EXPECT_PATH_IS } } // anonymous namespace
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/Support/AlignOfTest.cpp
//=== - llvm/unittest/Support/AlignOfTest.cpp - Alignment utility tests ----===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifdef _MSC_VER // Disable warnings about alignment-based structure padding. // This must be above the includes to suppress warnings in included templates. #pragma warning(disable:4324) #endif #include "llvm/Support/AlignOf.h" #include "llvm/Support/Compiler.h" #include "gtest/gtest.h" using namespace llvm; namespace { // Disable warnings about questionable type definitions. // We're testing that even questionable types work with the alignment utilities. #ifdef _MSC_VER #pragma warning(disable:4584) #endif // Suppress direct base '{anonymous}::S1' inaccessible in '{anonymous}::D9' // due to ambiguity warning. #ifdef __clang__ #pragma clang diagnostic ignored "-Wunknown-pragmas" #pragma clang diagnostic ignored "-Winaccessible-base" #elif ((__GNUC__ * 100) + __GNUC_MINOR__) >= 402 // Pragma based warning suppression was introduced in GGC 4.2. Additionally // this warning is "enabled by default". The warning still appears if -Wall is // suppressed. Apparently GCC suppresses it when -w is specifed, which is odd. #pragma GCC diagnostic warning "-w" #endif // Define some fixed alignment types to use in these tests. struct LLVM_ALIGNAS(1) A1 {}; struct LLVM_ALIGNAS(2) A2 {}; struct LLVM_ALIGNAS(4) A4 {}; struct LLVM_ALIGNAS(8) A8 {}; struct S1 {}; struct S2 { char a; }; struct S3 { int x; }; struct S4 { double y; }; struct S5 { A1 a1; A2 a2; A4 a4; A8 a8; }; struct S6 { double f(); }; struct D1 : S1 {}; struct D2 : S6 { float g(); }; struct D3 : S2 {}; struct D4 : S2 { int x; }; struct D5 : S3 { char c; }; struct D6 : S2, S3 {}; struct D7 : S1, S3 {}; struct D8 : S1, D4, D5 { double x[2]; }; struct D9 : S1, D1 { S1 s1; }; struct V1 { virtual ~V1(); }; struct V2 { int x; virtual ~V2(); }; struct V3 : V1 { ~V3() override; }; struct V4 : virtual V2 { int y; ~V4() override; }; struct V5 : V4, V3 { double z; ~V5() override; }; struct V6 : S1 { virtual ~V6(); }; struct V7 : virtual V2, virtual V6 { ~V7() override; }; struct V8 : V5, virtual V6, V7 { double zz; ~V8() override; }; double S6::f() { return 0.0; } float D2::g() { return 0.0f; } V1::~V1() {} V2::~V2() {} V3::~V3() {} V4::~V4() {} V5::~V5() {} V6::~V6() {} V7::~V7() {} V8::~V8() {} // Ensure alignment is a compile-time constant. char LLVM_ATTRIBUTE_UNUSED test_arr1 [AlignOf<char>::Alignment > 0] [AlignOf<short>::Alignment > 0] [AlignOf<int>::Alignment > 0] [AlignOf<long>::Alignment > 0] [AlignOf<long long>::Alignment > 0] [AlignOf<float>::Alignment > 0] [AlignOf<double>::Alignment > 0] [AlignOf<long double>::Alignment > 0] [AlignOf<void *>::Alignment > 0] [AlignOf<int *>::Alignment > 0] [AlignOf<double (*)(double)>::Alignment > 0] [AlignOf<double (S6::*)()>::Alignment > 0]; char LLVM_ATTRIBUTE_UNUSED test_arr2 [AlignOf<A1>::Alignment > 0] [AlignOf<A2>::Alignment > 0] [AlignOf<A4>::Alignment > 0] [AlignOf<A8>::Alignment > 0]; char LLVM_ATTRIBUTE_UNUSED test_arr3 [AlignOf<S1>::Alignment > 0] [AlignOf<S2>::Alignment > 0] [AlignOf<S3>::Alignment > 0] [AlignOf<S4>::Alignment > 0] [AlignOf<S5>::Alignment > 0] [AlignOf<S6>::Alignment > 0]; char LLVM_ATTRIBUTE_UNUSED test_arr4 [AlignOf<D1>::Alignment > 0] [AlignOf<D2>::Alignment > 0] [AlignOf<D3>::Alignment > 0] [AlignOf<D4>::Alignment > 0] [AlignOf<D5>::Alignment > 0] [AlignOf<D6>::Alignment > 0] [AlignOf<D7>::Alignment > 0] [AlignOf<D8>::Alignment > 0] [AlignOf<D9>::Alignment > 0]; char LLVM_ATTRIBUTE_UNUSED test_arr5 [AlignOf<V1>::Alignment > 0] [AlignOf<V2>::Alignment > 0] [AlignOf<V3>::Alignment > 0] [AlignOf<V4>::Alignment > 0] [AlignOf<V5>::Alignment > 0] [AlignOf<V6>::Alignment > 0] [AlignOf<V7>::Alignment > 0] [AlignOf<V8>::Alignment > 0]; TEST(AlignOfTest, BasicAlignmentInvariants) { EXPECT_LE(1u, alignOf<A1>()); EXPECT_LE(2u, alignOf<A2>()); EXPECT_LE(4u, alignOf<A4>()); EXPECT_LE(8u, alignOf<A8>()); EXPECT_EQ(1u, alignOf<char>()); EXPECT_LE(alignOf<char>(), alignOf<short>()); EXPECT_LE(alignOf<short>(), alignOf<int>()); EXPECT_LE(alignOf<int>(), alignOf<long>()); EXPECT_LE(alignOf<long>(), alignOf<long long>()); EXPECT_LE(alignOf<char>(), alignOf<float>()); EXPECT_LE(alignOf<float>(), alignOf<double>()); EXPECT_LE(alignOf<char>(), alignOf<long double>()); EXPECT_LE(alignOf<char>(), alignOf<void *>()); EXPECT_EQ(alignOf<void *>(), alignOf<int *>()); EXPECT_LE(alignOf<char>(), alignOf<S1>()); EXPECT_LE(alignOf<S1>(), alignOf<S2>()); EXPECT_LE(alignOf<S1>(), alignOf<S3>()); EXPECT_LE(alignOf<S1>(), alignOf<S4>()); EXPECT_LE(alignOf<S1>(), alignOf<S5>()); EXPECT_LE(alignOf<S1>(), alignOf<S6>()); EXPECT_LE(alignOf<S1>(), alignOf<D1>()); EXPECT_LE(alignOf<S1>(), alignOf<D2>()); EXPECT_LE(alignOf<S1>(), alignOf<D3>()); EXPECT_LE(alignOf<S1>(), alignOf<D4>()); EXPECT_LE(alignOf<S1>(), alignOf<D5>()); EXPECT_LE(alignOf<S1>(), alignOf<D6>()); EXPECT_LE(alignOf<S1>(), alignOf<D7>()); EXPECT_LE(alignOf<S1>(), alignOf<D8>()); EXPECT_LE(alignOf<S1>(), alignOf<D9>()); EXPECT_LE(alignOf<S1>(), alignOf<V1>()); EXPECT_LE(alignOf<V1>(), alignOf<V2>()); EXPECT_LE(alignOf<V1>(), alignOf<V3>()); EXPECT_LE(alignOf<V1>(), alignOf<V4>()); EXPECT_LE(alignOf<V1>(), alignOf<V5>()); EXPECT_LE(alignOf<V1>(), alignOf<V6>()); EXPECT_LE(alignOf<V1>(), alignOf<V7>()); EXPECT_LE(alignOf<V1>(), alignOf<V8>()); } TEST(AlignOfTest, BasicAlignedArray) { EXPECT_LE(1u, alignOf<AlignedCharArrayUnion<A1> >()); EXPECT_LE(2u, alignOf<AlignedCharArrayUnion<A2> >()); EXPECT_LE(4u, alignOf<AlignedCharArrayUnion<A4> >()); EXPECT_LE(8u, alignOf<AlignedCharArrayUnion<A8> >()); EXPECT_LE(1u, sizeof(AlignedCharArrayUnion<A1>)); EXPECT_LE(2u, sizeof(AlignedCharArrayUnion<A2>)); EXPECT_LE(4u, sizeof(AlignedCharArrayUnion<A4>)); EXPECT_LE(8u, sizeof(AlignedCharArrayUnion<A8>)); EXPECT_EQ(1u, (alignOf<AlignedCharArrayUnion<A1> >())); EXPECT_EQ(2u, (alignOf<AlignedCharArrayUnion<A1, A2> >())); EXPECT_EQ(4u, (alignOf<AlignedCharArrayUnion<A1, A2, A4> >())); EXPECT_EQ(8u, (alignOf<AlignedCharArrayUnion<A1, A2, A4, A8> >())); EXPECT_EQ(1u, sizeof(AlignedCharArrayUnion<A1>)); EXPECT_EQ(2u, sizeof(AlignedCharArrayUnion<A1, A2>)); EXPECT_EQ(4u, sizeof(AlignedCharArrayUnion<A1, A2, A4>)); EXPECT_EQ(8u, sizeof(AlignedCharArrayUnion<A1, A2, A4, A8>)); EXPECT_EQ(1u, (alignOf<AlignedCharArrayUnion<A1[1]> >())); EXPECT_EQ(2u, (alignOf<AlignedCharArrayUnion<A1[2], A2[1]> >())); EXPECT_EQ(4u, (alignOf<AlignedCharArrayUnion<A1[42], A2[55], A4[13]> >())); EXPECT_EQ(8u, (alignOf<AlignedCharArrayUnion<A1[2], A2[1], A4, A8> >())); EXPECT_EQ(1u, sizeof(AlignedCharArrayUnion<A1[1]>)); EXPECT_EQ(2u, sizeof(AlignedCharArrayUnion<A1[2], A2[1]>)); EXPECT_EQ(4u, sizeof(AlignedCharArrayUnion<A1[3], A2[2], A4>)); EXPECT_EQ(16u, sizeof(AlignedCharArrayUnion<A1, A2[3], A4[3], A8>)); // For other tests we simply assert that the alignment of the union mathes // that of the fundamental type and hope that we have any weird type // productions that would trigger bugs. EXPECT_EQ(alignOf<char>(), alignOf<AlignedCharArrayUnion<char> >()); EXPECT_EQ(alignOf<short>(), alignOf<AlignedCharArrayUnion<short> >()); EXPECT_EQ(alignOf<int>(), alignOf<AlignedCharArrayUnion<int> >()); EXPECT_EQ(alignOf<long>(), alignOf<AlignedCharArrayUnion<long> >()); EXPECT_EQ(alignOf<long long>(), alignOf<AlignedCharArrayUnion<long long> >()); EXPECT_EQ(alignOf<float>(), alignOf<AlignedCharArrayUnion<float> >()); EXPECT_EQ(alignOf<double>(), alignOf<AlignedCharArrayUnion<double> >()); EXPECT_EQ(alignOf<long double>(), alignOf<AlignedCharArrayUnion<long double> >()); EXPECT_EQ(alignOf<void *>(), alignOf<AlignedCharArrayUnion<void *> >()); EXPECT_EQ(alignOf<int *>(), alignOf<AlignedCharArrayUnion<int *> >()); EXPECT_EQ(alignOf<double (*)(double)>(), alignOf<AlignedCharArrayUnion<double (*)(double)> >()); EXPECT_EQ(alignOf<double (S6::*)()>(), alignOf<AlignedCharArrayUnion<double (S6::*)()> >()); EXPECT_EQ(alignOf<S1>(), alignOf<AlignedCharArrayUnion<S1> >()); EXPECT_EQ(alignOf<S2>(), alignOf<AlignedCharArrayUnion<S2> >()); EXPECT_EQ(alignOf<S3>(), alignOf<AlignedCharArrayUnion<S3> >()); EXPECT_EQ(alignOf<S4>(), alignOf<AlignedCharArrayUnion<S4> >()); EXPECT_EQ(alignOf<S5>(), alignOf<AlignedCharArrayUnion<S5> >()); EXPECT_EQ(alignOf<S6>(), alignOf<AlignedCharArrayUnion<S6> >()); EXPECT_EQ(alignOf<D1>(), alignOf<AlignedCharArrayUnion<D1> >()); EXPECT_EQ(alignOf<D2>(), alignOf<AlignedCharArrayUnion<D2> >()); EXPECT_EQ(alignOf<D3>(), alignOf<AlignedCharArrayUnion<D3> >()); EXPECT_EQ(alignOf<D4>(), alignOf<AlignedCharArrayUnion<D4> >()); EXPECT_EQ(alignOf<D5>(), alignOf<AlignedCharArrayUnion<D5> >()); EXPECT_EQ(alignOf<D6>(), alignOf<AlignedCharArrayUnion<D6> >()); EXPECT_EQ(alignOf<D7>(), alignOf<AlignedCharArrayUnion<D7> >()); EXPECT_EQ(alignOf<D8>(), alignOf<AlignedCharArrayUnion<D8> >()); EXPECT_EQ(alignOf<D9>(), alignOf<AlignedCharArrayUnion<D9> >()); EXPECT_EQ(alignOf<V1>(), alignOf<AlignedCharArrayUnion<V1> >()); EXPECT_EQ(alignOf<V2>(), alignOf<AlignedCharArrayUnion<V2> >()); EXPECT_EQ(alignOf<V3>(), alignOf<AlignedCharArrayUnion<V3> >()); EXPECT_EQ(alignOf<V4>(), alignOf<AlignedCharArrayUnion<V4> >()); EXPECT_EQ(alignOf<V5>(), alignOf<AlignedCharArrayUnion<V5> >()); EXPECT_EQ(alignOf<V6>(), alignOf<AlignedCharArrayUnion<V6> >()); EXPECT_EQ(alignOf<V7>(), alignOf<AlignedCharArrayUnion<V7> >()); // Some versions of MSVC get this wrong somewhat disturbingly. The failure // appears to be benign: alignOf<V8>() produces a preposterous value: 12 #ifndef _MSC_VER EXPECT_EQ(alignOf<V8>(), alignOf<AlignedCharArrayUnion<V8> >()); #endif EXPECT_EQ(sizeof(char), sizeof(AlignedCharArrayUnion<char>)); EXPECT_EQ(sizeof(char[1]), sizeof(AlignedCharArrayUnion<char[1]>)); EXPECT_EQ(sizeof(char[2]), sizeof(AlignedCharArrayUnion<char[2]>)); EXPECT_EQ(sizeof(char[3]), sizeof(AlignedCharArrayUnion<char[3]>)); EXPECT_EQ(sizeof(char[4]), sizeof(AlignedCharArrayUnion<char[4]>)); EXPECT_EQ(sizeof(char[5]), sizeof(AlignedCharArrayUnion<char[5]>)); EXPECT_EQ(sizeof(char[8]), sizeof(AlignedCharArrayUnion<char[8]>)); EXPECT_EQ(sizeof(char[13]), sizeof(AlignedCharArrayUnion<char[13]>)); EXPECT_EQ(sizeof(char[16]), sizeof(AlignedCharArrayUnion<char[16]>)); EXPECT_EQ(sizeof(char[21]), sizeof(AlignedCharArrayUnion<char[21]>)); EXPECT_EQ(sizeof(char[32]), sizeof(AlignedCharArrayUnion<char[32]>)); EXPECT_EQ(sizeof(short), sizeof(AlignedCharArrayUnion<short>)); EXPECT_EQ(sizeof(int), sizeof(AlignedCharArrayUnion<int>)); EXPECT_EQ(sizeof(long), sizeof(AlignedCharArrayUnion<long>)); EXPECT_EQ(sizeof(long long), sizeof(AlignedCharArrayUnion<long long>)); EXPECT_EQ(sizeof(float), sizeof(AlignedCharArrayUnion<float>)); EXPECT_EQ(sizeof(double), sizeof(AlignedCharArrayUnion<double>)); EXPECT_EQ(sizeof(long double), sizeof(AlignedCharArrayUnion<long double>)); EXPECT_EQ(sizeof(void *), sizeof(AlignedCharArrayUnion<void *>)); EXPECT_EQ(sizeof(int *), sizeof(AlignedCharArrayUnion<int *>)); EXPECT_EQ(sizeof(double (*)(double)), sizeof(AlignedCharArrayUnion<double (*)(double)>)); EXPECT_EQ(sizeof(double (S6::*)()), sizeof(AlignedCharArrayUnion<double (S6::*)()>)); EXPECT_EQ(sizeof(S1), sizeof(AlignedCharArrayUnion<S1>)); EXPECT_EQ(sizeof(S2), sizeof(AlignedCharArrayUnion<S2>)); EXPECT_EQ(sizeof(S3), sizeof(AlignedCharArrayUnion<S3>)); EXPECT_EQ(sizeof(S4), sizeof(AlignedCharArrayUnion<S4>)); EXPECT_EQ(sizeof(S5), sizeof(AlignedCharArrayUnion<S5>)); EXPECT_EQ(sizeof(S6), sizeof(AlignedCharArrayUnion<S6>)); EXPECT_EQ(sizeof(D1), sizeof(AlignedCharArrayUnion<D1>)); EXPECT_EQ(sizeof(D2), sizeof(AlignedCharArrayUnion<D2>)); EXPECT_EQ(sizeof(D3), sizeof(AlignedCharArrayUnion<D3>)); EXPECT_EQ(sizeof(D4), sizeof(AlignedCharArrayUnion<D4>)); EXPECT_EQ(sizeof(D5), sizeof(AlignedCharArrayUnion<D5>)); EXPECT_EQ(sizeof(D6), sizeof(AlignedCharArrayUnion<D6>)); EXPECT_EQ(sizeof(D7), sizeof(AlignedCharArrayUnion<D7>)); EXPECT_EQ(sizeof(D8), sizeof(AlignedCharArrayUnion<D8>)); EXPECT_EQ(sizeof(D9), sizeof(AlignedCharArrayUnion<D9>)); EXPECT_EQ(sizeof(D9[1]), sizeof(AlignedCharArrayUnion<D9[1]>)); EXPECT_EQ(sizeof(D9[2]), sizeof(AlignedCharArrayUnion<D9[2]>)); EXPECT_EQ(sizeof(D9[3]), sizeof(AlignedCharArrayUnion<D9[3]>)); EXPECT_EQ(sizeof(D9[4]), sizeof(AlignedCharArrayUnion<D9[4]>)); EXPECT_EQ(sizeof(D9[5]), sizeof(AlignedCharArrayUnion<D9[5]>)); EXPECT_EQ(sizeof(D9[8]), sizeof(AlignedCharArrayUnion<D9[8]>)); EXPECT_EQ(sizeof(D9[13]), sizeof(AlignedCharArrayUnion<D9[13]>)); EXPECT_EQ(sizeof(D9[16]), sizeof(AlignedCharArrayUnion<D9[16]>)); EXPECT_EQ(sizeof(D9[21]), sizeof(AlignedCharArrayUnion<D9[21]>)); EXPECT_EQ(sizeof(D9[32]), sizeof(AlignedCharArrayUnion<D9[32]>)); EXPECT_EQ(sizeof(V1), sizeof(AlignedCharArrayUnion<V1>)); EXPECT_EQ(sizeof(V2), sizeof(AlignedCharArrayUnion<V2>)); EXPECT_EQ(sizeof(V3), sizeof(AlignedCharArrayUnion<V3>)); EXPECT_EQ(sizeof(V4), sizeof(AlignedCharArrayUnion<V4>)); EXPECT_EQ(sizeof(V5), sizeof(AlignedCharArrayUnion<V5>)); EXPECT_EQ(sizeof(V6), sizeof(AlignedCharArrayUnion<V6>)); EXPECT_EQ(sizeof(V7), sizeof(AlignedCharArrayUnion<V7>)); // Some versions of MSVC also get this wrong. The failure again appears to be // benign: sizeof(V8) is only 52 bytes, but our array reserves 56. #ifndef _MSC_VER EXPECT_EQ(sizeof(V8), sizeof(AlignedCharArrayUnion<V8>)); #endif EXPECT_EQ(1u, (alignOf<AlignedCharArray<1, 1> >())); EXPECT_EQ(2u, (alignOf<AlignedCharArray<2, 1> >())); EXPECT_EQ(4u, (alignOf<AlignedCharArray<4, 1> >())); EXPECT_EQ(8u, (alignOf<AlignedCharArray<8, 1> >())); EXPECT_EQ(16u, (alignOf<AlignedCharArray<16, 1> >())); EXPECT_EQ(1u, sizeof(AlignedCharArray<1, 1>)); EXPECT_EQ(7u, sizeof(AlignedCharArray<1, 7>)); EXPECT_EQ(2u, sizeof(AlignedCharArray<2, 2>)); EXPECT_EQ(16u, sizeof(AlignedCharArray<2, 16>)); } }
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/Support/Casting.cpp
//===---------- llvm/unittest/Support/Casting.cpp - Casting tests ---------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/Support/Casting.h" #include "llvm/IR/User.h" #include "llvm/Support/Debug.h" #include "llvm/Support/raw_ostream.h" #include "gtest/gtest.h" #include <cstdlib> namespace llvm { // Used to test illegal cast. If a cast doesn't match any of the "real" ones, // it will match this one. struct IllegalCast; template <typename T> IllegalCast *cast(...) { return nullptr; } // set up two example classes // with conversion facility // struct bar { bar() {} struct foo *baz(); struct foo *caz(); struct foo *daz(); struct foo *naz(); private: bar(const bar &); }; struct foo { void ext() const; /* static bool classof(const bar *X) { cerr << "Classof: " << X << "\n"; return true; }*/ }; template <> struct isa_impl<foo, bar> { static inline bool doit(const bar &Val) { dbgs() << "Classof: " << &Val << "\n"; return true; } }; foo *bar::baz() { return cast<foo>(this); } foo *bar::caz() { return cast_or_null<foo>(this); } foo *bar::daz() { return dyn_cast<foo>(this); } foo *bar::naz() { return dyn_cast_or_null<foo>(this); } bar *fub(); template <> struct simplify_type<foo> { typedef int SimpleType; static SimpleType getSimplifiedValue(foo &Val) { return 0; } }; } // End llvm namespace using namespace llvm; // Test the peculiar behavior of Use in simplify_type. static_assert(std::is_same<simplify_type<Use>::SimpleType, Value *>::value, "Use doesn't simplify correctly!"); static_assert(std::is_same<simplify_type<Use *>::SimpleType, Value *>::value, "Use doesn't simplify correctly!"); // Test that a regular class behaves as expected. static_assert(std::is_same<simplify_type<foo>::SimpleType, int>::value, "Unexpected simplify_type result!"); static_assert(std::is_same<simplify_type<foo *>::SimpleType, foo *>::value, "Unexpected simplify_type result!"); namespace { const foo *null_foo = nullptr; bar B; extern bar &B1; bar &B1 = B; extern const bar *B2; // test various configurations of const const bar &B3 = B1; const bar *const B4 = B2; TEST(CastingTest, isa) { EXPECT_TRUE(isa<foo>(B1)); EXPECT_TRUE(isa<foo>(B2)); EXPECT_TRUE(isa<foo>(B3)); EXPECT_TRUE(isa<foo>(B4)); } TEST(CastingTest, cast) { foo &F1 = cast<foo>(B1); EXPECT_NE(&F1, null_foo); const foo *F3 = cast<foo>(B2); EXPECT_NE(F3, null_foo); const foo *F4 = cast<foo>(B2); EXPECT_NE(F4, null_foo); const foo &F5 = cast<foo>(B3); EXPECT_NE(&F5, null_foo); const foo *F6 = cast<foo>(B4); EXPECT_NE(F6, null_foo); // Can't pass null pointer to cast<>. // foo *F7 = cast<foo>(fub()); // EXPECT_EQ(F7, null_foo); foo *F8 = B1.baz(); EXPECT_NE(F8, null_foo); } TEST(CastingTest, cast_or_null) { const foo *F11 = cast_or_null<foo>(B2); EXPECT_NE(F11, null_foo); const foo *F12 = cast_or_null<foo>(B2); EXPECT_NE(F12, null_foo); const foo *F13 = cast_or_null<foo>(B4); EXPECT_NE(F13, null_foo); const foo *F14 = cast_or_null<foo>(fub()); // Shouldn't print. EXPECT_EQ(F14, null_foo); foo *F15 = B1.caz(); EXPECT_NE(F15, null_foo); } TEST(CastingTest, dyn_cast) { const foo *F1 = dyn_cast<foo>(B2); EXPECT_NE(F1, null_foo); const foo *F2 = dyn_cast<foo>(B2); EXPECT_NE(F2, null_foo); const foo *F3 = dyn_cast<foo>(B4); EXPECT_NE(F3, null_foo); // Can't pass null pointer to dyn_cast<>. // foo *F4 = dyn_cast<foo>(fub()); // EXPECT_EQ(F4, null_foo); foo *F5 = B1.daz(); EXPECT_NE(F5, null_foo); } TEST(CastingTest, dyn_cast_or_null) { const foo *F1 = dyn_cast_or_null<foo>(B2); EXPECT_NE(F1, null_foo); const foo *F2 = dyn_cast_or_null<foo>(B2); EXPECT_NE(F2, null_foo); const foo *F3 = dyn_cast_or_null<foo>(B4); EXPECT_NE(F3, null_foo); foo *F4 = dyn_cast_or_null<foo>(fub()); EXPECT_EQ(F4, null_foo); foo *F5 = B1.naz(); EXPECT_NE(F5, null_foo); } // These lines are errors... //foo *F20 = cast<foo>(B2); // Yields const foo* //foo &F21 = cast<foo>(B3); // Yields const foo& //foo *F22 = cast<foo>(B4); // Yields const foo* //foo &F23 = cast_or_null<foo>(B1); //const foo &F24 = cast_or_null<foo>(B3); const bar *B2 = &B; } // anonymous namespace bar *llvm::fub() { return nullptr; } namespace { namespace inferred_upcasting { // This test case verifies correct behavior of inferred upcasts when the // types are statically known to be OK to upcast. This is the case when, // for example, Derived inherits from Base, and we do `isa<Base>(Derived)`. // Note: This test will actually fail to compile without inferred // upcasting. class Base { public: // No classof. We are testing that the upcast is inferred. Base() {} }; class Derived : public Base { public: Derived() {} }; // Even with no explicit classof() in Base, we should still be able to cast // Derived to its base class. TEST(CastingTest, UpcastIsInferred) { Derived D; EXPECT_TRUE(isa<Base>(D)); Base *BP = dyn_cast<Base>(&D); EXPECT_TRUE(BP != nullptr); } // This test verifies that the inferred upcast takes precedence over an // explicitly written one. This is important because it verifies that the // dynamic check gets optimized away. class UseInferredUpcast { public: int Dummy; static bool classof(const UseInferredUpcast *) { return false; } }; TEST(CastingTest, InferredUpcastTakesPrecedence) { UseInferredUpcast UIU; // Since the explicit classof() returns false, this will fail if the // explicit one is used. EXPECT_TRUE(isa<UseInferredUpcast>(&UIU)); } } // end namespace inferred_upcasting } // end anonymous namespace // Test that we reject casts of temporaries (and so the illegal cast gets used). namespace TemporaryCast { struct pod {}; IllegalCast *testIllegalCast() { return cast<foo>(pod()); } } namespace { namespace pointer_wrappers { struct Base { bool IsDerived; Base(bool IsDerived = false) : IsDerived(IsDerived) {} }; struct Derived : Base { Derived() : Base(true) {} static bool classof(const Base *B) { return B->IsDerived; } }; class PTy { Base *B; public: PTy(Base *B) : B(B) {} explicit operator bool() const { return get(); } Base *get() const { return B; } }; } // end namespace pointer_wrappers } // end namespace namespace llvm { template <> struct simplify_type<pointer_wrappers::PTy> { typedef pointer_wrappers::Base *SimpleType; static SimpleType getSimplifiedValue(pointer_wrappers::PTy &P) { return P.get(); } }; template <> struct simplify_type<const pointer_wrappers::PTy> { typedef pointer_wrappers::Base *SimpleType; static SimpleType getSimplifiedValue(const pointer_wrappers::PTy &P) { return P.get(); } }; } // end namespace llvm namespace { namespace pointer_wrappers { // Some objects. pointer_wrappers::Base B; pointer_wrappers::Derived D; // Mutable "smart" pointers. pointer_wrappers::PTy MN(nullptr); pointer_wrappers::PTy MB(&B); pointer_wrappers::PTy MD(&D); // Const "smart" pointers. const pointer_wrappers::PTy CN(nullptr); const pointer_wrappers::PTy CB(&B); const pointer_wrappers::PTy CD(&D); TEST(CastingTest, smart_isa) { EXPECT_TRUE(!isa<pointer_wrappers::Derived>(MB)); EXPECT_TRUE(!isa<pointer_wrappers::Derived>(CB)); EXPECT_TRUE(isa<pointer_wrappers::Derived>(MD)); EXPECT_TRUE(isa<pointer_wrappers::Derived>(CD)); } TEST(CastingTest, smart_cast) { EXPECT_TRUE(cast<pointer_wrappers::Derived>(MD) == &D); EXPECT_TRUE(cast<pointer_wrappers::Derived>(CD) == &D); } TEST(CastingTest, smart_cast_or_null) { EXPECT_TRUE(cast_or_null<pointer_wrappers::Derived>(MN) == nullptr); EXPECT_TRUE(cast_or_null<pointer_wrappers::Derived>(CN) == nullptr); EXPECT_TRUE(cast_or_null<pointer_wrappers::Derived>(MD) == &D); EXPECT_TRUE(cast_or_null<pointer_wrappers::Derived>(CD) == &D); } TEST(CastingTest, smart_dyn_cast) { EXPECT_TRUE(dyn_cast<pointer_wrappers::Derived>(MB) == nullptr); EXPECT_TRUE(dyn_cast<pointer_wrappers::Derived>(CB) == nullptr); EXPECT_TRUE(dyn_cast<pointer_wrappers::Derived>(MD) == &D); EXPECT_TRUE(dyn_cast<pointer_wrappers::Derived>(CD) == &D); } TEST(CastingTest, smart_dyn_cast_or_null) { EXPECT_TRUE(dyn_cast_or_null<pointer_wrappers::Derived>(MN) == nullptr); EXPECT_TRUE(dyn_cast_or_null<pointer_wrappers::Derived>(CN) == nullptr); EXPECT_TRUE(dyn_cast_or_null<pointer_wrappers::Derived>(MB) == nullptr); EXPECT_TRUE(dyn_cast_or_null<pointer_wrappers::Derived>(CB) == nullptr); EXPECT_TRUE(dyn_cast_or_null<pointer_wrappers::Derived>(MD) == &D); EXPECT_TRUE(dyn_cast_or_null<pointer_wrappers::Derived>(CD) == &D); } } // end namespace pointer_wrappers } // end namespace
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/Support/MathExtrasTest.cpp
//===- unittests/Support/MathExtrasTest.cpp - math utils tests ------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "gtest/gtest.h" #include "llvm/Support/MathExtras.h" using namespace llvm; namespace { TEST(MathExtras, countTrailingZeros) { uint8_t Z8 = 0; uint16_t Z16 = 0; uint32_t Z32 = 0; uint64_t Z64 = 0; EXPECT_EQ(8u, countTrailingZeros(Z8)); EXPECT_EQ(16u, countTrailingZeros(Z16)); EXPECT_EQ(32u, countTrailingZeros(Z32)); EXPECT_EQ(64u, countTrailingZeros(Z64)); uint8_t NZ8 = 42; uint16_t NZ16 = 42; uint32_t NZ32 = 42; uint64_t NZ64 = 42; EXPECT_EQ(1u, countTrailingZeros(NZ8)); EXPECT_EQ(1u, countTrailingZeros(NZ16)); EXPECT_EQ(1u, countTrailingZeros(NZ32)); EXPECT_EQ(1u, countTrailingZeros(NZ64)); } TEST(MathExtras, countLeadingZeros) { uint8_t Z8 = 0; uint16_t Z16 = 0; uint32_t Z32 = 0; uint64_t Z64 = 0; EXPECT_EQ(8u, countLeadingZeros(Z8)); EXPECT_EQ(16u, countLeadingZeros(Z16)); EXPECT_EQ(32u, countLeadingZeros(Z32)); EXPECT_EQ(64u, countLeadingZeros(Z64)); uint8_t NZ8 = 42; uint16_t NZ16 = 42; uint32_t NZ32 = 42; uint64_t NZ64 = 42; EXPECT_EQ(2u, countLeadingZeros(NZ8)); EXPECT_EQ(10u, countLeadingZeros(NZ16)); EXPECT_EQ(26u, countLeadingZeros(NZ32)); EXPECT_EQ(58u, countLeadingZeros(NZ64)); EXPECT_EQ(8u, countLeadingZeros(0x00F000FFu)); EXPECT_EQ(8u, countLeadingZeros(0x00F12345u)); for (unsigned i = 0; i <= 30; ++i) { EXPECT_EQ(31 - i, countLeadingZeros(1u << i)); } EXPECT_EQ(8u, countLeadingZeros(0x00F1234500F12345ULL)); EXPECT_EQ(1u, countLeadingZeros(1ULL << 62)); for (unsigned i = 0; i <= 62; ++i) { EXPECT_EQ(63 - i, countLeadingZeros(1ULL << i)); } } TEST(MathExtras, findFirstSet) { uint8_t Z8 = 0; uint16_t Z16 = 0; uint32_t Z32 = 0; uint64_t Z64 = 0; EXPECT_EQ(0xFFULL, findFirstSet(Z8)); EXPECT_EQ(0xFFFFULL, findFirstSet(Z16)); EXPECT_EQ(0xFFFFFFFFULL, findFirstSet(Z32)); EXPECT_EQ(0xFFFFFFFFFFFFFFFFULL, findFirstSet(Z64)); uint8_t NZ8 = 42; uint16_t NZ16 = 42; uint32_t NZ32 = 42; uint64_t NZ64 = 42; EXPECT_EQ(1u, findFirstSet(NZ8)); EXPECT_EQ(1u, findFirstSet(NZ16)); EXPECT_EQ(1u, findFirstSet(NZ32)); EXPECT_EQ(1u, findFirstSet(NZ64)); } TEST(MathExtras, findLastSet) { uint8_t Z8 = 0; uint16_t Z16 = 0; uint32_t Z32 = 0; uint64_t Z64 = 0; EXPECT_EQ(0xFFULL, findLastSet(Z8)); EXPECT_EQ(0xFFFFULL, findLastSet(Z16)); EXPECT_EQ(0xFFFFFFFFULL, findLastSet(Z32)); EXPECT_EQ(0xFFFFFFFFFFFFFFFFULL, findLastSet(Z64)); uint8_t NZ8 = 42; uint16_t NZ16 = 42; uint32_t NZ32 = 42; uint64_t NZ64 = 42; EXPECT_EQ(5u, findLastSet(NZ8)); EXPECT_EQ(5u, findLastSet(NZ16)); EXPECT_EQ(5u, findLastSet(NZ32)); EXPECT_EQ(5u, findLastSet(NZ64)); } TEST(MathExtras, reverseBits) { uint8_t NZ8 = 42; uint16_t NZ16 = 42; uint32_t NZ32 = 42; uint64_t NZ64 = 42; EXPECT_EQ(0x54ULL, reverseBits(NZ8)); EXPECT_EQ(0x5400ULL, reverseBits(NZ16)); EXPECT_EQ(0x54000000ULL, reverseBits(NZ32)); EXPECT_EQ(0x5400000000000000ULL, reverseBits(NZ64)); } TEST(MathExtras, isPowerOf2_32) { EXPECT_TRUE(isPowerOf2_32(1 << 6)); EXPECT_TRUE(isPowerOf2_32(1 << 12)); EXPECT_FALSE(isPowerOf2_32((1 << 19) + 3)); EXPECT_FALSE(isPowerOf2_32(0xABCDEF0)); } TEST(MathExtras, isPowerOf2_64) { EXPECT_TRUE(isPowerOf2_64(1LL << 46)); EXPECT_TRUE(isPowerOf2_64(1LL << 12)); EXPECT_FALSE(isPowerOf2_64((1LL << 53) + 3)); EXPECT_FALSE(isPowerOf2_64(0xABCDEF0ABCDEF0LL)); } TEST(MathExtras, ByteSwap_32) { EXPECT_EQ(0x44332211u, ByteSwap_32(0x11223344)); EXPECT_EQ(0xDDCCBBAAu, ByteSwap_32(0xAABBCCDD)); } TEST(MathExtras, ByteSwap_64) { EXPECT_EQ(0x8877665544332211ULL, ByteSwap_64(0x1122334455667788LL)); EXPECT_EQ(0x1100FFEEDDCCBBAAULL, ByteSwap_64(0xAABBCCDDEEFF0011LL)); } TEST(MathExtras, countLeadingOnes) { for (int i = 30; i >= 0; --i) { // Start with all ones and unset some bit. EXPECT_EQ(31u - i, countLeadingOnes(0xFFFFFFFF ^ (1 << i))); } for (int i = 62; i >= 0; --i) { // Start with all ones and unset some bit. EXPECT_EQ(63u - i, countLeadingOnes(0xFFFFFFFFFFFFFFFFULL ^ (1LL << i))); } for (int i = 30; i >= 0; --i) { // Start with all ones and unset some bit. EXPECT_EQ(31u - i, countLeadingOnes(0xFFFFFFFF ^ (1 << i))); } } TEST(MathExtras, FloatBits) { static const float kValue = 5632.34f; EXPECT_FLOAT_EQ(kValue, BitsToFloat(FloatToBits(kValue))); } TEST(MathExtras, DoubleBits) { static const double kValue = 87987234.983498; // HLSL Change -fix implicit cast EXPECT_DOUBLE_EQ(kValue, BitsToDouble(DoubleToBits(kValue))); } TEST(MathExtras, MinAlign) { EXPECT_EQ(1u, MinAlign(2, 3)); EXPECT_EQ(2u, MinAlign(2, 4)); EXPECT_EQ(1u, MinAlign(17, 64)); EXPECT_EQ(256u, MinAlign(256, 512)); } TEST(MathExtras, NextPowerOf2) { EXPECT_EQ(4u, NextPowerOf2(3)); EXPECT_EQ(16u, NextPowerOf2(15)); EXPECT_EQ(256u, NextPowerOf2(128)); } TEST(MathExtras, RoundUpToAlignment) { EXPECT_EQ(8u, RoundUpToAlignment(5, 8)); EXPECT_EQ(24u, RoundUpToAlignment(17, 8)); EXPECT_EQ(0u, RoundUpToAlignment(~0LL, 8)); } }
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/ADT/StringMapTest.cpp
//===- llvm/unittest/ADT/StringMapMap.cpp - StringMap unit tests ----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "gtest/gtest.h" #include "llvm/ADT/StringMap.h" #include "llvm/Support/DataTypes.h" #include <tuple> using namespace llvm; namespace { // Test fixture class StringMapTest : public testing::Test { protected: StringMap<uint32_t> testMap; static const char testKey[]; static const uint32_t testValue; static const char* testKeyFirst; static size_t testKeyLength; static const std::string testKeyStr; void assertEmptyMap() { // Size tests EXPECT_EQ(0u, testMap.size()); EXPECT_TRUE(testMap.empty()); // Iterator tests EXPECT_TRUE(testMap.begin() == testMap.end()); // Lookup tests EXPECT_EQ(0u, testMap.count(testKey)); EXPECT_EQ(0u, testMap.count(StringRef(testKeyFirst, testKeyLength))); EXPECT_EQ(0u, testMap.count(testKeyStr)); EXPECT_TRUE(testMap.find(testKey) == testMap.end()); EXPECT_TRUE(testMap.find(StringRef(testKeyFirst, testKeyLength)) == testMap.end()); EXPECT_TRUE(testMap.find(testKeyStr) == testMap.end()); } void assertSingleItemMap() { // Size tests EXPECT_EQ(1u, testMap.size()); EXPECT_FALSE(testMap.begin() == testMap.end()); EXPECT_FALSE(testMap.empty()); // Iterator tests StringMap<uint32_t>::iterator it = testMap.begin(); EXPECT_STREQ(testKey, it->first().data()); EXPECT_EQ(testValue, it->second); ++it; EXPECT_TRUE(it == testMap.end()); // Lookup tests EXPECT_EQ(1u, testMap.count(testKey)); EXPECT_EQ(1u, testMap.count(StringRef(testKeyFirst, testKeyLength))); EXPECT_EQ(1u, testMap.count(testKeyStr)); EXPECT_TRUE(testMap.find(testKey) == testMap.begin()); EXPECT_TRUE(testMap.find(StringRef(testKeyFirst, testKeyLength)) == testMap.begin()); EXPECT_TRUE(testMap.find(testKeyStr) == testMap.begin()); } }; const char StringMapTest::testKey[] = "key"; const uint32_t StringMapTest::testValue = 1u; const char* StringMapTest::testKeyFirst = testKey; size_t StringMapTest::testKeyLength = sizeof(testKey) - 1; const std::string StringMapTest::testKeyStr(testKey); // Empty map tests. TEST_F(StringMapTest, EmptyMapTest) { assertEmptyMap(); } // Constant map tests. TEST_F(StringMapTest, ConstEmptyMapTest) { const StringMap<uint32_t>& constTestMap = testMap; // Size tests EXPECT_EQ(0u, constTestMap.size()); EXPECT_TRUE(constTestMap.empty()); // Iterator tests EXPECT_TRUE(constTestMap.begin() == constTestMap.end()); // Lookup tests EXPECT_EQ(0u, constTestMap.count(testKey)); EXPECT_EQ(0u, constTestMap.count(StringRef(testKeyFirst, testKeyLength))); EXPECT_EQ(0u, constTestMap.count(testKeyStr)); EXPECT_TRUE(constTestMap.find(testKey) == constTestMap.end()); EXPECT_TRUE(constTestMap.find(StringRef(testKeyFirst, testKeyLength)) == constTestMap.end()); EXPECT_TRUE(constTestMap.find(testKeyStr) == constTestMap.end()); } // A map with a single entry. TEST_F(StringMapTest, SingleEntryMapTest) { testMap[testKey] = testValue; assertSingleItemMap(); } // Test clear() method. TEST_F(StringMapTest, ClearTest) { testMap[testKey] = testValue; testMap.clear(); assertEmptyMap(); } // Test erase(iterator) method. TEST_F(StringMapTest, EraseIteratorTest) { testMap[testKey] = testValue; testMap.erase(testMap.begin()); assertEmptyMap(); } // Test erase(value) method. TEST_F(StringMapTest, EraseValueTest) { testMap[testKey] = testValue; testMap.erase(testKey); assertEmptyMap(); } // Test inserting two values and erasing one. TEST_F(StringMapTest, InsertAndEraseTest) { testMap[testKey] = testValue; testMap["otherKey"] = 2; testMap.erase("otherKey"); assertSingleItemMap(); } TEST_F(StringMapTest, SmallFullMapTest) { // StringMap has a tricky corner case when the map is small (<8 buckets) and // it fills up through a balanced pattern of inserts and erases. This can // lead to inf-loops in some cases (PR13148) so we test it explicitly here. llvm::StringMap<int> Map(2); Map["eins"] = 1; Map["zwei"] = 2; Map["drei"] = 3; Map.erase("drei"); Map.erase("eins"); Map["veir"] = 4; Map["funf"] = 5; EXPECT_EQ(3u, Map.size()); EXPECT_EQ(0, Map.lookup("eins")); EXPECT_EQ(2, Map.lookup("zwei")); EXPECT_EQ(0, Map.lookup("drei")); EXPECT_EQ(4, Map.lookup("veir")); EXPECT_EQ(5, Map.lookup("funf")); } // A more complex iteration test. TEST_F(StringMapTest, IterationTest) { bool visited[100]; // Insert 100 numbers into the map for (int i = 0; i < 100; ++i) { std::stringstream ss; ss << "key_" << i; testMap[ss.str()] = i; visited[i] = false; } // Iterate over all numbers and mark each one found. for (StringMap<uint32_t>::iterator it = testMap.begin(); it != testMap.end(); ++it) { std::stringstream ss; ss << "key_" << it->second; ASSERT_STREQ(ss.str().c_str(), it->first().data()); visited[it->second] = true; } // Ensure every number was visited. for (int i = 0; i < 100; ++i) { ASSERT_TRUE(visited[i]) << "Entry #" << i << " was never visited"; } } // HLSL Change begin // Test StringMapEntry::Create() method. TEST_F(StringMapTest, StringMapEntryTest) { MallocAllocator A; StringMap<uint32_t>::value_type* entry = StringMap<uint32_t>::value_type::Create( StringRef(testKeyFirst, testKeyLength), A, 1u); EXPECT_STREQ(testKey, entry->first().data()); EXPECT_EQ(1u, entry->second); entry->Destroy(A); } // HLSL Change end // Test insert() method. TEST_F(StringMapTest, InsertTest) { SCOPED_TRACE("InsertTest"); testMap.insert( StringMap<uint32_t>::value_type::Create( StringRef(testKeyFirst, testKeyLength), testMap.getAllocator(), 1u)); assertSingleItemMap(); } // Test insert(pair<K, V>) method TEST_F(StringMapTest, InsertPairTest) { bool Inserted; StringMap<uint32_t>::iterator NewIt; std::tie(NewIt, Inserted) = testMap.insert(std::make_pair(testKeyFirst, testValue)); EXPECT_EQ(1u, testMap.size()); EXPECT_EQ(testValue, testMap[testKeyFirst]); EXPECT_EQ(testKeyFirst, NewIt->first()); EXPECT_EQ(testValue, NewIt->second); EXPECT_TRUE(Inserted); StringMap<uint32_t>::iterator ExistingIt; std::tie(ExistingIt, Inserted) = testMap.insert(std::make_pair(testKeyFirst, testValue + 1)); EXPECT_EQ(1u, testMap.size()); EXPECT_EQ(testValue, testMap[testKeyFirst]); EXPECT_FALSE(Inserted); EXPECT_EQ(NewIt, ExistingIt); } // Test insert(pair<K, V>) method when rehashing occurs TEST_F(StringMapTest, InsertRehashingPairTest) { // Check that the correct iterator is returned when the inserted element is // moved to a different bucket during internal rehashing. This depends on // the particular key, and the implementation of StringMap and HashString. // Changes to those might result in this test not actually checking that. StringMap<uint32_t> t(1); EXPECT_EQ(1u, t.getNumBuckets()); StringMap<uint32_t>::iterator It = t.insert(std::make_pair("abcdef", 42)).first; EXPECT_EQ(2u, t.getNumBuckets()); EXPECT_EQ("abcdef", It->first()); EXPECT_EQ(42u, It->second); } // Create a non-default constructable value struct StringMapTestStruct { StringMapTestStruct(int i) : i(i) {} StringMapTestStruct() = delete; int i; }; TEST_F(StringMapTest, NonDefaultConstructable) { StringMap<StringMapTestStruct> t; t.insert(std::make_pair("Test", StringMapTestStruct(123))); StringMap<StringMapTestStruct>::iterator iter = t.find("Test"); ASSERT_NE(iter, t.end()); ASSERT_EQ(iter->second.i, 123); } struct Immovable { Immovable() {} Immovable(Immovable&&) = delete; // will disable the other special members }; struct MoveOnly { int i; MoveOnly(int i) : i(i) {} MoveOnly(const Immovable&) : i(0) {} MoveOnly(MoveOnly &&RHS) : i(RHS.i) {} MoveOnly &operator=(MoveOnly &&RHS) { i = RHS.i; return *this; } private: MoveOnly(const MoveOnly &) = delete; MoveOnly &operator=(const MoveOnly &) = delete; }; TEST_F(StringMapTest, MoveOnly) { StringMap<MoveOnly> t; t.insert(std::make_pair("Test", MoveOnly(42))); StringRef Key = "Test"; StringMapEntry<MoveOnly>::Create(Key, MoveOnly(42)) ->Destroy(); } TEST_F(StringMapTest, CtorArg) { StringRef Key = "Test"; StringMapEntry<MoveOnly>::Create(Key, Immovable()) ->Destroy(); } TEST_F(StringMapTest, MoveConstruct) { StringMap<int> A; A["x"] = 42; StringMap<int> B = std::move(A); ASSERT_EQ(A.size(), 0u); ASSERT_EQ(B.size(), 1u); ASSERT_EQ(B["x"], 42); ASSERT_EQ(B.count("y"), 0u); } TEST_F(StringMapTest, MoveAssignment) { StringMap<int> A; A["x"] = 42; StringMap<int> B; B["y"] = 117; A = std::move(B); ASSERT_EQ(A.size(), 1u); ASSERT_EQ(B.size(), 0u); ASSERT_EQ(A["y"], 117); ASSERT_EQ(B.count("x"), 0u); } struct Countable { int &InstanceCount; int Number; Countable(int Number, int &InstanceCount) : InstanceCount(InstanceCount), Number(Number) { ++InstanceCount; } Countable(Countable &&C) : InstanceCount(C.InstanceCount), Number(C.Number) { ++InstanceCount; C.Number = -1; } Countable(const Countable &C) : InstanceCount(C.InstanceCount), Number(C.Number) { ++InstanceCount; } Countable &operator=(Countable C) { Number = C.Number; return *this; } ~Countable() { --InstanceCount; } }; TEST_F(StringMapTest, MoveDtor) { int InstanceCount = 0; StringMap<Countable> A; A.insert(std::make_pair("x", Countable(42, InstanceCount))); ASSERT_EQ(InstanceCount, 1); auto I = A.find("x"); ASSERT_NE(I, A.end()); ASSERT_EQ(I->second.Number, 42); StringMap<Countable> B; B = std::move(A); ASSERT_EQ(InstanceCount, 1); ASSERT_TRUE(A.empty()); I = B.find("x"); ASSERT_NE(I, B.end()); ASSERT_EQ(I->second.Number, 42); B = StringMap<Countable>(); ASSERT_EQ(InstanceCount, 0); ASSERT_TRUE(B.empty()); } } // end anonymous namespace
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/ADT/IntrusiveRefCntPtrTest.cpp
//===- unittest/ADT/IntrusiveRefCntPtrTest.cpp ----------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/ADT/IntrusiveRefCntPtr.h" #include "gtest/gtest.h" namespace { struct VirtualRefCounted : public llvm::RefCountedBaseVPTR { virtual void f() {} }; } namespace llvm { // Run this test with valgrind to detect memory leaks. TEST(IntrusiveRefCntPtr, RefCountedBaseVPTRCopyDoesNotLeak) { VirtualRefCounted *V1 = new VirtualRefCounted; IntrusiveRefCntPtr<VirtualRefCounted> R1 = V1; VirtualRefCounted *V2 = new VirtualRefCounted(*V1); IntrusiveRefCntPtr<VirtualRefCounted> R2 = V2; } struct SimpleRefCounted : public RefCountedBase<SimpleRefCounted> {}; // Run this test with valgrind to detect memory leaks. TEST(IntrusiveRefCntPtr, RefCountedBaseCopyDoesNotLeak) { SimpleRefCounted *S1 = new SimpleRefCounted; IntrusiveRefCntPtr<SimpleRefCounted> R1 = S1; SimpleRefCounted *S2 = new SimpleRefCounted(*S1); IntrusiveRefCntPtr<SimpleRefCounted> R2 = S2; } struct InterceptRefCounted : public RefCountedBase<InterceptRefCounted> { InterceptRefCounted(bool *Released, bool *Retained) : Released(Released), Retained(Retained) {} bool * const Released; bool * const Retained; }; template <> struct IntrusiveRefCntPtrInfo<InterceptRefCounted> { static void retain(InterceptRefCounted *I) { *I->Retained = true; I->Retain(); } static void release(InterceptRefCounted *I) { *I->Released = true; I->Release(); } }; TEST(IntrusiveRefCntPtr, UsesTraitsToRetainAndRelease) { bool Released = false; bool Retained = false; { InterceptRefCounted *I = new InterceptRefCounted(&Released, &Retained); IntrusiveRefCntPtr<InterceptRefCounted> R = I; } EXPECT_TRUE(Released); EXPECT_TRUE(Retained); } } // end namespace llvm
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/ADT/TripleTest.cpp
//===----------- Triple.cpp - Triple unit tests ---------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "gtest/gtest.h" #include "llvm/ADT/Triple.h" using namespace llvm; namespace { TEST(TripleTest, BasicParsing) { Triple T; T = Triple(""); EXPECT_EQ("", T.getArchName().str()); EXPECT_EQ("", T.getVendorName().str()); EXPECT_EQ("", T.getOSName().str()); EXPECT_EQ("", T.getEnvironmentName().str()); T = Triple("-"); EXPECT_EQ("", T.getArchName().str()); EXPECT_EQ("", T.getVendorName().str()); EXPECT_EQ("", T.getOSName().str()); EXPECT_EQ("", T.getEnvironmentName().str()); T = Triple("--"); EXPECT_EQ("", T.getArchName().str()); EXPECT_EQ("", T.getVendorName().str()); EXPECT_EQ("", T.getOSName().str()); EXPECT_EQ("", T.getEnvironmentName().str()); T = Triple("---"); EXPECT_EQ("", T.getArchName().str()); EXPECT_EQ("", T.getVendorName().str()); EXPECT_EQ("", T.getOSName().str()); EXPECT_EQ("", T.getEnvironmentName().str()); T = Triple("----"); EXPECT_EQ("", T.getArchName().str()); EXPECT_EQ("", T.getVendorName().str()); EXPECT_EQ("", T.getOSName().str()); EXPECT_EQ("-", T.getEnvironmentName().str()); T = Triple("a"); EXPECT_EQ("a", T.getArchName().str()); EXPECT_EQ("", T.getVendorName().str()); EXPECT_EQ("", T.getOSName().str()); EXPECT_EQ("", T.getEnvironmentName().str()); T = Triple("a-b"); EXPECT_EQ("a", T.getArchName().str()); EXPECT_EQ("b", T.getVendorName().str()); EXPECT_EQ("", T.getOSName().str()); EXPECT_EQ("", T.getEnvironmentName().str()); T = Triple("a-b-c"); EXPECT_EQ("a", T.getArchName().str()); EXPECT_EQ("b", T.getVendorName().str()); EXPECT_EQ("c", T.getOSName().str()); EXPECT_EQ("", T.getEnvironmentName().str()); T = Triple("a-b-c-d"); EXPECT_EQ("a", T.getArchName().str()); EXPECT_EQ("b", T.getVendorName().str()); EXPECT_EQ("c", T.getOSName().str()); EXPECT_EQ("d", T.getEnvironmentName().str()); } TEST(TripleTest, ParsedIDs) { Triple T; T = Triple("i386-apple-darwin"); EXPECT_EQ(Triple::x86, T.getArch()); EXPECT_EQ(Triple::Apple, T.getVendor()); EXPECT_EQ(Triple::Darwin, T.getOS()); EXPECT_EQ(Triple::UnknownEnvironment, T.getEnvironment()); T = Triple("x86_64-pc-linux-gnu"); EXPECT_EQ(Triple::x86_64, T.getArch()); EXPECT_EQ(Triple::PC, T.getVendor()); EXPECT_EQ(Triple::Linux, T.getOS()); EXPECT_EQ(Triple::GNU, T.getEnvironment()); T = Triple("powerpc-bgp-linux"); EXPECT_EQ(Triple::ppc, T.getArch()); EXPECT_EQ(Triple::BGP, T.getVendor()); EXPECT_EQ(Triple::Linux, T.getOS()); EXPECT_EQ(Triple::UnknownEnvironment, T.getEnvironment()); T = Triple("powerpc-bgp-cnk"); EXPECT_EQ(Triple::ppc, T.getArch()); EXPECT_EQ(Triple::BGP, T.getVendor()); EXPECT_EQ(Triple::CNK, T.getOS()); EXPECT_EQ(Triple::UnknownEnvironment, T.getEnvironment()); T = Triple("powerpc64-bgq-linux"); EXPECT_EQ(Triple::ppc64, T.getArch()); EXPECT_EQ(Triple::BGQ, T.getVendor()); EXPECT_EQ(Triple::Linux, T.getOS()); EXPECT_EQ(Triple::UnknownEnvironment, T.getEnvironment()); T = Triple("powerpc-ibm-aix"); EXPECT_EQ(Triple::ppc, T.getArch()); EXPECT_EQ(Triple::IBM, T.getVendor()); EXPECT_EQ(Triple::AIX, T.getOS()); EXPECT_EQ(Triple::UnknownEnvironment, T.getEnvironment()); T = Triple("powerpc64-ibm-aix"); EXPECT_EQ(Triple::ppc64, T.getArch()); EXPECT_EQ(Triple::IBM, T.getVendor()); EXPECT_EQ(Triple::AIX, T.getOS()); EXPECT_EQ(Triple::UnknownEnvironment, T.getEnvironment()); T = Triple("powerpc-dunno-notsure"); EXPECT_EQ(Triple::ppc, T.getArch()); EXPECT_EQ(Triple::UnknownVendor, T.getVendor()); EXPECT_EQ(Triple::UnknownOS, T.getOS()); EXPECT_EQ(Triple::UnknownEnvironment, T.getEnvironment()); T = Triple("arm-none-none-eabi"); EXPECT_EQ(Triple::arm, T.getArch()); EXPECT_EQ(Triple::UnknownVendor, T.getVendor()); EXPECT_EQ(Triple::UnknownOS, T.getOS()); EXPECT_EQ(Triple::EABI, T.getEnvironment()); T = Triple("armv6hl-none-linux-gnueabi"); EXPECT_EQ(Triple::arm, T.getArch()); EXPECT_EQ(Triple::Linux, T.getOS()); EXPECT_EQ(Triple::UnknownVendor, T.getVendor()); EXPECT_EQ(Triple::GNUEABI, T.getEnvironment()); T = Triple("armv7hl-none-linux-gnueabi"); EXPECT_EQ(Triple::arm, T.getArch()); EXPECT_EQ(Triple::Linux, T.getOS()); EXPECT_EQ(Triple::UnknownVendor, T.getVendor()); EXPECT_EQ(Triple::GNUEABI, T.getEnvironment()); T = Triple("amdil-unknown-unknown"); EXPECT_EQ(Triple::amdil, T.getArch()); EXPECT_EQ(Triple::UnknownVendor, T.getVendor()); EXPECT_EQ(Triple::UnknownOS, T.getOS()); T = Triple("amdil64-unknown-unknown"); EXPECT_EQ(Triple::amdil64, T.getArch()); EXPECT_EQ(Triple::UnknownVendor, T.getVendor()); EXPECT_EQ(Triple::UnknownOS, T.getOS()); T = Triple("hsail-unknown-unknown"); EXPECT_EQ(Triple::hsail, T.getArch()); EXPECT_EQ(Triple::UnknownVendor, T.getVendor()); EXPECT_EQ(Triple::UnknownOS, T.getOS()); T = Triple("hsail64-unknown-unknown"); EXPECT_EQ(Triple::hsail64, T.getArch()); EXPECT_EQ(Triple::UnknownVendor, T.getVendor()); EXPECT_EQ(Triple::UnknownOS, T.getOS()); T = Triple("sparcel-unknown-unknown"); EXPECT_EQ(Triple::sparcel, T.getArch()); EXPECT_EQ(Triple::UnknownVendor, T.getVendor()); EXPECT_EQ(Triple::UnknownOS, T.getOS()); T = Triple("spir-unknown-unknown"); EXPECT_EQ(Triple::spir, T.getArch()); EXPECT_EQ(Triple::UnknownVendor, T.getVendor()); EXPECT_EQ(Triple::UnknownOS, T.getOS()); T = Triple("spir64-unknown-unknown"); EXPECT_EQ(Triple::spir64, T.getArch()); EXPECT_EQ(Triple::UnknownVendor, T.getVendor()); EXPECT_EQ(Triple::UnknownOS, T.getOS()); T = Triple("x86_64-unknown-cloudabi"); EXPECT_EQ(Triple::x86_64, T.getArch()); EXPECT_EQ(Triple::UnknownVendor, T.getVendor()); EXPECT_EQ(Triple::CloudABI, T.getOS()); EXPECT_EQ(Triple::UnknownEnvironment, T.getEnvironment()); T = Triple("wasm32-unknown-unknown"); EXPECT_EQ(Triple::wasm32, T.getArch()); EXPECT_EQ(Triple::UnknownVendor, T.getVendor()); EXPECT_EQ(Triple::UnknownOS, T.getOS()); EXPECT_EQ(Triple::UnknownEnvironment, T.getEnvironment()); T = Triple("wasm64-unknown-unknown"); EXPECT_EQ(Triple::wasm64, T.getArch()); EXPECT_EQ(Triple::UnknownVendor, T.getVendor()); EXPECT_EQ(Triple::UnknownOS, T.getOS()); EXPECT_EQ(Triple::UnknownEnvironment, T.getEnvironment()); T = Triple("huh"); EXPECT_EQ(Triple::UnknownArch, T.getArch()); } static std::string Join(StringRef A, StringRef B, StringRef C) { std::string Str = A; Str += '-'; Str += B; Str += '-'; Str += C; return Str; } static std::string Join(StringRef A, StringRef B, StringRef C, StringRef D) { std::string Str = A; Str += '-'; Str += B; Str += '-'; Str += C; Str += '-'; Str += D; return Str; } TEST(TripleTest, Normalization) { EXPECT_EQ("", Triple::normalize("")); EXPECT_EQ("-", Triple::normalize("-")); EXPECT_EQ("--", Triple::normalize("--")); EXPECT_EQ("---", Triple::normalize("---")); EXPECT_EQ("----", Triple::normalize("----")); EXPECT_EQ("a", Triple::normalize("a")); EXPECT_EQ("a-b", Triple::normalize("a-b")); EXPECT_EQ("a-b-c", Triple::normalize("a-b-c")); EXPECT_EQ("a-b-c-d", Triple::normalize("a-b-c-d")); EXPECT_EQ("i386-b-c", Triple::normalize("i386-b-c")); EXPECT_EQ("i386-a-c", Triple::normalize("a-i386-c")); EXPECT_EQ("i386-a-b", Triple::normalize("a-b-i386")); EXPECT_EQ("i386-a-b-c", Triple::normalize("a-b-c-i386")); EXPECT_EQ("a-pc-c", Triple::normalize("a-pc-c")); EXPECT_EQ("-pc-b-c", Triple::normalize("pc-b-c")); EXPECT_EQ("a-pc-b", Triple::normalize("a-b-pc")); EXPECT_EQ("a-pc-b-c", Triple::normalize("a-b-c-pc")); EXPECT_EQ("a-b-linux", Triple::normalize("a-b-linux")); EXPECT_EQ("--linux-b-c", Triple::normalize("linux-b-c")); EXPECT_EQ("a--linux-c", Triple::normalize("a-linux-c")); EXPECT_EQ("i386-pc-a", Triple::normalize("a-pc-i386")); EXPECT_EQ("i386-pc-", Triple::normalize("-pc-i386")); EXPECT_EQ("-pc-linux-c", Triple::normalize("linux-pc-c")); EXPECT_EQ("-pc-linux", Triple::normalize("linux-pc-")); EXPECT_EQ("i386", Triple::normalize("i386")); EXPECT_EQ("-pc", Triple::normalize("pc")); EXPECT_EQ("--linux", Triple::normalize("linux")); EXPECT_EQ("x86_64--linux-gnu", Triple::normalize("x86_64-gnu-linux")); // Check that normalizing a permutated set of valid components returns a // triple with the unpermuted components. StringRef C[4]; for (int Arch = 1+Triple::UnknownArch; Arch <= Triple::LastArchType; ++Arch) { C[0] = Triple::getArchTypeName(Triple::ArchType(Arch)); for (int Vendor = 1+Triple::UnknownVendor; Vendor <= Triple::LastVendorType; ++Vendor) { C[1] = Triple::getVendorTypeName(Triple::VendorType(Vendor)); for (int OS = 1+Triple::UnknownOS; OS <= Triple::LastOSType; ++OS) { if (OS == Triple::Win32) continue; C[2] = Triple::getOSTypeName(Triple::OSType(OS)); std::string E = Join(C[0], C[1], C[2]); EXPECT_EQ(E, Triple::normalize(Join(C[0], C[1], C[2]))); EXPECT_EQ(E, Triple::normalize(Join(C[0], C[2], C[1]))); EXPECT_EQ(E, Triple::normalize(Join(C[1], C[2], C[0]))); EXPECT_EQ(E, Triple::normalize(Join(C[1], C[0], C[2]))); EXPECT_EQ(E, Triple::normalize(Join(C[2], C[0], C[1]))); EXPECT_EQ(E, Triple::normalize(Join(C[2], C[1], C[0]))); for (int Env = 1 + Triple::UnknownEnvironment; Env <= Triple::LastEnvironmentType; ++Env) { C[3] = Triple::getEnvironmentTypeName(Triple::EnvironmentType(Env)); std::string F = Join(C[0], C[1], C[2], C[3]); EXPECT_EQ(F, Triple::normalize(Join(C[0], C[1], C[2], C[3]))); EXPECT_EQ(F, Triple::normalize(Join(C[0], C[1], C[3], C[2]))); EXPECT_EQ(F, Triple::normalize(Join(C[0], C[2], C[3], C[1]))); EXPECT_EQ(F, Triple::normalize(Join(C[0], C[2], C[1], C[3]))); EXPECT_EQ(F, Triple::normalize(Join(C[0], C[3], C[1], C[2]))); EXPECT_EQ(F, Triple::normalize(Join(C[0], C[3], C[2], C[1]))); EXPECT_EQ(F, Triple::normalize(Join(C[1], C[2], C[3], C[0]))); EXPECT_EQ(F, Triple::normalize(Join(C[1], C[2], C[0], C[3]))); EXPECT_EQ(F, Triple::normalize(Join(C[1], C[3], C[0], C[2]))); EXPECT_EQ(F, Triple::normalize(Join(C[1], C[3], C[2], C[0]))); EXPECT_EQ(F, Triple::normalize(Join(C[1], C[0], C[2], C[3]))); EXPECT_EQ(F, Triple::normalize(Join(C[1], C[0], C[3], C[2]))); EXPECT_EQ(F, Triple::normalize(Join(C[2], C[3], C[0], C[1]))); EXPECT_EQ(F, Triple::normalize(Join(C[2], C[3], C[1], C[0]))); EXPECT_EQ(F, Triple::normalize(Join(C[2], C[0], C[1], C[3]))); EXPECT_EQ(F, Triple::normalize(Join(C[2], C[0], C[3], C[1]))); EXPECT_EQ(F, Triple::normalize(Join(C[2], C[1], C[3], C[0]))); EXPECT_EQ(F, Triple::normalize(Join(C[2], C[1], C[0], C[3]))); EXPECT_EQ(F, Triple::normalize(Join(C[3], C[0], C[1], C[2]))); EXPECT_EQ(F, Triple::normalize(Join(C[3], C[0], C[2], C[1]))); EXPECT_EQ(F, Triple::normalize(Join(C[3], C[1], C[2], C[0]))); EXPECT_EQ(F, Triple::normalize(Join(C[3], C[1], C[0], C[2]))); EXPECT_EQ(F, Triple::normalize(Join(C[3], C[2], C[0], C[1]))); EXPECT_EQ(F, Triple::normalize(Join(C[3], C[2], C[1], C[0]))); } } } } // Various real-world funky triples. The value returned by GCC's config.sub // is given in the comment. EXPECT_EQ("i386--windows-gnu", Triple::normalize("i386-mingw32")); // i386-pc-mingw32 EXPECT_EQ("x86_64--linux-gnu", Triple::normalize("x86_64-linux-gnu")); // x86_64-pc-linux-gnu EXPECT_EQ("i486--linux-gnu", Triple::normalize("i486-linux-gnu")); // i486-pc-linux-gnu EXPECT_EQ("i386-redhat-linux", Triple::normalize("i386-redhat-linux")); // i386-redhat-linux-gnu EXPECT_EQ("i686--linux", Triple::normalize("i686-linux")); // i686-pc-linux-gnu EXPECT_EQ("arm-none--eabi", Triple::normalize("arm-none-eabi")); // arm-none-eabi } TEST(TripleTest, MutateName) { Triple T; EXPECT_EQ(Triple::UnknownArch, T.getArch()); EXPECT_EQ(Triple::UnknownVendor, T.getVendor()); EXPECT_EQ(Triple::UnknownOS, T.getOS()); EXPECT_EQ(Triple::UnknownEnvironment, T.getEnvironment()); T.setArchName("i386"); EXPECT_EQ(Triple::x86, T.getArch()); EXPECT_EQ("i386--", T.getTriple()); T.setVendorName("pc"); EXPECT_EQ(Triple::x86, T.getArch()); EXPECT_EQ(Triple::PC, T.getVendor()); EXPECT_EQ("i386-pc-", T.getTriple()); T.setOSName("linux"); EXPECT_EQ(Triple::x86, T.getArch()); EXPECT_EQ(Triple::PC, T.getVendor()); EXPECT_EQ(Triple::Linux, T.getOS()); EXPECT_EQ("i386-pc-linux", T.getTriple()); T.setEnvironmentName("gnu"); EXPECT_EQ(Triple::x86, T.getArch()); EXPECT_EQ(Triple::PC, T.getVendor()); EXPECT_EQ(Triple::Linux, T.getOS()); EXPECT_EQ("i386-pc-linux-gnu", T.getTriple()); T.setOSName("freebsd"); EXPECT_EQ(Triple::x86, T.getArch()); EXPECT_EQ(Triple::PC, T.getVendor()); EXPECT_EQ(Triple::FreeBSD, T.getOS()); EXPECT_EQ("i386-pc-freebsd-gnu", T.getTriple()); T.setOSAndEnvironmentName("darwin"); EXPECT_EQ(Triple::x86, T.getArch()); EXPECT_EQ(Triple::PC, T.getVendor()); EXPECT_EQ(Triple::Darwin, T.getOS()); EXPECT_EQ("i386-pc-darwin", T.getTriple()); } TEST(TripleTest, BitWidthPredicates) { Triple T; EXPECT_FALSE(T.isArch16Bit()); EXPECT_FALSE(T.isArch32Bit()); EXPECT_FALSE(T.isArch64Bit()); T.setArch(Triple::arm); EXPECT_FALSE(T.isArch16Bit()); EXPECT_TRUE(T.isArch32Bit()); EXPECT_FALSE(T.isArch64Bit()); T.setArch(Triple::hexagon); EXPECT_FALSE(T.isArch16Bit()); EXPECT_TRUE(T.isArch32Bit()); EXPECT_FALSE(T.isArch64Bit()); T.setArch(Triple::mips); EXPECT_FALSE(T.isArch16Bit()); EXPECT_TRUE(T.isArch32Bit()); EXPECT_FALSE(T.isArch64Bit()); T.setArch(Triple::mips64); EXPECT_FALSE(T.isArch16Bit()); EXPECT_FALSE(T.isArch32Bit()); EXPECT_TRUE(T.isArch64Bit()); T.setArch(Triple::msp430); EXPECT_TRUE(T.isArch16Bit()); EXPECT_FALSE(T.isArch32Bit()); EXPECT_FALSE(T.isArch64Bit()); T.setArch(Triple::ppc); EXPECT_FALSE(T.isArch16Bit()); EXPECT_TRUE(T.isArch32Bit()); EXPECT_FALSE(T.isArch64Bit()); T.setArch(Triple::ppc64); EXPECT_FALSE(T.isArch16Bit()); EXPECT_FALSE(T.isArch32Bit()); EXPECT_TRUE(T.isArch64Bit()); T.setArch(Triple::x86); EXPECT_FALSE(T.isArch16Bit()); EXPECT_TRUE(T.isArch32Bit()); EXPECT_FALSE(T.isArch64Bit()); T.setArch(Triple::x86_64); EXPECT_FALSE(T.isArch16Bit()); EXPECT_FALSE(T.isArch32Bit()); EXPECT_TRUE(T.isArch64Bit()); T.setArch(Triple::amdil); EXPECT_FALSE(T.isArch16Bit()); EXPECT_TRUE(T.isArch32Bit()); EXPECT_FALSE(T.isArch64Bit()); T.setArch(Triple::amdil64); EXPECT_FALSE(T.isArch16Bit()); EXPECT_FALSE(T.isArch32Bit()); EXPECT_TRUE(T.isArch64Bit()); T.setArch(Triple::hsail); EXPECT_FALSE(T.isArch16Bit()); EXPECT_TRUE(T.isArch32Bit()); EXPECT_FALSE(T.isArch64Bit()); T.setArch(Triple::hsail64); EXPECT_FALSE(T.isArch16Bit()); EXPECT_FALSE(T.isArch32Bit()); EXPECT_TRUE(T.isArch64Bit()); T.setArch(Triple::spir); EXPECT_FALSE(T.isArch16Bit()); EXPECT_TRUE(T.isArch32Bit()); EXPECT_FALSE(T.isArch64Bit()); T.setArch(Triple::spir64); EXPECT_FALSE(T.isArch16Bit()); EXPECT_FALSE(T.isArch32Bit()); EXPECT_TRUE(T.isArch64Bit()); T.setArch(Triple::sparc); EXPECT_FALSE(T.isArch16Bit()); EXPECT_TRUE(T.isArch32Bit()); EXPECT_FALSE(T.isArch64Bit()); T.setArch(Triple::sparcel); EXPECT_FALSE(T.isArch16Bit()); EXPECT_TRUE(T.isArch32Bit()); EXPECT_FALSE(T.isArch64Bit()); T.setArch(Triple::sparcv9); EXPECT_FALSE(T.isArch16Bit()); EXPECT_FALSE(T.isArch32Bit()); EXPECT_TRUE(T.isArch64Bit()); T.setArch(Triple::wasm32); EXPECT_FALSE(T.isArch16Bit()); EXPECT_TRUE(T.isArch32Bit()); EXPECT_FALSE(T.isArch64Bit()); T.setArch(Triple::wasm64); EXPECT_FALSE(T.isArch16Bit()); EXPECT_FALSE(T.isArch32Bit()); EXPECT_TRUE(T.isArch64Bit()); } TEST(TripleTest, BitWidthArchVariants) { Triple T; EXPECT_EQ(Triple::UnknownArch, T.get32BitArchVariant().getArch()); EXPECT_EQ(Triple::UnknownArch, T.get64BitArchVariant().getArch()); T.setArch(Triple::UnknownArch); EXPECT_EQ(Triple::UnknownArch, T.get32BitArchVariant().getArch()); EXPECT_EQ(Triple::UnknownArch, T.get64BitArchVariant().getArch()); T.setArch(Triple::mips); EXPECT_EQ(Triple::mips, T.get32BitArchVariant().getArch()); EXPECT_EQ(Triple::mips64, T.get64BitArchVariant().getArch()); T.setArch(Triple::mipsel); EXPECT_EQ(Triple::mipsel, T.get32BitArchVariant().getArch()); EXPECT_EQ(Triple::mips64el, T.get64BitArchVariant().getArch()); T.setArch(Triple::ppc); EXPECT_EQ(Triple::ppc, T.get32BitArchVariant().getArch()); EXPECT_EQ(Triple::ppc64, T.get64BitArchVariant().getArch()); T.setArch(Triple::nvptx); EXPECT_EQ(Triple::nvptx, T.get32BitArchVariant().getArch()); EXPECT_EQ(Triple::nvptx64, T.get64BitArchVariant().getArch()); T.setArch(Triple::sparc); EXPECT_EQ(Triple::sparc, T.get32BitArchVariant().getArch()); EXPECT_EQ(Triple::sparcv9, T.get64BitArchVariant().getArch()); T.setArch(Triple::x86); EXPECT_EQ(Triple::x86, T.get32BitArchVariant().getArch()); EXPECT_EQ(Triple::x86_64, T.get64BitArchVariant().getArch()); T.setArch(Triple::mips64); EXPECT_EQ(Triple::mips, T.get32BitArchVariant().getArch()); EXPECT_EQ(Triple::mips64, T.get64BitArchVariant().getArch()); T.setArch(Triple::mips64el); EXPECT_EQ(Triple::mipsel, T.get32BitArchVariant().getArch()); EXPECT_EQ(Triple::mips64el, T.get64BitArchVariant().getArch()); T.setArch(Triple::ppc64); EXPECT_EQ(Triple::ppc, T.get32BitArchVariant().getArch()); EXPECT_EQ(Triple::ppc64, T.get64BitArchVariant().getArch()); T.setArch(Triple::nvptx64); EXPECT_EQ(Triple::nvptx, T.get32BitArchVariant().getArch()); EXPECT_EQ(Triple::nvptx64, T.get64BitArchVariant().getArch()); T.setArch(Triple::sparcv9); EXPECT_EQ(Triple::sparc, T.get32BitArchVariant().getArch()); EXPECT_EQ(Triple::sparcv9, T.get64BitArchVariant().getArch()); T.setArch(Triple::x86_64); EXPECT_EQ(Triple::x86, T.get32BitArchVariant().getArch()); EXPECT_EQ(Triple::x86_64, T.get64BitArchVariant().getArch()); T.setArch(Triple::amdil); EXPECT_EQ(Triple::amdil, T.get32BitArchVariant().getArch()); EXPECT_EQ(Triple::amdil64, T.get64BitArchVariant().getArch()); T.setArch(Triple::amdil64); EXPECT_EQ(Triple::amdil, T.get32BitArchVariant().getArch()); EXPECT_EQ(Triple::amdil64, T.get64BitArchVariant().getArch()); T.setArch(Triple::hsail); EXPECT_EQ(Triple::hsail, T.get32BitArchVariant().getArch()); EXPECT_EQ(Triple::hsail64, T.get64BitArchVariant().getArch()); T.setArch(Triple::hsail64); EXPECT_EQ(Triple::hsail, T.get32BitArchVariant().getArch()); EXPECT_EQ(Triple::hsail64, T.get64BitArchVariant().getArch()); T.setArch(Triple::spir); EXPECT_EQ(Triple::spir, T.get32BitArchVariant().getArch()); EXPECT_EQ(Triple::spir64, T.get64BitArchVariant().getArch()); T.setArch(Triple::spir64); EXPECT_EQ(Triple::spir, T.get32BitArchVariant().getArch()); EXPECT_EQ(Triple::spir64, T.get64BitArchVariant().getArch()); T.setArch(Triple::wasm32); EXPECT_EQ(Triple::wasm32, T.get32BitArchVariant().getArch()); EXPECT_EQ(Triple::wasm64, T.get64BitArchVariant().getArch()); T.setArch(Triple::wasm64); EXPECT_EQ(Triple::wasm32, T.get32BitArchVariant().getArch()); EXPECT_EQ(Triple::wasm64, T.get64BitArchVariant().getArch()); } TEST(TripleTest, EndianArchVariants) { Triple T; EXPECT_EQ(Triple::UnknownArch, T.getBigEndianArchVariant().getArch()); EXPECT_EQ(Triple::UnknownArch, T.getLittleEndianArchVariant().getArch()); T.setArch(Triple::UnknownArch); EXPECT_EQ(Triple::UnknownArch, T.getBigEndianArchVariant().getArch()); EXPECT_EQ(Triple::UnknownArch, T.getLittleEndianArchVariant().getArch()); T.setArch(Triple::aarch64_be); EXPECT_EQ(Triple::aarch64_be, T.getBigEndianArchVariant().getArch()); EXPECT_EQ(Triple::aarch64, T.getLittleEndianArchVariant().getArch()); T.setArch(Triple::aarch64); EXPECT_EQ(Triple::aarch64_be, T.getBigEndianArchVariant().getArch()); EXPECT_EQ(Triple::aarch64, T.getLittleEndianArchVariant().getArch()); T.setArch(Triple::armeb); EXPECT_EQ(Triple::armeb, T.getBigEndianArchVariant().getArch()); EXPECT_EQ(Triple::UnknownArch, T.getLittleEndianArchVariant().getArch()); T.setArch(Triple::arm); EXPECT_EQ(Triple::UnknownArch, T.getBigEndianArchVariant().getArch()); EXPECT_EQ(Triple::arm, T.getLittleEndianArchVariant().getArch()); T.setArch(Triple::bpfeb); EXPECT_EQ(Triple::bpfeb, T.getBigEndianArchVariant().getArch()); EXPECT_EQ(Triple::bpfel, T.getLittleEndianArchVariant().getArch()); T.setArch(Triple::bpfel); EXPECT_EQ(Triple::bpfeb, T.getBigEndianArchVariant().getArch()); EXPECT_EQ(Triple::bpfel, T.getLittleEndianArchVariant().getArch()); T.setArch(Triple::mips64); EXPECT_EQ(Triple::mips64, T.getBigEndianArchVariant().getArch()); EXPECT_EQ(Triple::mips64el, T.getLittleEndianArchVariant().getArch()); T.setArch(Triple::mips64el); EXPECT_EQ(Triple::mips64, T.getBigEndianArchVariant().getArch()); EXPECT_EQ(Triple::mips64el, T.getLittleEndianArchVariant().getArch()); T.setArch(Triple::mips); EXPECT_EQ(Triple::mips, T.getBigEndianArchVariant().getArch()); EXPECT_EQ(Triple::mipsel, T.getLittleEndianArchVariant().getArch()); T.setArch(Triple::mipsel); EXPECT_EQ(Triple::mips, T.getBigEndianArchVariant().getArch()); EXPECT_EQ(Triple::mipsel, T.getLittleEndianArchVariant().getArch()); T.setArch(Triple::ppc); EXPECT_EQ(Triple::ppc, T.getBigEndianArchVariant().getArch()); EXPECT_EQ(Triple::UnknownArch, T.getLittleEndianArchVariant().getArch()); T.setArch(Triple::ppc64); EXPECT_EQ(Triple::ppc64, T.getBigEndianArchVariant().getArch()); EXPECT_EQ(Triple::ppc64le, T.getLittleEndianArchVariant().getArch()); T.setArch(Triple::ppc64le); EXPECT_EQ(Triple::ppc64, T.getBigEndianArchVariant().getArch()); EXPECT_EQ(Triple::ppc64le, T.getLittleEndianArchVariant().getArch()); T.setArch(Triple::sparc); EXPECT_EQ(Triple::sparc, T.getBigEndianArchVariant().getArch()); EXPECT_EQ(Triple::sparcel, T.getLittleEndianArchVariant().getArch()); T.setArch(Triple::sparcel); EXPECT_EQ(Triple::sparc, T.getBigEndianArchVariant().getArch()); EXPECT_EQ(Triple::sparcel, T.getLittleEndianArchVariant().getArch()); T.setArch(Triple::thumb); EXPECT_EQ(Triple::UnknownArch, T.getBigEndianArchVariant().getArch()); EXPECT_EQ(Triple::thumb, T.getLittleEndianArchVariant().getArch()); T.setArch(Triple::thumbeb); EXPECT_EQ(Triple::thumbeb, T.getBigEndianArchVariant().getArch()); EXPECT_EQ(Triple::UnknownArch, T.getLittleEndianArchVariant().getArch()); } TEST(TripleTest, getOSVersion) { Triple T; unsigned Major, Minor, Micro; T = Triple("i386-apple-darwin9"); EXPECT_TRUE(T.isMacOSX()); EXPECT_FALSE(T.isiOS()); EXPECT_FALSE(T.isArch16Bit()); EXPECT_TRUE(T.isArch32Bit()); EXPECT_FALSE(T.isArch64Bit()); T.getMacOSXVersion(Major, Minor, Micro); EXPECT_EQ((unsigned)10, Major); EXPECT_EQ((unsigned)5, Minor); EXPECT_EQ((unsigned)0, Micro); T.getiOSVersion(Major, Minor, Micro); EXPECT_EQ((unsigned)5, Major); EXPECT_EQ((unsigned)0, Minor); EXPECT_EQ((unsigned)0, Micro); T = Triple("x86_64-apple-darwin9"); EXPECT_TRUE(T.isMacOSX()); EXPECT_FALSE(T.isiOS()); EXPECT_FALSE(T.isArch16Bit()); EXPECT_FALSE(T.isArch32Bit()); EXPECT_TRUE(T.isArch64Bit()); T.getMacOSXVersion(Major, Minor, Micro); EXPECT_EQ((unsigned)10, Major); EXPECT_EQ((unsigned)5, Minor); EXPECT_EQ((unsigned)0, Micro); T.getiOSVersion(Major, Minor, Micro); EXPECT_EQ((unsigned)5, Major); EXPECT_EQ((unsigned)0, Minor); EXPECT_EQ((unsigned)0, Micro); T = Triple("x86_64-apple-macosx"); EXPECT_TRUE(T.isMacOSX()); EXPECT_FALSE(T.isiOS()); EXPECT_FALSE(T.isArch16Bit()); EXPECT_FALSE(T.isArch32Bit()); EXPECT_TRUE(T.isArch64Bit()); T.getMacOSXVersion(Major, Minor, Micro); EXPECT_EQ((unsigned)10, Major); EXPECT_EQ((unsigned)4, Minor); EXPECT_EQ((unsigned)0, Micro); T.getiOSVersion(Major, Minor, Micro); EXPECT_EQ((unsigned)5, Major); EXPECT_EQ((unsigned)0, Minor); EXPECT_EQ((unsigned)0, Micro); T = Triple("x86_64-apple-macosx10.7"); EXPECT_TRUE(T.isMacOSX()); EXPECT_FALSE(T.isiOS()); EXPECT_FALSE(T.isArch16Bit()); EXPECT_FALSE(T.isArch32Bit()); EXPECT_TRUE(T.isArch64Bit()); T.getMacOSXVersion(Major, Minor, Micro); EXPECT_EQ((unsigned)10, Major); EXPECT_EQ((unsigned)7, Minor); EXPECT_EQ((unsigned)0, Micro); T.getiOSVersion(Major, Minor, Micro); EXPECT_EQ((unsigned)5, Major); EXPECT_EQ((unsigned)0, Minor); EXPECT_EQ((unsigned)0, Micro); T = Triple("armv7-apple-ios"); EXPECT_FALSE(T.isMacOSX()); EXPECT_TRUE(T.isiOS()); EXPECT_FALSE(T.isArch16Bit()); EXPECT_TRUE(T.isArch32Bit()); EXPECT_FALSE(T.isArch64Bit()); T.getMacOSXVersion(Major, Minor, Micro); EXPECT_EQ((unsigned)10, Major); EXPECT_EQ((unsigned)4, Minor); EXPECT_EQ((unsigned)0, Micro); T.getiOSVersion(Major, Minor, Micro); EXPECT_EQ((unsigned)5, Major); EXPECT_EQ((unsigned)0, Minor); EXPECT_EQ((unsigned)0, Micro); T = Triple("armv7-apple-ios7.0"); EXPECT_FALSE(T.isMacOSX()); EXPECT_TRUE(T.isiOS()); EXPECT_FALSE(T.isArch16Bit()); EXPECT_TRUE(T.isArch32Bit()); EXPECT_FALSE(T.isArch64Bit()); T.getMacOSXVersion(Major, Minor, Micro); EXPECT_EQ((unsigned)10, Major); EXPECT_EQ((unsigned)4, Minor); EXPECT_EQ((unsigned)0, Micro); T.getiOSVersion(Major, Minor, Micro); EXPECT_EQ((unsigned)7, Major); EXPECT_EQ((unsigned)0, Minor); EXPECT_EQ((unsigned)0, Micro); } TEST(TripleTest, FileFormat) { EXPECT_EQ(Triple::ELF, Triple("i686-unknown-linux-gnu").getObjectFormat()); EXPECT_EQ(Triple::ELF, Triple("i686-unknown-freebsd").getObjectFormat()); EXPECT_EQ(Triple::ELF, Triple("i686-unknown-netbsd").getObjectFormat()); EXPECT_EQ(Triple::ELF, Triple("i686--win32-elf").getObjectFormat()); EXPECT_EQ(Triple::ELF, Triple("i686---elf").getObjectFormat()); EXPECT_EQ(Triple::MachO, Triple("i686-apple-macosx").getObjectFormat()); EXPECT_EQ(Triple::MachO, Triple("i686-apple-ios").getObjectFormat()); EXPECT_EQ(Triple::MachO, Triple("i686---macho").getObjectFormat()); EXPECT_EQ(Triple::COFF, Triple("i686--win32").getObjectFormat()); EXPECT_EQ(Triple::ELF, Triple("i686-pc-windows-msvc-elf").getObjectFormat()); EXPECT_EQ(Triple::ELF, Triple("i686-pc-cygwin-elf").getObjectFormat()); Triple MSVCNormalized(Triple::normalize("i686-pc-windows-msvc-elf")); EXPECT_EQ(Triple::ELF, MSVCNormalized.getObjectFormat()); Triple GNUWindowsNormalized(Triple::normalize("i686-pc-windows-gnu-elf")); EXPECT_EQ(Triple::ELF, GNUWindowsNormalized.getObjectFormat()); Triple CygnusNormalised(Triple::normalize("i686-pc-windows-cygnus-elf")); EXPECT_EQ(Triple::ELF, CygnusNormalised.getObjectFormat()); Triple CygwinNormalized(Triple::normalize("i686-pc-cygwin-elf")); EXPECT_EQ(Triple::ELF, CygwinNormalized.getObjectFormat()); Triple T = Triple(""); T.setObjectFormat(Triple::ELF); EXPECT_EQ(Triple::ELF, T.getObjectFormat()); } TEST(TripleTest, NormalizeWindows) { EXPECT_EQ("i686-pc-windows-msvc", Triple::normalize("i686-pc-win32")); EXPECT_EQ("i686--windows-msvc", Triple::normalize("i686-win32")); EXPECT_EQ("i686-pc-windows-gnu", Triple::normalize("i686-pc-mingw32")); EXPECT_EQ("i686--windows-gnu", Triple::normalize("i686-mingw32")); EXPECT_EQ("i686-pc-windows-gnu", Triple::normalize("i686-pc-mingw32-w64")); EXPECT_EQ("i686--windows-gnu", Triple::normalize("i686-mingw32-w64")); EXPECT_EQ("i686-pc-windows-cygnus", Triple::normalize("i686-pc-cygwin")); EXPECT_EQ("i686--windows-cygnus", Triple::normalize("i686-cygwin")); EXPECT_EQ("x86_64-pc-windows-msvc", Triple::normalize("x86_64-pc-win32")); EXPECT_EQ("x86_64--windows-msvc", Triple::normalize("x86_64-win32")); EXPECT_EQ("x86_64-pc-windows-gnu", Triple::normalize("x86_64-pc-mingw32")); EXPECT_EQ("x86_64--windows-gnu", Triple::normalize("x86_64-mingw32")); EXPECT_EQ("x86_64-pc-windows-gnu", Triple::normalize("x86_64-pc-mingw32-w64")); EXPECT_EQ("x86_64--windows-gnu", Triple::normalize("x86_64-mingw32-w64")); EXPECT_EQ("i686-pc-windows-elf", Triple::normalize("i686-pc-win32-elf")); EXPECT_EQ("i686--windows-elf", Triple::normalize("i686-win32-elf")); EXPECT_EQ("i686-pc-windows-macho", Triple::normalize("i686-pc-win32-macho")); EXPECT_EQ("i686--windows-macho", Triple::normalize("i686-win32-macho")); EXPECT_EQ("x86_64-pc-windows-elf", Triple::normalize("x86_64-pc-win32-elf")); EXPECT_EQ("x86_64--windows-elf", Triple::normalize("x86_64-win32-elf")); EXPECT_EQ("x86_64-pc-windows-macho", Triple::normalize("x86_64-pc-win32-macho")); EXPECT_EQ("x86_64--windows-macho", Triple::normalize("x86_64-win32-macho")); EXPECT_EQ("i686-pc-windows-cygnus", Triple::normalize("i686-pc-windows-cygnus")); EXPECT_EQ("i686-pc-windows-gnu", Triple::normalize("i686-pc-windows-gnu")); EXPECT_EQ("i686-pc-windows-itanium", Triple::normalize("i686-pc-windows-itanium")); EXPECT_EQ("i686-pc-windows-msvc", Triple::normalize("i686-pc-windows-msvc")); EXPECT_EQ("i686-pc-windows-elf", Triple::normalize("i686-pc-windows-elf-elf")); } TEST(TripleTest, getARMCPUForArch) { // Standard ARM Architectures. { llvm::Triple Triple("armv4-unknown-eabi"); EXPECT_STREQ("strongarm", Triple.getARMCPUForArch()); } { llvm::Triple Triple("armv4t-unknown-eabi"); EXPECT_STREQ("arm7tdmi", Triple.getARMCPUForArch()); } { llvm::Triple Triple("armv5-unknown-eabi"); EXPECT_STREQ("arm10tdmi", Triple.getARMCPUForArch()); } { llvm::Triple Triple("armv5t-unknown-eabi"); EXPECT_STREQ("arm10tdmi", Triple.getARMCPUForArch()); } { llvm::Triple Triple("armv5e-unknown-eabi"); EXPECT_STREQ("arm1022e", Triple.getARMCPUForArch()); } { llvm::Triple Triple("armv5tej-unknown-eabi"); EXPECT_STREQ("arm926ej-s", Triple.getARMCPUForArch()); } { llvm::Triple Triple("armv6-unknown-eabi"); EXPECT_STREQ("arm1136jf-s", Triple.getARMCPUForArch()); } { llvm::Triple Triple("armv6j-unknown-eabi"); EXPECT_STREQ("arm1136j-s", Triple.getARMCPUForArch()); } { llvm::Triple Triple("armv6k-unknown-eabi"); EXPECT_STREQ("arm1176jzf-s", Triple.getARMCPUForArch()); } { llvm::Triple Triple("armv6zk-unknown-eabi"); EXPECT_STREQ("arm1176jzf-s", Triple.getARMCPUForArch()); } { llvm::Triple Triple("armv6t2-unknown-eabi"); EXPECT_STREQ("arm1156t2-s", Triple.getARMCPUForArch()); } { llvm::Triple Triple("armv6m-unknown-eabi"); EXPECT_STREQ("cortex-m0", Triple.getARMCPUForArch()); } { llvm::Triple Triple("armv7-unknown-eabi"); EXPECT_STREQ("cortex-a8", Triple.getARMCPUForArch()); } { llvm::Triple Triple("armv7a-unknown-eabi"); EXPECT_STREQ("cortex-a8", Triple.getARMCPUForArch()); } { llvm::Triple Triple("armv7m-unknown-eabi"); EXPECT_STREQ("cortex-m3", Triple.getARMCPUForArch()); } { llvm::Triple Triple("armv7r-unknown-eabi"); EXPECT_STREQ("cortex-r4", Triple.getARMCPUForArch()); } { llvm::Triple Triple("armv7r-unknown-eabi"); EXPECT_STREQ("cortex-r4", Triple.getARMCPUForArch()); } { llvm::Triple Triple("armv7r-unknown-eabi"); EXPECT_STREQ("cortex-r4", Triple.getARMCPUForArch()); } { llvm::Triple Triple("armv7r-unknown-eabi"); EXPECT_STREQ("cortex-r4", Triple.getARMCPUForArch()); } { llvm::Triple Triple("armv8a-unknown-eabi"); EXPECT_STREQ("cortex-a53", Triple.getARMCPUForArch()); } { llvm::Triple Triple("armv8.1a-unknown-eabi"); EXPECT_STREQ("generic", Triple.getARMCPUForArch()); } // Non-synonym names, using -march style, not default arch. { llvm::Triple Triple("arm"); EXPECT_STREQ("cortex-a8", Triple.getARMCPUForArch("armv7-a")); } { llvm::Triple Triple("arm"); EXPECT_STREQ("cortex-m3", Triple.getARMCPUForArch("armv7-m")); } { llvm::Triple Triple("arm"); EXPECT_STREQ("cortex-a53", Triple.getARMCPUForArch("armv8")); } { llvm::Triple Triple("arm"); EXPECT_STREQ("cortex-a53", Triple.getARMCPUForArch("armv8-a")); } // Platform specific defaults. { llvm::Triple Triple("arm--nacl"); EXPECT_STREQ("cortex-a8", Triple.getARMCPUForArch()); } { llvm::Triple Triple("armv6-unknown-freebsd"); EXPECT_STREQ("arm1176jzf-s", Triple.getARMCPUForArch()); } { llvm::Triple Triple("thumbv6-unknown-freebsd"); EXPECT_STREQ("arm1176jzf-s", Triple.getARMCPUForArch()); } { llvm::Triple Triple("armebv6-unknown-freebsd"); EXPECT_STREQ("arm1176jzf-s", Triple.getARMCPUForArch()); } { llvm::Triple Triple("arm--win32"); EXPECT_STREQ("cortex-a9", Triple.getARMCPUForArch()); } // Some alternative architectures { llvm::Triple Triple("xscale-unknown-eabi"); EXPECT_STREQ("xscale", Triple.getARMCPUForArch()); } { llvm::Triple Triple("iwmmxt-unknown-eabi"); EXPECT_STREQ("iwmmxt", Triple.getARMCPUForArch()); } { llvm::Triple Triple("armv7s-apple-ios7"); EXPECT_STREQ("swift", Triple.getARMCPUForArch()); } { llvm::Triple Triple("armv7em-apple-ios7"); EXPECT_STREQ("cortex-m4", Triple.getARMCPUForArch()); } { llvm::Triple Triple("armv7l-linux-gnueabihf"); EXPECT_STREQ("cortex-a8", Triple.getARMCPUForArch()); } { llvm::Triple Triple("armv6sm-apple-ios7"); EXPECT_STREQ("cortex-m0", Triple.getARMCPUForArch()); } // armeb is permitted, but armebeb is not { llvm::Triple Triple("armeb-none-eabi"); EXPECT_STREQ("arm7tdmi", Triple.getARMCPUForArch()); } { llvm::Triple Triple("armebeb-none-eabi"); EXPECT_EQ(nullptr, Triple.getARMCPUForArch()); } { llvm::Triple Triple("armebv6eb-none-eabi"); EXPECT_EQ(nullptr, Triple.getARMCPUForArch()); } // armebv6 and armv6eb are permitted, but armebv6eb is not { llvm::Triple Triple("armebv6-non-eabi"); EXPECT_STREQ("arm1136jf-s", Triple.getARMCPUForArch()); } { llvm::Triple Triple("armv6eb-none-eabi"); EXPECT_STREQ("arm1136jf-s", Triple.getARMCPUForArch()); } // xscaleeb is permitted, but armebxscale is not { llvm::Triple Triple("xscaleeb-none-eabi"); EXPECT_STREQ("xscale", Triple.getARMCPUForArch()); } { llvm::Triple Triple("armebxscale-none-eabi"); EXPECT_EQ(nullptr, Triple.getARMCPUForArch()); } } TEST(TripleTest, NormalizeARM) { EXPECT_EQ("armv6--netbsd-eabi", Triple::normalize("armv6-netbsd-eabi")); EXPECT_EQ("armv7--netbsd-eabi", Triple::normalize("armv7-netbsd-eabi")); EXPECT_EQ("armv6eb--netbsd-eabi", Triple::normalize("armv6eb-netbsd-eabi")); EXPECT_EQ("armv7eb--netbsd-eabi", Triple::normalize("armv7eb-netbsd-eabi")); EXPECT_EQ("armv6--netbsd-eabihf", Triple::normalize("armv6-netbsd-eabihf")); EXPECT_EQ("armv7--netbsd-eabihf", Triple::normalize("armv7-netbsd-eabihf")); EXPECT_EQ("armv6eb--netbsd-eabihf", Triple::normalize("armv6eb-netbsd-eabihf")); EXPECT_EQ("armv7eb--netbsd-eabihf", Triple::normalize("armv7eb-netbsd-eabihf")); Triple T; T = Triple("armv6--netbsd-eabi"); EXPECT_EQ(Triple::arm, T.getArch()); T = Triple("armv6eb--netbsd-eabi"); EXPECT_EQ(Triple::armeb, T.getArch()); } TEST(TripleTest, ParseARMArch) { // ARM { Triple T = Triple("arm"); EXPECT_EQ(Triple::arm, T.getArch()); } { Triple T = Triple("armv6t2"); EXPECT_EQ(Triple::arm, T.getArch()); } { Triple T = Triple("armv8"); EXPECT_EQ(Triple::arm, T.getArch()); } { Triple T = Triple("armeb"); EXPECT_EQ(Triple::armeb, T.getArch()); } { Triple T = Triple("armv5eb"); EXPECT_EQ(Triple::armeb, T.getArch()); } { Triple T = Triple("armebv7m"); EXPECT_EQ(Triple::armeb, T.getArch()); } { Triple T = Triple("armv7eb"); EXPECT_EQ(Triple::armeb, T.getArch()); } // THUMB { Triple T = Triple("thumb"); EXPECT_EQ(Triple::thumb, T.getArch()); } { Triple T = Triple("thumbv7a"); EXPECT_EQ(Triple::thumb, T.getArch()); } { Triple T = Triple("thumbeb"); EXPECT_EQ(Triple::thumbeb, T.getArch()); } { Triple T = Triple("thumbv4teb"); EXPECT_EQ(Triple::thumbeb, T.getArch()); } { Triple T = Triple("thumbebv7"); EXPECT_EQ(Triple::thumbeb, T.getArch()); } { Triple T = Triple("armv6m"); EXPECT_EQ(Triple::thumb, T.getArch()); } { Triple T = Triple("thumbv2"); EXPECT_EQ(Triple::UnknownArch, T.getArch()); } { Triple T = Triple("thumbebv6eb"); EXPECT_EQ(Triple::UnknownArch, T.getArch()); } // AARCH64 { Triple T = Triple("arm64"); EXPECT_EQ(Triple::aarch64, T.getArch()); } { Triple T = Triple("aarch64"); EXPECT_EQ(Triple::aarch64, T.getArch()); } { Triple T = Triple("aarch64_be"); EXPECT_EQ(Triple::aarch64_be, T.getArch()); } { Triple T = Triple("aarch64be"); EXPECT_EQ(Triple::UnknownArch, T.getArch()); } { Triple T = Triple("arm64be"); EXPECT_EQ(Triple::UnknownArch, T.getArch()); } } } // end anonymous namespace
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/ADT/SCCIteratorTest.cpp
//===----- llvm/unittest/ADT/SCCIteratorTest.cpp - SCCIterator tests ------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/ADT/SCCIterator.h" #include "llvm/ADT/GraphTraits.h" #include "gtest/gtest.h" #include <limits.h> using namespace llvm; namespace llvm { /// Graph<N> - A graph with N nodes. Note that N can be at most 8. template <unsigned N> class Graph { private: // Disable copying. Graph(const Graph&); Graph& operator=(const Graph&); static void ValidateIndex(unsigned Idx) { assert(Idx < N && "Invalid node index!"); } public: /// NodeSubset - A subset of the graph's nodes. class NodeSubset { typedef unsigned char BitVector; // Where the limitation N <= 8 comes from. BitVector Elements; NodeSubset(BitVector e) : Elements(e) {} public: /// NodeSubset - Default constructor, creates an empty subset. NodeSubset() : Elements(0) { assert(N <= sizeof(BitVector)*CHAR_BIT && "Graph too big!"); } /// Comparison operators. bool operator==(const NodeSubset &other) const { return other.Elements == this->Elements; } bool operator!=(const NodeSubset &other) const { return !(*this == other); } /// AddNode - Add the node with the given index to the subset. void AddNode(unsigned Idx) { ValidateIndex(Idx); Elements |= 1U << Idx; } /// DeleteNode - Remove the node with the given index from the subset. void DeleteNode(unsigned Idx) { ValidateIndex(Idx); Elements &= ~(1U << Idx); } /// count - Return true if the node with the given index is in the subset. bool count(unsigned Idx) { ValidateIndex(Idx); return (Elements & (1U << Idx)) != 0; } /// isEmpty - Return true if this is the empty set. bool isEmpty() const { return Elements == 0; } /// isSubsetOf - Return true if this set is a subset of the given one. bool isSubsetOf(const NodeSubset &other) const { return (this->Elements | other.Elements) == other.Elements; } /// Complement - Return the complement of this subset. NodeSubset Complement() const { return ~(unsigned)this->Elements & ((1U << N) - 1); } /// Join - Return the union of this subset and the given one. NodeSubset Join(const NodeSubset &other) const { return this->Elements | other.Elements; } /// Meet - Return the intersection of this subset and the given one. NodeSubset Meet(const NodeSubset &other) const { return this->Elements & other.Elements; } }; /// NodeType - Node index and set of children of the node. typedef std::pair<unsigned, NodeSubset> NodeType; private: /// Nodes - The list of nodes for this graph. NodeType Nodes[N]; public: /// Graph - Default constructor. Creates an empty graph. Graph() { // Let each node know which node it is. This allows us to find the start of // the Nodes array given a pointer to any element of it. for (unsigned i = 0; i != N; ++i) Nodes[i].first = i; } /// AddEdge - Add an edge from the node with index FromIdx to the node with /// index ToIdx. void AddEdge(unsigned FromIdx, unsigned ToIdx) { ValidateIndex(FromIdx); Nodes[FromIdx].second.AddNode(ToIdx); } /// DeleteEdge - Remove the edge (if any) from the node with index FromIdx to /// the node with index ToIdx. void DeleteEdge(unsigned FromIdx, unsigned ToIdx) { ValidateIndex(FromIdx); Nodes[FromIdx].second.DeleteNode(ToIdx); } /// AccessNode - Get a pointer to the node with the given index. NodeType *AccessNode(unsigned Idx) const { ValidateIndex(Idx); // The constant cast is needed when working with GraphTraits, which insists // on taking a constant Graph. return const_cast<NodeType *>(&Nodes[Idx]); } /// NodesReachableFrom - Return the set of all nodes reachable from the given /// node. NodeSubset NodesReachableFrom(unsigned Idx) const { // This algorithm doesn't scale, but that doesn't matter given the small // size of our graphs. NodeSubset Reachable; // The initial node is reachable. Reachable.AddNode(Idx); do { NodeSubset Previous(Reachable); // Add in all nodes which are children of a reachable node. for (unsigned i = 0; i != N; ++i) if (Previous.count(i)) Reachable = Reachable.Join(Nodes[i].second); // If nothing changed then we have found all reachable nodes. if (Reachable == Previous) return Reachable; // Rinse and repeat. } while (1); } /// ChildIterator - Visit all children of a node. class ChildIterator { friend class Graph; /// FirstNode - Pointer to first node in the graph's Nodes array. NodeType *FirstNode; /// Children - Set of nodes which are children of this one and that haven't /// yet been visited. NodeSubset Children; ChildIterator(); // Disable default constructor. protected: ChildIterator(NodeType *F, NodeSubset C) : FirstNode(F), Children(C) {} public: /// ChildIterator - Copy constructor. ChildIterator(const ChildIterator& other) : FirstNode(other.FirstNode), Children(other.Children) {} /// Comparison operators. bool operator==(const ChildIterator &other) const { return other.FirstNode == this->FirstNode && other.Children == this->Children; } bool operator!=(const ChildIterator &other) const { return !(*this == other); } /// Prefix increment operator. ChildIterator& operator++() { // Find the next unvisited child node. for (unsigned i = 0; i != N; ++i) if (Children.count(i)) { // Remove that child - it has been visited. This is the increment! Children.DeleteNode(i); return *this; } assert(false && "Incrementing end iterator!"); return *this; // Avoid compiler warnings. } /// Postfix increment operator. ChildIterator operator++(int) { ChildIterator Result(*this); ++(*this); return Result; } /// Dereference operator. NodeType *operator*() { // Find the next unvisited child node. for (unsigned i = 0; i != N; ++i) if (Children.count(i)) // Return a pointer to it. return FirstNode + i; assert(false && "Dereferencing end iterator!"); return nullptr; // Avoid compiler warning. } }; /// child_begin - Return an iterator pointing to the first child of the given /// node. static ChildIterator child_begin(NodeType *Parent) { return ChildIterator(Parent - Parent->first, Parent->second); } /// child_end - Return the end iterator for children of the given node. static ChildIterator child_end(NodeType *Parent) { return ChildIterator(Parent - Parent->first, NodeSubset()); } }; template <unsigned N> struct GraphTraits<Graph<N> > { typedef typename Graph<N>::NodeType NodeType; typedef typename Graph<N>::ChildIterator ChildIteratorType; static inline NodeType *getEntryNode(const Graph<N> &G) { return G.AccessNode(0); } static inline ChildIteratorType child_begin(NodeType *Node) { return Graph<N>::child_begin(Node); } static inline ChildIteratorType child_end(NodeType *Node) { return Graph<N>::child_end(Node); } }; TEST(SCCIteratorTest, AllSmallGraphs) { // Test SCC computation against every graph with NUM_NODES nodes or less. // Since SCC considers every node to have an implicit self-edge, we only // create graphs for which every node has a self-edge. #define NUM_NODES 4 #define NUM_GRAPHS (NUM_NODES * (NUM_NODES - 1)) typedef Graph<NUM_NODES> GT; /// Enumerate all graphs using NUM_GRAPHS bits. static_assert(NUM_GRAPHS < sizeof(unsigned) * CHAR_BIT, "Too many graphs!"); for (unsigned GraphDescriptor = 0; GraphDescriptor < (1U << NUM_GRAPHS); ++GraphDescriptor) { GT G; // Add edges as specified by the descriptor. unsigned DescriptorCopy = GraphDescriptor; for (unsigned i = 0; i != NUM_NODES; ++i) for (unsigned j = 0; j != NUM_NODES; ++j) { // Always add a self-edge. if (i == j) { G.AddEdge(i, j); continue; } if (DescriptorCopy & 1) G.AddEdge(i, j); DescriptorCopy >>= 1; } // Test the SCC logic on this graph. /// NodesInSomeSCC - Those nodes which are in some SCC. GT::NodeSubset NodesInSomeSCC; for (scc_iterator<GT> I = scc_begin(G), E = scc_end(G); I != E; ++I) { const std::vector<GT::NodeType *> &SCC = *I; // Get the nodes in this SCC as a NodeSubset rather than a vector. GT::NodeSubset NodesInThisSCC; for (unsigned i = 0, e = SCC.size(); i != e; ++i) NodesInThisSCC.AddNode(SCC[i]->first); // There should be at least one node in every SCC. EXPECT_FALSE(NodesInThisSCC.isEmpty()); // Check that every node in the SCC is reachable from every other node in // the SCC. for (unsigned i = 0; i != NUM_NODES; ++i) if (NodesInThisSCC.count(i)) EXPECT_TRUE(NodesInThisSCC.isSubsetOf(G.NodesReachableFrom(i))); // OK, now that we now that every node in the SCC is reachable from every // other, this means that the set of nodes reachable from any node in the // SCC is the same as the set of nodes reachable from every node in the // SCC. Check that for every node N not in the SCC but reachable from the // SCC, no element of the SCC is reachable from N. for (unsigned i = 0; i != NUM_NODES; ++i) if (NodesInThisSCC.count(i)) { GT::NodeSubset NodesReachableFromSCC = G.NodesReachableFrom(i); GT::NodeSubset ReachableButNotInSCC = NodesReachableFromSCC.Meet(NodesInThisSCC.Complement()); for (unsigned j = 0; j != NUM_NODES; ++j) if (ReachableButNotInSCC.count(j)) EXPECT_TRUE(G.NodesReachableFrom(j).Meet(NodesInThisSCC).isEmpty()); // The result must be the same for all other nodes in this SCC, so // there is no point in checking them. break; } // This is indeed a SCC: a maximal set of nodes for which each node is // reachable from every other. // Check that we didn't already see this SCC. EXPECT_TRUE(NodesInSomeSCC.Meet(NodesInThisSCC).isEmpty()); NodesInSomeSCC = NodesInSomeSCC.Join(NodesInThisSCC); // Check a property that is specific to the LLVM SCC iterator and // guaranteed by it: if a node in SCC S1 has an edge to a node in // SCC S2, then S1 is visited *after* S2. This means that the set // of nodes reachable from this SCC must be contained either in the // union of this SCC and all previously visited SCC's. for (unsigned i = 0; i != NUM_NODES; ++i) if (NodesInThisSCC.count(i)) { GT::NodeSubset NodesReachableFromSCC = G.NodesReachableFrom(i); EXPECT_TRUE(NodesReachableFromSCC.isSubsetOf(NodesInSomeSCC)); // The result must be the same for all other nodes in this SCC, so // there is no point in checking them. break; } } // Finally, check that the nodes in some SCC are exactly those that are // reachable from the initial node. EXPECT_EQ(NodesInSomeSCC, G.NodesReachableFrom(0)); } } }
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/ADT/FoldingSet.cpp
//===- llvm/unittest/ADT/FoldingSetTest.cpp -------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // FoldingSet unit tests. // //===----------------------------------------------------------------------===// #include "gtest/gtest.h" #include "llvm/ADT/FoldingSet.h" #include <string> using namespace llvm; namespace { // Unaligned string test. TEST(FoldingSetTest, UnalignedStringTest) { SCOPED_TRACE("UnalignedStringTest"); FoldingSetNodeID a, b; // An aligned string std::string str1= "a test string"; a.AddString(str1); // An unaligned string std::string str2 = ">" + str1; b.AddString(str2.c_str() + 1); EXPECT_EQ(a.ComputeHash(), b.ComputeHash()); } }
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/ADT/APSIntTest.cpp
//===- llvm/unittest/ADT/APSIntTest.cpp - APSInt unit tests ---------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/ADT/APSInt.h" #include "gtest/gtest.h" using namespace llvm; namespace { TEST(APSIntTest, MoveTest) { APSInt A(32, true); EXPECT_TRUE(A.isUnsigned()); APSInt B(128, false); A = B; EXPECT_FALSE(A.isUnsigned()); APSInt C(B); EXPECT_FALSE(C.isUnsigned()); APInt Wide(256, 0); const uint64_t *Bits = Wide.getRawData(); APSInt D(std::move(Wide)); EXPECT_TRUE(D.isUnsigned()); EXPECT_EQ(Bits, D.getRawData()); // Verify that "Wide" was really moved. A = APSInt(64, true); EXPECT_TRUE(A.isUnsigned()); Wide = APInt(128, 1); Bits = Wide.getRawData(); A = std::move(Wide); EXPECT_TRUE(A.isUnsigned()); EXPECT_EQ(Bits, A.getRawData()); // Verify that "Wide" was really moved. } TEST(APSIntTest, get) { EXPECT_TRUE(APSInt::get(7).isSigned()); EXPECT_EQ(64u, APSInt::get(7).getBitWidth()); EXPECT_EQ(7u, APSInt::get(7).getZExtValue()); EXPECT_EQ(7, APSInt::get(7).getSExtValue()); EXPECT_TRUE(APSInt::get(-7).isSigned()); EXPECT_EQ(64u, APSInt::get(-7).getBitWidth()); EXPECT_EQ(-7, APSInt::get(-7).getSExtValue()); EXPECT_EQ(UINT64_C(0) - 7, APSInt::get(-7).getZExtValue()); } TEST(APSIntTest, getUnsigned) { EXPECT_TRUE(APSInt::getUnsigned(7).isUnsigned()); EXPECT_EQ(64u, APSInt::getUnsigned(7).getBitWidth()); EXPECT_EQ(7u, APSInt::getUnsigned(7).getZExtValue()); EXPECT_EQ(7, APSInt::getUnsigned(7).getSExtValue()); EXPECT_TRUE(APSInt::getUnsigned(-7).isUnsigned()); EXPECT_EQ(64u, APSInt::getUnsigned(-7).getBitWidth()); EXPECT_EQ(-7, APSInt::getUnsigned(-7).getSExtValue()); EXPECT_EQ(UINT64_C(0) - 7, APSInt::getUnsigned(-7).getZExtValue()); } TEST(APSIntTest, getExtValue) { EXPECT_TRUE(APSInt(APInt(3, 7), true).isUnsigned()); EXPECT_TRUE(APSInt(APInt(3, 7), false).isSigned()); EXPECT_TRUE(APSInt(APInt(4, 7), true).isUnsigned()); EXPECT_TRUE(APSInt(APInt(4, 7), false).isSigned()); EXPECT_TRUE(APSInt(APInt(4, -7), true).isUnsigned()); EXPECT_TRUE(APSInt(APInt(4, -7), false).isSigned()); EXPECT_EQ(7, APSInt(APInt(3, 7), true).getExtValue()); EXPECT_EQ(-1, APSInt(APInt(3, 7), false).getExtValue()); EXPECT_EQ(7, APSInt(APInt(4, 7), true).getExtValue()); EXPECT_EQ(7, APSInt(APInt(4, 7), false).getExtValue()); EXPECT_EQ(9, APSInt(APInt(4, -7), true).getExtValue()); EXPECT_EQ(-7, APSInt(APInt(4, -7), false).getExtValue()); } TEST(APSIntTest, compareValues) { auto U = [](uint64_t V) { return APSInt::getUnsigned(V); }; auto S = [](int64_t V) { return APSInt::get(V); }; // Bit-width matches and is-signed. EXPECT_TRUE(APSInt::compareValues(S(7), S(8)) < 0); EXPECT_TRUE(APSInt::compareValues(S(8), S(7)) > 0); EXPECT_TRUE(APSInt::compareValues(S(7), S(7)) == 0); EXPECT_TRUE(APSInt::compareValues(S(-7), S(8)) < 0); EXPECT_TRUE(APSInt::compareValues(S(8), S(-7)) > 0); EXPECT_TRUE(APSInt::compareValues(S(-7), S(-7)) == 0); EXPECT_TRUE(APSInt::compareValues(S(-7), S(-8)) > 0); EXPECT_TRUE(APSInt::compareValues(S(-8), S(-7)) < 0); EXPECT_TRUE(APSInt::compareValues(S(-7), S(-7)) == 0); // Bit-width matches and not is-signed. EXPECT_TRUE(APSInt::compareValues(U(7), U(8)) < 0); EXPECT_TRUE(APSInt::compareValues(U(8), U(7)) > 0); EXPECT_TRUE(APSInt::compareValues(U(7), U(7)) == 0); // Bit-width matches and mixed signs. EXPECT_TRUE(APSInt::compareValues(U(7), S(8)) < 0); EXPECT_TRUE(APSInt::compareValues(U(8), S(7)) > 0); EXPECT_TRUE(APSInt::compareValues(U(7), S(7)) == 0); EXPECT_TRUE(APSInt::compareValues(U(8), S(-7)) > 0); // Bit-width mismatch and is-signed. EXPECT_TRUE(APSInt::compareValues(S(7).trunc(32), S(8)) < 0); EXPECT_TRUE(APSInt::compareValues(S(8).trunc(32), S(7)) > 0); EXPECT_TRUE(APSInt::compareValues(S(7).trunc(32), S(7)) == 0); EXPECT_TRUE(APSInt::compareValues(S(-7).trunc(32), S(8)) < 0); EXPECT_TRUE(APSInt::compareValues(S(8).trunc(32), S(-7)) > 0); EXPECT_TRUE(APSInt::compareValues(S(-7).trunc(32), S(-7)) == 0); EXPECT_TRUE(APSInt::compareValues(S(-7).trunc(32), S(-8)) > 0); EXPECT_TRUE(APSInt::compareValues(S(-8).trunc(32), S(-7)) < 0); EXPECT_TRUE(APSInt::compareValues(S(-7).trunc(32), S(-7)) == 0); EXPECT_TRUE(APSInt::compareValues(S(7), S(8).trunc(32)) < 0); EXPECT_TRUE(APSInt::compareValues(S(8), S(7).trunc(32)) > 0); EXPECT_TRUE(APSInt::compareValues(S(7), S(7).trunc(32)) == 0); EXPECT_TRUE(APSInt::compareValues(S(-7), S(8).trunc(32)) < 0); EXPECT_TRUE(APSInt::compareValues(S(8), S(-7).trunc(32)) > 0); EXPECT_TRUE(APSInt::compareValues(S(-7), S(-7).trunc(32)) == 0); EXPECT_TRUE(APSInt::compareValues(S(-7), S(-8).trunc(32)) > 0); EXPECT_TRUE(APSInt::compareValues(S(-8), S(-7).trunc(32)) < 0); EXPECT_TRUE(APSInt::compareValues(S(-7), S(-7).trunc(32)) == 0); // Bit-width mismatch and not is-signed. EXPECT_TRUE(APSInt::compareValues(U(7), U(8).trunc(32)) < 0); EXPECT_TRUE(APSInt::compareValues(U(8), U(7).trunc(32)) > 0); EXPECT_TRUE(APSInt::compareValues(U(7), U(7).trunc(32)) == 0); EXPECT_TRUE(APSInt::compareValues(U(7).trunc(32), U(8)) < 0); EXPECT_TRUE(APSInt::compareValues(U(8).trunc(32), U(7)) > 0); EXPECT_TRUE(APSInt::compareValues(U(7).trunc(32), U(7)) == 0); // Bit-width mismatch and mixed signs. EXPECT_TRUE(APSInt::compareValues(U(7).trunc(32), S(8)) < 0); EXPECT_TRUE(APSInt::compareValues(U(8).trunc(32), S(7)) > 0); EXPECT_TRUE(APSInt::compareValues(U(7).trunc(32), S(7)) == 0); EXPECT_TRUE(APSInt::compareValues(U(8).trunc(32), S(-7)) > 0); EXPECT_TRUE(APSInt::compareValues(U(7), S(8).trunc(32)) < 0); EXPECT_TRUE(APSInt::compareValues(U(8), S(7).trunc(32)) > 0); EXPECT_TRUE(APSInt::compareValues(U(7), S(7).trunc(32)) == 0); EXPECT_TRUE(APSInt::compareValues(U(8), S(-7).trunc(32)) > 0); } TEST(APSIntTest, FromString) { EXPECT_EQ(APSInt("1").getExtValue(), 1); EXPECT_EQ(APSInt("-1").getExtValue(), -1); EXPECT_EQ(APSInt("0").getExtValue(), 0); EXPECT_EQ(APSInt("56789").getExtValue(), 56789); EXPECT_EQ(APSInt("-1234").getExtValue(), -1234); } #if defined(GTEST_HAS_DEATH_TEST) && !defined(NDEBUG) TEST(APSIntTest, StringDeath) { EXPECT_DEATH(APSInt(""), "Invalid string length"); EXPECT_DEATH(APSInt("1a"), "Invalid character in digit string"); } #endif } // end anonymous namespace
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/ADT/FunctionRefTest.cpp
//===- llvm/unittest/ADT/MakeUniqueTest.cpp - make_unique unit tests ------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/ADT/STLExtras.h" #include "gtest/gtest.h" using namespace llvm; namespace { // Ensure that copies of a function_ref copy the underlying state rather than // causing one function_ref to chain to the next. TEST(FunctionRefTest, Copy) { auto A = [] { return 1; }; auto B = [] { return 2; }; function_ref<int()> X = A; function_ref<int()> Y = X; X = B; EXPECT_EQ(1, Y()); } }
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/ADT/ilistTest.cpp
//===- llvm/unittest/ADT/APInt.cpp - APInt unit tests ---------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/ADT/ilist.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/ilist_node.h" #include "gtest/gtest.h" #include <ostream> using namespace llvm; namespace { struct Node : ilist_node<Node> { int Value; Node() {} Node(int Value) : Value(Value) {} Node(const Node&) = default; ~Node() { Value = -1; } }; TEST(ilistTest, Basic) { ilist<Node> List; List.push_back(Node(1)); EXPECT_EQ(1, List.back().Value); EXPECT_EQ(nullptr, List.back().getPrevNode()); EXPECT_EQ(nullptr, List.back().getNextNode()); List.push_back(Node(2)); EXPECT_EQ(2, List.back().Value); EXPECT_EQ(2, List.front().getNextNode()->Value); EXPECT_EQ(1, List.back().getPrevNode()->Value); const ilist<Node> &ConstList = List; EXPECT_EQ(2, ConstList.back().Value); EXPECT_EQ(2, ConstList.front().getNextNode()->Value); EXPECT_EQ(1, ConstList.back().getPrevNode()->Value); } TEST(ilistTest, SpliceOne) { ilist<Node> List; List.push_back(1); // The single-element splice operation supports noops. List.splice(List.begin(), List, List.begin()); EXPECT_EQ(1u, List.size()); EXPECT_EQ(1, List.front().Value); EXPECT_TRUE(std::next(List.begin()) == List.end()); // Altenative noop. Move the first element behind itself. List.push_back(2); List.push_back(3); List.splice(std::next(List.begin()), List, List.begin()); EXPECT_EQ(3u, List.size()); EXPECT_EQ(1, List.front().Value); EXPECT_EQ(2, std::next(List.begin())->Value); EXPECT_EQ(3, List.back().Value); } TEST(ilistTest, UnsafeClear) { ilist<Node> List; // Before even allocating a sentinel. List.clearAndLeakNodesUnsafely(); EXPECT_EQ(0u, List.size()); // Empty list with sentinel. ilist<Node>::iterator E = List.end(); List.clearAndLeakNodesUnsafely(); EXPECT_EQ(0u, List.size()); // The sentinel shouldn't change. EXPECT_TRUE(E == List.end()); // List with contents. List.push_back(1); ASSERT_EQ(1u, List.size()); Node *N = List.begin(); EXPECT_EQ(1, N->Value); List.clearAndLeakNodesUnsafely(); EXPECT_EQ(0u, List.size()); ASSERT_EQ(1, N->Value); delete N; // List is still functional. List.push_back(5); List.push_back(6); ASSERT_EQ(2u, List.size()); EXPECT_EQ(5, List.front().Value); EXPECT_EQ(6, List.back().Value); } }
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/ADT/PointerUnionTest.cpp
//===- llvm/unittest/ADT/PointerUnionTest.cpp - Optional unit tests -------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "gtest/gtest.h" #include "llvm/ADT/PointerUnion.h" using namespace llvm; namespace { typedef PointerUnion<int *, float *> PU; struct PointerUnionTest : public testing::Test { float f; int i; PU a, b, c, n; PointerUnionTest() : f(3.14f), i(42), a(&f), b(&i), c(&i), n() {} }; TEST_F(PointerUnionTest, Comparison) { EXPECT_TRUE(a == a); EXPECT_FALSE(a != a); EXPECT_TRUE(a != b); EXPECT_FALSE(a == b); EXPECT_TRUE(b == c); EXPECT_FALSE(b != c); EXPECT_TRUE(b != n); EXPECT_FALSE(b == n); } TEST_F(PointerUnionTest, Null) { EXPECT_FALSE(a.isNull()); EXPECT_FALSE(b.isNull()); EXPECT_TRUE(n.isNull()); EXPECT_FALSE(!a); EXPECT_FALSE(!b); EXPECT_TRUE(!n); // workaround an issue with EXPECT macros and explicit bool EXPECT_TRUE((bool)a); EXPECT_TRUE((bool)b); EXPECT_FALSE(n); EXPECT_NE(n, b); EXPECT_EQ(b, c); b = nullptr; EXPECT_EQ(n, b); EXPECT_NE(b, c); } TEST_F(PointerUnionTest, Is) { EXPECT_FALSE(a.is<int *>()); EXPECT_TRUE(a.is<float *>()); EXPECT_TRUE(b.is<int *>()); EXPECT_FALSE(b.is<float *>()); EXPECT_TRUE(n.is<int *>()); EXPECT_FALSE(n.is<float *>()); } TEST_F(PointerUnionTest, Get) { EXPECT_EQ(a.get<float *>(), &f); EXPECT_EQ(b.get<int *>(), &i); EXPECT_EQ(n.get<int *>(), (int *)nullptr); } } // end anonymous namespace
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/ADT/BitVectorTest.cpp
//===- llvm/unittest/ADT/BitVectorTest.cpp - BitVector tests --------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef __ppc__ #include "llvm/ADT/BitVector.h" #include "llvm/ADT/SmallBitVector.h" #include "gtest/gtest.h" using namespace llvm; namespace { // Test fixture template <typename T> class BitVectorTest : public ::testing::Test { }; // Test both BitVector and SmallBitVector with the same suite of tests. typedef ::testing::Types<BitVector, SmallBitVector> BitVectorTestTypes; TYPED_TEST_CASE(BitVectorTest, BitVectorTestTypes); TYPED_TEST(BitVectorTest, TrivialOperation) { TypeParam Vec; EXPECT_EQ(0U, Vec.count()); EXPECT_EQ(0U, Vec.size()); EXPECT_FALSE(Vec.any()); EXPECT_TRUE(Vec.all()); EXPECT_TRUE(Vec.none()); EXPECT_TRUE(Vec.empty()); Vec.resize(5, true); EXPECT_EQ(5U, Vec.count()); EXPECT_EQ(5U, Vec.size()); EXPECT_TRUE(Vec.any()); EXPECT_TRUE(Vec.all()); EXPECT_FALSE(Vec.none()); EXPECT_FALSE(Vec.empty()); Vec.resize(11); EXPECT_EQ(5U, Vec.count()); EXPECT_EQ(11U, Vec.size()); EXPECT_TRUE(Vec.any()); EXPECT_FALSE(Vec.all()); EXPECT_FALSE(Vec.none()); EXPECT_FALSE(Vec.empty()); TypeParam Inv = Vec; Inv.flip(); EXPECT_EQ(6U, Inv.count()); EXPECT_EQ(11U, Inv.size()); EXPECT_TRUE(Inv.any()); EXPECT_FALSE(Inv.all()); EXPECT_FALSE(Inv.none()); EXPECT_FALSE(Inv.empty()); EXPECT_FALSE(Inv == Vec); EXPECT_TRUE(Inv != Vec); Vec.flip(); EXPECT_TRUE(Inv == Vec); EXPECT_FALSE(Inv != Vec); // Add some "interesting" data to Vec. Vec.resize(23, true); Vec.resize(25, false); Vec.resize(26, true); Vec.resize(29, false); Vec.resize(33, true); Vec.resize(57, false); unsigned Count = 0; for (unsigned i = Vec.find_first(); i != -1u; i = Vec.find_next(i)) { ++Count; EXPECT_TRUE(Vec[i]); EXPECT_TRUE(Vec.test(i)); } EXPECT_EQ(Count, Vec.count()); EXPECT_EQ(Count, 23u); EXPECT_FALSE(Vec[0]); EXPECT_TRUE(Vec[32]); EXPECT_FALSE(Vec[56]); Vec.resize(61, false); TypeParam Copy = Vec; TypeParam Alt(3, false); Alt.resize(6, true); std::swap(Alt, Vec); EXPECT_TRUE(Copy == Alt); EXPECT_TRUE(Vec.size() == 6); EXPECT_TRUE(Vec.count() == 3); EXPECT_TRUE(Vec.find_first() == 3); std::swap(Copy, Vec); // Add some more "interesting" data. Vec.resize(68, true); Vec.resize(78, false); Vec.resize(89, true); Vec.resize(90, false); Vec.resize(91, true); Vec.resize(130, false); Count = 0; for (unsigned i = Vec.find_first(); i != -1u; i = Vec.find_next(i)) { ++Count; EXPECT_TRUE(Vec[i]); EXPECT_TRUE(Vec.test(i)); } EXPECT_EQ(Count, Vec.count()); EXPECT_EQ(Count, 42u); EXPECT_FALSE(Vec[0]); EXPECT_TRUE(Vec[32]); EXPECT_FALSE(Vec[60]); EXPECT_FALSE(Vec[129]); Vec.flip(60); EXPECT_TRUE(Vec[60]); EXPECT_EQ(Count + 1, Vec.count()); Vec.flip(60); EXPECT_FALSE(Vec[60]); EXPECT_EQ(Count, Vec.count()); Vec.reset(32); EXPECT_FALSE(Vec[32]); EXPECT_EQ(Count - 1, Vec.count()); Vec.set(32); EXPECT_TRUE(Vec[32]); EXPECT_EQ(Count, Vec.count()); Vec.flip(); EXPECT_EQ(Vec.size() - Count, Vec.count()); Vec.reset(); EXPECT_EQ(0U, Vec.count()); EXPECT_EQ(130U, Vec.size()); EXPECT_FALSE(Vec.any()); EXPECT_FALSE(Vec.all()); EXPECT_TRUE(Vec.none()); EXPECT_FALSE(Vec.empty()); Vec.flip(); EXPECT_EQ(130U, Vec.count()); EXPECT_EQ(130U, Vec.size()); EXPECT_TRUE(Vec.any()); EXPECT_TRUE(Vec.all()); EXPECT_FALSE(Vec.none()); EXPECT_FALSE(Vec.empty()); Vec.resize(64); EXPECT_EQ(64U, Vec.count()); EXPECT_EQ(64U, Vec.size()); EXPECT_TRUE(Vec.any()); EXPECT_TRUE(Vec.all()); EXPECT_FALSE(Vec.none()); EXPECT_FALSE(Vec.empty()); Vec.flip(); EXPECT_EQ(0U, Vec.count()); EXPECT_EQ(64U, Vec.size()); EXPECT_FALSE(Vec.any()); EXPECT_FALSE(Vec.all()); EXPECT_TRUE(Vec.none()); EXPECT_FALSE(Vec.empty()); Inv = TypeParam().flip(); EXPECT_EQ(0U, Inv.count()); EXPECT_EQ(0U, Inv.size()); EXPECT_FALSE(Inv.any()); EXPECT_TRUE(Inv.all()); EXPECT_TRUE(Inv.none()); EXPECT_TRUE(Inv.empty()); Vec.clear(); EXPECT_EQ(0U, Vec.count()); EXPECT_EQ(0U, Vec.size()); EXPECT_FALSE(Vec.any()); EXPECT_TRUE(Vec.all()); EXPECT_TRUE(Vec.none()); EXPECT_TRUE(Vec.empty()); } TYPED_TEST(BitVectorTest, CompoundAssignment) { TypeParam A; A.resize(10); A.set(4); A.set(7); TypeParam B; B.resize(50); B.set(5); B.set(18); A |= B; EXPECT_TRUE(A.test(4)); EXPECT_TRUE(A.test(5)); EXPECT_TRUE(A.test(7)); EXPECT_TRUE(A.test(18)); EXPECT_EQ(4U, A.count()); EXPECT_EQ(50U, A.size()); B.resize(10); B.set(); B.reset(2); B.reset(7); A &= B; EXPECT_FALSE(A.test(2)); EXPECT_FALSE(A.test(7)); EXPECT_EQ(2U, A.count()); EXPECT_EQ(50U, A.size()); B.resize(100); B.set(); A ^= B; EXPECT_TRUE(A.test(2)); EXPECT_TRUE(A.test(7)); EXPECT_EQ(98U, A.count()); EXPECT_EQ(100U, A.size()); } TYPED_TEST(BitVectorTest, ProxyIndex) { TypeParam Vec(3); EXPECT_TRUE(Vec.none()); Vec[0] = Vec[1] = Vec[2] = true; EXPECT_EQ(Vec.size(), Vec.count()); Vec[2] = Vec[1] = Vec[0] = false; EXPECT_TRUE(Vec.none()); } TYPED_TEST(BitVectorTest, PortableBitMask) { TypeParam A; const uint32_t Mask1[] = { 0x80000000, 6, 5 }; A.resize(10); A.setBitsInMask(Mask1, 3); EXPECT_EQ(10u, A.size()); EXPECT_FALSE(A.test(0)); A.resize(32); A.setBitsInMask(Mask1, 3); EXPECT_FALSE(A.test(0)); EXPECT_TRUE(A.test(31)); EXPECT_EQ(1u, A.count()); A.resize(33); A.setBitsInMask(Mask1, 1); EXPECT_EQ(1u, A.count()); A.setBitsInMask(Mask1, 2); EXPECT_EQ(1u, A.count()); A.resize(34); A.setBitsInMask(Mask1, 2); EXPECT_EQ(2u, A.count()); A.resize(65); A.setBitsInMask(Mask1, 3); EXPECT_EQ(4u, A.count()); A.setBitsNotInMask(Mask1, 1); EXPECT_EQ(32u+3u, A.count()); A.setBitsNotInMask(Mask1, 3); EXPECT_EQ(65u, A.count()); A.resize(96); EXPECT_EQ(65u, A.count()); A.clear(); A.resize(128); A.setBitsNotInMask(Mask1, 3); EXPECT_EQ(96u-5u, A.count()); A.clearBitsNotInMask(Mask1, 1); EXPECT_EQ(64-4u, A.count()); } TYPED_TEST(BitVectorTest, BinOps) { TypeParam A; TypeParam B; A.resize(65); EXPECT_FALSE(A.anyCommon(B)); EXPECT_FALSE(B.anyCommon(B)); B.resize(64); A.set(64); EXPECT_FALSE(A.anyCommon(B)); EXPECT_FALSE(B.anyCommon(A)); B.set(63); EXPECT_FALSE(A.anyCommon(B)); EXPECT_FALSE(B.anyCommon(A)); A.set(63); EXPECT_TRUE(A.anyCommon(B)); EXPECT_TRUE(B.anyCommon(A)); B.resize(70); B.set(64); B.reset(63); A.resize(64); EXPECT_FALSE(A.anyCommon(B)); EXPECT_FALSE(B.anyCommon(A)); } TYPED_TEST(BitVectorTest, RangeOps) { TypeParam A; A.resize(256); A.reset(); A.set(1, 255); EXPECT_FALSE(A.test(0)); EXPECT_TRUE( A.test(1)); EXPECT_TRUE( A.test(23)); EXPECT_TRUE( A.test(254)); EXPECT_FALSE(A.test(255)); TypeParam B; B.resize(256); B.set(); B.reset(1, 255); EXPECT_TRUE( B.test(0)); EXPECT_FALSE(B.test(1)); EXPECT_FALSE(B.test(23)); EXPECT_FALSE(B.test(254)); EXPECT_TRUE( B.test(255)); TypeParam C; C.resize(3); C.reset(); C.set(0, 1); EXPECT_TRUE(C.test(0)); EXPECT_FALSE( C.test(1)); EXPECT_FALSE( C.test(2)); TypeParam D; D.resize(3); D.set(); D.reset(0, 1); EXPECT_FALSE(D.test(0)); EXPECT_TRUE( D.test(1)); EXPECT_TRUE( D.test(2)); TypeParam E; E.resize(128); E.reset(); E.set(1, 33); EXPECT_FALSE(E.test(0)); EXPECT_TRUE( E.test(1)); EXPECT_TRUE( E.test(32)); EXPECT_FALSE(E.test(33)); TypeParam BufferOverrun; unsigned size = sizeof(unsigned long) * 8; BufferOverrun.resize(size); BufferOverrun.reset(0, size); BufferOverrun.set(0, size); } TYPED_TEST(BitVectorTest, CompoundTestReset) { TypeParam A(50, true); TypeParam B(50, false); TypeParam C(100, true); TypeParam D(100, false); EXPECT_FALSE(A.test(A)); EXPECT_TRUE(A.test(B)); EXPECT_FALSE(A.test(C)); EXPECT_TRUE(A.test(D)); EXPECT_FALSE(B.test(A)); EXPECT_FALSE(B.test(B)); EXPECT_FALSE(B.test(C)); EXPECT_FALSE(B.test(D)); EXPECT_TRUE(C.test(A)); EXPECT_TRUE(C.test(B)); EXPECT_FALSE(C.test(C)); EXPECT_TRUE(C.test(D)); A.reset(B); A.reset(D); EXPECT_TRUE(A.all()); A.reset(A); EXPECT_TRUE(A.none()); A.set(); A.reset(C); EXPECT_TRUE(A.none()); A.set(); C.reset(A); EXPECT_EQ(50, C.find_first()); C.reset(C); EXPECT_TRUE(C.none()); } } #endif
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/ADT/ImmutableMapTest.cpp
//===----------- ImmutableMapTest.cpp - ImmutableMap unit tests ------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "gtest/gtest.h" #include "llvm/ADT/ImmutableMap.h" using namespace llvm; namespace { TEST(ImmutableMapTest, EmptyIntMapTest) { ImmutableMap<int, int>::Factory f; EXPECT_TRUE(f.getEmptyMap() == f.getEmptyMap()); EXPECT_FALSE(f.getEmptyMap() != f.getEmptyMap()); EXPECT_TRUE(f.getEmptyMap().isEmpty()); ImmutableMap<int, int> S = f.getEmptyMap(); EXPECT_EQ(0u, S.getHeight()); EXPECT_TRUE(S.begin() == S.end()); EXPECT_FALSE(S.begin() != S.end()); } TEST(ImmutableMapTest, MultiElemIntMapTest) { ImmutableMap<int, int>::Factory f; ImmutableMap<int, int> S = f.getEmptyMap(); ImmutableMap<int, int> S2 = f.add(f.add(f.add(S, 3, 10), 4, 11), 5, 12); EXPECT_TRUE(S.isEmpty()); EXPECT_FALSE(S2.isEmpty()); EXPECT_EQ(nullptr, S.lookup(3)); EXPECT_EQ(nullptr, S.lookup(9)); EXPECT_EQ(10, *S2.lookup(3)); EXPECT_EQ(11, *S2.lookup(4)); EXPECT_EQ(12, *S2.lookup(5)); EXPECT_EQ(5, S2.getMaxElement()->first); EXPECT_EQ(3U, S2.getHeight()); } }
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/ADT/APIntTest.cpp
//===- llvm/unittest/ADT/APInt.cpp - APInt unit tests ---------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/ADT/APInt.h" #include "llvm/ADT/SmallString.h" #include "gtest/gtest.h" #include <array> #include <ostream> using namespace llvm; namespace { // Test that APInt shift left works when bitwidth > 64 and shiftamt == 0 TEST(APIntTest, ShiftLeftByZero) { APInt One = APInt::getNullValue(65) + 1; APInt Shl = One.shl(0); EXPECT_TRUE(Shl[0]); EXPECT_FALSE(Shl[1]); } TEST(APIntTest, i128_NegativeCount) { APInt Minus3(128, static_cast<uint64_t>(-3), true); EXPECT_EQ(126u, Minus3.countLeadingOnes()); EXPECT_EQ(-3, Minus3.getSExtValue()); APInt Minus1(128, static_cast<uint64_t>(-1), true); EXPECT_EQ(0u, Minus1.countLeadingZeros()); EXPECT_EQ(128u, Minus1.countLeadingOnes()); EXPECT_EQ(128u, Minus1.getActiveBits()); EXPECT_EQ(0u, Minus1.countTrailingZeros()); EXPECT_EQ(128u, Minus1.countTrailingOnes()); EXPECT_EQ(128u, Minus1.countPopulation()); EXPECT_EQ(-1, Minus1.getSExtValue()); } // XFAIL this test on FreeBSD where the system gcc-4.2.1 seems to miscompile it. #if defined(__llvm__) || !defined(__FreeBSD__) TEST(APIntTest, i33_Count) { APInt i33minus2(33, static_cast<uint64_t>(-2), true); EXPECT_EQ(0u, i33minus2.countLeadingZeros()); EXPECT_EQ(32u, i33minus2.countLeadingOnes()); EXPECT_EQ(33u, i33minus2.getActiveBits()); EXPECT_EQ(1u, i33minus2.countTrailingZeros()); EXPECT_EQ(32u, i33minus2.countPopulation()); EXPECT_EQ(-2, i33minus2.getSExtValue()); EXPECT_EQ(((uint64_t)-2)&((1ull<<33) -1), i33minus2.getZExtValue()); } #endif TEST(APIntTest, i65_Count) { APInt i65(65, 0, true); EXPECT_EQ(65u, i65.countLeadingZeros()); EXPECT_EQ(0u, i65.countLeadingOnes()); EXPECT_EQ(0u, i65.getActiveBits()); EXPECT_EQ(1u, i65.getActiveWords()); EXPECT_EQ(65u, i65.countTrailingZeros()); EXPECT_EQ(0u, i65.countPopulation()); APInt i65minus(65, 0, true); i65minus.setBit(64); EXPECT_EQ(0u, i65minus.countLeadingZeros()); EXPECT_EQ(1u, i65minus.countLeadingOnes()); EXPECT_EQ(65u, i65minus.getActiveBits()); EXPECT_EQ(64u, i65minus.countTrailingZeros()); EXPECT_EQ(1u, i65minus.countPopulation()); } TEST(APIntTest, i128_PositiveCount) { APInt u128max = APInt::getAllOnesValue(128); EXPECT_EQ(128u, u128max.countLeadingOnes()); EXPECT_EQ(0u, u128max.countLeadingZeros()); EXPECT_EQ(128u, u128max.getActiveBits()); EXPECT_EQ(0u, u128max.countTrailingZeros()); EXPECT_EQ(128u, u128max.countTrailingOnes()); EXPECT_EQ(128u, u128max.countPopulation()); APInt u64max(128, static_cast<uint64_t>(-1), false); EXPECT_EQ(64u, u64max.countLeadingZeros()); EXPECT_EQ(0u, u64max.countLeadingOnes()); EXPECT_EQ(64u, u64max.getActiveBits()); EXPECT_EQ(0u, u64max.countTrailingZeros()); EXPECT_EQ(64u, u64max.countTrailingOnes()); EXPECT_EQ(64u, u64max.countPopulation()); EXPECT_EQ((uint64_t)~0ull, u64max.getZExtValue()); APInt zero(128, 0, true); EXPECT_EQ(128u, zero.countLeadingZeros()); EXPECT_EQ(0u, zero.countLeadingOnes()); EXPECT_EQ(0u, zero.getActiveBits()); EXPECT_EQ(128u, zero.countTrailingZeros()); EXPECT_EQ(0u, zero.countTrailingOnes()); EXPECT_EQ(0u, zero.countPopulation()); EXPECT_EQ(0u, zero.getSExtValue()); EXPECT_EQ(0u, zero.getZExtValue()); APInt one(128, 1, true); EXPECT_EQ(127u, one.countLeadingZeros()); EXPECT_EQ(0u, one.countLeadingOnes()); EXPECT_EQ(1u, one.getActiveBits()); EXPECT_EQ(0u, one.countTrailingZeros()); EXPECT_EQ(1u, one.countTrailingOnes()); EXPECT_EQ(1u, one.countPopulation()); EXPECT_EQ(1, one.getSExtValue()); EXPECT_EQ(1u, one.getZExtValue()); } TEST(APIntTest, i1) { const APInt neg_two(1, static_cast<uint64_t>(-2), true); const APInt neg_one(1, static_cast<uint64_t>(-1), true); const APInt zero(1, 0); const APInt one(1, 1); const APInt two(1, 2); EXPECT_EQ(0, neg_two.getSExtValue()); EXPECT_EQ(-1, neg_one.getSExtValue()); EXPECT_EQ(1u, neg_one.getZExtValue()); EXPECT_EQ(0u, zero.getZExtValue()); EXPECT_EQ(-1, one.getSExtValue()); EXPECT_EQ(1u, one.getZExtValue()); EXPECT_EQ(0u, two.getZExtValue()); EXPECT_EQ(0, two.getSExtValue()); // Basic equalities for 1-bit values. EXPECT_EQ(zero, two); EXPECT_EQ(zero, neg_two); EXPECT_EQ(one, neg_one); EXPECT_EQ(two, neg_two); // Min/max signed values. EXPECT_TRUE(zero.isMaxSignedValue()); EXPECT_FALSE(one.isMaxSignedValue()); EXPECT_FALSE(zero.isMinSignedValue()); EXPECT_TRUE(one.isMinSignedValue()); // Additions. EXPECT_EQ(two, one + one); EXPECT_EQ(zero, neg_one + one); EXPECT_EQ(neg_two, neg_one + neg_one); // Subtractions. EXPECT_EQ(neg_two, neg_one - one); EXPECT_EQ(two, one - neg_one); EXPECT_EQ(zero, one - one); // Shifts. EXPECT_EQ(zero, one << one); EXPECT_EQ(one, one << zero); EXPECT_EQ(zero, one.shl(1)); EXPECT_EQ(one, one.shl(0)); EXPECT_EQ(zero, one.lshr(1)); EXPECT_EQ(zero, one.ashr(1)); // Rotates. EXPECT_EQ(one, one.rotl(0)); EXPECT_EQ(one, one.rotl(1)); EXPECT_EQ(one, one.rotr(0)); EXPECT_EQ(one, one.rotr(1)); // Multiplies. EXPECT_EQ(neg_one, neg_one * one); EXPECT_EQ(neg_one, one * neg_one); EXPECT_EQ(one, neg_one * neg_one); EXPECT_EQ(one, one * one); // Divides. EXPECT_EQ(neg_one, one.sdiv(neg_one)); EXPECT_EQ(neg_one, neg_one.sdiv(one)); EXPECT_EQ(one, neg_one.sdiv(neg_one)); EXPECT_EQ(one, one.sdiv(one)); EXPECT_EQ(neg_one, one.udiv(neg_one)); EXPECT_EQ(neg_one, neg_one.udiv(one)); EXPECT_EQ(one, neg_one.udiv(neg_one)); EXPECT_EQ(one, one.udiv(one)); // Remainders. EXPECT_EQ(zero, neg_one.srem(one)); EXPECT_EQ(zero, neg_one.urem(one)); EXPECT_EQ(zero, one.srem(neg_one)); // sdivrem { APInt q(8, 0); APInt r(8, 0); APInt one(8, 1); APInt two(8, 2); APInt nine(8, 9); APInt four(8, 4); EXPECT_EQ(nine.srem(two), one); EXPECT_EQ(nine.srem(-two), one); EXPECT_EQ((-nine).srem(two), -one); EXPECT_EQ((-nine).srem(-two), -one); APInt::sdivrem(nine, two, q, r); EXPECT_EQ(four, q); EXPECT_EQ(one, r); APInt::sdivrem(-nine, two, q, r); EXPECT_EQ(-four, q); EXPECT_EQ(-one, r); APInt::sdivrem(nine, -two, q, r); EXPECT_EQ(-four, q); EXPECT_EQ(one, r); APInt::sdivrem(-nine, -two, q, r); EXPECT_EQ(four, q); EXPECT_EQ(-one, r); } } TEST(APIntTest, compare) { std::array<APInt, 5> testVals{{ APInt{16, 2}, APInt{16, 1}, APInt{16, 0}, APInt{16, (uint64_t)-1, true}, APInt{16, (uint64_t)-2, true}, }}; for (auto &arg1 : testVals) for (auto &arg2 : testVals) { auto uv1 = arg1.getZExtValue(); auto uv2 = arg2.getZExtValue(); auto sv1 = arg1.getSExtValue(); auto sv2 = arg2.getSExtValue(); EXPECT_EQ(uv1 < uv2, arg1.ult(arg2)); EXPECT_EQ(uv1 <= uv2, arg1.ule(arg2)); EXPECT_EQ(uv1 > uv2, arg1.ugt(arg2)); EXPECT_EQ(uv1 >= uv2, arg1.uge(arg2)); EXPECT_EQ(sv1 < sv2, arg1.slt(arg2)); EXPECT_EQ(sv1 <= sv2, arg1.sle(arg2)); EXPECT_EQ(sv1 > sv2, arg1.sgt(arg2)); EXPECT_EQ(sv1 >= sv2, arg1.sge(arg2)); EXPECT_EQ(uv1 < uv2, arg1.ult(uv2)); EXPECT_EQ(uv1 <= uv2, arg1.ule(uv2)); EXPECT_EQ(uv1 > uv2, arg1.ugt(uv2)); EXPECT_EQ(uv1 >= uv2, arg1.uge(uv2)); EXPECT_EQ(sv1 < sv2, arg1.slt(sv2)); EXPECT_EQ(sv1 <= sv2, arg1.sle(sv2)); EXPECT_EQ(sv1 > sv2, arg1.sgt(sv2)); EXPECT_EQ(sv1 >= sv2, arg1.sge(sv2)); } } TEST(APIntTest, compareWithRawIntegers) { EXPECT_TRUE(!APInt(8, 1).uge(256)); EXPECT_TRUE(!APInt(8, 1).ugt(256)); EXPECT_TRUE( APInt(8, 1).ule(256)); EXPECT_TRUE( APInt(8, 1).ult(256)); EXPECT_TRUE(!APInt(8, 1).sge(256)); EXPECT_TRUE(!APInt(8, 1).sgt(256)); EXPECT_TRUE( APInt(8, 1).sle(256)); EXPECT_TRUE( APInt(8, 1).slt(256)); EXPECT_TRUE(!(APInt(8, 0) == 256)); EXPECT_TRUE( APInt(8, 0) != 256); EXPECT_TRUE(!(APInt(8, 1) == 256)); EXPECT_TRUE( APInt(8, 1) != 256); auto uint64max = UINT64_MAX; auto int64max = INT64_MAX; auto int64min = INT64_MIN; auto u64 = APInt{128, uint64max}; auto s64 = APInt{128, static_cast<uint64_t>(int64max), true}; auto big = u64 + 1; EXPECT_TRUE( u64.uge(uint64max)); EXPECT_TRUE(!u64.ugt(uint64max)); EXPECT_TRUE( u64.ule(uint64max)); EXPECT_TRUE(!u64.ult(uint64max)); EXPECT_TRUE( u64.sge(int64max)); EXPECT_TRUE( u64.sgt(int64max)); EXPECT_TRUE(!u64.sle(int64max)); EXPECT_TRUE(!u64.slt(int64max)); EXPECT_TRUE( u64.sge(int64min)); EXPECT_TRUE( u64.sgt(int64min)); EXPECT_TRUE(!u64.sle(int64min)); EXPECT_TRUE(!u64.slt(int64min)); EXPECT_TRUE(u64 == uint64max); EXPECT_TRUE(u64 != int64max); EXPECT_TRUE(u64 != int64min); EXPECT_TRUE(!s64.uge(uint64max)); EXPECT_TRUE(!s64.ugt(uint64max)); EXPECT_TRUE( s64.ule(uint64max)); EXPECT_TRUE( s64.ult(uint64max)); EXPECT_TRUE( s64.sge(int64max)); EXPECT_TRUE(!s64.sgt(int64max)); EXPECT_TRUE( s64.sle(int64max)); EXPECT_TRUE(!s64.slt(int64max)); EXPECT_TRUE( s64.sge(int64min)); EXPECT_TRUE( s64.sgt(int64min)); EXPECT_TRUE(!s64.sle(int64min)); EXPECT_TRUE(!s64.slt(int64min)); EXPECT_TRUE(s64 != uint64max); EXPECT_TRUE(s64 == int64max); EXPECT_TRUE(s64 != int64min); EXPECT_TRUE( big.uge(uint64max)); EXPECT_TRUE( big.ugt(uint64max)); EXPECT_TRUE(!big.ule(uint64max)); EXPECT_TRUE(!big.ult(uint64max)); EXPECT_TRUE( big.sge(int64max)); EXPECT_TRUE( big.sgt(int64max)); EXPECT_TRUE(!big.sle(int64max)); EXPECT_TRUE(!big.slt(int64max)); EXPECT_TRUE( big.sge(int64min)); EXPECT_TRUE( big.sgt(int64min)); EXPECT_TRUE(!big.sle(int64min)); EXPECT_TRUE(!big.slt(int64min)); EXPECT_TRUE(big != uint64max); EXPECT_TRUE(big != int64max); EXPECT_TRUE(big != int64min); } TEST(APIntTest, compareWithInt64Min) { int64_t edge = INT64_MIN; int64_t edgeP1 = edge + 1; int64_t edgeM1 = INT64_MAX; auto a = APInt{64, static_cast<uint64_t>(edge), true}; EXPECT_TRUE(!a.slt(edge)); EXPECT_TRUE( a.sle(edge)); EXPECT_TRUE(!a.sgt(edge)); EXPECT_TRUE( a.sge(edge)); EXPECT_TRUE( a.slt(edgeP1)); EXPECT_TRUE( a.sle(edgeP1)); EXPECT_TRUE(!a.sgt(edgeP1)); EXPECT_TRUE(!a.sge(edgeP1)); EXPECT_TRUE( a.slt(edgeM1)); EXPECT_TRUE( a.sle(edgeM1)); EXPECT_TRUE(!a.sgt(edgeM1)); EXPECT_TRUE(!a.sge(edgeM1)); } TEST(APIntTest, compareWithHalfInt64Max) { uint64_t edge = 0x4000000000000000; uint64_t edgeP1 = edge + 1; uint64_t edgeM1 = edge - 1; auto a = APInt{64, edge}; EXPECT_TRUE(!a.ult(edge)); EXPECT_TRUE( a.ule(edge)); EXPECT_TRUE(!a.ugt(edge)); EXPECT_TRUE( a.uge(edge)); EXPECT_TRUE( a.ult(edgeP1)); EXPECT_TRUE( a.ule(edgeP1)); EXPECT_TRUE(!a.ugt(edgeP1)); EXPECT_TRUE(!a.uge(edgeP1)); EXPECT_TRUE(!a.ult(edgeM1)); EXPECT_TRUE(!a.ule(edgeM1)); EXPECT_TRUE( a.ugt(edgeM1)); EXPECT_TRUE( a.uge(edgeM1)); EXPECT_TRUE(!a.slt(edge)); EXPECT_TRUE( a.sle(edge)); EXPECT_TRUE(!a.sgt(edge)); EXPECT_TRUE( a.sge(edge)); EXPECT_TRUE( a.slt(edgeP1)); EXPECT_TRUE( a.sle(edgeP1)); EXPECT_TRUE(!a.sgt(edgeP1)); EXPECT_TRUE(!a.sge(edgeP1)); EXPECT_TRUE(!a.slt(edgeM1)); EXPECT_TRUE(!a.sle(edgeM1)); EXPECT_TRUE( a.sgt(edgeM1)); EXPECT_TRUE( a.sge(edgeM1)); } // Tests different div/rem varaints using scheme (a * b + c) / a void testDiv(APInt a, APInt b, APInt c) { ASSERT_TRUE(a.uge(b)); // Must: a >= b ASSERT_TRUE(a.ugt(c)); // Must: a > c auto p = a * b + c; auto q = p.udiv(a); auto r = p.urem(a); EXPECT_EQ(b, q); EXPECT_EQ(c, r); APInt::udivrem(p, a, q, r); EXPECT_EQ(b, q); EXPECT_EQ(c, r); q = p.sdiv(a); r = p.srem(a); EXPECT_EQ(b, q); EXPECT_EQ(c, r); APInt::sdivrem(p, a, q, r); EXPECT_EQ(b, q); EXPECT_EQ(c, r); if (b.ugt(c)) { // Test also symmetric case q = p.udiv(b); r = p.urem(b); EXPECT_EQ(a, q); EXPECT_EQ(c, r); APInt::udivrem(p, b, q, r); EXPECT_EQ(a, q); EXPECT_EQ(c, r); q = p.sdiv(b); r = p.srem(b); EXPECT_EQ(a, q); EXPECT_EQ(c, r); APInt::sdivrem(p, b, q, r); EXPECT_EQ(a, q); EXPECT_EQ(c, r); } } TEST(APIntTest, divrem_big1) { // Tests KnuthDiv rare step D6 testDiv({256, "1ffffffffffffffff", 16}, {256, "1ffffffffffffffff", 16}, {256, 0}); } TEST(APIntTest, divrem_big2) { // Tests KnuthDiv rare step D6 testDiv({1024, "112233ceff" "cecece000000ffffffffffffffffffff" "ffffffffffffffffffffffffffffffff" "ffffffffffffffffffffffffffffffff" "ffffffffffffffffffffffffffffff33", 16}, {1024, "111111ffffffffffffffff" "ffffffffffffffffffffffffffffffff" "fffffffffffffffffffffffffffffccf" "ffffffffffffffffffffffffffffff00", 16}, {1024, 7919}); } TEST(APIntTest, divrem_big3) { // Tests KnuthDiv case without shift testDiv({256, "80000001ffffffffffffffff", 16}, {256, "ffffffffffffff0000000", 16}, {256, 4219}); } TEST(APIntTest, divrem_big4) { // Tests heap allocation in divide() enfoced by huge numbers testDiv(APInt{4096, 5}.shl(2001), APInt{4096, 1}.shl(2000), APInt{4096, 4219*13}); } TEST(APIntTest, divrem_big5) { // Tests one word divisor case of divide() testDiv(APInt{1024, 19}.shl(811), APInt{1024, 4356013}, // one word APInt{1024, 1}); } TEST(APIntTest, divrem_big6) { // Tests some rare "borrow" cases in D4 step testDiv(APInt{512, "ffffffffffffffff00000000000000000000000001", 16}, APInt{512, "10000000000000001000000000000001", 16}, APInt{512, "10000000000000000000000000000000", 16}); } TEST(APIntTest, divrem_big7) { // Yet another test for KnuthDiv rare step D6. testDiv({224, "800000008000000200000005", 16}, {224, "fffffffd", 16}, {224, "80000000800000010000000f", 16}); } TEST(APIntTest, fromString) { EXPECT_EQ(APInt(32, 0), APInt(32, "0", 2)); EXPECT_EQ(APInt(32, 1), APInt(32, "1", 2)); EXPECT_EQ(APInt(32, 2), APInt(32, "10", 2)); EXPECT_EQ(APInt(32, 3), APInt(32, "11", 2)); EXPECT_EQ(APInt(32, 4), APInt(32, "100", 2)); EXPECT_EQ(APInt(32, 0), APInt(32, "+0", 2)); EXPECT_EQ(APInt(32, 1), APInt(32, "+1", 2)); EXPECT_EQ(APInt(32, 2), APInt(32, "+10", 2)); EXPECT_EQ(APInt(32, 3), APInt(32, "+11", 2)); EXPECT_EQ(APInt(32, 4), APInt(32, "+100", 2)); EXPECT_EQ(APInt(32, uint64_t(-0LL)), APInt(32, "-0", 2)); EXPECT_EQ(APInt(32, uint64_t(-1LL)), APInt(32, "-1", 2)); EXPECT_EQ(APInt(32, uint64_t(-2LL)), APInt(32, "-10", 2)); EXPECT_EQ(APInt(32, uint64_t(-3LL)), APInt(32, "-11", 2)); EXPECT_EQ(APInt(32, uint64_t(-4LL)), APInt(32, "-100", 2)); EXPECT_EQ(APInt(32, 0), APInt(32, "0", 8)); EXPECT_EQ(APInt(32, 1), APInt(32, "1", 8)); EXPECT_EQ(APInt(32, 7), APInt(32, "7", 8)); EXPECT_EQ(APInt(32, 8), APInt(32, "10", 8)); EXPECT_EQ(APInt(32, 15), APInt(32, "17", 8)); EXPECT_EQ(APInt(32, 16), APInt(32, "20", 8)); EXPECT_EQ(APInt(32, +0), APInt(32, "+0", 8)); EXPECT_EQ(APInt(32, +1), APInt(32, "+1", 8)); EXPECT_EQ(APInt(32, +7), APInt(32, "+7", 8)); EXPECT_EQ(APInt(32, +8), APInt(32, "+10", 8)); EXPECT_EQ(APInt(32, +15), APInt(32, "+17", 8)); EXPECT_EQ(APInt(32, +16), APInt(32, "+20", 8)); EXPECT_EQ(APInt(32, uint64_t(-0LL)), APInt(32, "-0", 8)); EXPECT_EQ(APInt(32, uint64_t(-1LL)), APInt(32, "-1", 8)); EXPECT_EQ(APInt(32, uint64_t(-7LL)), APInt(32, "-7", 8)); EXPECT_EQ(APInt(32, uint64_t(-8LL)), APInt(32, "-10", 8)); EXPECT_EQ(APInt(32, uint64_t(-15LL)), APInt(32, "-17", 8)); EXPECT_EQ(APInt(32, uint64_t(-16LL)), APInt(32, "-20", 8)); EXPECT_EQ(APInt(32, 0), APInt(32, "0", 10)); EXPECT_EQ(APInt(32, 1), APInt(32, "1", 10)); EXPECT_EQ(APInt(32, 9), APInt(32, "9", 10)); EXPECT_EQ(APInt(32, 10), APInt(32, "10", 10)); EXPECT_EQ(APInt(32, 19), APInt(32, "19", 10)); EXPECT_EQ(APInt(32, 20), APInt(32, "20", 10)); EXPECT_EQ(APInt(32, uint64_t(-0LL)), APInt(32, "-0", 10)); EXPECT_EQ(APInt(32, uint64_t(-1LL)), APInt(32, "-1", 10)); EXPECT_EQ(APInt(32, uint64_t(-9LL)), APInt(32, "-9", 10)); EXPECT_EQ(APInt(32, uint64_t(-10LL)), APInt(32, "-10", 10)); EXPECT_EQ(APInt(32, uint64_t(-19LL)), APInt(32, "-19", 10)); EXPECT_EQ(APInt(32, uint64_t(-20LL)), APInt(32, "-20", 10)); EXPECT_EQ(APInt(32, 0), APInt(32, "0", 16)); EXPECT_EQ(APInt(32, 1), APInt(32, "1", 16)); EXPECT_EQ(APInt(32, 15), APInt(32, "F", 16)); EXPECT_EQ(APInt(32, 16), APInt(32, "10", 16)); EXPECT_EQ(APInt(32, 31), APInt(32, "1F", 16)); EXPECT_EQ(APInt(32, 32), APInt(32, "20", 16)); EXPECT_EQ(APInt(32, uint64_t(-0LL)), APInt(32, "-0", 16)); EXPECT_EQ(APInt(32, uint64_t(-1LL)), APInt(32, "-1", 16)); EXPECT_EQ(APInt(32, uint64_t(-15LL)), APInt(32, "-F", 16)); EXPECT_EQ(APInt(32, uint64_t(-16LL)), APInt(32, "-10", 16)); EXPECT_EQ(APInt(32, uint64_t(-31LL)), APInt(32, "-1F", 16)); EXPECT_EQ(APInt(32, uint64_t(-32LL)), APInt(32, "-20", 16)); EXPECT_EQ(APInt(32, 0), APInt(32, "0", 36)); EXPECT_EQ(APInt(32, 1), APInt(32, "1", 36)); EXPECT_EQ(APInt(32, 35), APInt(32, "Z", 36)); EXPECT_EQ(APInt(32, 36), APInt(32, "10", 36)); EXPECT_EQ(APInt(32, 71), APInt(32, "1Z", 36)); EXPECT_EQ(APInt(32, 72), APInt(32, "20", 36)); EXPECT_EQ(APInt(32, uint64_t(-0LL)), APInt(32, "-0", 36)); EXPECT_EQ(APInt(32, uint64_t(-1LL)), APInt(32, "-1", 36)); EXPECT_EQ(APInt(32, uint64_t(-35LL)), APInt(32, "-Z", 36)); EXPECT_EQ(APInt(32, uint64_t(-36LL)), APInt(32, "-10", 36)); EXPECT_EQ(APInt(32, uint64_t(-71LL)), APInt(32, "-1Z", 36)); EXPECT_EQ(APInt(32, uint64_t(-72LL)), APInt(32, "-20", 36)); } TEST(APIntTest, FromArray) { EXPECT_EQ(APInt(32, uint64_t(1)), APInt(32, ArrayRef<uint64_t>(1))); } TEST(APIntTest, StringBitsNeeded2) { EXPECT_EQ(1U, APInt::getBitsNeeded( "0", 2)); EXPECT_EQ(1U, APInt::getBitsNeeded( "1", 2)); EXPECT_EQ(2U, APInt::getBitsNeeded( "10", 2)); EXPECT_EQ(2U, APInt::getBitsNeeded( "11", 2)); EXPECT_EQ(3U, APInt::getBitsNeeded("100", 2)); EXPECT_EQ(1U, APInt::getBitsNeeded( "+0", 2)); EXPECT_EQ(1U, APInt::getBitsNeeded( "+1", 2)); EXPECT_EQ(2U, APInt::getBitsNeeded( "+10", 2)); EXPECT_EQ(2U, APInt::getBitsNeeded( "+11", 2)); EXPECT_EQ(3U, APInt::getBitsNeeded("+100", 2)); EXPECT_EQ(2U, APInt::getBitsNeeded( "-0", 2)); EXPECT_EQ(2U, APInt::getBitsNeeded( "-1", 2)); EXPECT_EQ(3U, APInt::getBitsNeeded( "-10", 2)); EXPECT_EQ(3U, APInt::getBitsNeeded( "-11", 2)); EXPECT_EQ(4U, APInt::getBitsNeeded("-100", 2)); } TEST(APIntTest, StringBitsNeeded8) { EXPECT_EQ(3U, APInt::getBitsNeeded( "0", 8)); EXPECT_EQ(3U, APInt::getBitsNeeded( "7", 8)); EXPECT_EQ(6U, APInt::getBitsNeeded("10", 8)); EXPECT_EQ(6U, APInt::getBitsNeeded("17", 8)); EXPECT_EQ(6U, APInt::getBitsNeeded("20", 8)); EXPECT_EQ(3U, APInt::getBitsNeeded( "+0", 8)); EXPECT_EQ(3U, APInt::getBitsNeeded( "+7", 8)); EXPECT_EQ(6U, APInt::getBitsNeeded("+10", 8)); EXPECT_EQ(6U, APInt::getBitsNeeded("+17", 8)); EXPECT_EQ(6U, APInt::getBitsNeeded("+20", 8)); EXPECT_EQ(4U, APInt::getBitsNeeded( "-0", 8)); EXPECT_EQ(4U, APInt::getBitsNeeded( "-7", 8)); EXPECT_EQ(7U, APInt::getBitsNeeded("-10", 8)); EXPECT_EQ(7U, APInt::getBitsNeeded("-17", 8)); EXPECT_EQ(7U, APInt::getBitsNeeded("-20", 8)); } TEST(APIntTest, StringBitsNeeded10) { EXPECT_EQ(1U, APInt::getBitsNeeded( "0", 10)); EXPECT_EQ(2U, APInt::getBitsNeeded( "3", 10)); EXPECT_EQ(4U, APInt::getBitsNeeded( "9", 10)); EXPECT_EQ(4U, APInt::getBitsNeeded("10", 10)); EXPECT_EQ(5U, APInt::getBitsNeeded("19", 10)); EXPECT_EQ(5U, APInt::getBitsNeeded("20", 10)); EXPECT_EQ(1U, APInt::getBitsNeeded( "+0", 10)); EXPECT_EQ(4U, APInt::getBitsNeeded( "+9", 10)); EXPECT_EQ(4U, APInt::getBitsNeeded("+10", 10)); EXPECT_EQ(5U, APInt::getBitsNeeded("+19", 10)); EXPECT_EQ(5U, APInt::getBitsNeeded("+20", 10)); EXPECT_EQ(2U, APInt::getBitsNeeded( "-0", 10)); EXPECT_EQ(5U, APInt::getBitsNeeded( "-9", 10)); EXPECT_EQ(5U, APInt::getBitsNeeded("-10", 10)); EXPECT_EQ(6U, APInt::getBitsNeeded("-19", 10)); EXPECT_EQ(6U, APInt::getBitsNeeded("-20", 10)); } TEST(APIntTest, StringBitsNeeded16) { EXPECT_EQ(4U, APInt::getBitsNeeded( "0", 16)); EXPECT_EQ(4U, APInt::getBitsNeeded( "F", 16)); EXPECT_EQ(8U, APInt::getBitsNeeded("10", 16)); EXPECT_EQ(8U, APInt::getBitsNeeded("1F", 16)); EXPECT_EQ(8U, APInt::getBitsNeeded("20", 16)); EXPECT_EQ(4U, APInt::getBitsNeeded( "+0", 16)); EXPECT_EQ(4U, APInt::getBitsNeeded( "+F", 16)); EXPECT_EQ(8U, APInt::getBitsNeeded("+10", 16)); EXPECT_EQ(8U, APInt::getBitsNeeded("+1F", 16)); EXPECT_EQ(8U, APInt::getBitsNeeded("+20", 16)); EXPECT_EQ(5U, APInt::getBitsNeeded( "-0", 16)); EXPECT_EQ(5U, APInt::getBitsNeeded( "-F", 16)); EXPECT_EQ(9U, APInt::getBitsNeeded("-10", 16)); EXPECT_EQ(9U, APInt::getBitsNeeded("-1F", 16)); EXPECT_EQ(9U, APInt::getBitsNeeded("-20", 16)); } TEST(APIntTest, toString) { SmallString<16> S; bool isSigned; APInt(8, 0).toString(S, 2, true, true); EXPECT_EQ(S.str().str(), "0b0"); S.clear(); APInt(8, 0).toString(S, 8, true, true); EXPECT_EQ(S.str().str(), "00"); S.clear(); APInt(8, 0).toString(S, 10, true, true); EXPECT_EQ(S.str().str(), "0"); S.clear(); APInt(8, 0).toString(S, 16, true, true); EXPECT_EQ(S.str().str(), "0x0"); S.clear(); APInt(8, 0).toString(S, 36, true, false); EXPECT_EQ(S.str().str(), "0"); S.clear(); isSigned = false; APInt(8, 255, isSigned).toString(S, 2, isSigned, true); EXPECT_EQ(S.str().str(), "0b11111111"); S.clear(); APInt(8, 255, isSigned).toString(S, 8, isSigned, true); EXPECT_EQ(S.str().str(), "0377"); S.clear(); APInt(8, 255, isSigned).toString(S, 10, isSigned, true); EXPECT_EQ(S.str().str(), "255"); S.clear(); APInt(8, 255, isSigned).toString(S, 16, isSigned, true); EXPECT_EQ(S.str().str(), "0xFF"); S.clear(); APInt(8, 255, isSigned).toString(S, 36, isSigned, false); EXPECT_EQ(S.str().str(), "73"); S.clear(); isSigned = true; APInt(8, 255, isSigned).toString(S, 2, isSigned, true); EXPECT_EQ(S.str().str(), "-0b1"); S.clear(); APInt(8, 255, isSigned).toString(S, 8, isSigned, true); EXPECT_EQ(S.str().str(), "-01"); S.clear(); APInt(8, 255, isSigned).toString(S, 10, isSigned, true); EXPECT_EQ(S.str().str(), "-1"); S.clear(); APInt(8, 255, isSigned).toString(S, 16, isSigned, true); EXPECT_EQ(S.str().str(), "-0x1"); S.clear(); APInt(8, 255, isSigned).toString(S, 36, isSigned, false); EXPECT_EQ(S.str().str(), "-1"); S.clear(); } TEST(APIntTest, Log2) { EXPECT_EQ(APInt(15, 7).logBase2(), 2U); EXPECT_EQ(APInt(15, 7).ceilLogBase2(), 3U); EXPECT_EQ(APInt(15, 7).exactLogBase2(), -1); EXPECT_EQ(APInt(15, 8).logBase2(), 3U); EXPECT_EQ(APInt(15, 8).ceilLogBase2(), 3U); EXPECT_EQ(APInt(15, 8).exactLogBase2(), 3); EXPECT_EQ(APInt(15, 9).logBase2(), 3U); EXPECT_EQ(APInt(15, 9).ceilLogBase2(), 4U); EXPECT_EQ(APInt(15, 9).exactLogBase2(), -1); } TEST(APIntTest, magic) { EXPECT_EQ(APInt(32, 3).magic().m, APInt(32, "55555556", 16)); EXPECT_EQ(APInt(32, 3).magic().s, 0U); EXPECT_EQ(APInt(32, 5).magic().m, APInt(32, "66666667", 16)); EXPECT_EQ(APInt(32, 5).magic().s, 1U); EXPECT_EQ(APInt(32, 7).magic().m, APInt(32, "92492493", 16)); EXPECT_EQ(APInt(32, 7).magic().s, 2U); } TEST(APIntTest, magicu) { EXPECT_EQ(APInt(32, 3).magicu().m, APInt(32, "AAAAAAAB", 16)); EXPECT_EQ(APInt(32, 3).magicu().s, 1U); EXPECT_EQ(APInt(32, 5).magicu().m, APInt(32, "CCCCCCCD", 16)); EXPECT_EQ(APInt(32, 5).magicu().s, 2U); EXPECT_EQ(APInt(32, 7).magicu().m, APInt(32, "24924925", 16)); EXPECT_EQ(APInt(32, 7).magicu().s, 3U); EXPECT_EQ(APInt(64, 25).magicu(1).m, APInt(64, "A3D70A3D70A3D70B", 16)); EXPECT_EQ(APInt(64, 25).magicu(1).s, 4U); } #ifdef GTEST_HAS_DEATH_TEST #ifndef NDEBUG TEST(APIntTest, StringDeath) { EXPECT_DEATH(APInt(0, "", 0), "Bitwidth too small"); EXPECT_DEATH(APInt(32, "", 0), "Invalid string length"); EXPECT_DEATH(APInt(32, "0", 0), "Radix should be 2, 8, 10, 16, or 36!"); EXPECT_DEATH(APInt(32, "", 10), "Invalid string length"); EXPECT_DEATH(APInt(32, "-", 10), "String is only a sign, needs a value."); EXPECT_DEATH(APInt(1, "1234", 10), "Insufficient bit width"); EXPECT_DEATH(APInt(32, "\0", 10), "Invalid string length"); EXPECT_DEATH(APInt(32, StringRef("1\02", 3), 10), "Invalid character in digit string"); EXPECT_DEATH(APInt(32, "1L", 10), "Invalid character in digit string"); } #endif #endif TEST(APIntTest, mul_clear) { APInt ValA(65, -1ULL); APInt ValB(65, 4); APInt ValC(65, 0); ValC = ValA * ValB; ValA *= ValB; EXPECT_EQ(ValA.toString(10, false), ValC.toString(10, false)); } TEST(APIntTest, Rotate) { EXPECT_EQ(APInt(8, 1), APInt(8, 1).rotl(0)); EXPECT_EQ(APInt(8, 2), APInt(8, 1).rotl(1)); EXPECT_EQ(APInt(8, 4), APInt(8, 1).rotl(2)); EXPECT_EQ(APInt(8, 16), APInt(8, 1).rotl(4)); EXPECT_EQ(APInt(8, 1), APInt(8, 1).rotl(8)); EXPECT_EQ(APInt(8, 16), APInt(8, 16).rotl(0)); EXPECT_EQ(APInt(8, 32), APInt(8, 16).rotl(1)); EXPECT_EQ(APInt(8, 64), APInt(8, 16).rotl(2)); EXPECT_EQ(APInt(8, 1), APInt(8, 16).rotl(4)); EXPECT_EQ(APInt(8, 16), APInt(8, 16).rotl(8)); EXPECT_EQ(APInt(8, 16), APInt(8, 16).rotr(0)); EXPECT_EQ(APInt(8, 8), APInt(8, 16).rotr(1)); EXPECT_EQ(APInt(8, 4), APInt(8, 16).rotr(2)); EXPECT_EQ(APInt(8, 1), APInt(8, 16).rotr(4)); EXPECT_EQ(APInt(8, 16), APInt(8, 16).rotr(8)); EXPECT_EQ(APInt(8, 1), APInt(8, 1).rotr(0)); EXPECT_EQ(APInt(8, 128), APInt(8, 1).rotr(1)); EXPECT_EQ(APInt(8, 64), APInt(8, 1).rotr(2)); EXPECT_EQ(APInt(8, 16), APInt(8, 1).rotr(4)); EXPECT_EQ(APInt(8, 1), APInt(8, 1).rotr(8)); APInt Big(256, "00004000800000000000000000003fff8000000000000000", 16); APInt Rot(256, "3fff80000000000000000000000000000000000040008000", 16); EXPECT_EQ(Rot, Big.rotr(144)); } TEST(APIntTest, Splat) { APInt ValA(8, 0x01); EXPECT_EQ(ValA, APInt::getSplat(8, ValA)); EXPECT_EQ(APInt(64, 0x0101010101010101ULL), APInt::getSplat(64, ValA)); APInt ValB(3, 5); EXPECT_EQ(APInt(4, 0xD), APInt::getSplat(4, ValB)); EXPECT_EQ(APInt(15, 0xDB6D), APInt::getSplat(15, ValB)); } TEST(APIntTest, tcDecrement) { // Test single word decrement. // No out borrow. { integerPart singleWord = ~integerPart(0) << (integerPartWidth - 1); integerPart carry = APInt::tcDecrement(&singleWord, 1); EXPECT_EQ(carry, integerPart(0)); EXPECT_EQ(singleWord, ~integerPart(0) >> 1); } // With out borrow. { integerPart singleWord = 0; integerPart carry = APInt::tcDecrement(&singleWord, 1); EXPECT_EQ(carry, integerPart(1)); EXPECT_EQ(singleWord, ~integerPart(0)); } // Test multiword decrement. // No across word borrow, no out borrow. { integerPart test[4] = {0x1, 0x1, 0x1, 0x1}; integerPart expected[4] = {0x0, 0x1, 0x1, 0x1}; APInt::tcDecrement(test, 4); EXPECT_EQ(APInt::tcCompare(test, expected, 4), 0); } // 1 across word borrow, no out borrow. { integerPart test[4] = {0x0, 0xF, 0x1, 0x1}; integerPart expected[4] = {~integerPart(0), 0xE, 0x1, 0x1}; integerPart carry = APInt::tcDecrement(test, 4); EXPECT_EQ(carry, integerPart(0)); EXPECT_EQ(APInt::tcCompare(test, expected, 4), 0); } // 2 across word borrow, no out borrow. { integerPart test[4] = {0x0, 0x0, 0xC, 0x1}; integerPart expected[4] = {~integerPart(0), ~integerPart(0), 0xB, 0x1}; integerPart carry = APInt::tcDecrement(test, 4); EXPECT_EQ(carry, integerPart(0)); EXPECT_EQ(APInt::tcCompare(test, expected, 4), 0); } // 3 across word borrow, no out borrow. { integerPart test[4] = {0x0, 0x0, 0x0, 0x1}; integerPart expected[4] = {~integerPart(0), ~integerPart(0), ~integerPart(0), 0x0}; integerPart carry = APInt::tcDecrement(test, 4); EXPECT_EQ(carry, integerPart(0)); EXPECT_EQ(APInt::tcCompare(test, expected, 4), 0); } // 3 across word borrow, with out borrow. { integerPart test[4] = {0x0, 0x0, 0x0, 0x0}; integerPart expected[4] = {~integerPart(0), ~integerPart(0), ~integerPart(0), ~integerPart(0)}; integerPart carry = APInt::tcDecrement(test, 4); EXPECT_EQ(carry, integerPart(1)); EXPECT_EQ(APInt::tcCompare(test, expected, 4), 0); } } TEST(APIntTest, arrayAccess) { // Single word check. uint64_t E1 = 0x2CA7F46BF6569915ULL; APInt A1(64, E1); for (unsigned i = 0, e = 64; i < e; ++i) { EXPECT_EQ(bool(E1 & (1ULL << i)), A1[i]); } // Multiword check. integerPart E2[4] = { 0xEB6EB136591CBA21ULL, 0x7B9358BD6A33F10AULL, 0x7E7FFA5EADD8846ULL, 0x305F341CA00B613DULL }; APInt A2(integerPartWidth*4, E2); for (unsigned i = 0; i < 4; ++i) { for (unsigned j = 0; j < integerPartWidth; ++j) { EXPECT_EQ(bool(E2[i] & (1ULL << j)), A2[i*integerPartWidth + j]); } } } TEST(APIntTest, LargeAPIntConstruction) { // Check that we can properly construct very large APInt. It is very // unlikely that people will ever do this, but it is a legal input, // so we should not crash on it. APInt A9(UINT32_MAX, 0); EXPECT_FALSE(A9.getBoolValue()); } TEST(APIntTest, nearestLogBase2) { // Single word check. // Test round up. uint64_t I1 = 0x1800001; APInt A1(64, I1); EXPECT_EQ(A1.nearestLogBase2(), A1.ceilLogBase2()); // Test round down. uint64_t I2 = 0x1000011; APInt A2(64, I2); EXPECT_EQ(A2.nearestLogBase2(), A2.logBase2()); // Test ties round up. uint64_t I3 = 0x1800000; APInt A3(64, I3); EXPECT_EQ(A3.nearestLogBase2(), A3.ceilLogBase2()); // Multiple word check. // Test round up. integerPart I4[4] = {0x0, 0xF, 0x18, 0x0}; APInt A4(integerPartWidth*4, I4); EXPECT_EQ(A4.nearestLogBase2(), A4.ceilLogBase2()); // Test round down. integerPart I5[4] = {0x0, 0xF, 0x10, 0x0}; APInt A5(integerPartWidth*4, I5); EXPECT_EQ(A5.nearestLogBase2(), A5.logBase2()); // Test ties round up. uint64_t I6[4] = {0x0, 0x0, 0x0, 0x18}; APInt A6(integerPartWidth*4, I6); EXPECT_EQ(A6.nearestLogBase2(), A6.ceilLogBase2()); // Test BitWidth == 1 special cases. APInt A7(1, 1); EXPECT_EQ(A7.nearestLogBase2(), 0ULL); APInt A8(1, 0); EXPECT_EQ(A8.nearestLogBase2(), UINT32_MAX); // Test the zero case when we have a bit width large enough such // that the bit width is larger than UINT32_MAX-1. APInt A9(UINT32_MAX, 0); EXPECT_EQ(A9.nearestLogBase2(), UINT32_MAX); } TEST(APIntTest, IsSplat) { APInt A(32, 0x01010101); EXPECT_FALSE(A.isSplat(1)); EXPECT_FALSE(A.isSplat(2)); EXPECT_FALSE(A.isSplat(4)); EXPECT_TRUE(A.isSplat(8)); EXPECT_TRUE(A.isSplat(16)); EXPECT_TRUE(A.isSplat(32)); APInt B(24, 0xAAAAAA); EXPECT_FALSE(B.isSplat(1)); EXPECT_TRUE(B.isSplat(2)); EXPECT_TRUE(B.isSplat(4)); EXPECT_TRUE(B.isSplat(8)); EXPECT_TRUE(B.isSplat(24)); APInt C(24, 0xABAAAB); EXPECT_FALSE(C.isSplat(1)); EXPECT_FALSE(C.isSplat(2)); EXPECT_FALSE(C.isSplat(4)); EXPECT_FALSE(C.isSplat(8)); EXPECT_TRUE(C.isSplat(24)); APInt D(32, 0xABBAABBA); EXPECT_FALSE(D.isSplat(1)); EXPECT_FALSE(D.isSplat(2)); EXPECT_FALSE(D.isSplat(4)); EXPECT_FALSE(D.isSplat(8)); EXPECT_TRUE(D.isSplat(16)); EXPECT_TRUE(D.isSplat(32)); APInt E(32, 0); EXPECT_TRUE(E.isSplat(1)); EXPECT_TRUE(E.isSplat(2)); EXPECT_TRUE(E.isSplat(4)); EXPECT_TRUE(E.isSplat(8)); EXPECT_TRUE(E.isSplat(16)); EXPECT_TRUE(E.isSplat(32)); } #if defined(__clang__) // Disable the pragma warning from versions of Clang without -Wself-move #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunknown-pragmas" // Disable the warning that triggers on exactly what is being tested. #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wself-move" #endif TEST(APIntTest, SelfMoveAssignment) { APInt X(32, 0xdeadbeef); X = std::move(X); EXPECT_EQ(32u, X.getBitWidth()); EXPECT_EQ(0xdeadbeefULL, X.getLimitedValue()); uint64_t Bits[] = {0xdeadbeefdeadbeefULL, 0xdeadbeefdeadbeefULL}; APInt Y(128, Bits); Y = std::move(Y); EXPECT_EQ(128u, Y.getBitWidth()); EXPECT_EQ(~0ULL, Y.getLimitedValue()); const uint64_t *Raw = Y.getRawData(); EXPECT_EQ(2u, Y.getNumWords()); EXPECT_EQ(0xdeadbeefdeadbeefULL, Raw[0]); EXPECT_EQ(0xdeadbeefdeadbeefULL, Raw[1]); } #if defined(__clang__) #pragma clang diagnostic pop #pragma clang diagnostic pop #endif }
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/ADT/DenseMapTest.cpp
//===- llvm/unittest/ADT/DenseMapMap.cpp - DenseMap unit tests --*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "gtest/gtest.h" #include "llvm/ADT/DenseMap.h" #include <map> #include <set> using namespace llvm; namespace { uint32_t getTestKey(int i, uint32_t *) { return i; } uint32_t getTestValue(int i, uint32_t *) { return 42 + i; } uint32_t *getTestKey(int i, uint32_t **) { static uint32_t dummy_arr1[8192]; assert(i < 8192 && "Only support 8192 dummy keys."); return &dummy_arr1[i]; } uint32_t *getTestValue(int i, uint32_t **) { static uint32_t dummy_arr1[8192]; assert(i < 8192 && "Only support 8192 dummy keys."); return &dummy_arr1[i]; } /// \brief A test class that tries to check that construction and destruction /// occur correctly. class CtorTester { static std::set<CtorTester *> Constructed; int Value; public: explicit CtorTester(int Value = 0) : Value(Value) { EXPECT_TRUE(Constructed.insert(this).second); } CtorTester(uint32_t Value) : Value(Value) { EXPECT_TRUE(Constructed.insert(this).second); } CtorTester(const CtorTester &Arg) : Value(Arg.Value) { EXPECT_TRUE(Constructed.insert(this).second); } CtorTester &operator=(const CtorTester &) = default; ~CtorTester() { EXPECT_EQ(1u, Constructed.erase(this)); } operator uint32_t() const { return Value; } int getValue() const { return Value; } bool operator==(const CtorTester &RHS) const { return Value == RHS.Value; } }; std::set<CtorTester *> CtorTester::Constructed; struct CtorTesterMapInfo { static inline CtorTester getEmptyKey() { return CtorTester(-1); } static inline CtorTester getTombstoneKey() { return CtorTester(-2); } static unsigned getHashValue(const CtorTester &Val) { return Val.getValue() * 37u; } static bool isEqual(const CtorTester &LHS, const CtorTester &RHS) { return LHS == RHS; } }; CtorTester getTestKey(int i, CtorTester *) { return CtorTester(i); } CtorTester getTestValue(int i, CtorTester *) { return CtorTester(42 + i); } // Test fixture, with helper functions implemented by forwarding to global // function overloads selected by component types of the type parameter. This // allows all of the map implementations to be tested with shared // implementations of helper routines. template <typename T> class DenseMapTest : public ::testing::Test { protected: T Map; static typename T::key_type *const dummy_key_ptr; static typename T::mapped_type *const dummy_value_ptr; typename T::key_type getKey(int i = 0) { return getTestKey(i, dummy_key_ptr); } typename T::mapped_type getValue(int i = 0) { return getTestValue(i, dummy_value_ptr); } }; template <typename T> typename T::key_type *const DenseMapTest<T>::dummy_key_ptr = nullptr; template <typename T> typename T::mapped_type *const DenseMapTest<T>::dummy_value_ptr = nullptr; // Register these types for testing. typedef ::testing::Types<DenseMap<uint32_t, uint32_t>, DenseMap<uint32_t *, uint32_t *>, DenseMap<CtorTester, CtorTester, CtorTesterMapInfo>, SmallDenseMap<uint32_t, uint32_t>, SmallDenseMap<uint32_t *, uint32_t *>, SmallDenseMap<CtorTester, CtorTester, 4, CtorTesterMapInfo> > DenseMapTestTypes; TYPED_TEST_CASE(DenseMapTest, DenseMapTestTypes); // Empty map tests TYPED_TEST(DenseMapTest, EmptyIntMapTest) { // Size tests EXPECT_EQ(0u, this->Map.size()); EXPECT_TRUE(this->Map.empty()); // Iterator tests EXPECT_TRUE(this->Map.begin() == this->Map.end()); // Lookup tests EXPECT_FALSE(this->Map.count(this->getKey())); EXPECT_TRUE(this->Map.find(this->getKey()) == this->Map.end()); #if !defined(_MSC_VER) || defined(__clang__) EXPECT_EQ(typename TypeParam::mapped_type(), this->Map.lookup(this->getKey())); #else // MSVC, at least old versions, cannot parse the typename to disambiguate // TypeParam::mapped_type as a type. However, because MSVC doesn't implement // two-phase name lookup, it also doesn't require the typename. Deal with // this mutual incompatibility through specialized code. EXPECT_EQ(TypeParam::mapped_type(), this->Map.lookup(this->getKey())); #endif } // Constant map tests TYPED_TEST(DenseMapTest, ConstEmptyMapTest) { const TypeParam &ConstMap = this->Map; EXPECT_EQ(0u, ConstMap.size()); EXPECT_TRUE(ConstMap.empty()); EXPECT_TRUE(ConstMap.begin() == ConstMap.end()); } // A map with a single entry TYPED_TEST(DenseMapTest, SingleEntryMapTest) { this->Map[this->getKey()] = this->getValue(); // Size tests EXPECT_EQ(1u, this->Map.size()); EXPECT_FALSE(this->Map.begin() == this->Map.end()); EXPECT_FALSE(this->Map.empty()); // Iterator tests typename TypeParam::iterator it = this->Map.begin(); EXPECT_EQ(this->getKey(), it->first); EXPECT_EQ(this->getValue(), it->second); ++it; EXPECT_TRUE(it == this->Map.end()); // Lookup tests EXPECT_TRUE(this->Map.count(this->getKey())); EXPECT_TRUE(this->Map.find(this->getKey()) == this->Map.begin()); EXPECT_EQ(this->getValue(), this->Map.lookup(this->getKey())); EXPECT_EQ(this->getValue(), this->Map[this->getKey()]); } // Test clear() method TYPED_TEST(DenseMapTest, ClearTest) { this->Map[this->getKey()] = this->getValue(); this->Map.clear(); EXPECT_EQ(0u, this->Map.size()); EXPECT_TRUE(this->Map.empty()); EXPECT_TRUE(this->Map.begin() == this->Map.end()); } // Test erase(iterator) method TYPED_TEST(DenseMapTest, EraseTest) { this->Map[this->getKey()] = this->getValue(); this->Map.erase(this->Map.begin()); EXPECT_EQ(0u, this->Map.size()); EXPECT_TRUE(this->Map.empty()); EXPECT_TRUE(this->Map.begin() == this->Map.end()); } // Test erase(value) method TYPED_TEST(DenseMapTest, EraseTest2) { this->Map[this->getKey()] = this->getValue(); this->Map.erase(this->getKey()); EXPECT_EQ(0u, this->Map.size()); EXPECT_TRUE(this->Map.empty()); EXPECT_TRUE(this->Map.begin() == this->Map.end()); } // Test insert() method TYPED_TEST(DenseMapTest, InsertTest) { this->Map.insert(std::make_pair(this->getKey(), this->getValue())); EXPECT_EQ(1u, this->Map.size()); EXPECT_EQ(this->getValue(), this->Map[this->getKey()]); } // Test copy constructor method TYPED_TEST(DenseMapTest, CopyConstructorTest) { this->Map[this->getKey()] = this->getValue(); TypeParam copyMap(this->Map); EXPECT_EQ(1u, copyMap.size()); EXPECT_EQ(this->getValue(), copyMap[this->getKey()]); } // Test copy constructor method where SmallDenseMap isn't small. TYPED_TEST(DenseMapTest, CopyConstructorNotSmallTest) { for (int Key = 0; Key < 5; ++Key) this->Map[this->getKey(Key)] = this->getValue(Key); TypeParam copyMap(this->Map); EXPECT_EQ(5u, copyMap.size()); for (int Key = 0; Key < 5; ++Key) EXPECT_EQ(this->getValue(Key), copyMap[this->getKey(Key)]); } // Test copying from a default-constructed map. TYPED_TEST(DenseMapTest, CopyConstructorFromDefaultTest) { TypeParam copyMap(this->Map); EXPECT_TRUE(copyMap.empty()); } // Test copying from an empty map where SmallDenseMap isn't small. TYPED_TEST(DenseMapTest, CopyConstructorFromEmptyTest) { for (int Key = 0; Key < 5; ++Key) this->Map[this->getKey(Key)] = this->getValue(Key); this->Map.clear(); TypeParam copyMap(this->Map); EXPECT_TRUE(copyMap.empty()); } // Test assignment operator method TYPED_TEST(DenseMapTest, AssignmentTest) { this->Map[this->getKey()] = this->getValue(); TypeParam copyMap = this->Map; EXPECT_EQ(1u, copyMap.size()); EXPECT_EQ(this->getValue(), copyMap[this->getKey()]); // test self-assignment. copyMap = static_cast<TypeParam>(copyMap); // HLSL - silence warning EXPECT_EQ(1u, copyMap.size()); EXPECT_EQ(this->getValue(), copyMap[this->getKey()]); } // Test swap method TYPED_TEST(DenseMapTest, SwapTest) { this->Map[this->getKey()] = this->getValue(); TypeParam otherMap; this->Map.swap(otherMap); EXPECT_EQ(0u, this->Map.size()); EXPECT_TRUE(this->Map.empty()); EXPECT_EQ(1u, otherMap.size()); EXPECT_EQ(this->getValue(), otherMap[this->getKey()]); this->Map.swap(otherMap); EXPECT_EQ(0u, otherMap.size()); EXPECT_TRUE(otherMap.empty()); EXPECT_EQ(1u, this->Map.size()); EXPECT_EQ(this->getValue(), this->Map[this->getKey()]); // Make this more interesting by inserting 100 numbers into the map. for (int i = 0; i < 100; ++i) this->Map[this->getKey(i)] = this->getValue(i); this->Map.swap(otherMap); EXPECT_EQ(0u, this->Map.size()); EXPECT_TRUE(this->Map.empty()); EXPECT_EQ(100u, otherMap.size()); for (int i = 0; i < 100; ++i) EXPECT_EQ(this->getValue(i), otherMap[this->getKey(i)]); this->Map.swap(otherMap); EXPECT_EQ(0u, otherMap.size()); EXPECT_TRUE(otherMap.empty()); EXPECT_EQ(100u, this->Map.size()); for (int i = 0; i < 100; ++i) EXPECT_EQ(this->getValue(i), this->Map[this->getKey(i)]); } // A more complex iteration test TYPED_TEST(DenseMapTest, IterationTest) { bool visited[100]; std::map<typename TypeParam::key_type, unsigned> visitedIndex; // Insert 100 numbers into the map for (int i = 0; i < 100; ++i) { visited[i] = false; visitedIndex[this->getKey(i)] = i; this->Map[this->getKey(i)] = this->getValue(i); } // Iterate over all numbers and mark each one found. for (typename TypeParam::iterator it = this->Map.begin(); it != this->Map.end(); ++it) visited[visitedIndex[it->first]] = true; // Ensure every number was visited. for (int i = 0; i < 100; ++i) ASSERT_TRUE(visited[i]) << "Entry #" << i << " was never visited"; } // const_iterator test TYPED_TEST(DenseMapTest, ConstIteratorTest) { // Check conversion from iterator to const_iterator. typename TypeParam::iterator it = this->Map.begin(); typename TypeParam::const_iterator cit(it); EXPECT_TRUE(it == cit); // Check copying of const_iterators. typename TypeParam::const_iterator cit2(cit); EXPECT_TRUE(cit == cit2); } // Make sure DenseMap works with StringRef keys. TEST(DenseMapCustomTest, StringRefTest) { DenseMap<StringRef, int> M; M["a"] = 1; M["b"] = 2; M["c"] = 3; EXPECT_EQ(3u, M.size()); EXPECT_EQ(1, M.lookup("a")); EXPECT_EQ(2, M.lookup("b")); EXPECT_EQ(3, M.lookup("c")); EXPECT_EQ(0, M.lookup("q")); // Test the empty string, spelled various ways. EXPECT_EQ(0, M.lookup("")); EXPECT_EQ(0, M.lookup(StringRef())); EXPECT_EQ(0, M.lookup(StringRef("a", 0))); M[""] = 42; EXPECT_EQ(42, M.lookup("")); EXPECT_EQ(42, M.lookup(StringRef())); EXPECT_EQ(42, M.lookup(StringRef("a", 0))); } // Key traits that allows lookup with either an unsigned or char* key; // In the latter case, "a" == 0, "b" == 1 and so on. struct TestDenseMapInfo { static inline unsigned getEmptyKey() { return ~0; } static inline unsigned getTombstoneKey() { return ~0U - 1; } static unsigned getHashValue(const unsigned& Val) { return Val * 37U; } static unsigned getHashValue(const char* Val) { return (unsigned)(Val[0] - 'a') * 37U; } static bool isEqual(const unsigned& LHS, const unsigned& RHS) { return LHS == RHS; } static bool isEqual(const char* LHS, const unsigned& RHS) { return (unsigned)(LHS[0] - 'a') == RHS; } }; // find_as() tests TEST(DenseMapCustomTest, FindAsTest) { DenseMap<unsigned, unsigned, TestDenseMapInfo> map; map[0] = 1; map[1] = 2; map[2] = 3; // Size tests EXPECT_EQ(3u, map.size()); // Normal lookup tests EXPECT_EQ(1u, map.count(1)); EXPECT_EQ(1u, map.find(0)->second); EXPECT_EQ(2u, map.find(1)->second); EXPECT_EQ(3u, map.find(2)->second); EXPECT_TRUE(map.find(3) == map.end()); // find_as() tests EXPECT_EQ(1u, map.find_as("a")->second); EXPECT_EQ(2u, map.find_as("b")->second); EXPECT_EQ(3u, map.find_as("c")->second); EXPECT_TRUE(map.find_as("d") == map.end()); } struct ContiguousDenseMapInfo { static inline unsigned getEmptyKey() { return ~0; } static inline unsigned getTombstoneKey() { return ~0U - 1; } static unsigned getHashValue(const unsigned& Val) { return Val; } static bool isEqual(const unsigned& LHS, const unsigned& RHS) { return LHS == RHS; } }; // Test that filling a small dense map with exactly the number of elements in // the map grows to have enough space for an empty bucket. TEST(DenseMapCustomTest, SmallDenseMapGrowTest) { SmallDenseMap<unsigned, unsigned, 32, ContiguousDenseMapInfo> map; // Add some number of elements, then delete a few to leave us some tombstones. // If we just filled the map with 32 elements we'd grow because of not enough // tombstones which masks the issue here. for (unsigned i = 0; i < 20; ++i) map[i] = i + 1; for (unsigned i = 0; i < 10; ++i) map.erase(i); for (unsigned i = 20; i < 32; ++i) map[i] = i + 1; // Size tests EXPECT_EQ(22u, map.size()); // Try to find an element which doesn't exist. There was a bug in // SmallDenseMap which led to a map with num elements == small capacity not // having an empty bucket any more. Finding an element not in the map would // therefore never terminate. EXPECT_TRUE(map.find(32) == map.end()); } TEST(DenseMapCustomTest, TryEmplaceTest) { DenseMap<int, std::unique_ptr<int>> Map; std::unique_ptr<int> P(new int(2)); auto Try1 = Map.try_emplace(0, new int(1)); EXPECT_TRUE(Try1.second); auto Try2 = Map.try_emplace(0, std::move(P)); EXPECT_FALSE(Try2.second); EXPECT_EQ(Try1.first, Try2.first); EXPECT_NE(nullptr, P); } }
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/ADT/StringRefTest.cpp
//===- llvm/unittest/ADT/StringRefTest.cpp - StringRef unit tests ---------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/ADT/StringRef.h" #include "llvm/ADT/Hashing.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringExtras.h" #include "llvm/Support/Allocator.h" #include "llvm/Support/raw_ostream.h" #include "gtest/gtest.h" using namespace llvm; namespace llvm { std::ostream &operator<<(std::ostream &OS, const StringRef &S) { OS << S.str(); return OS; } std::ostream &operator<<(std::ostream &OS, const std::pair<StringRef, StringRef> &P) { OS << "(" << P.first << ", " << P.second << ")"; return OS; } } namespace { TEST(StringRefTest, Construction) { EXPECT_EQ("", StringRef()); EXPECT_EQ("hello", StringRef("hello")); EXPECT_EQ("hello", StringRef("hello world", 5)); EXPECT_EQ("hello", StringRef(std::string("hello"))); } TEST(StringRefTest, Iteration) { StringRef S("hello"); const char *p = "hello"; for (const char *it = S.begin(), *ie = S.end(); it != ie; ++it, ++p) EXPECT_EQ(*it, *p); } TEST(StringRefTest, StringOps) { const char *p = "hello"; EXPECT_EQ(p, StringRef(p, 0).data()); EXPECT_TRUE(StringRef().empty()); EXPECT_EQ((size_t) 5, StringRef("hello").size()); EXPECT_EQ(-1, StringRef("aab").compare("aad")); EXPECT_EQ( 0, StringRef("aab").compare("aab")); EXPECT_EQ( 1, StringRef("aab").compare("aaa")); EXPECT_EQ(-1, StringRef("aab").compare("aabb")); EXPECT_EQ( 1, StringRef("aab").compare("aa")); EXPECT_EQ( 1, StringRef("\xFF").compare("\1")); EXPECT_EQ(-1, StringRef("AaB").compare_lower("aAd")); EXPECT_EQ( 0, StringRef("AaB").compare_lower("aab")); EXPECT_EQ( 1, StringRef("AaB").compare_lower("AAA")); EXPECT_EQ(-1, StringRef("AaB").compare_lower("aaBb")); EXPECT_EQ(-1, StringRef("AaB").compare_lower("bb")); EXPECT_EQ( 1, StringRef("aaBb").compare_lower("AaB")); EXPECT_EQ( 1, StringRef("bb").compare_lower("AaB")); EXPECT_EQ( 1, StringRef("AaB").compare_lower("aA")); EXPECT_EQ( 1, StringRef("\xFF").compare_lower("\1")); EXPECT_EQ(-1, StringRef("aab").compare_numeric("aad")); EXPECT_EQ( 0, StringRef("aab").compare_numeric("aab")); EXPECT_EQ( 1, StringRef("aab").compare_numeric("aaa")); EXPECT_EQ(-1, StringRef("aab").compare_numeric("aabb")); EXPECT_EQ( 1, StringRef("aab").compare_numeric("aa")); EXPECT_EQ(-1, StringRef("1").compare_numeric("10")); EXPECT_EQ( 0, StringRef("10").compare_numeric("10")); EXPECT_EQ( 0, StringRef("10a").compare_numeric("10a")); EXPECT_EQ( 1, StringRef("2").compare_numeric("1")); EXPECT_EQ( 0, StringRef("llvm_v1i64_ty").compare_numeric("llvm_v1i64_ty")); EXPECT_EQ( 1, StringRef("\xFF").compare_numeric("\1")); EXPECT_EQ( 1, StringRef("V16").compare_numeric("V1_q0")); EXPECT_EQ(-1, StringRef("V1_q0").compare_numeric("V16")); EXPECT_EQ(-1, StringRef("V8_q0").compare_numeric("V16")); EXPECT_EQ( 1, StringRef("V16").compare_numeric("V8_q0")); EXPECT_EQ(-1, StringRef("V1_q0").compare_numeric("V8_q0")); EXPECT_EQ( 1, StringRef("V8_q0").compare_numeric("V1_q0")); } TEST(StringRefTest, Operators) { EXPECT_EQ("", StringRef()); EXPECT_TRUE(StringRef("aab") < StringRef("aad")); EXPECT_FALSE(StringRef("aab") < StringRef("aab")); EXPECT_TRUE(StringRef("aab") <= StringRef("aab")); EXPECT_FALSE(StringRef("aab") <= StringRef("aaa")); EXPECT_TRUE(StringRef("aad") > StringRef("aab")); EXPECT_FALSE(StringRef("aab") > StringRef("aab")); EXPECT_TRUE(StringRef("aab") >= StringRef("aab")); EXPECT_FALSE(StringRef("aaa") >= StringRef("aab")); EXPECT_EQ(StringRef("aab"), StringRef("aab")); EXPECT_FALSE(StringRef("aab") == StringRef("aac")); EXPECT_FALSE(StringRef("aab") != StringRef("aab")); EXPECT_TRUE(StringRef("aab") != StringRef("aac")); EXPECT_EQ('a', StringRef("aab")[1]); } TEST(StringRefTest, Substr) { StringRef Str("hello"); EXPECT_EQ("lo", Str.substr(3)); EXPECT_EQ("", Str.substr(100)); EXPECT_EQ("hello", Str.substr(0, 100)); EXPECT_EQ("o", Str.substr(4, 10)); } TEST(StringRefTest, Slice) { StringRef Str("hello"); EXPECT_EQ("l", Str.slice(2, 3)); EXPECT_EQ("ell", Str.slice(1, 4)); EXPECT_EQ("llo", Str.slice(2, 100)); EXPECT_EQ("", Str.slice(2, 1)); EXPECT_EQ("", Str.slice(10, 20)); } TEST(StringRefTest, Split) { StringRef Str("hello"); EXPECT_EQ(std::make_pair(StringRef("hello"), StringRef("")), Str.split('X')); EXPECT_EQ(std::make_pair(StringRef("h"), StringRef("llo")), Str.split('e')); EXPECT_EQ(std::make_pair(StringRef(""), StringRef("ello")), Str.split('h')); EXPECT_EQ(std::make_pair(StringRef("he"), StringRef("lo")), Str.split('l')); EXPECT_EQ(std::make_pair(StringRef("hell"), StringRef("")), Str.split('o')); EXPECT_EQ(std::make_pair(StringRef("hello"), StringRef("")), Str.rsplit('X')); EXPECT_EQ(std::make_pair(StringRef("h"), StringRef("llo")), Str.rsplit('e')); EXPECT_EQ(std::make_pair(StringRef(""), StringRef("ello")), Str.rsplit('h')); EXPECT_EQ(std::make_pair(StringRef("hel"), StringRef("o")), Str.rsplit('l')); EXPECT_EQ(std::make_pair(StringRef("hell"), StringRef("")), Str.rsplit('o')); } TEST(StringRefTest, Split2) { SmallVector<StringRef, 5> parts; SmallVector<StringRef, 5> expected; expected.push_back("ab"); expected.push_back("c"); StringRef(",ab,,c,").split(parts, ",", -1, false); EXPECT_TRUE(parts == expected); expected.clear(); parts.clear(); expected.push_back(""); expected.push_back("ab"); expected.push_back(""); expected.push_back("c"); expected.push_back(""); StringRef(",ab,,c,").split(parts, ",", -1, true); EXPECT_TRUE(parts == expected); expected.clear(); parts.clear(); expected.push_back(""); StringRef("").split(parts, ",", -1, true); EXPECT_TRUE(parts == expected); expected.clear(); parts.clear(); StringRef("").split(parts, ",", -1, false); EXPECT_TRUE(parts == expected); expected.clear(); parts.clear(); StringRef(",").split(parts, ",", -1, false); EXPECT_TRUE(parts == expected); expected.clear(); parts.clear(); expected.push_back(""); expected.push_back(""); StringRef(",").split(parts, ",", -1, true); EXPECT_TRUE(parts == expected); expected.clear(); parts.clear(); expected.push_back("a"); expected.push_back("b"); StringRef("a,b").split(parts, ",", -1, true); EXPECT_TRUE(parts == expected); // Test MaxSplit expected.clear(); parts.clear(); expected.push_back("a,,b,c"); StringRef("a,,b,c").split(parts, ",", 0, true); EXPECT_TRUE(parts == expected); expected.clear(); parts.clear(); expected.push_back("a,,b,c"); StringRef("a,,b,c").split(parts, ",", 0, false); EXPECT_TRUE(parts == expected); expected.clear(); parts.clear(); expected.push_back("a"); expected.push_back(",b,c"); StringRef("a,,b,c").split(parts, ",", 1, true); EXPECT_TRUE(parts == expected); expected.clear(); parts.clear(); expected.push_back("a"); expected.push_back(",b,c"); StringRef("a,,b,c").split(parts, ",", 1, false); EXPECT_TRUE(parts == expected); expected.clear(); parts.clear(); expected.push_back("a"); expected.push_back(""); expected.push_back("b,c"); StringRef("a,,b,c").split(parts, ",", 2, true); EXPECT_TRUE(parts == expected); expected.clear(); parts.clear(); expected.push_back("a"); expected.push_back("b,c"); StringRef("a,,b,c").split(parts, ",", 2, false); EXPECT_TRUE(parts == expected); expected.clear(); parts.clear(); expected.push_back("a"); expected.push_back(""); expected.push_back("b"); expected.push_back("c"); StringRef("a,,b,c").split(parts, ",", 3, true); EXPECT_TRUE(parts == expected); expected.clear(); parts.clear(); expected.push_back("a"); expected.push_back("b"); expected.push_back("c"); StringRef("a,,b,c").split(parts, ",", 3, false); EXPECT_TRUE(parts == expected); } TEST(StringRefTest, Trim) { StringRef Str0("hello"); StringRef Str1(" hello "); StringRef Str2(" hello "); EXPECT_EQ(StringRef("hello"), Str0.rtrim()); EXPECT_EQ(StringRef(" hello"), Str1.rtrim()); EXPECT_EQ(StringRef(" hello"), Str2.rtrim()); EXPECT_EQ(StringRef("hello"), Str0.ltrim()); EXPECT_EQ(StringRef("hello "), Str1.ltrim()); EXPECT_EQ(StringRef("hello "), Str2.ltrim()); EXPECT_EQ(StringRef("hello"), Str0.trim()); EXPECT_EQ(StringRef("hello"), Str1.trim()); EXPECT_EQ(StringRef("hello"), Str2.trim()); EXPECT_EQ(StringRef("ello"), Str0.trim("hhhhhhhhhhh")); EXPECT_EQ(StringRef(""), StringRef("").trim()); EXPECT_EQ(StringRef(""), StringRef(" ").trim()); EXPECT_EQ(StringRef("\0", 1), StringRef(" \0 ", 3).trim()); EXPECT_EQ(StringRef("\0\0", 2), StringRef("\0\0", 2).trim()); EXPECT_EQ(StringRef("x"), StringRef("\0\0x\0\0", 5).trim(StringRef("\0", 1))); } TEST(StringRefTest, StartsWith) { StringRef Str("hello"); EXPECT_TRUE(Str.startswith("")); EXPECT_TRUE(Str.startswith("he")); EXPECT_FALSE(Str.startswith("helloworld")); EXPECT_FALSE(Str.startswith("hi")); } TEST(StringRefTest, StartsWithLower) { StringRef Str("heLLo"); EXPECT_TRUE(Str.startswith_lower("")); EXPECT_TRUE(Str.startswith_lower("he")); EXPECT_TRUE(Str.startswith_lower("hell")); EXPECT_TRUE(Str.startswith_lower("HELlo")); EXPECT_FALSE(Str.startswith_lower("helloworld")); EXPECT_FALSE(Str.startswith_lower("hi")); } TEST(StringRefTest, EndsWith) { StringRef Str("hello"); EXPECT_TRUE(Str.endswith("")); EXPECT_TRUE(Str.endswith("lo")); EXPECT_FALSE(Str.endswith("helloworld")); EXPECT_FALSE(Str.endswith("worldhello")); EXPECT_FALSE(Str.endswith("so")); } TEST(StringRefTest, EndsWithLower) { StringRef Str("heLLo"); EXPECT_TRUE(Str.endswith_lower("")); EXPECT_TRUE(Str.endswith_lower("lo")); EXPECT_TRUE(Str.endswith_lower("LO")); EXPECT_TRUE(Str.endswith_lower("ELlo")); EXPECT_FALSE(Str.endswith_lower("helloworld")); EXPECT_FALSE(Str.endswith_lower("hi")); } TEST(StringRefTest, Find) { StringRef Str("hello"); EXPECT_EQ(2U, Str.find('l')); EXPECT_EQ(StringRef::npos, Str.find('z')); EXPECT_EQ(StringRef::npos, Str.find("helloworld")); EXPECT_EQ(0U, Str.find("hello")); EXPECT_EQ(1U, Str.find("ello")); EXPECT_EQ(StringRef::npos, Str.find("zz")); EXPECT_EQ(2U, Str.find("ll", 2)); EXPECT_EQ(StringRef::npos, Str.find("ll", 3)); EXPECT_EQ(0U, Str.find("")); StringRef LongStr("hellx xello hell ello world foo bar hello"); EXPECT_EQ(36U, LongStr.find("hello")); EXPECT_EQ(28U, LongStr.find("foo")); EXPECT_EQ(12U, LongStr.find("hell", 2)); EXPECT_EQ(0U, LongStr.find("")); EXPECT_EQ(3U, Str.rfind('l')); EXPECT_EQ(StringRef::npos, Str.rfind('z')); EXPECT_EQ(StringRef::npos, Str.rfind("helloworld")); EXPECT_EQ(0U, Str.rfind("hello")); EXPECT_EQ(1U, Str.rfind("ello")); EXPECT_EQ(StringRef::npos, Str.rfind("zz")); EXPECT_EQ(2U, Str.find_first_of('l')); EXPECT_EQ(1U, Str.find_first_of("el")); EXPECT_EQ(StringRef::npos, Str.find_first_of("xyz")); EXPECT_EQ(1U, Str.find_first_not_of('h')); EXPECT_EQ(4U, Str.find_first_not_of("hel")); EXPECT_EQ(StringRef::npos, Str.find_first_not_of("hello")); EXPECT_EQ(3U, Str.find_last_not_of('o')); EXPECT_EQ(1U, Str.find_last_not_of("lo")); EXPECT_EQ(StringRef::npos, Str.find_last_not_of("helo")); } TEST(StringRefTest, Count) { StringRef Str("hello"); EXPECT_EQ(2U, Str.count('l')); EXPECT_EQ(1U, Str.count('o')); EXPECT_EQ(0U, Str.count('z')); EXPECT_EQ(0U, Str.count("helloworld")); EXPECT_EQ(1U, Str.count("hello")); EXPECT_EQ(1U, Str.count("ello")); EXPECT_EQ(0U, Str.count("zz")); } TEST(StringRefTest, EditDistance) { StringRef Str("hello"); EXPECT_EQ(2U, Str.edit_distance("hill")); } TEST(StringRefTest, Misc) { std::string Storage; raw_string_ostream OS(Storage); OS << StringRef("hello"); EXPECT_EQ("hello", OS.str()); } TEST(StringRefTest, Hashing) { EXPECT_EQ(hash_value(std::string()), hash_value(StringRef())); EXPECT_EQ(hash_value(std::string()), hash_value(StringRef(""))); std::string S = "hello world"; hash_code H = hash_value(S); EXPECT_EQ(H, hash_value(StringRef("hello world"))); EXPECT_EQ(H, hash_value(StringRef(S))); EXPECT_NE(H, hash_value(StringRef("hello worl"))); EXPECT_EQ(hash_value(std::string("hello worl")), hash_value(StringRef("hello worl"))); EXPECT_NE(H, hash_value(StringRef("hello world "))); EXPECT_EQ(hash_value(std::string("hello world ")), hash_value(StringRef("hello world "))); EXPECT_EQ(H, hash_value(StringRef("hello world\0"))); EXPECT_NE(hash_value(std::string("ello worl")), hash_value(StringRef("hello world").slice(1, -1))); } struct UnsignedPair { const char *Str; uint64_t Expected; } Unsigned[] = { {"0", 0} , {"255", 255} , {"256", 256} , {"65535", 65535} , {"65536", 65536} , {"4294967295", 4294967295ULL} , {"4294967296", 4294967296ULL} , {"18446744073709551615", 18446744073709551615ULL} , {"042", 34} , {"0x42", 66} , {"0b101010", 42} }; struct SignedPair { const char *Str; int64_t Expected; } Signed[] = { {"0", 0} , {"-0", 0} , {"127", 127} , {"128", 128} , {"-128", -128} , {"-129", -129} , {"32767", 32767} , {"32768", 32768} , {"-32768", -32768} , {"-32769", -32769} , {"2147483647", 2147483647LL} , {"2147483648", 2147483648LL} , {"-2147483648", -2147483648LL} , {"-2147483649", -2147483649LL} , {"-9223372036854775808", -(9223372036854775807LL) - 1} , {"042", 34} , {"0x42", 66} , {"0b101010", 42} , {"-042", -34} , {"-0x42", -66} , {"-0b101010", -42} }; TEST(StringRefTest, getAsInteger) { uint8_t U8; uint16_t U16; uint32_t U32; uint64_t U64; for (size_t i = 0; i < array_lengthof(Unsigned); ++i) { bool U8Success = StringRef(Unsigned[i].Str).getAsInteger(0, U8); if (static_cast<uint8_t>(Unsigned[i].Expected) == Unsigned[i].Expected) { ASSERT_FALSE(U8Success); EXPECT_EQ(U8, Unsigned[i].Expected); } else { ASSERT_TRUE(U8Success); } bool U16Success = StringRef(Unsigned[i].Str).getAsInteger(0, U16); if (static_cast<uint16_t>(Unsigned[i].Expected) == Unsigned[i].Expected) { ASSERT_FALSE(U16Success); EXPECT_EQ(U16, Unsigned[i].Expected); } else { ASSERT_TRUE(U16Success); } bool U32Success = StringRef(Unsigned[i].Str).getAsInteger(0, U32); if (static_cast<uint32_t>(Unsigned[i].Expected) == Unsigned[i].Expected) { ASSERT_FALSE(U32Success); EXPECT_EQ(U32, Unsigned[i].Expected); } else { ASSERT_TRUE(U32Success); } bool U64Success = StringRef(Unsigned[i].Str).getAsInteger(0, U64); if (static_cast<uint64_t>(Unsigned[i].Expected) == Unsigned[i].Expected) { ASSERT_FALSE(U64Success); EXPECT_EQ(U64, Unsigned[i].Expected); } else { ASSERT_TRUE(U64Success); } } int8_t S8; int16_t S16; int32_t S32; int64_t S64; for (size_t i = 0; i < array_lengthof(Signed); ++i) { bool S8Success = StringRef(Signed[i].Str).getAsInteger(0, S8); if (static_cast<int8_t>(Signed[i].Expected) == Signed[i].Expected) { ASSERT_FALSE(S8Success); EXPECT_EQ(S8, Signed[i].Expected); } else { ASSERT_TRUE(S8Success); } bool S16Success = StringRef(Signed[i].Str).getAsInteger(0, S16); if (static_cast<int16_t>(Signed[i].Expected) == Signed[i].Expected) { ASSERT_FALSE(S16Success); EXPECT_EQ(S16, Signed[i].Expected); } else { ASSERT_TRUE(S16Success); } bool S32Success = StringRef(Signed[i].Str).getAsInteger(0, S32); if (static_cast<int32_t>(Signed[i].Expected) == Signed[i].Expected) { ASSERT_FALSE(S32Success); EXPECT_EQ(S32, Signed[i].Expected); } else { ASSERT_TRUE(S32Success); } bool S64Success = StringRef(Signed[i].Str).getAsInteger(0, S64); if (static_cast<int64_t>(Signed[i].Expected) == Signed[i].Expected) { ASSERT_FALSE(S64Success); EXPECT_EQ(S64, Signed[i].Expected); } else { ASSERT_TRUE(S64Success); } } } static const char* BadStrings[] = { "18446744073709551617" // value just over max , "123456789012345678901" // value way too large , "4t23v" // illegal decimal characters , "0x123W56" // illegal hex characters , "0b2" // illegal bin characters , "08" // illegal oct characters , "0o8" // illegal oct characters , "-123" // negative unsigned value }; TEST(StringRefTest, getAsUnsignedIntegerBadStrings) { unsigned long long U64; for (size_t i = 0; i < array_lengthof(BadStrings); ++i) { bool IsBadNumber = StringRef(BadStrings[i]).getAsInteger(0, U64); ASSERT_TRUE(IsBadNumber); } } static const char *join_input[] = { "a", "b", "c" }; static const char join_result1[] = "a"; static const char join_result2[] = "a:b:c"; static const char join_result3[] = "a::b::c"; TEST(StringRefTest, joinStrings) { std::vector<StringRef> v1; std::vector<std::string> v2; for (size_t i = 0; i < array_lengthof(join_input); ++i) { v1.push_back(join_input[i]); v2.push_back(join_input[i]); } bool v1_join1 = join(v1.begin(), v1.begin() + 1, ":") == join_result1; EXPECT_TRUE(v1_join1); bool v1_join2 = join(v1.begin(), v1.end(), ":") == join_result2; EXPECT_TRUE(v1_join2); bool v1_join3 = join(v1.begin(), v1.end(), "::") == join_result3; EXPECT_TRUE(v1_join3); bool v2_join1 = join(v2.begin(), v2.begin() + 1, ":") == join_result1; EXPECT_TRUE(v2_join1); bool v2_join2 = join(v2.begin(), v2.end(), ":") == join_result2; EXPECT_TRUE(v2_join2); bool v2_join3 = join(v2.begin(), v2.end(), "::") == join_result3; EXPECT_TRUE(v2_join3); } TEST(StringRefTest, AllocatorCopy) { BumpPtrAllocator Alloc; StringRef Str1 = "hello"; StringRef Str2 = "bye"; StringRef Str1c = Str1.copy(Alloc); StringRef Str2c = Str2.copy(Alloc); EXPECT_TRUE(Str1.equals(Str1c)); EXPECT_NE(Str1.data(), Str1c.data()); EXPECT_TRUE(Str2.equals(Str2c)); EXPECT_NE(Str2.data(), Str2c.data()); } } // end anonymous namespace
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/ADT/ImmutableSetTest.cpp
//===----------- ImmutableSetTest.cpp - ImmutableSet unit tests ------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "gtest/gtest.h" #include "llvm/ADT/ImmutableSet.h" using namespace llvm; namespace { class ImmutableSetTest : public testing::Test { protected: // for callback tests static char buffer[10]; struct MyIter { int counter; char *ptr; MyIter() : counter(0), ptr(buffer) { for (unsigned i=0; i<sizeof(buffer);++i) buffer[i]='\0'; } void operator()(char c) { *ptr++ = c; ++counter; } }; }; char ImmutableSetTest::buffer[10]; TEST_F(ImmutableSetTest, EmptyIntSetTest) { ImmutableSet<int>::Factory f; EXPECT_TRUE(f.getEmptySet() == f.getEmptySet()); EXPECT_FALSE(f.getEmptySet() != f.getEmptySet()); EXPECT_TRUE(f.getEmptySet().isEmpty()); ImmutableSet<int> S = f.getEmptySet(); EXPECT_EQ(0u, S.getHeight()); EXPECT_TRUE(S.begin() == S.end()); EXPECT_FALSE(S.begin() != S.end()); } TEST_F(ImmutableSetTest, OneElemIntSetTest) { ImmutableSet<int>::Factory f; ImmutableSet<int> S = f.getEmptySet(); ImmutableSet<int> S2 = f.add(S, 3); EXPECT_TRUE(S.isEmpty()); EXPECT_FALSE(S2.isEmpty()); EXPECT_FALSE(S == S2); EXPECT_TRUE(S != S2); EXPECT_FALSE(S.contains(3)); EXPECT_TRUE(S2.contains(3)); EXPECT_FALSE(S2.begin() == S2.end()); EXPECT_TRUE(S2.begin() != S2.end()); ImmutableSet<int> S3 = f.add(S, 2); EXPECT_TRUE(S.isEmpty()); EXPECT_FALSE(S3.isEmpty()); EXPECT_FALSE(S == S3); EXPECT_TRUE(S != S3); EXPECT_FALSE(S.contains(2)); EXPECT_TRUE(S3.contains(2)); EXPECT_FALSE(S2 == S3); EXPECT_TRUE(S2 != S3); EXPECT_FALSE(S2.contains(2)); EXPECT_FALSE(S3.contains(3)); } TEST_F(ImmutableSetTest, MultiElemIntSetTest) { ImmutableSet<int>::Factory f; ImmutableSet<int> S = f.getEmptySet(); ImmutableSet<int> S2 = f.add(f.add(f.add(S, 3), 4), 5); ImmutableSet<int> S3 = f.add(f.add(f.add(S2, 9), 20), 43); ImmutableSet<int> S4 = f.add(S2, 9); EXPECT_TRUE(S.isEmpty()); EXPECT_FALSE(S2.isEmpty()); EXPECT_FALSE(S3.isEmpty()); EXPECT_FALSE(S4.isEmpty()); EXPECT_FALSE(S.contains(3)); EXPECT_FALSE(S.contains(9)); EXPECT_TRUE(S2.contains(3)); EXPECT_TRUE(S2.contains(4)); EXPECT_TRUE(S2.contains(5)); EXPECT_FALSE(S2.contains(9)); EXPECT_FALSE(S2.contains(0)); EXPECT_TRUE(S3.contains(43)); EXPECT_TRUE(S3.contains(20)); EXPECT_TRUE(S3.contains(9)); EXPECT_TRUE(S3.contains(3)); EXPECT_TRUE(S3.contains(4)); EXPECT_TRUE(S3.contains(5)); EXPECT_FALSE(S3.contains(0)); EXPECT_TRUE(S4.contains(9)); EXPECT_TRUE(S4.contains(3)); EXPECT_TRUE(S4.contains(4)); EXPECT_TRUE(S4.contains(5)); EXPECT_FALSE(S4.contains(20)); EXPECT_FALSE(S4.contains(43)); } TEST_F(ImmutableSetTest, RemoveIntSetTest) { ImmutableSet<int>::Factory f; ImmutableSet<int> S = f.getEmptySet(); ImmutableSet<int> S2 = f.add(f.add(S, 4), 5); ImmutableSet<int> S3 = f.add(S2, 3); ImmutableSet<int> S4 = f.remove(S3, 3); EXPECT_TRUE(S3.contains(3)); EXPECT_FALSE(S2.contains(3)); EXPECT_FALSE(S4.contains(3)); EXPECT_TRUE(S2 == S4); EXPECT_TRUE(S3 != S2); EXPECT_TRUE(S3 != S4); EXPECT_TRUE(S3.contains(4)); EXPECT_TRUE(S3.contains(5)); EXPECT_TRUE(S4.contains(4)); EXPECT_TRUE(S4.contains(5)); } TEST_F(ImmutableSetTest, CallbackCharSetTest) { ImmutableSet<char>::Factory f; ImmutableSet<char> S = f.getEmptySet(); ImmutableSet<char> S2 = f.add(f.add(f.add(S, 'a'), 'e'), 'i'); ImmutableSet<char> S3 = f.add(f.add(S2, 'o'), 'u'); S3.foreach<MyIter>(); ASSERT_STREQ("aeiou", buffer); } TEST_F(ImmutableSetTest, Callback2CharSetTest) { ImmutableSet<char>::Factory f; ImmutableSet<char> S = f.getEmptySet(); ImmutableSet<char> S2 = f.add(f.add(f.add(S, 'b'), 'c'), 'd'); ImmutableSet<char> S3 = f.add(f.add(f.add(S2, 'f'), 'g'), 'h'); MyIter obj; S3.foreach<MyIter>(obj); ASSERT_STREQ("bcdfgh", buffer); ASSERT_EQ(6, obj.counter); MyIter obj2; S2.foreach<MyIter>(obj2); ASSERT_STREQ("bcd", buffer); ASSERT_EQ(3, obj2.counter); MyIter obj3; S.foreach<MyIter>(obj); ASSERT_STREQ("", buffer); ASSERT_EQ(0, obj3.counter); } TEST_F(ImmutableSetTest, IterLongSetTest) { ImmutableSet<long>::Factory f; ImmutableSet<long> S = f.getEmptySet(); ImmutableSet<long> S2 = f.add(f.add(f.add(S, 0), 1), 2); ImmutableSet<long> S3 = f.add(f.add(f.add(S2, 3), 4), 5); int i = 0; for (ImmutableSet<long>::iterator I = S.begin(), E = S.end(); I != E; ++I) { ASSERT_EQ(i++, *I); } ASSERT_EQ(0, i); i = 0; for (ImmutableSet<long>::iterator I = S2.begin(), E = S2.end(); I != E; ++I) { ASSERT_EQ(i++, *I); } ASSERT_EQ(3, i); i = 0; for (ImmutableSet<long>::iterator I = S3.begin(), E = S3.end(); I != E; I++) { ASSERT_EQ(i++, *I); } ASSERT_EQ(6, i); } }
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/ADT/MapVectorTest.cpp
//===- unittest/ADT/MapVectorTest.cpp - MapVector unit tests ----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "gtest/gtest.h" #include "llvm/ADT/MapVector.h" #include "llvm/ADT/iterator_range.h" #include <utility> using namespace llvm; TEST(MapVectorTest, swap) { MapVector<int, int> MV1, MV2; std::pair<MapVector<int, int>::iterator, bool> R; R = MV1.insert(std::make_pair(1, 2)); ASSERT_EQ(R.first, MV1.begin()); EXPECT_EQ(R.first->first, 1); EXPECT_EQ(R.first->second, 2); EXPECT_TRUE(R.second); EXPECT_FALSE(MV1.empty()); EXPECT_TRUE(MV2.empty()); MV2.swap(MV1); EXPECT_TRUE(MV1.empty()); EXPECT_FALSE(MV2.empty()); auto I = MV1.find(1); ASSERT_EQ(MV1.end(), I); I = MV2.find(1); ASSERT_EQ(I, MV2.begin()); EXPECT_EQ(I->first, 1); EXPECT_EQ(I->second, 2); } TEST(MapVectorTest, insert_pop) { MapVector<int, int> MV; std::pair<MapVector<int, int>::iterator, bool> R; R = MV.insert(std::make_pair(1, 2)); ASSERT_EQ(R.first, MV.begin()); EXPECT_EQ(R.first->first, 1); EXPECT_EQ(R.first->second, 2); EXPECT_TRUE(R.second); R = MV.insert(std::make_pair(1, 3)); ASSERT_EQ(R.first, MV.begin()); EXPECT_EQ(R.first->first, 1); EXPECT_EQ(R.first->second, 2); EXPECT_FALSE(R.second); R = MV.insert(std::make_pair(4, 5)); ASSERT_NE(R.first, MV.end()); EXPECT_EQ(R.first->first, 4); EXPECT_EQ(R.first->second, 5); EXPECT_TRUE(R.second); EXPECT_EQ(MV.size(), 2u); EXPECT_EQ(MV[1], 2); EXPECT_EQ(MV[4], 5); MV.pop_back(); EXPECT_EQ(MV.size(), 1u); EXPECT_EQ(MV[1], 2); R = MV.insert(std::make_pair(4, 7)); ASSERT_NE(R.first, MV.end()); EXPECT_EQ(R.first->first, 4); EXPECT_EQ(R.first->second, 7); EXPECT_TRUE(R.second); EXPECT_EQ(MV.size(), 2u); EXPECT_EQ(MV[1], 2); EXPECT_EQ(MV[4], 7); } TEST(MapVectorTest, erase) { MapVector<int, int> MV; MV.insert(std::make_pair(1, 2)); MV.insert(std::make_pair(3, 4)); MV.insert(std::make_pair(5, 6)); ASSERT_EQ(MV.size(), 3u); MV.erase(MV.find(1)); ASSERT_EQ(MV.size(), 2u); ASSERT_EQ(MV.find(1), MV.end()); ASSERT_EQ(MV[3], 4); ASSERT_EQ(MV[5], 6); ASSERT_EQ(MV.erase(3), 1u); ASSERT_EQ(MV.size(), 1u); ASSERT_EQ(MV.find(3), MV.end()); ASSERT_EQ(MV[5], 6); ASSERT_EQ(MV.erase(79), 0u); ASSERT_EQ(MV.size(), 1u); } TEST(MapVectorTest, remove_if) { MapVector<int, int> MV; MV.insert(std::make_pair(1, 11)); MV.insert(std::make_pair(2, 12)); MV.insert(std::make_pair(3, 13)); MV.insert(std::make_pair(4, 14)); MV.insert(std::make_pair(5, 15)); MV.insert(std::make_pair(6, 16)); ASSERT_EQ(MV.size(), 6u); MV.remove_if([](const std::pair<int, int> &Val) { return Val.second % 2; }); ASSERT_EQ(MV.size(), 3u); ASSERT_EQ(MV.find(1), MV.end()); ASSERT_EQ(MV.find(3), MV.end()); ASSERT_EQ(MV.find(5), MV.end()); ASSERT_EQ(MV[2], 12); ASSERT_EQ(MV[4], 14); ASSERT_EQ(MV[6], 16); } TEST(MapVectorTest, iteration_test) { MapVector<int, int> MV; MV.insert(std::make_pair(1, 11)); MV.insert(std::make_pair(2, 12)); MV.insert(std::make_pair(3, 13)); MV.insert(std::make_pair(4, 14)); MV.insert(std::make_pair(5, 15)); MV.insert(std::make_pair(6, 16)); ASSERT_EQ(MV.size(), 6u); int count = 1; for (auto P : make_range(MV.begin(), MV.end())) { ASSERT_EQ(P.first, count); count++; } count = 6; for (auto P : make_range(MV.rbegin(), MV.rend())) { ASSERT_EQ(P.first, count); count--; } } TEST(SmallMapVectorSmallTest, insert_pop) { SmallMapVector<int, int, 32> MV; std::pair<SmallMapVector<int, int, 32>::iterator, bool> R; R = MV.insert(std::make_pair(1, 2)); ASSERT_EQ(R.first, MV.begin()); EXPECT_EQ(R.first->first, 1); EXPECT_EQ(R.first->second, 2); EXPECT_TRUE(R.second); R = MV.insert(std::make_pair(1, 3)); ASSERT_EQ(R.first, MV.begin()); EXPECT_EQ(R.first->first, 1); EXPECT_EQ(R.first->second, 2); EXPECT_FALSE(R.second); R = MV.insert(std::make_pair(4, 5)); ASSERT_NE(R.first, MV.end()); EXPECT_EQ(R.first->first, 4); EXPECT_EQ(R.first->second, 5); EXPECT_TRUE(R.second); EXPECT_EQ(MV.size(), 2u); EXPECT_EQ(MV[1], 2); EXPECT_EQ(MV[4], 5); MV.pop_back(); EXPECT_EQ(MV.size(), 1u); EXPECT_EQ(MV[1], 2); R = MV.insert(std::make_pair(4, 7)); ASSERT_NE(R.first, MV.end()); EXPECT_EQ(R.first->first, 4); EXPECT_EQ(R.first->second, 7); EXPECT_TRUE(R.second); EXPECT_EQ(MV.size(), 2u); EXPECT_EQ(MV[1], 2); EXPECT_EQ(MV[4], 7); } TEST(SmallMapVectorSmallTest, erase) { SmallMapVector<int, int, 32> MV; MV.insert(std::make_pair(1, 2)); MV.insert(std::make_pair(3, 4)); MV.insert(std::make_pair(5, 6)); ASSERT_EQ(MV.size(), 3u); MV.erase(MV.find(1)); ASSERT_EQ(MV.size(), 2u); ASSERT_EQ(MV.find(1), MV.end()); ASSERT_EQ(MV[3], 4); ASSERT_EQ(MV[5], 6); ASSERT_EQ(MV.erase(3), 1u); ASSERT_EQ(MV.size(), 1u); ASSERT_EQ(MV.find(3), MV.end()); ASSERT_EQ(MV[5], 6); ASSERT_EQ(MV.erase(79), 0u); ASSERT_EQ(MV.size(), 1u); } TEST(SmallMapVectorSmallTest, remove_if) { SmallMapVector<int, int, 32> MV; MV.insert(std::make_pair(1, 11)); MV.insert(std::make_pair(2, 12)); MV.insert(std::make_pair(3, 13)); MV.insert(std::make_pair(4, 14)); MV.insert(std::make_pair(5, 15)); MV.insert(std::make_pair(6, 16)); ASSERT_EQ(MV.size(), 6u); MV.remove_if([](const std::pair<int, int> &Val) { return Val.second % 2; }); ASSERT_EQ(MV.size(), 3u); ASSERT_EQ(MV.find(1), MV.end()); ASSERT_EQ(MV.find(3), MV.end()); ASSERT_EQ(MV.find(5), MV.end()); ASSERT_EQ(MV[2], 12); ASSERT_EQ(MV[4], 14); ASSERT_EQ(MV[6], 16); } TEST(SmallMapVectorSmallTest, iteration_test) { SmallMapVector<int, int, 32> MV; MV.insert(std::make_pair(1, 11)); MV.insert(std::make_pair(2, 12)); MV.insert(std::make_pair(3, 13)); MV.insert(std::make_pair(4, 14)); MV.insert(std::make_pair(5, 15)); MV.insert(std::make_pair(6, 16)); ASSERT_EQ(MV.size(), 6u); int count = 1; for (auto P : make_range(MV.begin(), MV.end())) { ASSERT_EQ(P.first, count); count++; } count = 6; for (auto P : make_range(MV.rbegin(), MV.rend())) { ASSERT_EQ(P.first, count); count--; } } TEST(SmallMapVectorLargeTest, insert_pop) { SmallMapVector<int, int, 1> MV; std::pair<SmallMapVector<int, int, 1>::iterator, bool> R; R = MV.insert(std::make_pair(1, 2)); ASSERT_EQ(R.first, MV.begin()); EXPECT_EQ(R.first->first, 1); EXPECT_EQ(R.first->second, 2); EXPECT_TRUE(R.second); R = MV.insert(std::make_pair(1, 3)); ASSERT_EQ(R.first, MV.begin()); EXPECT_EQ(R.first->first, 1); EXPECT_EQ(R.first->second, 2); EXPECT_FALSE(R.second); R = MV.insert(std::make_pair(4, 5)); ASSERT_NE(R.first, MV.end()); EXPECT_EQ(R.first->first, 4); EXPECT_EQ(R.first->second, 5); EXPECT_TRUE(R.second); EXPECT_EQ(MV.size(), 2u); EXPECT_EQ(MV[1], 2); EXPECT_EQ(MV[4], 5); MV.pop_back(); EXPECT_EQ(MV.size(), 1u); EXPECT_EQ(MV[1], 2); R = MV.insert(std::make_pair(4, 7)); ASSERT_NE(R.first, MV.end()); EXPECT_EQ(R.first->first, 4); EXPECT_EQ(R.first->second, 7); EXPECT_TRUE(R.second); EXPECT_EQ(MV.size(), 2u); EXPECT_EQ(MV[1], 2); EXPECT_EQ(MV[4], 7); } TEST(SmallMapVectorLargeTest, erase) { SmallMapVector<int, int, 1> MV; MV.insert(std::make_pair(1, 2)); MV.insert(std::make_pair(3, 4)); MV.insert(std::make_pair(5, 6)); ASSERT_EQ(MV.size(), 3u); MV.erase(MV.find(1)); ASSERT_EQ(MV.size(), 2u); ASSERT_EQ(MV.find(1), MV.end()); ASSERT_EQ(MV[3], 4); ASSERT_EQ(MV[5], 6); ASSERT_EQ(MV.erase(3), 1u); ASSERT_EQ(MV.size(), 1u); ASSERT_EQ(MV.find(3), MV.end()); ASSERT_EQ(MV[5], 6); ASSERT_EQ(MV.erase(79), 0u); ASSERT_EQ(MV.size(), 1u); } TEST(SmallMapVectorLargeTest, remove_if) { SmallMapVector<int, int, 1> MV; MV.insert(std::make_pair(1, 11)); MV.insert(std::make_pair(2, 12)); MV.insert(std::make_pair(3, 13)); MV.insert(std::make_pair(4, 14)); MV.insert(std::make_pair(5, 15)); MV.insert(std::make_pair(6, 16)); ASSERT_EQ(MV.size(), 6u); MV.remove_if([](const std::pair<int, int> &Val) { return Val.second % 2; }); ASSERT_EQ(MV.size(), 3u); ASSERT_EQ(MV.find(1), MV.end()); ASSERT_EQ(MV.find(3), MV.end()); ASSERT_EQ(MV.find(5), MV.end()); ASSERT_EQ(MV[2], 12); ASSERT_EQ(MV[4], 14); ASSERT_EQ(MV[6], 16); } TEST(SmallMapVectorLargeTest, iteration_test) { SmallMapVector<int, int, 1> MV; MV.insert(std::make_pair(1, 11)); MV.insert(std::make_pair(2, 12)); MV.insert(std::make_pair(3, 13)); MV.insert(std::make_pair(4, 14)); MV.insert(std::make_pair(5, 15)); MV.insert(std::make_pair(6, 16)); ASSERT_EQ(MV.size(), 6u); int count = 1; for (auto P : make_range(MV.begin(), MV.end())) { ASSERT_EQ(P.first, count); count++; } count = 6; for (auto P : make_range(MV.rbegin(), MV.rend())) { ASSERT_EQ(P.first, count); count--; } }
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/ADT/ArrayRefTest.cpp
//===- llvm/unittest/ADT/ArrayRefTest.cpp - ArrayRef unit tests -----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/ADT/ArrayRef.h" #include "llvm/Support/Allocator.h" #include "llvm/Support/raw_ostream.h" #include "gtest/gtest.h" #include <vector> using namespace llvm; // Check that the ArrayRef-of-pointer converting constructor only allows adding // cv qualifiers (not removing them, or otherwise changing the type) static_assert( std::is_convertible<ArrayRef<int *>, ArrayRef<const int *>>::value, "Adding const"); static_assert( std::is_convertible<ArrayRef<int *>, ArrayRef<volatile int *>>::value, "Adding volatile"); static_assert(!std::is_convertible<ArrayRef<int *>, ArrayRef<float *>>::value, "Changing pointer of one type to a pointer of another"); static_assert( !std::is_convertible<ArrayRef<const int *>, ArrayRef<int *>>::value, "Removing const"); static_assert( !std::is_convertible<ArrayRef<volatile int *>, ArrayRef<int *>>::value, "Removing volatile"); namespace llvm { TEST(ArrayRefTest, AllocatorCopy) { BumpPtrAllocator Alloc; static const uint16_t Words1[] = { 1, 4, 200, 37 }; ArrayRef<uint16_t> Array1 = makeArrayRef(Words1, 4); static const uint16_t Words2[] = { 11, 4003, 67, 64000, 13 }; ArrayRef<uint16_t> Array2 = makeArrayRef(Words2, 5); ArrayRef<uint16_t> Array1c = Array1.copy(Alloc); ArrayRef<uint16_t> Array2c = Array2.copy(Alloc); EXPECT_TRUE(Array1.equals(Array1c)); EXPECT_NE(Array1.data(), Array1c.data()); EXPECT_TRUE(Array2.equals(Array2c)); EXPECT_NE(Array2.data(), Array2c.data()); } TEST(ArrayRefTest, DropBack) { static const int TheNumbers[] = {4, 8, 15, 16, 23, 42}; ArrayRef<int> AR1(TheNumbers); ArrayRef<int> AR2(TheNumbers, AR1.size() - 1); EXPECT_TRUE(AR1.drop_back().equals(AR2)); } TEST(ArrayRefTest, Equals) { static const int A1[] = {1, 2, 3, 4, 5, 6, 7, 8}; ArrayRef<int> AR1(A1); EXPECT_TRUE(AR1.equals({1, 2, 3, 4, 5, 6, 7, 8})); EXPECT_FALSE(AR1.equals({8, 1, 2, 4, 5, 6, 6, 7})); EXPECT_FALSE(AR1.equals({2, 4, 5, 6, 6, 7, 8, 1})); EXPECT_FALSE(AR1.equals({0, 1, 2, 4, 5, 6, 6, 7})); EXPECT_FALSE(AR1.equals({1, 2, 42, 4, 5, 6, 7, 8})); EXPECT_FALSE(AR1.equals({42, 2, 3, 4, 5, 6, 7, 8})); EXPECT_FALSE(AR1.equals({1, 2, 3, 4, 5, 6, 7, 42})); EXPECT_FALSE(AR1.equals({1, 2, 3, 4, 5, 6, 7})); EXPECT_FALSE(AR1.equals({1, 2, 3, 4, 5, 6, 7, 8, 9})); ArrayRef<int> AR1a = AR1.drop_back(); EXPECT_TRUE(AR1a.equals({1, 2, 3, 4, 5, 6, 7})); EXPECT_FALSE(AR1a.equals({1, 2, 3, 4, 5, 6, 7, 8})); ArrayRef<int> AR1b = AR1a.slice(2, 4); EXPECT_TRUE(AR1b.equals({3, 4, 5, 6})); EXPECT_FALSE(AR1b.equals({2, 3, 4, 5, 6})); EXPECT_FALSE(AR1b.equals({3, 4, 5, 6, 7})); } TEST(ArrayRefTest, EmptyEquals) { EXPECT_TRUE(ArrayRef<unsigned>() == ArrayRef<unsigned>()); } TEST(ArrayRefTest, ConstConvert) { int buf[4]; for (int i = 0; i < 4; ++i) buf[i] = i; static int *A[] = {&buf[0], &buf[1], &buf[2], &buf[3]}; ArrayRef<const int *> a((ArrayRef<int *>(A))); a = ArrayRef<int *>(A); } static std::vector<int> ReturnTest12() { return {1, 2}; } static void ArgTest12(ArrayRef<int> A) { EXPECT_EQ(2U, A.size()); EXPECT_EQ(1, A[0]); EXPECT_EQ(2, A[1]); } TEST(ArrayRefTest, InitializerList) { std::initializer_list<int> InitList = { 0, 1, 2, 3, 4 }; ArrayRef<int> A = InitList; for (int i = 0; i < 5; ++i) EXPECT_EQ(i, A[i]); std::vector<int> B = ReturnTest12(); A = B; EXPECT_EQ(1, A[0]); EXPECT_EQ(2, A[1]); ArgTest12({1, 2}); } } // end anonymous namespace
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/ADT/IteratorTest.cpp
//===- IteratorTest.cpp - Unit tests for iterator utilities ---------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/ADT/iterator.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallVector.h" #include "gtest/gtest.h" using namespace llvm; namespace { TEST(PointeeIteratorTest, Basic) { int arr[4] = {1, 2, 3, 4}; SmallVector<int *, 4> V; V.push_back(&arr[0]); V.push_back(&arr[1]); V.push_back(&arr[2]); V.push_back(&arr[3]); typedef pointee_iterator<SmallVectorImpl<int *>::const_iterator> test_iterator; test_iterator Begin, End; Begin = V.begin(); End = test_iterator(V.end()); test_iterator I = Begin; for (int i = 0; i < 4; ++i) { EXPECT_EQ(*V[i], *I); EXPECT_EQ(I, Begin + i); EXPECT_EQ(I, std::next(Begin, i)); test_iterator J = Begin; J += i; EXPECT_EQ(I, J); EXPECT_EQ(*V[i], Begin[i]); EXPECT_NE(I, End); EXPECT_GT(End, I); EXPECT_LT(I, End); EXPECT_GE(I, Begin); EXPECT_LE(Begin, I); EXPECT_EQ(i, I - Begin); EXPECT_EQ(i, std::distance(Begin, I)); EXPECT_EQ(Begin, I - i); test_iterator K = I++; EXPECT_EQ(K, std::prev(I)); } EXPECT_EQ(End, I); } TEST(PointeeIteratorTest, SmartPointer) { SmallVector<std::unique_ptr<int>, 4> V; V.push_back(make_unique<int>(1)); V.push_back(make_unique<int>(2)); V.push_back(make_unique<int>(3)); V.push_back(make_unique<int>(4)); typedef pointee_iterator< SmallVectorImpl<std::unique_ptr<int>>::const_iterator> test_iterator; test_iterator Begin, End; Begin = V.begin(); End = test_iterator(V.end()); test_iterator I = Begin; for (int i = 0; i < 4; ++i) { EXPECT_EQ(*V[i], *I); EXPECT_EQ(I, Begin + i); EXPECT_EQ(I, std::next(Begin, i)); test_iterator J = Begin; J += i; EXPECT_EQ(I, J); EXPECT_EQ(*V[i], Begin[i]); EXPECT_NE(I, End); EXPECT_GT(End, I); EXPECT_LT(I, End); EXPECT_GE(I, Begin); EXPECT_LE(Begin, I); EXPECT_EQ(i, I - Begin); EXPECT_EQ(i, std::distance(Begin, I)); EXPECT_EQ(Begin, I - i); test_iterator K = I++; EXPECT_EQ(K, std::prev(I)); } EXPECT_EQ(End, I); } TEST(FilterIteratorTest, Lambda) { auto IsOdd = [](int N) { return N % 2 == 1; }; int A[] = {0, 1, 2, 3, 4, 5, 6}; auto Range = make_filter_range(A, IsOdd); SmallVector<int, 3> Actual(Range.begin(), Range.end()); EXPECT_EQ((SmallVector<int, 3>{1, 3, 5}), Actual); } TEST(FilterIteratorTest, CallableObject) { int Counter = 0; struct Callable { int &Counter; Callable(int &Counter) : Counter(Counter) {} bool operator()(int N) { Counter++; return N % 2 == 1; } }; Callable IsOdd(Counter); int A[] = {0, 1, 2, 3, 4, 5, 6}; auto Range = make_filter_range(A, IsOdd); EXPECT_EQ(2, Counter); SmallVector<int, 3> Actual(Range.begin(), Range.end()); EXPECT_GE(Counter, 7); EXPECT_EQ((SmallVector<int, 3>{1, 3, 5}), Actual); } TEST(FilterIteratorTest, FunctionPointer) { bool (*IsOdd)(int) = [](int N) { return N % 2 == 1; }; int A[] = {0, 1, 2, 3, 4, 5, 6}; auto Range = make_filter_range(A, IsOdd); SmallVector<int, 3> Actual(Range.begin(), Range.end()); EXPECT_EQ((SmallVector<int, 3>{1, 3, 5}), Actual); } TEST(FilterIteratorTest, Composition) { auto IsOdd = [](int N) { return N % 2 == 1; }; std::unique_ptr<int> A[] = {make_unique<int>(0), make_unique<int>(1), make_unique<int>(2), make_unique<int>(3), make_unique<int>(4), make_unique<int>(5), make_unique<int>(6)}; using PointeeIterator = pointee_iterator<std::unique_ptr<int> *>; auto Range = make_filter_range( make_range(PointeeIterator(std::begin(A)), PointeeIterator(std::end(A))), IsOdd); SmallVector<int, 3> Actual(Range.begin(), Range.end()); EXPECT_EQ((SmallVector<int, 3>{1, 3, 5}), Actual); } TEST(FilterIteratorTest, InputIterator) { struct InputIterator : iterator_adaptor_base<InputIterator, int *, std::input_iterator_tag> { using BaseT = iterator_adaptor_base<InputIterator, int *, std::input_iterator_tag>; InputIterator(int *It) : BaseT(It) {} }; auto IsOdd = [](int N) { return N % 2 == 1; }; int A[] = {0, 1, 2, 3, 4, 5, 6}; auto Range = make_filter_range( make_range(InputIterator(std::begin(A)), InputIterator(std::end(A))), IsOdd); SmallVector<int, 3> Actual(Range.begin(), Range.end()); EXPECT_EQ((SmallVector<int, 3>{1, 3, 5}), Actual); } TEST(PointerIterator, Basic) { int A[] = {1, 2, 3, 4}; pointer_iterator<int *> Begin(std::begin(A)), End(std::end(A)); EXPECT_EQ(A, *Begin); ++Begin; EXPECT_EQ(A + 1, *Begin); ++Begin; EXPECT_EQ(A + 2, *Begin); ++Begin; EXPECT_EQ(A + 3, *Begin); ++Begin; EXPECT_EQ(Begin, End); } TEST(PointerIterator, Const) { int A[] = {1, 2, 3, 4}; const pointer_iterator<int *> Begin(std::begin(A)); EXPECT_EQ(A, *Begin); EXPECT_EQ(A + 1, std::next(*Begin, 1)); EXPECT_EQ(A + 2, std::next(*Begin, 2)); EXPECT_EQ(A + 3, std::next(*Begin, 3)); EXPECT_EQ(A + 4, std::next(*Begin, 4)); } TEST(ZipIteratorTest, Basic) { using namespace std; const SmallVector<unsigned, 6> pi{3, 1, 4, 1, 5, 9}; SmallVector<bool, 6> odd{1, 1, 0, 1, 1, 1}; const char message[] = "yynyyy\0"; for (auto tup : zip(pi, odd, message)) { EXPECT_EQ(get<0>(tup) & 0x01, get<1>(tup)); EXPECT_EQ(get<0>(tup) & 0x01 ? 'y' : 'n', get<2>(tup)); } // note the rvalue for (auto tup : zip(pi, SmallVector<bool, 0>{1, 1, 0, 1, 1})) { EXPECT_EQ(get<0>(tup) & 0x01, get<1>(tup)); } } TEST(ZipIteratorTest, ZipFirstBasic) { using namespace std; const SmallVector<unsigned, 6> pi{3, 1, 4, 1, 5, 9}; unsigned iters = 0; for (auto tup : zip_first(SmallVector<bool, 0>{1, 1, 0, 1}, pi)) { EXPECT_EQ(get<0>(tup), get<1>(tup) & 0x01); iters += 1; } EXPECT_EQ(iters, 4u); } TEST(ZipIteratorTest, Mutability) { using namespace std; const SmallVector<unsigned, 4> pi{3, 1, 4, 1, 5, 9}; char message[] = "hello zip\0"; for (auto tup : zip(pi, message, message)) { EXPECT_EQ(get<1>(tup), get<2>(tup)); get<2>(tup) = get<0>(tup) & 0x01 ? 'y' : 'n'; } // note the rvalue for (auto tup : zip(message, "yynyyyzip\0")) { EXPECT_EQ(get<0>(tup), get<1>(tup)); } } TEST(ZipIteratorTest, ZipFirstMutability) { using namespace std; vector<unsigned> pi{3, 1, 4, 1, 5, 9}; unsigned iters = 0; for (auto tup : zip_first(SmallVector<bool, 0>{1, 1, 0, 1}, pi)) { get<1>(tup) = get<0>(tup); iters += 1; } EXPECT_EQ(iters, 4u); for (auto tup : zip_first(SmallVector<bool, 0>{1, 1, 0, 1}, pi)) { EXPECT_EQ(get<0>(tup), get<1>(tup)); } } } // anonymous namespace
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/ADT/PostOrderIteratorTest.cpp
//===- PostOrderIteratorTest.cpp - PostOrderIterator unit tests -----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "gtest/gtest.h" #include "llvm/ADT/PostOrderIterator.h" #include "llvm/IR/BasicBlock.h" #include "llvm/IR/CFG.h" using namespace llvm; // // /////////////////////////////////////////////////////////////////////////////// namespace { // Whether we're able to compile TEST(PostOrderIteratorTest, Compiles) { typedef SmallPtrSet<void *, 4> ExtSetTy; // Tests that template specializations are kept up to date void *Null = nullptr; po_iterator_storage<std::set<void *>, false> PIS; PIS.insertEdge(Null, Null); ExtSetTy Ext; po_iterator_storage<ExtSetTy, true> PISExt(Ext); PIS.insertEdge(Null, Null); // Test above, but going through po_iterator (which inherits from template // base) BasicBlock *NullBB = nullptr; auto PI = po_end(NullBB); PI.insertEdge(NullBB, NullBB); auto PIExt = po_ext_end(NullBB, Ext); PIExt.insertEdge(NullBB, NullBB); } }
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/ADT/TinyPtrVectorTest.cpp
//===- llvm/unittest/ADT/TinyPtrVectorTest.cpp ----------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // TinyPtrVector unit tests. // //===----------------------------------------------------------------------===// #include "llvm/ADT/TinyPtrVector.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Support/type_traits.h" #include "gtest/gtest.h" #include <algorithm> #include <list> #include <random> #include <vector> using namespace llvm; namespace { template <typename VectorT> class TinyPtrVectorTest : public testing::Test { protected: typedef typename VectorT::value_type PtrT; typedef typename std::remove_pointer<PtrT>::type ValueT; VectorT V; VectorT V2; ValueT TestValues[1024]; std::vector<PtrT> TestPtrs; TinyPtrVectorTest() { for (size_t i = 0, e = array_lengthof(TestValues); i != e; ++i) TestPtrs.push_back(&TestValues[i]); std::shuffle(TestPtrs.begin(), TestPtrs.end(), std::mt19937{}); } ArrayRef<PtrT> testArray(size_t N) { return makeArrayRef(&TestPtrs[0], N); } void appendValues(VectorT &V, ArrayRef<PtrT> Values) { for (size_t i = 0, e = Values.size(); i != e; ++i) V.push_back(Values[i]); } void setVectors(ArrayRef<PtrT> Values1, ArrayRef<PtrT> Values2) { V.clear(); appendValues(V, Values1); V2.clear(); appendValues(V2, Values2); } void expectValues(const VectorT &V, ArrayRef<PtrT> Values) { EXPECT_EQ(Values.empty(), V.empty()); EXPECT_EQ(Values.size(), V.size()); for (size_t i = 0, e = Values.size(); i != e; ++i) { EXPECT_EQ(Values[i], V[i]); EXPECT_EQ(Values[i], *std::next(V.begin(), i)); } EXPECT_EQ(V.end(), std::next(V.begin(), Values.size())); } }; typedef ::testing::Types<TinyPtrVector<int*>, TinyPtrVector<double*> > TinyPtrVectorTestTypes; TYPED_TEST_CASE(TinyPtrVectorTest, TinyPtrVectorTestTypes); TYPED_TEST(TinyPtrVectorTest, EmptyTest) { this->expectValues(this->V, this->testArray(0)); } TYPED_TEST(TinyPtrVectorTest, PushPopBack) { this->V.push_back(this->TestPtrs[0]); this->expectValues(this->V, this->testArray(1)); this->V.push_back(this->TestPtrs[1]); this->expectValues(this->V, this->testArray(2)); this->V.push_back(this->TestPtrs[2]); this->expectValues(this->V, this->testArray(3)); this->V.push_back(this->TestPtrs[3]); this->expectValues(this->V, this->testArray(4)); this->V.push_back(this->TestPtrs[4]); this->expectValues(this->V, this->testArray(5)); // Pop and clobber a few values to keep things interesting. this->V.pop_back(); this->expectValues(this->V, this->testArray(4)); this->V.pop_back(); this->expectValues(this->V, this->testArray(3)); this->TestPtrs[3] = &this->TestValues[42]; this->TestPtrs[4] = &this->TestValues[43]; this->V.push_back(this->TestPtrs[3]); this->expectValues(this->V, this->testArray(4)); this->V.push_back(this->TestPtrs[4]); this->expectValues(this->V, this->testArray(5)); this->V.pop_back(); this->expectValues(this->V, this->testArray(4)); this->V.pop_back(); this->expectValues(this->V, this->testArray(3)); this->V.pop_back(); this->expectValues(this->V, this->testArray(2)); this->V.pop_back(); this->expectValues(this->V, this->testArray(1)); this->V.pop_back(); this->expectValues(this->V, this->testArray(0)); this->appendValues(this->V, this->testArray(42)); this->expectValues(this->V, this->testArray(42)); } TYPED_TEST(TinyPtrVectorTest, ClearTest) { this->expectValues(this->V, this->testArray(0)); this->V.clear(); this->expectValues(this->V, this->testArray(0)); this->appendValues(this->V, this->testArray(1)); this->expectValues(this->V, this->testArray(1)); this->V.clear(); this->expectValues(this->V, this->testArray(0)); this->appendValues(this->V, this->testArray(42)); this->expectValues(this->V, this->testArray(42)); this->V.clear(); this->expectValues(this->V, this->testArray(0)); } TYPED_TEST(TinyPtrVectorTest, CopyAndMoveCtorTest) { this->appendValues(this->V, this->testArray(42)); TypeParam Copy(this->V); this->expectValues(Copy, this->testArray(42)); // This is a separate copy, and so it shouldn't destroy the original. Copy.clear(); this->expectValues(Copy, this->testArray(0)); this->expectValues(this->V, this->testArray(42)); TypeParam Copy2(this->V2); this->appendValues(Copy2, this->testArray(42)); this->expectValues(Copy2, this->testArray(42)); this->expectValues(this->V2, this->testArray(0)); TypeParam Move(std::move(Copy2)); this->expectValues(Move, this->testArray(42)); this->expectValues(Copy2, this->testArray(0)); } TYPED_TEST(TinyPtrVectorTest, CopyAndMoveTest) { this->V = this->V2; this->expectValues(this->V, this->testArray(0)); this->expectValues(this->V2, this->testArray(0)); this->V = std::move(this->V2); this->expectValues(this->V, this->testArray(0)); this->setVectors(this->testArray(1), this->testArray(0)); this->V = this->V2; this->expectValues(this->V, this->testArray(0)); this->expectValues(this->V2, this->testArray(0)); this->setVectors(this->testArray(1), this->testArray(0)); this->V = std::move(this->V2); this->expectValues(this->V, this->testArray(0)); this->setVectors(this->testArray(2), this->testArray(0)); this->V = this->V2; this->expectValues(this->V, this->testArray(0)); this->expectValues(this->V2, this->testArray(0)); this->setVectors(this->testArray(2), this->testArray(0)); this->V = std::move(this->V2); this->expectValues(this->V, this->testArray(0)); this->setVectors(this->testArray(42), this->testArray(0)); this->V = this->V2; this->expectValues(this->V, this->testArray(0)); this->expectValues(this->V2, this->testArray(0)); this->setVectors(this->testArray(42), this->testArray(0)); this->V = std::move(this->V2); this->expectValues(this->V, this->testArray(0)); this->setVectors(this->testArray(0), this->testArray(1)); this->V = this->V2; this->expectValues(this->V, this->testArray(1)); this->expectValues(this->V2, this->testArray(1)); this->setVectors(this->testArray(0), this->testArray(1)); this->V = std::move(this->V2); this->expectValues(this->V, this->testArray(1)); this->setVectors(this->testArray(0), this->testArray(2)); this->V = this->V2; this->expectValues(this->V, this->testArray(2)); this->expectValues(this->V2, this->testArray(2)); this->setVectors(this->testArray(0), this->testArray(2)); this->V = std::move(this->V2); this->expectValues(this->V, this->testArray(2)); this->setVectors(this->testArray(0), this->testArray(42)); this->V = this->V2; this->expectValues(this->V, this->testArray(42)); this->expectValues(this->V2, this->testArray(42)); this->setVectors(this->testArray(0), this->testArray(42)); this->V = std::move(this->V2); this->expectValues(this->V, this->testArray(42)); this->setVectors(this->testArray(1), this->testArray(1)); this->V = this->V2; this->expectValues(this->V, this->testArray(1)); this->expectValues(this->V2, this->testArray(1)); this->V = std::move(this->V2); this->expectValues(this->V, this->testArray(1)); this->setVectors(this->testArray(1), this->testArray(2)); this->V = this->V2; this->expectValues(this->V, this->testArray(2)); this->expectValues(this->V2, this->testArray(2)); this->setVectors(this->testArray(1), this->testArray(2)); this->V = std::move(this->V2); this->expectValues(this->V, this->testArray(2)); this->setVectors(this->testArray(1), this->testArray(42)); this->V = this->V2; this->expectValues(this->V, this->testArray(42)); this->expectValues(this->V2, this->testArray(42)); this->setVectors(this->testArray(1), this->testArray(42)); this->V = std::move(this->V2); this->expectValues(this->V, this->testArray(42)); this->setVectors(this->testArray(2), this->testArray(1)); this->V = this->V2; this->expectValues(this->V, this->testArray(1)); this->expectValues(this->V2, this->testArray(1)); this->setVectors(this->testArray(2), this->testArray(1)); this->V = std::move(this->V2); this->expectValues(this->V, this->testArray(1)); this->setVectors(this->testArray(2), this->testArray(2)); this->V = this->V2; this->expectValues(this->V, this->testArray(2)); this->expectValues(this->V2, this->testArray(2)); this->setVectors(this->testArray(2), this->testArray(2)); this->V = std::move(this->V2); this->expectValues(this->V, this->testArray(2)); this->setVectors(this->testArray(2), this->testArray(42)); this->V = this->V2; this->expectValues(this->V, this->testArray(42)); this->expectValues(this->V2, this->testArray(42)); this->setVectors(this->testArray(2), this->testArray(42)); this->V = std::move(this->V2); this->expectValues(this->V, this->testArray(42)); this->setVectors(this->testArray(42), this->testArray(1)); this->V = this->V2; this->expectValues(this->V, this->testArray(1)); this->expectValues(this->V2, this->testArray(1)); this->setVectors(this->testArray(42), this->testArray(1)); this->V = std::move(this->V2); this->expectValues(this->V, this->testArray(1)); this->setVectors(this->testArray(42), this->testArray(2)); this->V = this->V2; this->expectValues(this->V, this->testArray(2)); this->expectValues(this->V2, this->testArray(2)); this->setVectors(this->testArray(42), this->testArray(2)); this->V = std::move(this->V2); this->expectValues(this->V, this->testArray(2)); this->setVectors(this->testArray(42), this->testArray(42)); this->V = this->V2; this->expectValues(this->V, this->testArray(42)); this->expectValues(this->V2, this->testArray(42)); this->setVectors(this->testArray(42), this->testArray(42)); this->V = std::move(this->V2); this->expectValues(this->V, this->testArray(42)); } TYPED_TEST(TinyPtrVectorTest, EraseTest) { this->appendValues(this->V, this->testArray(1)); this->expectValues(this->V, this->testArray(1)); this->V.erase(this->V.begin()); this->expectValues(this->V, this->testArray(0)); this->appendValues(this->V, this->testArray(42)); this->expectValues(this->V, this->testArray(42)); this->V.erase(this->V.begin()); this->TestPtrs.erase(this->TestPtrs.begin()); this->expectValues(this->V, this->testArray(41)); this->V.erase(std::next(this->V.begin(), 1)); this->TestPtrs.erase(std::next(this->TestPtrs.begin(), 1)); this->expectValues(this->V, this->testArray(40)); this->V.erase(std::next(this->V.begin(), 2)); this->TestPtrs.erase(std::next(this->TestPtrs.begin(), 2)); this->expectValues(this->V, this->testArray(39)); this->V.erase(std::next(this->V.begin(), 5)); this->TestPtrs.erase(std::next(this->TestPtrs.begin(), 5)); this->expectValues(this->V, this->testArray(38)); this->V.erase(std::next(this->V.begin(), 13)); this->TestPtrs.erase(std::next(this->TestPtrs.begin(), 13)); this->expectValues(this->V, this->testArray(37)); typename TypeParam::iterator I = this->V.begin(); do { I = this->V.erase(I); } while (I != this->V.end()); this->expectValues(this->V, this->testArray(0)); } TYPED_TEST(TinyPtrVectorTest, EraseRangeTest) { this->appendValues(this->V, this->testArray(1)); this->expectValues(this->V, this->testArray(1)); this->V.erase(this->V.begin(), this->V.begin()); this->expectValues(this->V, this->testArray(1)); this->V.erase(this->V.end(), this->V.end()); this->expectValues(this->V, this->testArray(1)); this->V.erase(this->V.begin(), this->V.end()); this->expectValues(this->V, this->testArray(0)); this->appendValues(this->V, this->testArray(42)); this->expectValues(this->V, this->testArray(42)); this->V.erase(this->V.begin(), std::next(this->V.begin(), 1)); this->TestPtrs.erase(this->TestPtrs.begin(), std::next(this->TestPtrs.begin(), 1)); this->expectValues(this->V, this->testArray(41)); this->V.erase(std::next(this->V.begin(), 1), std::next(this->V.begin(), 2)); this->TestPtrs.erase(std::next(this->TestPtrs.begin(), 1), std::next(this->TestPtrs.begin(), 2)); this->expectValues(this->V, this->testArray(40)); this->V.erase(std::next(this->V.begin(), 2), std::next(this->V.begin(), 4)); this->TestPtrs.erase(std::next(this->TestPtrs.begin(), 2), std::next(this->TestPtrs.begin(), 4)); this->expectValues(this->V, this->testArray(38)); this->V.erase(std::next(this->V.begin(), 5), std::next(this->V.begin(), 10)); this->TestPtrs.erase(std::next(this->TestPtrs.begin(), 5), std::next(this->TestPtrs.begin(), 10)); this->expectValues(this->V, this->testArray(33)); this->V.erase(std::next(this->V.begin(), 13), std::next(this->V.begin(), 26)); this->TestPtrs.erase(std::next(this->TestPtrs.begin(), 13), std::next(this->TestPtrs.begin(), 26)); this->expectValues(this->V, this->testArray(20)); this->V.erase(std::next(this->V.begin(), 7), this->V.end()); this->expectValues(this->V, this->testArray(7)); this->V.erase(this->V.begin(), this->V.end()); this->expectValues(this->V, this->testArray(0)); } TYPED_TEST(TinyPtrVectorTest, Insert) { this->V.insert(this->V.end(), this->TestPtrs[0]); this->expectValues(this->V, this->testArray(1)); this->V.clear(); this->appendValues(this->V, this->testArray(4)); this->expectValues(this->V, this->testArray(4)); this->V.insert(this->V.end(), this->TestPtrs[4]); this->expectValues(this->V, this->testArray(5)); this->V.insert(this->V.begin(), this->TestPtrs[42]); this->TestPtrs.insert(this->TestPtrs.begin(), this->TestPtrs[42]); this->expectValues(this->V, this->testArray(6)); this->V.insert(std::next(this->V.begin(), 3), this->TestPtrs[43]); this->TestPtrs.insert(std::next(this->TestPtrs.begin(), 3), this->TestPtrs[43]); this->expectValues(this->V, this->testArray(7)); } TYPED_TEST(TinyPtrVectorTest, InsertRange) { this->V.insert(this->V.end(), this->TestPtrs.begin(), this->TestPtrs.begin()); this->expectValues(this->V, this->testArray(0)); this->V.insert(this->V.begin(), this->TestPtrs.begin(), this->TestPtrs.begin()); this->expectValues(this->V, this->testArray(0)); this->V.insert(this->V.end(), this->TestPtrs.end(), this->TestPtrs.end()); this->expectValues(this->V, this->testArray(0)); this->V.insert(this->V.end(), this->TestPtrs.begin(), std::next(this->TestPtrs.begin())); this->expectValues(this->V, this->testArray(1)); this->V.clear(); this->V.insert(this->V.end(), this->TestPtrs.begin(), std::next(this->TestPtrs.begin(), 2)); this->expectValues(this->V, this->testArray(2)); this->V.clear(); this->V.insert(this->V.end(), this->TestPtrs.begin(), std::next(this->TestPtrs.begin(), 42)); this->expectValues(this->V, this->testArray(42)); this->V.clear(); this->V.insert(this->V.end(), std::next(this->TestPtrs.begin(), 5), std::next(this->TestPtrs.begin(), 13)); this->V.insert(this->V.begin(), std::next(this->TestPtrs.begin(), 0), std::next(this->TestPtrs.begin(), 3)); this->V.insert(std::next(this->V.begin(), 2), std::next(this->TestPtrs.begin(), 2), std::next(this->TestPtrs.begin(), 4)); this->V.erase(std::next(this->V.begin(), 4)); this->V.insert(std::next(this->V.begin(), 4), std::next(this->TestPtrs.begin(), 4), std::next(this->TestPtrs.begin(), 5)); this->expectValues(this->V, this->testArray(13)); } } TEST(TinyPtrVectorTest, SingleEltCtorTest) { int v = 55; TinyPtrVector<int *> V(&v); EXPECT_TRUE(V.size() == 1); EXPECT_FALSE(V.empty()); EXPECT_TRUE(V.front() == &v); } TEST(TinyPtrVectorTest, ArrayRefCtorTest) { int data_array[128]; std::vector<int *> data; for (unsigned i = 0, e = 128; i != e; ++i) { data_array[i] = 324 - int(i); data.push_back(&data_array[i]); } TinyPtrVector<int *> V(data); EXPECT_TRUE(V.size() == 128); EXPECT_FALSE(V.empty()); for (unsigned i = 0, e = 128; i != e; ++i) { EXPECT_TRUE(V[i] == data[i]); } } TEST(TinyPtrVectorTest, MutableArrayRefTest) { int data_array[128]; std::vector<int *> data; for (unsigned i = 0, e = 128; i != e; ++i) { data_array[i] = 324 - int(i); data.push_back(&data_array[i]); } TinyPtrVector<int *> V(data); EXPECT_TRUE(V.size() == 128); EXPECT_FALSE(V.empty()); MutableArrayRef<int *> mut_array = V; for (unsigned i = 0, e = 128; i != e; ++i) { EXPECT_TRUE(mut_array[i] == data[i]); mut_array[i] = 324 + mut_array[i]; EXPECT_TRUE(mut_array[i] == (324 + data[i])); } }
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/ADT/PackedVectorTest.cpp
//===- llvm/unittest/ADT/PackedVectorTest.cpp - PackedVector tests --------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef __ppc__ #include "llvm/ADT/PackedVector.h" #include "gtest/gtest.h" using namespace llvm; namespace { TEST(PackedVectorTest, Operation) { PackedVector<unsigned, 2> Vec; EXPECT_EQ(0U, Vec.size()); EXPECT_TRUE(Vec.empty()); Vec.resize(5); EXPECT_EQ(5U, Vec.size()); EXPECT_FALSE(Vec.empty()); Vec.resize(11); EXPECT_EQ(11U, Vec.size()); EXPECT_FALSE(Vec.empty()); PackedVector<unsigned, 2> Vec2(3); EXPECT_EQ(3U, Vec2.size()); EXPECT_FALSE(Vec2.empty()); Vec.clear(); EXPECT_EQ(0U, Vec.size()); EXPECT_TRUE(Vec.empty()); Vec.push_back(2); Vec.push_back(0); Vec.push_back(1); Vec.push_back(3); EXPECT_EQ(2U, Vec[0]); EXPECT_EQ(0U, Vec[1]); EXPECT_EQ(1U, Vec[2]); EXPECT_EQ(3U, Vec[3]); EXPECT_FALSE(Vec == Vec2); EXPECT_TRUE(Vec != Vec2); Vec2.swap(Vec); EXPECT_EQ(3U, Vec.size()); EXPECT_FALSE(Vec.empty()); EXPECT_EQ(0U, Vec[0]); EXPECT_EQ(0U, Vec[1]); EXPECT_EQ(0U, Vec[2]); EXPECT_EQ(2U, Vec2[0]); EXPECT_EQ(0U, Vec2[1]); EXPECT_EQ(1U, Vec2[2]); EXPECT_EQ(3U, Vec2[3]); Vec = Vec2; EXPECT_TRUE(Vec == Vec2); EXPECT_FALSE(Vec != Vec2); Vec[1] = 1; Vec2[1] = 2; Vec |= Vec2; EXPECT_EQ(3U, Vec[1]); } #ifdef EXPECT_DEBUG_DEATH TEST(PackedVectorTest, UnsignedValues) { PackedVector<unsigned, 2> Vec(1); Vec[0] = 0; Vec[0] = 1; Vec[0] = 2; Vec[0] = 3; EXPECT_DEBUG_DEATH(Vec[0] = 4, "value is too big"); EXPECT_DEBUG_DEATH(Vec[0] = -1, "value is too big"); EXPECT_DEBUG_DEATH(Vec[0] = 0x100, "value is too big"); PackedVector<unsigned, 3> Vec2(1); Vec2[0] = 0; Vec2[0] = 7; EXPECT_DEBUG_DEATH(Vec[0] = 8, "value is too big"); } TEST(PackedVectorTest, SignedValues) { PackedVector<signed, 2> Vec(1); Vec[0] = -2; Vec[0] = -1; Vec[0] = 0; Vec[0] = 1; EXPECT_DEBUG_DEATH(Vec[0] = -3, "value is too big"); EXPECT_DEBUG_DEATH(Vec[0] = 2, "value is too big"); PackedVector<signed, 3> Vec2(1); Vec2[0] = -4; Vec2[0] = 3; EXPECT_DEBUG_DEATH(Vec[0] = -5, "value is too big"); EXPECT_DEBUG_DEATH(Vec[0] = 4, "value is too big"); } #endif } #endif
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/ADT/SparseMultiSetTest.cpp
//===------ ADT/SparseSetTest.cpp - SparseSet unit tests - -----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/ADT/SparseMultiSet.h" #include "gtest/gtest.h" using namespace llvm; namespace { typedef SparseMultiSet<unsigned> USet; // Empty set tests. TEST(SparseMultiSetTest, EmptySet) { USet Set; EXPECT_TRUE(Set.empty()); EXPECT_EQ(0u, Set.size()); Set.setUniverse(10); // Lookups on empty set. EXPECT_TRUE(Set.find(0) == Set.end()); EXPECT_TRUE(Set.find(9) == Set.end()); // Same thing on a const reference. const USet &CSet = Set; EXPECT_TRUE(CSet.empty()); EXPECT_EQ(0u, CSet.size()); EXPECT_TRUE(CSet.find(0) == CSet.end()); USet::const_iterator I = CSet.find(5); EXPECT_TRUE(I == CSet.end()); } // Single entry set tests. TEST(SparseMultiSetTest, SingleEntrySet) { USet Set; Set.setUniverse(10); USet::iterator I = Set.insert(5); EXPECT_TRUE(I != Set.end()); EXPECT_TRUE(*I == 5); EXPECT_FALSE(Set.empty()); EXPECT_EQ(1u, Set.size()); EXPECT_TRUE(Set.find(0) == Set.end()); EXPECT_TRUE(Set.find(9) == Set.end()); EXPECT_FALSE(Set.contains(0)); EXPECT_TRUE(Set.contains(5)); // Extra insert. I = Set.insert(5); EXPECT_TRUE(I != Set.end()); EXPECT_TRUE(I == ++Set.find(5)); I--; EXPECT_TRUE(I == Set.find(5)); // Erase non-existent element. I = Set.find(1); EXPECT_TRUE(I == Set.end()); EXPECT_EQ(2u, Set.size()); EXPECT_EQ(5u, *Set.find(5)); // Erase iterator. I = Set.find(5); EXPECT_TRUE(I != Set.end()); I = Set.erase(I); EXPECT_TRUE(I != Set.end()); I = Set.erase(I); EXPECT_TRUE(I == Set.end()); EXPECT_TRUE(Set.empty()); } // Multiple entry set tests. TEST(SparseMultiSetTest, MultipleEntrySet) { USet Set; Set.setUniverse(10); Set.insert(5); Set.insert(5); Set.insert(5); Set.insert(3); Set.insert(2); Set.insert(1); Set.insert(4); EXPECT_EQ(7u, Set.size()); // Erase last element by key. EXPECT_TRUE(Set.erase(Set.find(4)) == Set.end()); EXPECT_EQ(6u, Set.size()); EXPECT_FALSE(Set.contains(4)); EXPECT_TRUE(Set.find(4) == Set.end()); // Erase first element by key. EXPECT_EQ(3u, Set.count(5)); EXPECT_TRUE(Set.find(5) != Set.end()); EXPECT_TRUE(Set.erase(Set.find(5)) != Set.end()); EXPECT_EQ(5u, Set.size()); EXPECT_EQ(2u, Set.count(5)); Set.insert(6); Set.insert(7); EXPECT_EQ(7u, Set.size()); // Erase tail by iterator. EXPECT_TRUE(Set.getTail(6) == Set.getHead(6)); USet::iterator I = Set.erase(Set.find(6)); EXPECT_TRUE(I == Set.end()); EXPECT_EQ(6u, Set.size()); // Erase tails by iterator. EXPECT_EQ(2u, Set.count(5)); I = Set.getTail(5); I = Set.erase(I); EXPECT_TRUE(I == Set.end()); --I; EXPECT_EQ(1u, Set.count(5)); EXPECT_EQ(5u, *I); I = Set.erase(I); EXPECT_TRUE(I == Set.end()); EXPECT_EQ(0u, Set.count(5)); Set.insert(8); Set.insert(8); Set.insert(8); Set.insert(8); Set.insert(8); // Erase all the 8s EXPECT_EQ(5, std::distance(Set.getHead(8), Set.end())); Set.eraseAll(8); EXPECT_EQ(0, std::distance(Set.getHead(8), Set.end())); // Clear and resize the universe. Set.clear(); EXPECT_EQ(0u, Set.size()); EXPECT_FALSE(Set.contains(3)); Set.setUniverse(1000); // Add more than 256 elements. for (unsigned i = 100; i != 800; ++i) Set.insert(i); for (unsigned i = 0; i != 10; ++i) Set.eraseAll(i); for (unsigned i = 100; i != 800; ++i) EXPECT_EQ(1u, Set.count(i)); EXPECT_FALSE(Set.contains(99)); EXPECT_FALSE(Set.contains(800)); EXPECT_EQ(700u, Set.size()); } // Test out iterators TEST(SparseMultiSetTest, Iterators) { USet Set; Set.setUniverse(100); Set.insert(0); Set.insert(1); Set.insert(2); Set.insert(0); Set.insert(1); Set.insert(0); USet::RangePair RangePair = Set.equal_range(0); USet::iterator B = RangePair.first; USet::iterator E = RangePair.second; // Move the iterators around, going to end and coming back. EXPECT_EQ(3, std::distance(B, E)); EXPECT_EQ(B, --(--(--E))); EXPECT_EQ(++(++(++E)), Set.end()); EXPECT_EQ(B, --(--(--E))); EXPECT_EQ(++(++(++E)), Set.end()); // Insert into the tail, and move around again Set.insert(0); EXPECT_EQ(B, --(--(--(--E)))); EXPECT_EQ(++(++(++(++E))), Set.end()); EXPECT_EQ(B, --(--(--(--E)))); EXPECT_EQ(++(++(++(++E))), Set.end()); // Erase a tail, and move around again USet::iterator Erased = Set.erase(Set.getTail(0)); EXPECT_EQ(Erased, E); EXPECT_EQ(B, --(--(--E))); USet Set2; Set2.setUniverse(11); Set2.insert(3); EXPECT_TRUE(!Set2.contains(0)); EXPECT_TRUE(!Set.contains(3)); EXPECT_EQ(Set2.getHead(3), Set2.getTail(3)); EXPECT_EQ(Set2.getHead(0), Set2.getTail(0)); B = Set2.find(3); EXPECT_EQ(Set2.find(3), --(++B)); } struct Alt { unsigned Value; explicit Alt(unsigned x) : Value(x) {} unsigned getSparseSetIndex() const { return Value - 1000; } }; TEST(SparseMultiSetTest, AltStructSet) { typedef SparseMultiSet<Alt> ASet; ASet Set; Set.setUniverse(10); Set.insert(Alt(1005)); ASet::iterator I = Set.find(5); ASSERT_TRUE(I != Set.end()); EXPECT_EQ(1005u, I->Value); Set.insert(Alt(1006)); Set.insert(Alt(1006)); I = Set.erase(Set.find(6)); ASSERT_TRUE(I != Set.end()); EXPECT_EQ(1006u, I->Value); I = Set.erase(Set.find(6)); ASSERT_TRUE(I == Set.end()); EXPECT_TRUE(Set.contains(5)); EXPECT_FALSE(Set.contains(6)); } } // namespace
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/ADT/SparseBitVectorTest.cpp
//===- llvm/unittest/ADT/SparseBitVectorTest.cpp - SparseBitVector tests --===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/ADT/SparseBitVector.h" #include "gtest/gtest.h" using namespace llvm; namespace { TEST(SparseBitVectorTest, TrivialOperation) { SparseBitVector<> Vec; EXPECT_EQ(0U, Vec.count()); EXPECT_FALSE(Vec.test(17)); Vec.set(5); EXPECT_TRUE(Vec.test(5)); EXPECT_FALSE(Vec.test(17)); Vec.reset(6); EXPECT_TRUE(Vec.test(5)); EXPECT_FALSE(Vec.test(6)); Vec.reset(5); EXPECT_FALSE(Vec.test(5)); EXPECT_TRUE(Vec.test_and_set(17)); EXPECT_FALSE(Vec.test_and_set(17)); EXPECT_TRUE(Vec.test(17)); Vec.clear(); EXPECT_FALSE(Vec.test(17)); } }
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/ADT/IntervalMapTest.cpp
//===---- ADT/IntervalMapTest.cpp - IntervalMap unit tests ------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/ADT/IntervalMap.h" #include "gtest/gtest.h" using namespace llvm; namespace { typedef IntervalMap<unsigned, unsigned, 4> UUMap; // Empty map tests TEST(IntervalMapTest, EmptyMap) { UUMap::Allocator allocator; UUMap map(allocator); EXPECT_TRUE(map.empty()); // Lookup on empty map. EXPECT_EQ(0u, map.lookup(0)); EXPECT_EQ(7u, map.lookup(0, 7)); EXPECT_EQ(0u, map.lookup(~0u-1)); EXPECT_EQ(7u, map.lookup(~0u-1, 7)); // Iterators. EXPECT_TRUE(map.begin() == map.begin()); EXPECT_TRUE(map.begin() == map.end()); EXPECT_TRUE(map.end() == map.end()); EXPECT_FALSE(map.begin() != map.begin()); EXPECT_FALSE(map.begin() != map.end()); EXPECT_FALSE(map.end() != map.end()); EXPECT_FALSE(map.begin().valid()); EXPECT_FALSE(map.end().valid()); UUMap::iterator I = map.begin(); EXPECT_FALSE(I.valid()); EXPECT_TRUE(I == map.end()); // Default constructor and cross-constness compares. UUMap::const_iterator CI; CI = map.begin(); EXPECT_TRUE(CI == I); UUMap::iterator I2; I2 = map.end(); EXPECT_TRUE(I2 == CI); } // Single entry map tests TEST(IntervalMapTest, SingleEntryMap) { UUMap::Allocator allocator; UUMap map(allocator); map.insert(100, 150, 1); EXPECT_FALSE(map.empty()); // Lookup around interval. EXPECT_EQ(0u, map.lookup(0)); EXPECT_EQ(0u, map.lookup(99)); EXPECT_EQ(1u, map.lookup(100)); EXPECT_EQ(1u, map.lookup(101)); EXPECT_EQ(1u, map.lookup(125)); EXPECT_EQ(1u, map.lookup(149)); EXPECT_EQ(1u, map.lookup(150)); EXPECT_EQ(0u, map.lookup(151)); EXPECT_EQ(0u, map.lookup(200)); EXPECT_EQ(0u, map.lookup(~0u-1)); // Iterators. EXPECT_TRUE(map.begin() == map.begin()); EXPECT_FALSE(map.begin() == map.end()); EXPECT_TRUE(map.end() == map.end()); EXPECT_TRUE(map.begin().valid()); EXPECT_FALSE(map.end().valid()); // Iter deref. UUMap::iterator I = map.begin(); ASSERT_TRUE(I.valid()); EXPECT_EQ(100u, I.start()); EXPECT_EQ(150u, I.stop()); EXPECT_EQ(1u, I.value()); // Preincrement. ++I; EXPECT_FALSE(I.valid()); EXPECT_FALSE(I == map.begin()); EXPECT_TRUE(I == map.end()); // PreDecrement. --I; ASSERT_TRUE(I.valid()); EXPECT_EQ(100u, I.start()); EXPECT_EQ(150u, I.stop()); EXPECT_EQ(1u, I.value()); EXPECT_TRUE(I == map.begin()); EXPECT_FALSE(I == map.end()); // Change the value. I.setValue(2); ASSERT_TRUE(I.valid()); EXPECT_EQ(100u, I.start()); EXPECT_EQ(150u, I.stop()); EXPECT_EQ(2u, I.value()); // Grow the bounds. I.setStart(0); ASSERT_TRUE(I.valid()); EXPECT_EQ(0u, I.start()); EXPECT_EQ(150u, I.stop()); EXPECT_EQ(2u, I.value()); I.setStop(200); ASSERT_TRUE(I.valid()); EXPECT_EQ(0u, I.start()); EXPECT_EQ(200u, I.stop()); EXPECT_EQ(2u, I.value()); // Shrink the bounds. I.setStart(150); ASSERT_TRUE(I.valid()); EXPECT_EQ(150u, I.start()); EXPECT_EQ(200u, I.stop()); EXPECT_EQ(2u, I.value()); I.setStop(160); ASSERT_TRUE(I.valid()); EXPECT_EQ(150u, I.start()); EXPECT_EQ(160u, I.stop()); EXPECT_EQ(2u, I.value()); // Erase last elem. I.erase(); EXPECT_TRUE(map.empty()); EXPECT_EQ(0, std::distance(map.begin(), map.end())); } // Flat coalescing tests. TEST(IntervalMapTest, RootCoalescing) { UUMap::Allocator allocator; UUMap map(allocator); map.insert(100, 150, 1); // Coalesce from the left. map.insert(90, 99, 1); EXPECT_EQ(1, std::distance(map.begin(), map.end())); EXPECT_EQ(90u, map.start()); EXPECT_EQ(150u, map.stop()); // Coalesce from the right. map.insert(151, 200, 1); EXPECT_EQ(1, std::distance(map.begin(), map.end())); EXPECT_EQ(90u, map.start()); EXPECT_EQ(200u, map.stop()); // Non-coalesce from the left. map.insert(60, 89, 2); EXPECT_EQ(2, std::distance(map.begin(), map.end())); EXPECT_EQ(60u, map.start()); EXPECT_EQ(200u, map.stop()); EXPECT_EQ(2u, map.lookup(89)); EXPECT_EQ(1u, map.lookup(90)); UUMap::iterator I = map.begin(); EXPECT_EQ(60u, I.start()); EXPECT_EQ(89u, I.stop()); EXPECT_EQ(2u, I.value()); ++I; EXPECT_EQ(90u, I.start()); EXPECT_EQ(200u, I.stop()); EXPECT_EQ(1u, I.value()); ++I; EXPECT_FALSE(I.valid()); // Non-coalesce from the right. map.insert(201, 210, 2); EXPECT_EQ(3, std::distance(map.begin(), map.end())); EXPECT_EQ(60u, map.start()); EXPECT_EQ(210u, map.stop()); EXPECT_EQ(2u, map.lookup(201)); EXPECT_EQ(1u, map.lookup(200)); // Erase from the left. map.begin().erase(); EXPECT_EQ(2, std::distance(map.begin(), map.end())); EXPECT_EQ(90u, map.start()); EXPECT_EQ(210u, map.stop()); // Erase from the right. (--map.end()).erase(); EXPECT_EQ(1, std::distance(map.begin(), map.end())); EXPECT_EQ(90u, map.start()); EXPECT_EQ(200u, map.stop()); // Add non-coalescing, then trigger coalescing with setValue. map.insert(80, 89, 2); map.insert(201, 210, 2); EXPECT_EQ(3, std::distance(map.begin(), map.end())); (++map.begin()).setValue(2); EXPECT_EQ(1, std::distance(map.begin(), map.end())); I = map.begin(); ASSERT_TRUE(I.valid()); EXPECT_EQ(80u, I.start()); EXPECT_EQ(210u, I.stop()); EXPECT_EQ(2u, I.value()); } // Flat multi-coalescing tests. TEST(IntervalMapTest, RootMultiCoalescing) { UUMap::Allocator allocator; UUMap map(allocator); map.insert(140, 150, 1); map.insert(160, 170, 1); map.insert(100, 110, 1); map.insert(120, 130, 1); EXPECT_EQ(4, std::distance(map.begin(), map.end())); EXPECT_EQ(100u, map.start()); EXPECT_EQ(170u, map.stop()); // Verify inserts. UUMap::iterator I = map.begin(); EXPECT_EQ(100u, I.start()); EXPECT_EQ(110u, I.stop()); ++I; EXPECT_EQ(120u, I.start()); EXPECT_EQ(130u, I.stop()); ++I; EXPECT_EQ(140u, I.start()); EXPECT_EQ(150u, I.stop()); ++I; EXPECT_EQ(160u, I.start()); EXPECT_EQ(170u, I.stop()); ++I; EXPECT_FALSE(I.valid()); // Test advanceTo on flat tree. I = map.begin(); I.advanceTo(135); ASSERT_TRUE(I.valid()); EXPECT_EQ(140u, I.start()); EXPECT_EQ(150u, I.stop()); I.advanceTo(145); ASSERT_TRUE(I.valid()); EXPECT_EQ(140u, I.start()); EXPECT_EQ(150u, I.stop()); I.advanceTo(200); EXPECT_FALSE(I.valid()); I.advanceTo(300); EXPECT_FALSE(I.valid()); // Coalesce left with followers. // [100;110] [120;130] [140;150] [160;170] map.insert(111, 115, 1); I = map.begin(); ASSERT_TRUE(I.valid()); EXPECT_EQ(100u, I.start()); EXPECT_EQ(115u, I.stop()); ++I; ASSERT_TRUE(I.valid()); EXPECT_EQ(120u, I.start()); EXPECT_EQ(130u, I.stop()); ++I; ASSERT_TRUE(I.valid()); EXPECT_EQ(140u, I.start()); EXPECT_EQ(150u, I.stop()); ++I; ASSERT_TRUE(I.valid()); EXPECT_EQ(160u, I.start()); EXPECT_EQ(170u, I.stop()); ++I; EXPECT_FALSE(I.valid()); // Coalesce right with followers. // [100;115] [120;130] [140;150] [160;170] map.insert(135, 139, 1); I = map.begin(); ASSERT_TRUE(I.valid()); EXPECT_EQ(100u, I.start()); EXPECT_EQ(115u, I.stop()); ++I; ASSERT_TRUE(I.valid()); EXPECT_EQ(120u, I.start()); EXPECT_EQ(130u, I.stop()); ++I; ASSERT_TRUE(I.valid()); EXPECT_EQ(135u, I.start()); EXPECT_EQ(150u, I.stop()); ++I; ASSERT_TRUE(I.valid()); EXPECT_EQ(160u, I.start()); EXPECT_EQ(170u, I.stop()); ++I; EXPECT_FALSE(I.valid()); // Coalesce left and right with followers. // [100;115] [120;130] [135;150] [160;170] map.insert(131, 134, 1); I = map.begin(); ASSERT_TRUE(I.valid()); EXPECT_EQ(100u, I.start()); EXPECT_EQ(115u, I.stop()); ++I; ASSERT_TRUE(I.valid()); EXPECT_EQ(120u, I.start()); EXPECT_EQ(150u, I.stop()); ++I; ASSERT_TRUE(I.valid()); EXPECT_EQ(160u, I.start()); EXPECT_EQ(170u, I.stop()); ++I; EXPECT_FALSE(I.valid()); // Test clear() on non-branched map. map.clear(); EXPECT_TRUE(map.empty()); EXPECT_TRUE(map.begin() == map.end()); } // Branched, non-coalescing tests. TEST(IntervalMapTest, Branched) { UUMap::Allocator allocator; UUMap map(allocator); // Insert enough intervals to force a branched tree. // This creates 9 leaf nodes with 11 elements each, tree height = 1. for (unsigned i = 1; i < 100; ++i) { map.insert(10*i, 10*i+5, i); EXPECT_EQ(10u, map.start()); EXPECT_EQ(10*i+5, map.stop()); } // Tree limits. EXPECT_FALSE(map.empty()); EXPECT_EQ(10u, map.start()); EXPECT_EQ(995u, map.stop()); // Tree lookup. for (unsigned i = 1; i < 100; ++i) { EXPECT_EQ(0u, map.lookup(10*i-1)); EXPECT_EQ(i, map.lookup(10*i)); EXPECT_EQ(i, map.lookup(10*i+5)); EXPECT_EQ(0u, map.lookup(10*i+6)); } // Forward iteration. UUMap::iterator I = map.begin(); for (unsigned i = 1; i < 100; ++i) { ASSERT_TRUE(I.valid()); EXPECT_EQ(10*i, I.start()); EXPECT_EQ(10*i+5, I.stop()); EXPECT_EQ(i, *I); ++I; } EXPECT_FALSE(I.valid()); EXPECT_TRUE(I == map.end()); // Backwards iteration. for (unsigned i = 99; i; --i) { --I; ASSERT_TRUE(I.valid()); EXPECT_EQ(10*i, I.start()); EXPECT_EQ(10*i+5, I.stop()); EXPECT_EQ(i, *I); } EXPECT_TRUE(I == map.begin()); // Test advanceTo in same node. I.advanceTo(20); ASSERT_TRUE(I.valid()); EXPECT_EQ(20u, I.start()); EXPECT_EQ(25u, I.stop()); // Change value, no coalescing. I.setValue(0); ASSERT_TRUE(I.valid()); EXPECT_EQ(20u, I.start()); EXPECT_EQ(25u, I.stop()); EXPECT_EQ(0u, I.value()); // Close the gap right, no coalescing. I.setStop(29); ASSERT_TRUE(I.valid()); EXPECT_EQ(20u, I.start()); EXPECT_EQ(29u, I.stop()); EXPECT_EQ(0u, I.value()); // Change value, no coalescing. I.setValue(2); ASSERT_TRUE(I.valid()); EXPECT_EQ(20u, I.start()); EXPECT_EQ(29u, I.stop()); EXPECT_EQ(2u, I.value()); // Change value, now coalescing. I.setValue(3); ASSERT_TRUE(I.valid()); EXPECT_EQ(20u, I.start()); EXPECT_EQ(35u, I.stop()); EXPECT_EQ(3u, I.value()); // Close the gap, now coalescing. I.setValue(4); ASSERT_TRUE(I.valid()); I.setStop(39); ASSERT_TRUE(I.valid()); EXPECT_EQ(20u, I.start()); EXPECT_EQ(45u, I.stop()); EXPECT_EQ(4u, I.value()); // advanceTo another node. I.advanceTo(200); ASSERT_TRUE(I.valid()); EXPECT_EQ(200u, I.start()); EXPECT_EQ(205u, I.stop()); // Close the gap left, no coalescing. I.setStart(196); ASSERT_TRUE(I.valid()); EXPECT_EQ(196u, I.start()); EXPECT_EQ(205u, I.stop()); EXPECT_EQ(20u, I.value()); // Change value, no coalescing. I.setValue(0); ASSERT_TRUE(I.valid()); EXPECT_EQ(196u, I.start()); EXPECT_EQ(205u, I.stop()); EXPECT_EQ(0u, I.value()); // Change value, now coalescing. I.setValue(19); ASSERT_TRUE(I.valid()); EXPECT_EQ(190u, I.start()); EXPECT_EQ(205u, I.stop()); EXPECT_EQ(19u, I.value()); // Close the gap, now coalescing. I.setValue(18); ASSERT_TRUE(I.valid()); I.setStart(186); ASSERT_TRUE(I.valid()); EXPECT_EQ(180u, I.start()); EXPECT_EQ(205u, I.stop()); EXPECT_EQ(18u, I.value()); // Erase from the front. I = map.begin(); for (unsigned i = 0; i != 20; ++i) { I.erase(); EXPECT_TRUE(I == map.begin()); EXPECT_FALSE(map.empty()); EXPECT_EQ(I.start(), map.start()); EXPECT_EQ(995u, map.stop()); } // Test clear() on branched map. map.clear(); EXPECT_TRUE(map.empty()); EXPECT_TRUE(map.begin() == map.end()); } // Branched, high, non-coalescing tests. TEST(IntervalMapTest, Branched2) { UUMap::Allocator allocator; UUMap map(allocator); // Insert enough intervals to force a height >= 2 tree. for (unsigned i = 1; i < 1000; ++i) map.insert(10*i, 10*i+5, i); // Tree limits. EXPECT_FALSE(map.empty()); EXPECT_EQ(10u, map.start()); EXPECT_EQ(9995u, map.stop()); // Tree lookup. for (unsigned i = 1; i < 1000; ++i) { EXPECT_EQ(0u, map.lookup(10*i-1)); EXPECT_EQ(i, map.lookup(10*i)); EXPECT_EQ(i, map.lookup(10*i+5)); EXPECT_EQ(0u, map.lookup(10*i+6)); } // Forward iteration. UUMap::iterator I = map.begin(); for (unsigned i = 1; i < 1000; ++i) { ASSERT_TRUE(I.valid()); EXPECT_EQ(10*i, I.start()); EXPECT_EQ(10*i+5, I.stop()); EXPECT_EQ(i, *I); ++I; } EXPECT_FALSE(I.valid()); EXPECT_TRUE(I == map.end()); // Backwards iteration. for (unsigned i = 999; i; --i) { --I; ASSERT_TRUE(I.valid()); EXPECT_EQ(10*i, I.start()); EXPECT_EQ(10*i+5, I.stop()); EXPECT_EQ(i, *I); } EXPECT_TRUE(I == map.begin()); // Test advanceTo in same node. I.advanceTo(20); ASSERT_TRUE(I.valid()); EXPECT_EQ(20u, I.start()); EXPECT_EQ(25u, I.stop()); // advanceTo sibling leaf node. I.advanceTo(200); ASSERT_TRUE(I.valid()); EXPECT_EQ(200u, I.start()); EXPECT_EQ(205u, I.stop()); // advanceTo further. I.advanceTo(2000); ASSERT_TRUE(I.valid()); EXPECT_EQ(2000u, I.start()); EXPECT_EQ(2005u, I.stop()); // advanceTo beyond end() I.advanceTo(20000); EXPECT_FALSE(I.valid()); // end().advanceTo() is valid as long as x > map.stop() I.advanceTo(30000); EXPECT_FALSE(I.valid()); // Test clear() on branched map. map.clear(); EXPECT_TRUE(map.empty()); EXPECT_TRUE(map.begin() == map.end()); } // Random insertions, coalescing to a single interval. TEST(IntervalMapTest, RandomCoalescing) { UUMap::Allocator allocator; UUMap map(allocator); // This is a poor PRNG with maximal period: // x_n = 5 x_{n-1} + 1 mod 2^N unsigned x = 100; for (unsigned i = 0; i != 4096; ++i) { map.insert(10*x, 10*x+9, 1); EXPECT_GE(10*x, map.start()); EXPECT_LE(10*x+9, map.stop()); x = (5*x+1)%4096; } // Map should be fully coalesced after that exercise. EXPECT_FALSE(map.empty()); EXPECT_EQ(0u, map.start()); EXPECT_EQ(40959u, map.stop()); EXPECT_EQ(1, std::distance(map.begin(), map.end())); } TEST(IntervalMapOverlapsTest, SmallMaps) { typedef IntervalMapOverlaps<UUMap,UUMap> UUOverlaps; UUMap::Allocator allocator; UUMap mapA(allocator); UUMap mapB(allocator); // empty, empty. EXPECT_FALSE(UUOverlaps(mapA, mapB).valid()); mapA.insert(1, 2, 3); // full, empty EXPECT_FALSE(UUOverlaps(mapA, mapB).valid()); // empty, full EXPECT_FALSE(UUOverlaps(mapB, mapA).valid()); mapB.insert(3, 4, 5); // full, full, non-overlapping EXPECT_FALSE(UUOverlaps(mapA, mapB).valid()); EXPECT_FALSE(UUOverlaps(mapB, mapA).valid()); // Add an overlapping segment. mapA.insert(4, 5, 6); UUOverlaps AB(mapA, mapB); ASSERT_TRUE(AB.valid()); EXPECT_EQ(4u, AB.a().start()); EXPECT_EQ(3u, AB.b().start()); ++AB; EXPECT_FALSE(AB.valid()); UUOverlaps BA(mapB, mapA); ASSERT_TRUE(BA.valid()); EXPECT_EQ(3u, BA.a().start()); EXPECT_EQ(4u, BA.b().start()); // advance past end. BA.advanceTo(6); EXPECT_FALSE(BA.valid()); // advance an invalid iterator. BA.advanceTo(7); EXPECT_FALSE(BA.valid()); } TEST(IntervalMapOverlapsTest, BigMaps) { typedef IntervalMapOverlaps<UUMap,UUMap> UUOverlaps; UUMap::Allocator allocator; UUMap mapA(allocator); UUMap mapB(allocator); // [0;4] [10;14] [20;24] ... for (unsigned n = 0; n != 100; ++n) mapA.insert(10*n, 10*n+4, n); // [5;6] [15;16] [25;26] ... for (unsigned n = 10; n != 20; ++n) mapB.insert(10*n+5, 10*n+6, n); // [208;209] [218;219] ... for (unsigned n = 20; n != 30; ++n) mapB.insert(10*n+8, 10*n+9, n); // insert some overlapping segments. mapB.insert(400, 400, 400); mapB.insert(401, 401, 401); mapB.insert(402, 500, 402); mapB.insert(600, 601, 402); UUOverlaps AB(mapA, mapB); ASSERT_TRUE(AB.valid()); EXPECT_EQ(400u, AB.a().start()); EXPECT_EQ(400u, AB.b().start()); ++AB; ASSERT_TRUE(AB.valid()); EXPECT_EQ(400u, AB.a().start()); EXPECT_EQ(401u, AB.b().start()); ++AB; ASSERT_TRUE(AB.valid()); EXPECT_EQ(400u, AB.a().start()); EXPECT_EQ(402u, AB.b().start()); ++AB; ASSERT_TRUE(AB.valid()); EXPECT_EQ(410u, AB.a().start()); EXPECT_EQ(402u, AB.b().start()); ++AB; ASSERT_TRUE(AB.valid()); EXPECT_EQ(420u, AB.a().start()); EXPECT_EQ(402u, AB.b().start()); AB.skipB(); ASSERT_TRUE(AB.valid()); EXPECT_EQ(600u, AB.a().start()); EXPECT_EQ(600u, AB.b().start()); ++AB; EXPECT_FALSE(AB.valid()); // Test advanceTo. UUOverlaps AB2(mapA, mapB); AB2.advanceTo(410); ASSERT_TRUE(AB2.valid()); EXPECT_EQ(410u, AB2.a().start()); EXPECT_EQ(402u, AB2.b().start()); // It is valid to advanceTo with any monotonic sequence. AB2.advanceTo(411); ASSERT_TRUE(AB2.valid()); EXPECT_EQ(410u, AB2.a().start()); EXPECT_EQ(402u, AB2.b().start()); // Check reversed maps. UUOverlaps BA(mapB, mapA); ASSERT_TRUE(BA.valid()); EXPECT_EQ(400u, BA.b().start()); EXPECT_EQ(400u, BA.a().start()); ++BA; ASSERT_TRUE(BA.valid()); EXPECT_EQ(400u, BA.b().start()); EXPECT_EQ(401u, BA.a().start()); ++BA; ASSERT_TRUE(BA.valid()); EXPECT_EQ(400u, BA.b().start()); EXPECT_EQ(402u, BA.a().start()); ++BA; ASSERT_TRUE(BA.valid()); EXPECT_EQ(410u, BA.b().start()); EXPECT_EQ(402u, BA.a().start()); ++BA; ASSERT_TRUE(BA.valid()); EXPECT_EQ(420u, BA.b().start()); EXPECT_EQ(402u, BA.a().start()); BA.skipA(); ASSERT_TRUE(BA.valid()); EXPECT_EQ(600u, BA.b().start()); EXPECT_EQ(600u, BA.a().start()); ++BA; EXPECT_FALSE(BA.valid()); // Test advanceTo. UUOverlaps BA2(mapB, mapA); BA2.advanceTo(410); ASSERT_TRUE(BA2.valid()); EXPECT_EQ(410u, BA2.b().start()); EXPECT_EQ(402u, BA2.a().start()); BA2.advanceTo(411); ASSERT_TRUE(BA2.valid()); EXPECT_EQ(410u, BA2.b().start()); EXPECT_EQ(402u, BA2.a().start()); } } // namespace
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/ADT/RangeAdapterTest.cpp
//===- RangeAdapterTest.cpp - Unit tests for range adapters --------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/iterator_range.h" #include "gtest/gtest.h" #include <iterator> #include <list> #include <vector> using namespace llvm; namespace { // A wrapper around vector which exposes rbegin(), rend(). class ReverseOnlyVector { std::vector<int> Vec; public: ReverseOnlyVector(std::initializer_list<int> list) : Vec(list) {} typedef std::vector<int>::reverse_iterator reverse_iterator; typedef std::vector<int>::const_reverse_iterator const_reverse_iterator; reverse_iterator rbegin() { return Vec.rbegin(); } reverse_iterator rend() { return Vec.rend(); } const_reverse_iterator rbegin() const { return Vec.rbegin(); } const_reverse_iterator rend() const { return Vec.rend(); } }; // A wrapper around vector which exposes begin(), end(), rbegin() and rend(). // begin() and end() don't have implementations as this ensures that we will // get a linker error if reverse() chooses begin()/end() over rbegin(), rend(). class BidirectionalVector { mutable std::vector<int> Vec; public: BidirectionalVector(std::initializer_list<int> list) : Vec(list) {} typedef std::vector<int>::iterator iterator; iterator begin() const; iterator end() const; typedef std::vector<int>::reverse_iterator reverse_iterator; reverse_iterator rbegin() const { return Vec.rbegin(); } reverse_iterator rend() const { return Vec.rend(); } }; /// This is the same as BidirectionalVector but with the addition of const /// begin/rbegin methods to ensure that the type traits for has_rbegin works. class BidirectionalVectorConsts { std::vector<int> Vec; public: BidirectionalVectorConsts(std::initializer_list<int> list) : Vec(list) {} typedef std::vector<int>::iterator iterator; typedef std::vector<int>::const_iterator const_iterator; iterator begin(); iterator end(); const_iterator begin() const; const_iterator end() const; typedef std::vector<int>::reverse_iterator reverse_iterator; typedef std::vector<int>::const_reverse_iterator const_reverse_iterator; reverse_iterator rbegin() { return Vec.rbegin(); } reverse_iterator rend() { return Vec.rend(); } const_reverse_iterator rbegin() const { return Vec.rbegin(); } const_reverse_iterator rend() const { return Vec.rend(); } }; /// Check that types with custom iterators work. class CustomIteratorVector { mutable std::vector<int> V; public: CustomIteratorVector(std::initializer_list<int> list) : V(list) {} typedef std::vector<int>::iterator iterator; class reverse_iterator { std::vector<int>::iterator I; public: reverse_iterator() = default; reverse_iterator(const reverse_iterator &) = default; reverse_iterator &operator=(const reverse_iterator &) = default; explicit reverse_iterator(std::vector<int>::iterator I) : I(I) {} reverse_iterator &operator++() { --I; return *this; } reverse_iterator &operator--() { ++I; return *this; } int &operator*() const { return *std::prev(I); } int *operator->() const { return &*std::prev(I); } friend bool operator==(const reverse_iterator &L, const reverse_iterator &R) { return L.I == R.I; } friend bool operator!=(const reverse_iterator &L, const reverse_iterator &R) { return !(L == R); } }; iterator begin() const { return V.begin(); } iterator end() const { return V.end(); } reverse_iterator rbegin() const { return reverse_iterator(V.end()); } reverse_iterator rend() const { return reverse_iterator(V.begin()); } }; template <typename R> void TestRev(const R &r) { int counter = 3; for (int i : r) EXPECT_EQ(i, counter--); } // Test fixture template <typename T> class RangeAdapterLValueTest : public ::testing::Test {}; typedef ::testing::Types<std::vector<int>, std::list<int>, int[4]> RangeAdapterLValueTestTypes; TYPED_TEST_CASE(RangeAdapterLValueTest, RangeAdapterLValueTestTypes); TYPED_TEST(RangeAdapterLValueTest, TrivialOperation) { TypeParam v = {0, 1, 2, 3}; TestRev(reverse(v)); const TypeParam c = {0, 1, 2, 3}; TestRev(reverse(c)); } template <typename T> struct RangeAdapterRValueTest : testing::Test {}; typedef ::testing::Types<std::vector<int>, std::list<int>, CustomIteratorVector, ReverseOnlyVector, BidirectionalVector, BidirectionalVectorConsts> RangeAdapterRValueTestTypes; TYPED_TEST_CASE(RangeAdapterRValueTest, RangeAdapterRValueTestTypes); TYPED_TEST(RangeAdapterRValueTest, TrivialOperation) { TestRev(reverse(TypeParam({0, 1, 2, 3}))); } TYPED_TEST(RangeAdapterRValueTest, HasRbegin) { static_assert(has_rbegin<TypeParam>::value, "rbegin() should be defined"); } TYPED_TEST(RangeAdapterRValueTest, RangeType) { static_assert( std::is_same< decltype(reverse(*static_cast<TypeParam *>(nullptr)).begin()), decltype(static_cast<TypeParam *>(nullptr)->rbegin())>::value, "reverse().begin() should have the same type as rbegin()"); static_assert( std::is_same< decltype(reverse(*static_cast<const TypeParam *>(nullptr)).begin()), decltype(static_cast<const TypeParam *>(nullptr)->rbegin())>::value, "reverse().begin() should have the same type as rbegin() [const]"); } } // anonymous namespace
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/ADT/DenseSetTest.cpp
//===- llvm/unittest/ADT/DenseSetTest.cpp - DenseSet unit tests --*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "gtest/gtest.h" #include "llvm/ADT/DenseSet.h" using namespace llvm; namespace { // Test fixture class DenseSetTest : public testing::Test { }; // Test hashing with a set of only two entries. TEST_F(DenseSetTest, DoubleEntrySetTest) { llvm::DenseSet<unsigned> set(2); set.insert(0); set.insert(1); // Original failure was an infinite loop in this call: EXPECT_EQ(0u, set.count(2)); } struct TestDenseSetInfo { static inline unsigned getEmptyKey() { return ~0; } static inline unsigned getTombstoneKey() { return ~0U - 1; } static unsigned getHashValue(const unsigned& Val) { return Val * 37U; } static unsigned getHashValue(const char* Val) { return (unsigned)(Val[0] - 'a') * 37U; } static bool isEqual(const unsigned& LHS, const unsigned& RHS) { return LHS == RHS; } static bool isEqual(const char* LHS, const unsigned& RHS) { return (unsigned)(LHS[0] - 'a') == RHS; } }; TEST(DenseSetCustomTest, FindAsTest) { DenseSet<unsigned, TestDenseSetInfo> set; set.insert(0); set.insert(1); set.insert(2); // Size tests EXPECT_EQ(3u, set.size()); // Normal lookup tests EXPECT_EQ(1u, set.count(1)); EXPECT_EQ(0u, *set.find(0)); EXPECT_EQ(1u, *set.find(1)); EXPECT_EQ(2u, *set.find(2)); EXPECT_TRUE(set.find(3) == set.end()); // find_as() tests EXPECT_EQ(0u, *set.find_as("a")); EXPECT_EQ(1u, *set.find_as("b")); EXPECT_EQ(2u, *set.find_as("c")); EXPECT_TRUE(set.find_as("d") == set.end()); } }
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/ADT/CMakeLists.txt
set(LLVM_LINK_COMPONENTS Support ) set(ADTSources APFloatTest.cpp APIntTest.cpp APSIntTest.cpp ArrayRefTest.cpp BitVectorTest.cpp DAGDeltaAlgorithmTest.cpp DeltaAlgorithmTest.cpp DenseMapTest.cpp DenseSetTest.cpp FoldingSet.cpp FunctionRefTest.cpp HashingTest.cpp ilistTest.cpp ImmutableMapTest.cpp ImmutableSetTest.cpp IntEqClassesTest.cpp IntervalMapTest.cpp IntrusiveRefCntPtrTest.cpp IteratorTest.cpp MakeUniqueTest.cpp MapVectorTest.cpp OptionalTest.cpp PackedVectorTest.cpp PointerIntPairTest.cpp PointerUnionTest.cpp PostOrderIteratorTest.cpp RangeAdapterTest.cpp SCCIteratorTest.cpp SmallPtrSetTest.cpp SmallStringTest.cpp SmallVectorTest.cpp SparseBitVectorTest.cpp SparseMultiSetTest.cpp SparseSetTest.cpp StringMapTest.cpp StringRefTest.cpp TinyPtrVectorTest.cpp TripleTest.cpp TwineTest.cpp VariadicFunctionTest.cpp ) add_llvm_unittest(ADTTests ${ADTSources} ) add_dependencies(ADTTests intrinsics_gen)
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/ADT/SmallStringTest.cpp
//===- llvm/unittest/ADT/SmallStringTest.cpp ------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // SmallString unit tests. // //===----------------------------------------------------------------------===// #include "llvm/ADT/SmallString.h" #include "gtest/gtest.h" #include <climits> #include <cstring> #include <stdarg.h> using namespace llvm; namespace { // Test fixture class class SmallStringTest : public testing::Test { protected: typedef SmallString<40> StringType; StringType theString; void assertEmpty(StringType & v) { // Size tests EXPECT_EQ(0u, v.size()); EXPECT_TRUE(v.empty()); // Iterator tests EXPECT_TRUE(v.begin() == v.end()); } }; // New string test. TEST_F(SmallStringTest, EmptyStringTest) { SCOPED_TRACE("EmptyStringTest"); assertEmpty(theString); EXPECT_TRUE(theString.rbegin() == theString.rend()); } TEST_F(SmallStringTest, AssignRepeated) { theString.assign(3, 'a'); EXPECT_EQ(3u, theString.size()); EXPECT_STREQ("aaa", theString.c_str()); } TEST_F(SmallStringTest, AssignIterPair) { StringRef abc = "abc"; theString.assign(abc.begin(), abc.end()); EXPECT_EQ(3u, theString.size()); EXPECT_STREQ("abc", theString.c_str()); } TEST_F(SmallStringTest, AssignStringRef) { StringRef abc = "abc"; theString.assign(abc); EXPECT_EQ(3u, theString.size()); EXPECT_STREQ("abc", theString.c_str()); } TEST_F(SmallStringTest, AssignSmallVector) { StringRef abc = "abc"; SmallVector<char, 10> abcVec(abc.begin(), abc.end()); theString.assign(abcVec); EXPECT_EQ(3u, theString.size()); EXPECT_STREQ("abc", theString.c_str()); } TEST_F(SmallStringTest, AppendIterPair) { StringRef abc = "abc"; theString.append(abc.begin(), abc.end()); theString.append(abc.begin(), abc.end()); EXPECT_EQ(6u, theString.size()); EXPECT_STREQ("abcabc", theString.c_str()); } TEST_F(SmallStringTest, AppendStringRef) { StringRef abc = "abc"; theString.append(abc); theString.append(abc); EXPECT_EQ(6u, theString.size()); EXPECT_STREQ("abcabc", theString.c_str()); } TEST_F(SmallStringTest, AppendSmallVector) { StringRef abc = "abc"; SmallVector<char, 10> abcVec(abc.begin(), abc.end()); theString.append(abcVec); theString.append(abcVec); EXPECT_EQ(6u, theString.size()); EXPECT_STREQ("abcabc", theString.c_str()); } TEST_F(SmallStringTest, Substr) { theString = "hello"; EXPECT_EQ("lo", theString.substr(3)); EXPECT_EQ("", theString.substr(100)); EXPECT_EQ("hello", theString.substr(0, 100)); EXPECT_EQ("o", theString.substr(4, 10)); } TEST_F(SmallStringTest, Slice) { theString = "hello"; EXPECT_EQ("l", theString.slice(2, 3)); EXPECT_EQ("ell", theString.slice(1, 4)); EXPECT_EQ("llo", theString.slice(2, 100)); EXPECT_EQ("", theString.slice(2, 1)); EXPECT_EQ("", theString.slice(10, 20)); } TEST_F(SmallStringTest, Find) { theString = "hello"; EXPECT_EQ(2U, theString.find('l')); EXPECT_EQ(StringRef::npos, theString.find('z')); EXPECT_EQ(StringRef::npos, theString.find("helloworld")); EXPECT_EQ(0U, theString.find("hello")); EXPECT_EQ(1U, theString.find("ello")); EXPECT_EQ(StringRef::npos, theString.find("zz")); EXPECT_EQ(2U, theString.find("ll", 2)); EXPECT_EQ(StringRef::npos, theString.find("ll", 3)); EXPECT_EQ(0U, theString.find("")); EXPECT_EQ(3U, theString.rfind('l')); EXPECT_EQ(StringRef::npos, theString.rfind('z')); EXPECT_EQ(StringRef::npos, theString.rfind("helloworld")); EXPECT_EQ(0U, theString.rfind("hello")); EXPECT_EQ(1U, theString.rfind("ello")); EXPECT_EQ(StringRef::npos, theString.rfind("zz")); EXPECT_EQ(2U, theString.find_first_of('l')); EXPECT_EQ(1U, theString.find_first_of("el")); EXPECT_EQ(StringRef::npos, theString.find_first_of("xyz")); EXPECT_EQ(1U, theString.find_first_not_of('h')); EXPECT_EQ(4U, theString.find_first_not_of("hel")); EXPECT_EQ(StringRef::npos, theString.find_first_not_of("hello")); theString = "hellx xello hell ello world foo bar hello"; EXPECT_EQ(36U, theString.find("hello")); EXPECT_EQ(28U, theString.find("foo")); EXPECT_EQ(12U, theString.find("hell", 2)); EXPECT_EQ(0U, theString.find("")); } TEST_F(SmallStringTest, Count) { theString = "hello"; EXPECT_EQ(2U, theString.count('l')); EXPECT_EQ(1U, theString.count('o')); EXPECT_EQ(0U, theString.count('z')); EXPECT_EQ(0U, theString.count("helloworld")); EXPECT_EQ(1U, theString.count("hello")); EXPECT_EQ(1U, theString.count("ello")); EXPECT_EQ(0U, theString.count("zz")); } TEST(StringRefTest, Comparisons) { EXPECT_EQ(-1, SmallString<10>("aab").compare("aad")); EXPECT_EQ( 0, SmallString<10>("aab").compare("aab")); EXPECT_EQ( 1, SmallString<10>("aab").compare("aaa")); EXPECT_EQ(-1, SmallString<10>("aab").compare("aabb")); EXPECT_EQ( 1, SmallString<10>("aab").compare("aa")); EXPECT_EQ( 1, SmallString<10>("\xFF").compare("\1")); EXPECT_EQ(-1, SmallString<10>("AaB").compare_lower("aAd")); EXPECT_EQ( 0, SmallString<10>("AaB").compare_lower("aab")); EXPECT_EQ( 1, SmallString<10>("AaB").compare_lower("AAA")); EXPECT_EQ(-1, SmallString<10>("AaB").compare_lower("aaBb")); EXPECT_EQ( 1, SmallString<10>("AaB").compare_lower("aA")); EXPECT_EQ( 1, SmallString<10>("\xFF").compare_lower("\1")); EXPECT_EQ(-1, SmallString<10>("aab").compare_numeric("aad")); EXPECT_EQ( 0, SmallString<10>("aab").compare_numeric("aab")); EXPECT_EQ( 1, SmallString<10>("aab").compare_numeric("aaa")); EXPECT_EQ(-1, SmallString<10>("aab").compare_numeric("aabb")); EXPECT_EQ( 1, SmallString<10>("aab").compare_numeric("aa")); EXPECT_EQ(-1, SmallString<10>("1").compare_numeric("10")); EXPECT_EQ( 0, SmallString<10>("10").compare_numeric("10")); EXPECT_EQ( 0, SmallString<10>("10a").compare_numeric("10a")); EXPECT_EQ( 1, SmallString<10>("2").compare_numeric("1")); EXPECT_EQ( 0, SmallString<10>("llvm_v1i64_ty").compare_numeric("llvm_v1i64_ty")); EXPECT_EQ( 1, SmallString<10>("\xFF").compare_numeric("\1")); EXPECT_EQ( 1, SmallString<10>("V16").compare_numeric("V1_q0")); EXPECT_EQ(-1, SmallString<10>("V1_q0").compare_numeric("V16")); EXPECT_EQ(-1, SmallString<10>("V8_q0").compare_numeric("V16")); EXPECT_EQ( 1, SmallString<10>("V16").compare_numeric("V8_q0")); EXPECT_EQ(-1, SmallString<10>("V1_q0").compare_numeric("V8_q0")); EXPECT_EQ( 1, SmallString<10>("V8_q0").compare_numeric("V1_q0")); } }
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/ADT/SparseSetTest.cpp
//===------ ADT/SparseSetTest.cpp - SparseSet unit tests - -----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/ADT/SparseSet.h" #include "gtest/gtest.h" using namespace llvm; namespace { typedef SparseSet<unsigned> USet; // Empty set tests. TEST(SparseSetTest, EmptySet) { USet Set; EXPECT_TRUE(Set.empty()); EXPECT_TRUE(Set.begin() == Set.end()); EXPECT_EQ(0u, Set.size()); Set.setUniverse(10); // Lookups on empty set. EXPECT_TRUE(Set.find(0) == Set.end()); EXPECT_TRUE(Set.find(9) == Set.end()); // Same thing on a const reference. const USet &CSet = Set; EXPECT_TRUE(CSet.empty()); EXPECT_TRUE(CSet.begin() == CSet.end()); EXPECT_EQ(0u, CSet.size()); EXPECT_TRUE(CSet.find(0) == CSet.end()); USet::const_iterator I = CSet.find(5); EXPECT_TRUE(I == CSet.end()); } // Single entry set tests. TEST(SparseSetTest, SingleEntrySet) { USet Set; Set.setUniverse(10); std::pair<USet::iterator, bool> IP = Set.insert(5); EXPECT_TRUE(IP.second); EXPECT_TRUE(IP.first == Set.begin()); EXPECT_FALSE(Set.empty()); EXPECT_FALSE(Set.begin() == Set.end()); EXPECT_TRUE(Set.begin() + 1 == Set.end()); EXPECT_EQ(1u, Set.size()); EXPECT_TRUE(Set.find(0) == Set.end()); EXPECT_TRUE(Set.find(9) == Set.end()); EXPECT_FALSE(Set.count(0)); EXPECT_TRUE(Set.count(5)); // Redundant insert. IP = Set.insert(5); EXPECT_FALSE(IP.second); EXPECT_TRUE(IP.first == Set.begin()); // Erase non-existent element. EXPECT_FALSE(Set.erase(1)); EXPECT_EQ(1u, Set.size()); EXPECT_EQ(5u, *Set.begin()); // Erase iterator. USet::iterator I = Set.find(5); EXPECT_TRUE(I == Set.begin()); I = Set.erase(I); EXPECT_TRUE(I == Set.end()); EXPECT_TRUE(Set.empty()); } // Multiple entry set tests. TEST(SparseSetTest, MultipleEntrySet) { USet Set; Set.setUniverse(10); Set.insert(5); Set.insert(3); Set.insert(2); Set.insert(1); Set.insert(4); EXPECT_EQ(5u, Set.size()); // Without deletions, iteration order == insertion order. USet::const_iterator I = Set.begin(); EXPECT_EQ(5u, *I); ++I; EXPECT_EQ(3u, *I); ++I; EXPECT_EQ(2u, *I); ++I; EXPECT_EQ(1u, *I); ++I; EXPECT_EQ(4u, *I); ++I; EXPECT_TRUE(I == Set.end()); // Redundant insert. std::pair<USet::iterator, bool> IP = Set.insert(3); EXPECT_FALSE(IP.second); EXPECT_TRUE(IP.first == Set.begin() + 1); // Erase last element by key. EXPECT_TRUE(Set.erase(4)); EXPECT_EQ(4u, Set.size()); EXPECT_FALSE(Set.count(4)); EXPECT_FALSE(Set.erase(4)); EXPECT_EQ(4u, Set.size()); EXPECT_FALSE(Set.count(4)); // Erase first element by key. EXPECT_TRUE(Set.count(5)); EXPECT_TRUE(Set.find(5) == Set.begin()); EXPECT_TRUE(Set.erase(5)); EXPECT_EQ(3u, Set.size()); EXPECT_FALSE(Set.count(5)); EXPECT_FALSE(Set.erase(5)); EXPECT_EQ(3u, Set.size()); EXPECT_FALSE(Set.count(5)); Set.insert(6); Set.insert(7); EXPECT_EQ(5u, Set.size()); // Erase last element by iterator. I = Set.erase(Set.end() - 1); EXPECT_TRUE(I == Set.end()); EXPECT_EQ(4u, Set.size()); // Erase second element by iterator. I = Set.erase(Set.begin() + 1); EXPECT_TRUE(I == Set.begin() + 1); // Clear and resize the universe. Set.clear(); EXPECT_FALSE(Set.count(5)); Set.setUniverse(1000); // Add more than 256 elements. for (unsigned i = 100; i != 800; ++i) Set.insert(i); for (unsigned i = 0; i != 10; ++i) Set.erase(i); for (unsigned i = 100; i != 800; ++i) EXPECT_TRUE(Set.count(i)); EXPECT_FALSE(Set.count(99)); EXPECT_FALSE(Set.count(800)); EXPECT_EQ(700u, Set.size()); } struct Alt { unsigned Value; explicit Alt(unsigned x) : Value(x) {} unsigned getSparseSetIndex() const { return Value - 1000; } }; TEST(SparseSetTest, AltStructSet) { typedef SparseSet<Alt> ASet; ASet Set; Set.setUniverse(10); Set.insert(Alt(1005)); ASet::iterator I = Set.find(5); ASSERT_TRUE(I == Set.begin()); EXPECT_EQ(1005u, I->Value); Set.insert(Alt(1006)); Set.insert(Alt(1006)); I = Set.erase(Set.begin()); ASSERT_TRUE(I == Set.begin()); EXPECT_EQ(1006u, I->Value); EXPECT_FALSE(Set.erase(5)); EXPECT_TRUE(Set.erase(6)); } } // namespace
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/ADT/HashingTest.cpp
//===- llvm/unittest/ADT/HashingTest.cpp ----------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Hashing.h unit tests. // //===----------------------------------------------------------------------===// #include "gtest/gtest.h" #include "llvm/ADT/Hashing.h" #include "llvm/Support/DataTypes.h" #include <deque> #include <list> #include <map> #include <vector> namespace llvm { // Helper for test code to print hash codes. void PrintTo(const hash_code &code, std::ostream *os) { *os << static_cast<size_t>(code); } // Fake an object that is recognized as hashable data to test super large // objects. struct LargeTestInteger { uint64_t arr[8]; }; struct NonPOD { uint64_t x, y; NonPOD(uint64_t x, uint64_t y) : x(x), y(y) {} friend hash_code hash_value(const NonPOD &obj) { return hash_combine(obj.x, obj.y); } }; namespace hashing { namespace detail { template <> struct is_hashable_data<LargeTestInteger> : std::true_type {}; } // namespace detail } // namespace hashing } // namespace llvm using namespace llvm; namespace { enum TestEnumeration { TE_Foo = 42, TE_Bar = 43 }; TEST(HashingTest, HashValueBasicTest) { int x = 42, y = 43, c = 'x'; void *p = nullptr; uint64_t i = 71; const unsigned ci = 71; volatile int vi = 71; const volatile int cvi = 71; uintptr_t addr = reinterpret_cast<uintptr_t>(&y); EXPECT_EQ(hash_value(42), hash_value(x)); EXPECT_EQ(hash_value(42), hash_value(TE_Foo)); EXPECT_NE(hash_value(42), hash_value(y)); EXPECT_NE(hash_value(42), hash_value(TE_Bar)); EXPECT_NE(hash_value(42), hash_value(p)); EXPECT_EQ(hash_value(71), hash_value(i)); EXPECT_EQ(hash_value(71), hash_value(ci)); EXPECT_EQ(hash_value(71), hash_value(vi)); EXPECT_EQ(hash_value(71), hash_value(cvi)); EXPECT_EQ(hash_value(c), hash_value('x')); EXPECT_EQ(hash_value('4'), hash_value('0' + 4)); EXPECT_EQ(hash_value(addr), hash_value(&y)); } TEST(HashingTest, HashValueStdPair) { EXPECT_EQ(hash_combine(42, 43), hash_value(std::make_pair(42, 43))); EXPECT_NE(hash_combine(43, 42), hash_value(std::make_pair(42, 43))); EXPECT_NE(hash_combine(42, 43), hash_value(std::make_pair(42ull, 43ull))); EXPECT_NE(hash_combine(42, 43), hash_value(std::make_pair(42, 43ull))); EXPECT_NE(hash_combine(42, 43), hash_value(std::make_pair(42ull, 43))); // Note that pairs are implicitly flattened to a direct sequence of data and // hashed efficiently as a consequence. EXPECT_EQ(hash_combine(42, 43, 44), hash_value(std::make_pair(42, std::make_pair(43, 44)))); EXPECT_EQ(hash_value(std::make_pair(42, std::make_pair(43, 44))), hash_value(std::make_pair(std::make_pair(42, 43), 44))); // Ensure that pairs which have padding bytes *inside* them don't get treated // this way. EXPECT_EQ(hash_combine('0', hash_combine(1ull, '2')), hash_value(std::make_pair('0', std::make_pair(1ull, '2')))); // Ensure that non-POD pairs don't explode the traits used. NonPOD obj1(1, 2), obj2(3, 4), obj3(5, 6); EXPECT_EQ(hash_combine(obj1, hash_combine(obj2, obj3)), hash_value(std::make_pair(obj1, std::make_pair(obj2, obj3)))); } TEST(HashingTest, HashValueStdString) { std::string s = "Hello World!"; EXPECT_EQ(hash_combine_range(s.c_str(), s.c_str() + s.size()), hash_value(s)); EXPECT_EQ(hash_combine_range(s.c_str(), s.c_str() + s.size() - 1), hash_value(s.substr(0, s.size() - 1))); EXPECT_EQ(hash_combine_range(s.c_str() + 1, s.c_str() + s.size() - 1), hash_value(s.substr(1, s.size() - 2))); std::wstring ws = L"Hello Wide World!"; EXPECT_EQ(hash_combine_range(ws.c_str(), ws.c_str() + ws.size()), hash_value(ws)); EXPECT_EQ(hash_combine_range(ws.c_str(), ws.c_str() + ws.size() - 1), hash_value(ws.substr(0, ws.size() - 1))); EXPECT_EQ(hash_combine_range(ws.c_str() + 1, ws.c_str() + ws.size() - 1), hash_value(ws.substr(1, ws.size() - 2))); } template <typename T, size_t N> T *begin(T (&arr)[N]) { return arr; } template <typename T, size_t N> T *end(T (&arr)[N]) { return arr + N; } // Provide a dummy, hashable type designed for easy verification: its hash is // the same as its value. struct HashableDummy { size_t value; }; hash_code hash_value(HashableDummy dummy) { return dummy.value; } TEST(HashingTest, HashCombineRangeBasicTest) { // Leave this uninitialized in the hope that valgrind will catch bad reads. int dummy; hash_code dummy_hash = hash_combine_range(&dummy, &dummy); EXPECT_NE(hash_code(0), dummy_hash); const int arr1[] = { 1, 2, 3 }; hash_code arr1_hash = hash_combine_range(begin(arr1), end(arr1)); EXPECT_NE(dummy_hash, arr1_hash); EXPECT_EQ(arr1_hash, hash_combine_range(begin(arr1), end(arr1))); const std::vector<int> vec(begin(arr1), end(arr1)); EXPECT_EQ(arr1_hash, hash_combine_range(vec.begin(), vec.end())); const std::list<int> list(begin(arr1), end(arr1)); EXPECT_EQ(arr1_hash, hash_combine_range(list.begin(), list.end())); const std::deque<int> deque(begin(arr1), end(arr1)); EXPECT_EQ(arr1_hash, hash_combine_range(deque.begin(), deque.end())); const int arr2[] = { 3, 2, 1 }; hash_code arr2_hash = hash_combine_range(begin(arr2), end(arr2)); EXPECT_NE(dummy_hash, arr2_hash); EXPECT_NE(arr1_hash, arr2_hash); const int arr3[] = { 1, 1, 2, 3 }; hash_code arr3_hash = hash_combine_range(begin(arr3), end(arr3)); EXPECT_NE(dummy_hash, arr3_hash); EXPECT_NE(arr1_hash, arr3_hash); const int arr4[] = { 1, 2, 3, 3 }; hash_code arr4_hash = hash_combine_range(begin(arr4), end(arr4)); EXPECT_NE(dummy_hash, arr4_hash); EXPECT_NE(arr1_hash, arr4_hash); const size_t arr5[] = { 1, 2, 3 }; const HashableDummy d_arr5[] = { {1}, {2}, {3} }; hash_code arr5_hash = hash_combine_range(begin(arr5), end(arr5)); hash_code d_arr5_hash = hash_combine_range(begin(d_arr5), end(d_arr5)); EXPECT_EQ(arr5_hash, d_arr5_hash); } TEST(HashingTest, HashCombineRangeLengthDiff) { // Test that as only the length varies, we compute different hash codes for // sequences. std::map<size_t, size_t> code_to_size; std::vector<char> all_one_c(256, '\xff'); for (unsigned Idx = 1, Size = all_one_c.size(); Idx < Size; ++Idx) { hash_code code = hash_combine_range(&all_one_c[0], &all_one_c[0] + Idx); std::map<size_t, size_t>::iterator I = code_to_size.insert(std::make_pair(code, Idx)).first; EXPECT_EQ(Idx, I->second); } code_to_size.clear(); std::vector<char> all_zero_c(256, '\0'); for (unsigned Idx = 1, Size = all_zero_c.size(); Idx < Size; ++Idx) { hash_code code = hash_combine_range(&all_zero_c[0], &all_zero_c[0] + Idx); std::map<size_t, size_t>::iterator I = code_to_size.insert(std::make_pair(code, Idx)).first; EXPECT_EQ(Idx, I->second); } code_to_size.clear(); std::vector<unsigned> all_one_int(512, -1); for (unsigned Idx = 1, Size = all_one_int.size(); Idx < Size; ++Idx) { hash_code code = hash_combine_range(&all_one_int[0], &all_one_int[0] + Idx); std::map<size_t, size_t>::iterator I = code_to_size.insert(std::make_pair(code, Idx)).first; EXPECT_EQ(Idx, I->second); } code_to_size.clear(); std::vector<unsigned> all_zero_int(512, 0); for (unsigned Idx = 1, Size = all_zero_int.size(); Idx < Size; ++Idx) { hash_code code = hash_combine_range(&all_zero_int[0], &all_zero_int[0] + Idx); std::map<size_t, size_t>::iterator I = code_to_size.insert(std::make_pair(code, Idx)).first; EXPECT_EQ(Idx, I->second); } } TEST(HashingTest, HashCombineRangeGoldenTest) { struct { const char *s; uint64_t hash; } golden_data[] = { #if SIZE_MAX == UINT64_MAX { "a", 0xaeb6f9d5517c61f8ULL }, { "ab", 0x7ab1edb96be496b4ULL }, { "abc", 0xe38e60bf19c71a3fULL }, { "abcde", 0xd24461a66de97f6eULL }, { "abcdefgh", 0x4ef872ec411dec9dULL }, { "abcdefghijklm", 0xe8a865539f4eadfeULL }, { "abcdefghijklmnopqrstu", 0x261cdf85faaf4e79ULL }, { "abcdefghijklmnopqrstuvwxyzabcdef", 0x43ba70e4198e3b2aULL }, { "abcdefghijklmnopqrstuvwxyzabcdef" "abcdefghijklmnopqrstuvwxyzghijkl" "abcdefghijklmnopqrstuvwxyzmnopqr" "abcdefghijklmnopqrstuvwxyzstuvwx" "abcdefghijklmnopqrstuvwxyzyzabcd", 0xdcd57fb2afdf72beULL }, { "a", 0xaeb6f9d5517c61f8ULL }, { "aa", 0xf2b3b69a9736a1ebULL }, { "aaa", 0xf752eb6f07b1cafeULL }, { "aaaaa", 0x812bd21e1236954cULL }, { "aaaaaaaa", 0xff07a2cff08ac587ULL }, { "aaaaaaaaaaaaa", 0x84ac949d54d704ecULL }, { "aaaaaaaaaaaaaaaaaaaaa", 0xcb2c8fb6be8f5648ULL }, { "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 0xcc40ab7f164091b6ULL }, { "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 0xc58e174c1e78ffe9ULL }, { "z", 0x1ba160d7e8f8785cULL }, { "zz", 0x2c5c03172f1285d7ULL }, { "zzz", 0x9d2c4f4b507a2ac3ULL }, { "zzzzz", 0x0f03b9031735693aULL }, { "zzzzzzzz", 0xe674147c8582c08eULL }, { "zzzzzzzzzzzzz", 0x3162d9fa6938db83ULL }, { "zzzzzzzzzzzzzzzzzzzzz", 0x37b9a549e013620cULL }, { "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz", 0x8921470aff885016ULL }, { "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz", 0xf60fdcd9beb08441ULL }, { "a", 0xaeb6f9d5517c61f8ULL }, { "ab", 0x7ab1edb96be496b4ULL }, { "aba", 0x3edb049950884d0aULL }, { "ababa", 0x8f2de9e73a97714bULL }, { "abababab", 0xee14a29ddf0ce54cULL }, { "ababababababa", 0x38b3ddaada2d52b4ULL }, { "ababababababababababa", 0xd3665364219f2b85ULL }, { "abababababababababababababababab", 0xa75cd6afbf1bc972ULL }, { "abababababababababababababababab" "abababababababababababababababab" "abababababababababababababababab" "abababababababababababababababab" "abababababababababababababababab", 0x840192d129f7a22bULL } #elif SIZE_MAX == UINT32_MAX { "a", 0x000000004605f745ULL }, { "ab", 0x00000000d5f06301ULL }, { "abc", 0x00000000559fe1eeULL }, { "abcde", 0x00000000424028d7ULL }, { "abcdefgh", 0x000000007bb119f8ULL }, { "abcdefghijklm", 0x00000000edbca513ULL }, { "abcdefghijklmnopqrstu", 0x000000007c15712eULL }, { "abcdefghijklmnopqrstuvwxyzabcdef", 0x000000000b3aad66ULL }, { "abcdefghijklmnopqrstuvwxyzabcdef" "abcdefghijklmnopqrstuvwxyzghijkl" "abcdefghijklmnopqrstuvwxyzmnopqr" "abcdefghijklmnopqrstuvwxyzstuvwx" "abcdefghijklmnopqrstuvwxyzyzabcd", 0x000000008c758c8bULL }, { "a", 0x000000004605f745ULL }, { "aa", 0x00000000dc0a52daULL }, { "aaa", 0x00000000b309274fULL }, { "aaaaa", 0x00000000203b5ef6ULL }, { "aaaaaaaa", 0x00000000a429e18fULL }, { "aaaaaaaaaaaaa", 0x000000008662070bULL }, { "aaaaaaaaaaaaaaaaaaaaa", 0x000000003f11151cULL }, { "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 0x000000008600fe20ULL }, { "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 0x000000004e0e0804ULL }, { "z", 0x00000000c5e405e9ULL }, { "zz", 0x00000000a8d8a2c6ULL }, { "zzz", 0x00000000fc2af672ULL }, { "zzzzz", 0x0000000047d9efe6ULL }, { "zzzzzzzz", 0x0000000080d77794ULL }, { "zzzzzzzzzzzzz", 0x00000000405f93adULL }, { "zzzzzzzzzzzzzzzzzzzzz", 0x00000000fc72838dULL }, { "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz", 0x000000007ce160f1ULL }, { "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz", 0x00000000aed9ed1bULL }, { "a", 0x000000004605f745ULL }, { "ab", 0x00000000d5f06301ULL }, { "aba", 0x00000000a85cd91bULL }, { "ababa", 0x000000009e3bb52eULL }, { "abababab", 0x000000002709b3b9ULL }, { "ababababababa", 0x000000003a234174ULL }, { "ababababababababababa", 0x000000005c63e5ceULL }, { "abababababababababababababababab", 0x0000000013f74334ULL }, { "abababababababababababababababab" "abababababababababababababababab" "abababababababababababababababab" "abababababababababababababababab" "abababababababababababababababab", 0x00000000c1a6f135ULL }, #else #error This test only supports 64-bit and 32-bit systems. #endif }; for (unsigned i = 0; i < sizeof(golden_data)/sizeof(*golden_data); ++i) { StringRef str = golden_data[i].s; hash_code hash = hash_combine_range(str.begin(), str.end()); #if 0 // Enable this to generate paste-able text for the above structure. std::string member_str = "\"" + str.str() + "\","; fprintf(stderr, " { %-35s 0x%016llxULL },\n", member_str.c_str(), static_cast<uint64_t>(hash)); #endif EXPECT_EQ(static_cast<size_t>(golden_data[i].hash), static_cast<size_t>(hash)); } } TEST(HashingTest, HashCombineBasicTest) { // Hashing a sequence of homogenous types matches range hashing. const int i1 = 42, i2 = 43, i3 = 123, i4 = 999, i5 = 0, i6 = 79; const int arr1[] = { i1, i2, i3, i4, i5, i6 }; EXPECT_EQ(hash_combine_range(arr1, arr1 + 1), hash_combine(i1)); EXPECT_EQ(hash_combine_range(arr1, arr1 + 2), hash_combine(i1, i2)); EXPECT_EQ(hash_combine_range(arr1, arr1 + 3), hash_combine(i1, i2, i3)); EXPECT_EQ(hash_combine_range(arr1, arr1 + 4), hash_combine(i1, i2, i3, i4)); EXPECT_EQ(hash_combine_range(arr1, arr1 + 5), hash_combine(i1, i2, i3, i4, i5)); EXPECT_EQ(hash_combine_range(arr1, arr1 + 6), hash_combine(i1, i2, i3, i4, i5, i6)); // Hashing a sequence of heterogeneous types which *happen* to all produce the // same data for hashing produces the same as a range-based hash of the // fundamental values. const size_t s1 = 1024, s2 = 8888, s3 = 9000000; const HashableDummy d1 = { 1024 }, d2 = { 8888 }, d3 = { 9000000 }; const size_t arr2[] = { s1, s2, s3 }; EXPECT_EQ(hash_combine_range(begin(arr2), end(arr2)), hash_combine(s1, s2, s3)); EXPECT_EQ(hash_combine(s1, s2, s3), hash_combine(s1, s2, d3)); EXPECT_EQ(hash_combine(s1, s2, s3), hash_combine(s1, d2, s3)); EXPECT_EQ(hash_combine(s1, s2, s3), hash_combine(d1, s2, s3)); EXPECT_EQ(hash_combine(s1, s2, s3), hash_combine(d1, d2, s3)); EXPECT_EQ(hash_combine(s1, s2, s3), hash_combine(d1, d2, d3)); // Permuting values causes hashes to change. EXPECT_NE(hash_combine(i1, i1, i1), hash_combine(i1, i1, i2)); EXPECT_NE(hash_combine(i1, i1, i1), hash_combine(i1, i2, i1)); EXPECT_NE(hash_combine(i1, i1, i1), hash_combine(i2, i1, i1)); EXPECT_NE(hash_combine(i1, i1, i1), hash_combine(i2, i2, i1)); EXPECT_NE(hash_combine(i1, i1, i1), hash_combine(i2, i2, i2)); EXPECT_NE(hash_combine(i2, i1, i1), hash_combine(i1, i1, i2)); EXPECT_NE(hash_combine(i1, i1, i2), hash_combine(i1, i2, i1)); EXPECT_NE(hash_combine(i1, i2, i1), hash_combine(i2, i1, i1)); // Changing type w/o changing value causes hashes to change. EXPECT_NE(hash_combine(i1, i2, i3), hash_combine((char)i1, i2, i3)); EXPECT_NE(hash_combine(i1, i2, i3), hash_combine(i1, (char)i2, i3)); EXPECT_NE(hash_combine(i1, i2, i3), hash_combine(i1, i2, (char)i3)); // This is array of uint64, but it should have the exact same byte pattern as // an array of LargeTestIntegers. const uint64_t bigarr[] = { 0xaaaaaaaaababababULL, 0xacacacacbcbcbcbcULL, 0xccddeeffeeddccbbULL, 0xdeadbeafdeadbeefULL, 0xfefefefededededeULL, 0xafafafafededededULL, 0xffffeeeeddddccccULL, 0xaaaacbcbffffababULL, 0xaaaaaaaaababababULL, 0xacacacacbcbcbcbcULL, 0xccddeeffeeddccbbULL, 0xdeadbeafdeadbeefULL, 0xfefefefededededeULL, 0xafafafafededededULL, 0xffffeeeeddddccccULL, 0xaaaacbcbffffababULL, 0xaaaaaaaaababababULL, 0xacacacacbcbcbcbcULL, 0xccddeeffeeddccbbULL, 0xdeadbeafdeadbeefULL, 0xfefefefededededeULL, 0xafafafafededededULL, 0xffffeeeeddddccccULL, 0xaaaacbcbffffababULL }; // Hash a preposterously large integer, both aligned with the buffer and // misaligned. const LargeTestInteger li = { { 0xaaaaaaaaababababULL, 0xacacacacbcbcbcbcULL, 0xccddeeffeeddccbbULL, 0xdeadbeafdeadbeefULL, 0xfefefefededededeULL, 0xafafafafededededULL, 0xffffeeeeddddccccULL, 0xaaaacbcbffffababULL } }; // Rotate the storage from 'li'. const LargeTestInteger l2 = { { 0xacacacacbcbcbcbcULL, 0xccddeeffeeddccbbULL, 0xdeadbeafdeadbeefULL, 0xfefefefededededeULL, 0xafafafafededededULL, 0xffffeeeeddddccccULL, 0xaaaacbcbffffababULL, 0xaaaaaaaaababababULL } }; const LargeTestInteger l3 = { { 0xccddeeffeeddccbbULL, 0xdeadbeafdeadbeefULL, 0xfefefefededededeULL, 0xafafafafededededULL, 0xffffeeeeddddccccULL, 0xaaaacbcbffffababULL, 0xaaaaaaaaababababULL, 0xacacacacbcbcbcbcULL } }; EXPECT_EQ(hash_combine_range(begin(bigarr), end(bigarr)), hash_combine(li, li, li)); EXPECT_EQ(hash_combine_range(bigarr, bigarr + 9), hash_combine(bigarr[0], l2)); EXPECT_EQ(hash_combine_range(bigarr, bigarr + 10), hash_combine(bigarr[0], bigarr[1], l3)); EXPECT_EQ(hash_combine_range(bigarr, bigarr + 17), hash_combine(li, bigarr[0], l2)); EXPECT_EQ(hash_combine_range(bigarr, bigarr + 18), hash_combine(li, bigarr[0], bigarr[1], l3)); EXPECT_EQ(hash_combine_range(bigarr, bigarr + 18), hash_combine(bigarr[0], l2, bigarr[9], l3)); EXPECT_EQ(hash_combine_range(bigarr, bigarr + 20), hash_combine(bigarr[0], l2, bigarr[9], l3, bigarr[18], bigarr[19])); } TEST(HashingTest, HashCombineArgs18) { // This tests that we can pass in up to 18 args. #define CHECK_SAME(...) \ EXPECT_EQ(hash_combine(__VA_ARGS__), hash_combine(__VA_ARGS__)) CHECK_SAME(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18); CHECK_SAME(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17); CHECK_SAME(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); CHECK_SAME(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15); CHECK_SAME(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14); CHECK_SAME(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13); CHECK_SAME(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12); CHECK_SAME(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11); CHECK_SAME(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); CHECK_SAME(1, 2, 3, 4, 5, 6, 7, 8, 9); CHECK_SAME(1, 2, 3, 4, 5, 6, 7, 8); CHECK_SAME(1, 2, 3, 4, 5, 6, 7); CHECK_SAME(1, 2, 3, 4, 5, 6); CHECK_SAME(1, 2, 3, 4, 5); CHECK_SAME(1, 2, 3, 4); CHECK_SAME(1, 2, 3); CHECK_SAME(1, 2); CHECK_SAME(1); #undef CHECK_SAME } }
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/ADT/MakeUniqueTest.cpp
//===- llvm/unittest/ADT/MakeUniqueTest.cpp - make_unique unit tests ------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/ADT/STLExtras.h" #include "gtest/gtest.h" #include <tuple> using namespace llvm; namespace { TEST(MakeUniqueTest, SingleObject) { auto p0 = make_unique<int>(); EXPECT_TRUE((bool)p0); EXPECT_EQ(0, *p0); auto p1 = make_unique<int>(5); EXPECT_TRUE((bool)p1); EXPECT_EQ(5, *p1); auto p2 = make_unique<std::tuple<int, int>>(0, 1); EXPECT_TRUE((bool)p2); EXPECT_EQ(std::make_tuple(0, 1), *p2); auto p3 = make_unique<std::tuple<int, int, int>>(0, 1, 2); EXPECT_TRUE((bool)p3); EXPECT_EQ(std::make_tuple(0, 1, 2), *p3); auto p4 = make_unique<std::tuple<int, int, int, int>>(0, 1, 2, 3); EXPECT_TRUE((bool)p4); EXPECT_EQ(std::make_tuple(0, 1, 2, 3), *p4); auto p5 = make_unique<std::tuple<int, int, int, int, int>>(0, 1, 2, 3, 4); EXPECT_TRUE((bool)p5); EXPECT_EQ(std::make_tuple(0, 1, 2, 3, 4), *p5); auto p6 = make_unique<std::tuple<int, int, int, int, int, int>>(0, 1, 2, 3, 4, 5); EXPECT_TRUE((bool)p6); EXPECT_EQ(std::make_tuple(0, 1, 2, 3, 4, 5), *p6); auto p7 = make_unique<std::tuple<int, int, int, int, int, int, int>>( 0, 1, 2, 3, 4, 5, 6); EXPECT_TRUE((bool)p7); EXPECT_EQ(std::make_tuple(0, 1, 2, 3, 4, 5, 6), *p7); auto p8 = make_unique<std::tuple<int, int, int, int, int, int, int, int>>( 0, 1, 2, 3, 4, 5, 6, 7); EXPECT_TRUE((bool)p8); EXPECT_EQ(std::make_tuple(0, 1, 2, 3, 4, 5, 6, 7), *p8); auto p9 = make_unique<std::tuple<int, int, int, int, int, int, int, int, int>>( 0, 1, 2, 3, 4, 5, 6, 7, 8); EXPECT_TRUE((bool)p9); EXPECT_EQ(std::make_tuple(0, 1, 2, 3, 4, 5, 6, 7, 8), *p9); auto p10 = make_unique<std::tuple<int, int, int, int, int, int, int, int, int, int>>( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9); EXPECT_TRUE((bool)p10); EXPECT_EQ(std::make_tuple(0, 1, 2, 3, 4, 5, 6, 7, 8, 9), *p10); } TEST(MakeUniqueTest, Array) { auto p1 = make_unique<int[]>(2); EXPECT_TRUE((bool)p1); EXPECT_EQ(0, p1[0]); EXPECT_EQ(0, p1[1]); } }
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/ADT/VariadicFunctionTest.cpp
//===----------- VariadicFunctionTest.cpp - VariadicFunction unit tests ---===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "gtest/gtest.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/VariadicFunction.h" using namespace llvm; namespace { // Defines a variadic function StringCat() to join strings. // StringCat()'s arguments and return value have class types. std::string StringCatImpl(ArrayRef<const std::string *> Args) { std::string S; for (unsigned i = 0, e = Args.size(); i < e; ++i) S += *Args[i]; return S; } const VariadicFunction<std::string, std::string, StringCatImpl> StringCat = {}; TEST(VariadicFunctionTest, WorksForClassTypes) { EXPECT_EQ("", StringCat()); EXPECT_EQ("a", StringCat("a")); EXPECT_EQ("abc", StringCat("a", "bc")); EXPECT_EQ("0123456789abcdefghijklmnopqrstuv", StringCat("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v")); } // Defines a variadic function Sum(), whose arguments and return value // have primitive types. // The return type of SumImp() is deliberately different from its // argument type, as we want to test that this works. long SumImpl(ArrayRef<const int *> Args) { long Result = 0; for (unsigned i = 0, e = Args.size(); i < e; ++i) Result += *Args[i]; return Result; } const VariadicFunction<long, int, SumImpl> Sum = {}; TEST(VariadicFunctionTest, WorksForPrimitiveTypes) { EXPECT_EQ(0, Sum()); EXPECT_EQ(1, Sum(1)); EXPECT_EQ(12, Sum(10, 2)); EXPECT_EQ(1234567, Sum(1000000, 200000, 30000, 4000, 500, 60, 7)); } // Appends an array of strings to dest and returns the number of // characters appended. int StringAppendImpl(std::string *Dest, ArrayRef<const std::string *> Args) { int Chars = 0; for (unsigned i = 0, e = Args.size(); i < e; ++i) { Chars += Args[i]->size(); *Dest += *Args[i]; } return Chars; } const VariadicFunction1<int, std::string *, std::string, StringAppendImpl> StringAppend = {}; TEST(VariadicFunction1Test, Works) { std::string S0("hi"); EXPECT_EQ(0, StringAppend(&S0)); EXPECT_EQ("hi", S0); std::string S1("bin"); EXPECT_EQ(2, StringAppend(&S1, "go")); EXPECT_EQ("bingo", S1); std::string S4("Fab4"); EXPECT_EQ(4 + 4 + 6 + 5, StringAppend(&S4, "John", "Paul", "George", "Ringo")); EXPECT_EQ("Fab4JohnPaulGeorgeRingo", S4); } // Counts how many optional arguments fall in the given range. // Returns the result in *num_in_range. We make the return type void // as we want to test that VariadicFunction* can handle it. void CountInRangeImpl(int *NumInRange, int Low, int High, ArrayRef<const int *> Args) { *NumInRange = 0; for (unsigned i = 0, e = Args.size(); i < e; ++i) if (Low <= *Args[i] && *Args[i] <= High) ++(*NumInRange); } const VariadicFunction3<void, int *, int, int, int, CountInRangeImpl> CountInRange = {}; TEST(VariadicFunction3Test, Works) { int N = -1; CountInRange(&N, -100, 100); EXPECT_EQ(0, N); CountInRange(&N, -100, 100, 42); EXPECT_EQ(1, N); CountInRange(&N, -100, 100, 1, 999, -200, 42); EXPECT_EQ(2, N); } } // namespace
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/ADT/TwineTest.cpp
//===- TwineTest.cpp - Twine unit tests -----------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/ADT/Twine.h" #include "llvm/ADT/SmallString.h" #include "llvm/Support/raw_ostream.h" #include "gtest/gtest.h" using namespace llvm; namespace { std::string repr(const Twine &Value) { std::string res; llvm::raw_string_ostream OS(res); Value.printRepr(OS); return OS.str(); } TEST(TwineTest, Construction) { EXPECT_EQ("", Twine().str()); EXPECT_EQ("hi", Twine("hi").str()); EXPECT_EQ("hi", Twine(std::string("hi")).str()); EXPECT_EQ("hi", Twine(StringRef("hi")).str()); EXPECT_EQ("hi", Twine(StringRef(std::string("hi"))).str()); EXPECT_EQ("hi", Twine(StringRef("hithere", 2)).str()); EXPECT_EQ("hi", Twine(SmallString<4>("hi")).str()); } TEST(TwineTest, Numbers) { EXPECT_EQ("123", Twine(123U).str()); EXPECT_EQ("123", Twine(123).str()); EXPECT_EQ("-123", Twine(-123).str()); EXPECT_EQ("123", Twine(123).str()); EXPECT_EQ("-123", Twine(-123).str()); EXPECT_EQ("7b", Twine::utohexstr(123).str()); } TEST(TwineTest, Characters) { EXPECT_EQ("x", Twine('x').str()); EXPECT_EQ("x", Twine(static_cast<unsigned char>('x')).str()); EXPECT_EQ("x", Twine(static_cast<signed char>('x')).str()); } TEST(TwineTest, Concat) { // Check verse repr, since we care about the actual representation not just // the result. // Concat with null. EXPECT_EQ("(Twine null empty)", repr(Twine("hi").concat(Twine::createNull()))); EXPECT_EQ("(Twine null empty)", repr(Twine::createNull().concat(Twine("hi")))); // Concat with empty. EXPECT_EQ("(Twine cstring:\"hi\" empty)", repr(Twine("hi").concat(Twine()))); EXPECT_EQ("(Twine cstring:\"hi\" empty)", repr(Twine().concat(Twine("hi")))); EXPECT_EQ("(Twine smallstring:\"hi\" empty)", repr(Twine().concat(Twine(SmallString<5>("hi"))))); EXPECT_EQ("(Twine smallstring:\"hey\" cstring:\"there\")", repr(Twine(SmallString<7>("hey")).concat(Twine("there")))); // Concatenation of unary ropes. EXPECT_EQ("(Twine cstring:\"a\" cstring:\"b\")", repr(Twine("a").concat(Twine("b")))); // Concatenation of other ropes. EXPECT_EQ("(Twine rope:(Twine cstring:\"a\" cstring:\"b\") cstring:\"c\")", repr(Twine("a").concat(Twine("b")).concat(Twine("c")))); EXPECT_EQ("(Twine cstring:\"a\" rope:(Twine cstring:\"b\" cstring:\"c\"))", repr(Twine("a").concat(Twine("b").concat(Twine("c"))))); EXPECT_EQ("(Twine cstring:\"a\" rope:(Twine smallstring:\"b\" cstring:\"c\"))", repr(Twine("a").concat(Twine(SmallString<3>("b")).concat(Twine("c"))))); } TEST(TwineTest, toNullTerminatedStringRef) { SmallString<8> storage; EXPECT_EQ(0, *Twine("hello").toNullTerminatedStringRef(storage).end()); EXPECT_EQ(0, *Twine(StringRef("hello")).toNullTerminatedStringRef(storage).end()); EXPECT_EQ(0, *Twine(SmallString<11>("hello")) .toNullTerminatedStringRef(storage) .end()); } // I suppose linking in the entire code generator to add a unit test to check // the code size of the concat operation is overkill... :) } // end anonymous namespace
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/ADT/APFloatTest.cpp
//===- llvm/unittest/ADT/APFloat.cpp - APFloat unit tests ---------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/ADT/APFloat.h" #include "llvm/ADT/APSInt.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Support/raw_ostream.h" #include "gtest/gtest.h" #include <cmath> #include <ostream> #include <string> using namespace llvm; static double convertToDoubleFromString(const char *Str) { llvm::APFloat F(0.0); F.convertFromString(Str, llvm::APFloat::rmNearestTiesToEven); return F.convertToDouble(); } static std::string convertToString(double d, unsigned Prec, unsigned Pad) { llvm::SmallVector<char, 100> Buffer; llvm::APFloat F(d); F.toString(Buffer, Prec, Pad); return std::string(Buffer.data(), Buffer.size()); } namespace { TEST(APFloatTest, isSignaling) { // We test qNaN, -qNaN, +sNaN, -sNaN with and without payloads. *NOTE* The // positive/negative distinction is included only since the getQNaN/getSNaN // API provides the option. APInt payload = APInt::getOneBitSet(4, 2); EXPECT_FALSE(APFloat::getQNaN(APFloat::IEEEsingle, false).isSignaling()); EXPECT_FALSE(APFloat::getQNaN(APFloat::IEEEsingle, true).isSignaling()); EXPECT_FALSE(APFloat::getQNaN(APFloat::IEEEsingle, false, &payload).isSignaling()); EXPECT_FALSE(APFloat::getQNaN(APFloat::IEEEsingle, true, &payload).isSignaling()); EXPECT_TRUE(APFloat::getSNaN(APFloat::IEEEsingle, false).isSignaling()); EXPECT_TRUE(APFloat::getSNaN(APFloat::IEEEsingle, true).isSignaling()); EXPECT_TRUE(APFloat::getSNaN(APFloat::IEEEsingle, false, &payload).isSignaling()); EXPECT_TRUE(APFloat::getSNaN(APFloat::IEEEsingle, true, &payload).isSignaling()); } TEST(APFloatTest, next) { APFloat test(APFloat::IEEEquad, APFloat::uninitialized); APFloat expected(APFloat::IEEEquad, APFloat::uninitialized); // 1. Test Special Cases Values. // // Test all special values for nextUp and nextDown perscribed by IEEE-754R // 2008. These are: // 1. +inf // 2. -inf // 3. getLargest() // 4. -getLargest() // 5. getSmallest() // 6. -getSmallest() // 7. qNaN // 8. sNaN // 9. +0 // 10. -0 // nextUp(+inf) = +inf. test = APFloat::getInf(APFloat::IEEEquad, false); expected = APFloat::getInf(APFloat::IEEEquad, false); EXPECT_EQ(test.next(false), APFloat::opOK); EXPECT_TRUE(test.isInfinity()); EXPECT_TRUE(!test.isNegative()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextDown(+inf) = -nextUp(-inf) = -(-getLargest()) = getLargest() test = APFloat::getInf(APFloat::IEEEquad, false); expected = APFloat::getLargest(APFloat::IEEEquad, false); EXPECT_EQ(test.next(true), APFloat::opOK); EXPECT_TRUE(!test.isNegative()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextUp(-inf) = -getLargest() test = APFloat::getInf(APFloat::IEEEquad, true); expected = APFloat::getLargest(APFloat::IEEEquad, true); EXPECT_EQ(test.next(false), APFloat::opOK); EXPECT_TRUE(test.isNegative()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextDown(-inf) = -nextUp(+inf) = -(+inf) = -inf. test = APFloat::getInf(APFloat::IEEEquad, true); expected = APFloat::getInf(APFloat::IEEEquad, true); EXPECT_EQ(test.next(true), APFloat::opOK); EXPECT_TRUE(test.isInfinity() && test.isNegative()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextUp(getLargest()) = +inf test = APFloat::getLargest(APFloat::IEEEquad, false); expected = APFloat::getInf(APFloat::IEEEquad, false); EXPECT_EQ(test.next(false), APFloat::opOK); EXPECT_TRUE(test.isInfinity() && !test.isNegative()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextDown(getLargest()) = -nextUp(-getLargest()) // = -(-getLargest() + inc) // = getLargest() - inc. test = APFloat::getLargest(APFloat::IEEEquad, false); expected = APFloat(APFloat::IEEEquad, "0x1.fffffffffffffffffffffffffffep+16383"); EXPECT_EQ(test.next(true), APFloat::opOK); EXPECT_TRUE(!test.isInfinity() && !test.isNegative()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextUp(-getLargest()) = -getLargest() + inc. test = APFloat::getLargest(APFloat::IEEEquad, true); expected = APFloat(APFloat::IEEEquad, "-0x1.fffffffffffffffffffffffffffep+16383"); EXPECT_EQ(test.next(false), APFloat::opOK); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextDown(-getLargest()) = -nextUp(getLargest()) = -(inf) = -inf. test = APFloat::getLargest(APFloat::IEEEquad, true); expected = APFloat::getInf(APFloat::IEEEquad, true); EXPECT_EQ(test.next(true), APFloat::opOK); EXPECT_TRUE(test.isInfinity() && test.isNegative()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextUp(getSmallest()) = getSmallest() + inc. test = APFloat(APFloat::IEEEquad, "0x0.0000000000000000000000000001p-16382"); expected = APFloat(APFloat::IEEEquad, "0x0.0000000000000000000000000002p-16382"); EXPECT_EQ(test.next(false), APFloat::opOK); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextDown(getSmallest()) = -nextUp(-getSmallest()) = -(-0) = +0. test = APFloat(APFloat::IEEEquad, "0x0.0000000000000000000000000001p-16382"); expected = APFloat::getZero(APFloat::IEEEquad, false); EXPECT_EQ(test.next(true), APFloat::opOK); EXPECT_TRUE(test.isZero() && !test.isNegative()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextUp(-getSmallest()) = -0. test = APFloat(APFloat::IEEEquad, "-0x0.0000000000000000000000000001p-16382"); expected = APFloat::getZero(APFloat::IEEEquad, true); EXPECT_EQ(test.next(false), APFloat::opOK); EXPECT_TRUE(test.isZero() && test.isNegative()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextDown(-getSmallest()) = -nextUp(getSmallest()) = -getSmallest() - inc. test = APFloat(APFloat::IEEEquad, "-0x0.0000000000000000000000000001p-16382"); expected = APFloat(APFloat::IEEEquad, "-0x0.0000000000000000000000000002p-16382"); EXPECT_EQ(test.next(true), APFloat::opOK); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextUp(qNaN) = qNaN test = APFloat::getQNaN(APFloat::IEEEquad, false); expected = APFloat::getQNaN(APFloat::IEEEquad, false); EXPECT_EQ(test.next(false), APFloat::opOK); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextDown(qNaN) = qNaN test = APFloat::getQNaN(APFloat::IEEEquad, false); expected = APFloat::getQNaN(APFloat::IEEEquad, false); EXPECT_EQ(test.next(true), APFloat::opOK); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextUp(sNaN) = qNaN test = APFloat::getSNaN(APFloat::IEEEquad, false); expected = APFloat::getQNaN(APFloat::IEEEquad, false); EXPECT_EQ(test.next(false), APFloat::opInvalidOp); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextDown(sNaN) = qNaN test = APFloat::getSNaN(APFloat::IEEEquad, false); expected = APFloat::getQNaN(APFloat::IEEEquad, false); EXPECT_EQ(test.next(true), APFloat::opInvalidOp); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextUp(+0) = +getSmallest() test = APFloat::getZero(APFloat::IEEEquad, false); expected = APFloat::getSmallest(APFloat::IEEEquad, false); EXPECT_EQ(test.next(false), APFloat::opOK); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextDown(+0) = -nextUp(-0) = -getSmallest() test = APFloat::getZero(APFloat::IEEEquad, false); expected = APFloat::getSmallest(APFloat::IEEEquad, true); EXPECT_EQ(test.next(true), APFloat::opOK); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextUp(-0) = +getSmallest() test = APFloat::getZero(APFloat::IEEEquad, true); expected = APFloat::getSmallest(APFloat::IEEEquad, false); EXPECT_EQ(test.next(false), APFloat::opOK); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextDown(-0) = -nextUp(0) = -getSmallest() test = APFloat::getZero(APFloat::IEEEquad, true); expected = APFloat::getSmallest(APFloat::IEEEquad, true); EXPECT_EQ(test.next(true), APFloat::opOK); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // 2. Binade Boundary Tests. // 2a. Test denormal <-> normal binade boundaries. // * nextUp(+Largest Denormal) -> +Smallest Normal. // * nextDown(-Largest Denormal) -> -Smallest Normal. // * nextUp(-Smallest Normal) -> -Largest Denormal. // * nextDown(+Smallest Normal) -> +Largest Denormal. // nextUp(+Largest Denormal) -> +Smallest Normal. test = APFloat(APFloat::IEEEquad, "0x0.ffffffffffffffffffffffffffffp-16382"); expected = APFloat(APFloat::IEEEquad, "0x1.0000000000000000000000000000p-16382"); EXPECT_EQ(test.next(false), APFloat::opOK); EXPECT_FALSE(test.isDenormal()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextDown(-Largest Denormal) -> -Smallest Normal. test = APFloat(APFloat::IEEEquad, "-0x0.ffffffffffffffffffffffffffffp-16382"); expected = APFloat(APFloat::IEEEquad, "-0x1.0000000000000000000000000000p-16382"); EXPECT_EQ(test.next(true), APFloat::opOK); EXPECT_FALSE(test.isDenormal()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextUp(-Smallest Normal) -> -LargestDenormal. test = APFloat(APFloat::IEEEquad, "-0x1.0000000000000000000000000000p-16382"); expected = APFloat(APFloat::IEEEquad, "-0x0.ffffffffffffffffffffffffffffp-16382"); EXPECT_EQ(test.next(false), APFloat::opOK); EXPECT_TRUE(test.isDenormal()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextDown(+Smallest Normal) -> +Largest Denormal. test = APFloat(APFloat::IEEEquad, "+0x1.0000000000000000000000000000p-16382"); expected = APFloat(APFloat::IEEEquad, "+0x0.ffffffffffffffffffffffffffffp-16382"); EXPECT_EQ(test.next(true), APFloat::opOK); EXPECT_TRUE(test.isDenormal()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // 2b. Test normal <-> normal binade boundaries. // * nextUp(-Normal Binade Boundary) -> -Normal Binade Boundary + 1. // * nextDown(+Normal Binade Boundary) -> +Normal Binade Boundary - 1. // * nextUp(+Normal Binade Boundary - 1) -> +Normal Binade Boundary. // * nextDown(-Normal Binade Boundary + 1) -> -Normal Binade Boundary. // nextUp(-Normal Binade Boundary) -> -Normal Binade Boundary + 1. test = APFloat(APFloat::IEEEquad, "-0x1p+1"); expected = APFloat(APFloat::IEEEquad, "-0x1.ffffffffffffffffffffffffffffp+0"); EXPECT_EQ(test.next(false), APFloat::opOK); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextDown(+Normal Binade Boundary) -> +Normal Binade Boundary - 1. test = APFloat(APFloat::IEEEquad, "0x1p+1"); expected = APFloat(APFloat::IEEEquad, "0x1.ffffffffffffffffffffffffffffp+0"); EXPECT_EQ(test.next(true), APFloat::opOK); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextUp(+Normal Binade Boundary - 1) -> +Normal Binade Boundary. test = APFloat(APFloat::IEEEquad, "0x1.ffffffffffffffffffffffffffffp+0"); expected = APFloat(APFloat::IEEEquad, "0x1p+1"); EXPECT_EQ(test.next(false), APFloat::opOK); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextDown(-Normal Binade Boundary + 1) -> -Normal Binade Boundary. test = APFloat(APFloat::IEEEquad, "-0x1.ffffffffffffffffffffffffffffp+0"); expected = APFloat(APFloat::IEEEquad, "-0x1p+1"); EXPECT_EQ(test.next(true), APFloat::opOK); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // 2c. Test using next at binade boundaries with a direction away from the // binade boundary. Away from denormal <-> normal boundaries. // // This is to make sure that even though we are at a binade boundary, since // we are rounding away, we do not trigger the binade boundary code. Thus we // test: // * nextUp(-Largest Denormal) -> -Largest Denormal + inc. // * nextDown(+Largest Denormal) -> +Largest Denormal - inc. // * nextUp(+Smallest Normal) -> +Smallest Normal + inc. // * nextDown(-Smallest Normal) -> -Smallest Normal - inc. // nextUp(-Largest Denormal) -> -Largest Denormal + inc. test = APFloat(APFloat::IEEEquad, "-0x0.ffffffffffffffffffffffffffffp-16382"); expected = APFloat(APFloat::IEEEquad, "-0x0.fffffffffffffffffffffffffffep-16382"); EXPECT_EQ(test.next(false), APFloat::opOK); EXPECT_TRUE(test.isDenormal()); EXPECT_TRUE(test.isNegative()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextDown(+Largest Denormal) -> +Largest Denormal - inc. test = APFloat(APFloat::IEEEquad, "0x0.ffffffffffffffffffffffffffffp-16382"); expected = APFloat(APFloat::IEEEquad, "0x0.fffffffffffffffffffffffffffep-16382"); EXPECT_EQ(test.next(true), APFloat::opOK); EXPECT_TRUE(test.isDenormal()); EXPECT_TRUE(!test.isNegative()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextUp(+Smallest Normal) -> +Smallest Normal + inc. test = APFloat(APFloat::IEEEquad, "0x1.0000000000000000000000000000p-16382"); expected = APFloat(APFloat::IEEEquad, "0x1.0000000000000000000000000001p-16382"); EXPECT_EQ(test.next(false), APFloat::opOK); EXPECT_TRUE(!test.isDenormal()); EXPECT_TRUE(!test.isNegative()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextDown(-Smallest Normal) -> -Smallest Normal - inc. test = APFloat(APFloat::IEEEquad, "-0x1.0000000000000000000000000000p-16382"); expected = APFloat(APFloat::IEEEquad, "-0x1.0000000000000000000000000001p-16382"); EXPECT_EQ(test.next(true), APFloat::opOK); EXPECT_TRUE(!test.isDenormal()); EXPECT_TRUE(test.isNegative()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // 2d. Test values which cause our exponent to go to min exponent. This // is to ensure that guards in the code to check for min exponent // trigger properly. // * nextUp(-0x1p-16381) -> -0x1.ffffffffffffffffffffffffffffp-16382 // * nextDown(-0x1.ffffffffffffffffffffffffffffp-16382) -> // -0x1p-16381 // * nextUp(0x1.ffffffffffffffffffffffffffffp-16382) -> 0x1p-16382 // * nextDown(0x1p-16382) -> 0x1.ffffffffffffffffffffffffffffp-16382 // nextUp(-0x1p-16381) -> -0x1.ffffffffffffffffffffffffffffp-16382 test = APFloat(APFloat::IEEEquad, "-0x1p-16381"); expected = APFloat(APFloat::IEEEquad, "-0x1.ffffffffffffffffffffffffffffp-16382"); EXPECT_EQ(test.next(false), APFloat::opOK); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextDown(-0x1.ffffffffffffffffffffffffffffp-16382) -> // -0x1p-16381 test = APFloat(APFloat::IEEEquad, "-0x1.ffffffffffffffffffffffffffffp-16382"); expected = APFloat(APFloat::IEEEquad, "-0x1p-16381"); EXPECT_EQ(test.next(true), APFloat::opOK); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextUp(0x1.ffffffffffffffffffffffffffffp-16382) -> 0x1p-16381 test = APFloat(APFloat::IEEEquad, "0x1.ffffffffffffffffffffffffffffp-16382"); expected = APFloat(APFloat::IEEEquad, "0x1p-16381"); EXPECT_EQ(test.next(false), APFloat::opOK); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextDown(0x1p-16381) -> 0x1.ffffffffffffffffffffffffffffp-16382 test = APFloat(APFloat::IEEEquad, "0x1p-16381"); expected = APFloat(APFloat::IEEEquad, "0x1.ffffffffffffffffffffffffffffp-16382"); EXPECT_EQ(test.next(true), APFloat::opOK); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // 3. Now we test both denormal/normal computation which will not cause us // to go across binade boundaries. Specifically we test: // * nextUp(+Denormal) -> +Denormal. // * nextDown(+Denormal) -> +Denormal. // * nextUp(-Denormal) -> -Denormal. // * nextDown(-Denormal) -> -Denormal. // * nextUp(+Normal) -> +Normal. // * nextDown(+Normal) -> +Normal. // * nextUp(-Normal) -> -Normal. // * nextDown(-Normal) -> -Normal. // nextUp(+Denormal) -> +Denormal. test = APFloat(APFloat::IEEEquad, "0x0.ffffffffffffffffffffffff000cp-16382"); expected = APFloat(APFloat::IEEEquad, "0x0.ffffffffffffffffffffffff000dp-16382"); EXPECT_EQ(test.next(false), APFloat::opOK); EXPECT_TRUE(test.isDenormal()); EXPECT_TRUE(!test.isNegative()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextDown(+Denormal) -> +Denormal. test = APFloat(APFloat::IEEEquad, "0x0.ffffffffffffffffffffffff000cp-16382"); expected = APFloat(APFloat::IEEEquad, "0x0.ffffffffffffffffffffffff000bp-16382"); EXPECT_EQ(test.next(true), APFloat::opOK); EXPECT_TRUE(test.isDenormal()); EXPECT_TRUE(!test.isNegative()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextUp(-Denormal) -> -Denormal. test = APFloat(APFloat::IEEEquad, "-0x0.ffffffffffffffffffffffff000cp-16382"); expected = APFloat(APFloat::IEEEquad, "-0x0.ffffffffffffffffffffffff000bp-16382"); EXPECT_EQ(test.next(false), APFloat::opOK); EXPECT_TRUE(test.isDenormal()); EXPECT_TRUE(test.isNegative()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextDown(-Denormal) -> -Denormal test = APFloat(APFloat::IEEEquad, "-0x0.ffffffffffffffffffffffff000cp-16382"); expected = APFloat(APFloat::IEEEquad, "-0x0.ffffffffffffffffffffffff000dp-16382"); EXPECT_EQ(test.next(true), APFloat::opOK); EXPECT_TRUE(test.isDenormal()); EXPECT_TRUE(test.isNegative()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextUp(+Normal) -> +Normal. test = APFloat(APFloat::IEEEquad, "0x1.ffffffffffffffffffffffff000cp-16000"); expected = APFloat(APFloat::IEEEquad, "0x1.ffffffffffffffffffffffff000dp-16000"); EXPECT_EQ(test.next(false), APFloat::opOK); EXPECT_TRUE(!test.isDenormal()); EXPECT_TRUE(!test.isNegative()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextDown(+Normal) -> +Normal. test = APFloat(APFloat::IEEEquad, "0x1.ffffffffffffffffffffffff000cp-16000"); expected = APFloat(APFloat::IEEEquad, "0x1.ffffffffffffffffffffffff000bp-16000"); EXPECT_EQ(test.next(true), APFloat::opOK); EXPECT_TRUE(!test.isDenormal()); EXPECT_TRUE(!test.isNegative()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextUp(-Normal) -> -Normal. test = APFloat(APFloat::IEEEquad, "-0x1.ffffffffffffffffffffffff000cp-16000"); expected = APFloat(APFloat::IEEEquad, "-0x1.ffffffffffffffffffffffff000bp-16000"); EXPECT_EQ(test.next(false), APFloat::opOK); EXPECT_TRUE(!test.isDenormal()); EXPECT_TRUE(test.isNegative()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextDown(-Normal) -> -Normal. test = APFloat(APFloat::IEEEquad, "-0x1.ffffffffffffffffffffffff000cp-16000"); expected = APFloat(APFloat::IEEEquad, "-0x1.ffffffffffffffffffffffff000dp-16000"); EXPECT_EQ(test.next(true), APFloat::opOK); EXPECT_TRUE(!test.isDenormal()); EXPECT_TRUE(test.isNegative()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); } TEST(APFloatTest, FMA) { APFloat::roundingMode rdmd = APFloat::rmNearestTiesToEven; { APFloat f1(14.5f); APFloat f2(-14.5f); APFloat f3(225.0f); f1.fusedMultiplyAdd(f2, f3, APFloat::rmNearestTiesToEven); EXPECT_EQ(14.75f, f1.convertToFloat()); } { APFloat Val2(2.0f); APFloat f1((float)1.17549435e-38F); APFloat f2((float)1.17549435e-38F); f1.divide(Val2, rdmd); f2.divide(Val2, rdmd); APFloat f3(12.0f); f1.fusedMultiplyAdd(f2, f3, APFloat::rmNearestTiesToEven); EXPECT_EQ(12.0f, f1.convertToFloat()); } // Test for correct zero sign when answer is exactly zero. // fma(1.0, -1.0, 1.0) -> +ve 0. { APFloat f1(1.0); APFloat f2(-1.0); APFloat f3(1.0); f1.fusedMultiplyAdd(f2, f3, APFloat::rmNearestTiesToEven); EXPECT_TRUE(!f1.isNegative() && f1.isZero()); } // Test for correct zero sign when answer is exactly zero and rounding towards // negative. // fma(1.0, -1.0, 1.0) -> +ve 0. { APFloat f1(1.0); APFloat f2(-1.0); APFloat f3(1.0); f1.fusedMultiplyAdd(f2, f3, APFloat::rmTowardNegative); EXPECT_TRUE(f1.isNegative() && f1.isZero()); } // Test for correct (in this case -ve) sign when adding like signed zeros. // Test fma(0.0, -0.0, -0.0) -> -ve 0. { APFloat f1(0.0); APFloat f2(-0.0); APFloat f3(-0.0); f1.fusedMultiplyAdd(f2, f3, APFloat::rmNearestTiesToEven); EXPECT_TRUE(f1.isNegative() && f1.isZero()); } // Test -ve sign preservation when small negative results underflow. { APFloat f1(APFloat::IEEEdouble, "-0x1p-1074"); APFloat f2(APFloat::IEEEdouble, "+0x1p-1074"); APFloat f3(0.0); f1.fusedMultiplyAdd(f2, f3, APFloat::rmNearestTiesToEven); EXPECT_TRUE(f1.isNegative() && f1.isZero()); } // Test x87 extended precision case from http://llvm.org/PR20728. { APFloat M1(APFloat::x87DoubleExtended, 1.0); APFloat M2(APFloat::x87DoubleExtended, 1.0); APFloat A(APFloat::x87DoubleExtended, 3.0); bool losesInfo = false; M1.fusedMultiplyAdd(M1, A, APFloat::rmNearestTiesToEven); M1.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo); EXPECT_FALSE(losesInfo); EXPECT_EQ(4.0f, M1.convertToFloat()); } } TEST(APFloatTest, MinNum) { APFloat f1(1.0); APFloat f2(2.0); APFloat nan = APFloat::getNaN(APFloat::IEEEdouble); EXPECT_EQ(1.0, minnum(f1, f2).convertToDouble()); EXPECT_EQ(1.0, minnum(f2, f1).convertToDouble()); EXPECT_EQ(1.0, minnum(f1, nan).convertToDouble()); EXPECT_EQ(1.0, minnum(nan, f1).convertToDouble()); } TEST(APFloatTest, MaxNum) { APFloat f1(1.0); APFloat f2(2.0); APFloat nan = APFloat::getNaN(APFloat::IEEEdouble); EXPECT_EQ(2.0, maxnum(f1, f2).convertToDouble()); EXPECT_EQ(2.0, maxnum(f2, f1).convertToDouble()); EXPECT_EQ(1.0, maxnum(f1, nan).convertToDouble()); EXPECT_EQ(1.0, minnum(nan, f1).convertToDouble()); } TEST(APFloatTest, Denormal) { APFloat::roundingMode rdmd = APFloat::rmNearestTiesToEven; // Test single precision { const char *MinNormalStr = "1.17549435082228750797e-38"; EXPECT_FALSE(APFloat(APFloat::IEEEsingle, MinNormalStr).isDenormal()); EXPECT_FALSE(APFloat(APFloat::IEEEsingle, 0.0).isDenormal()); APFloat Val2(APFloat::IEEEsingle, 2.0e0); APFloat T(APFloat::IEEEsingle, MinNormalStr); T.divide(Val2, rdmd); EXPECT_TRUE(T.isDenormal()); } // Test double precision { const char *MinNormalStr = "2.22507385850720138309e-308"; EXPECT_FALSE(APFloat(APFloat::IEEEdouble, MinNormalStr).isDenormal()); EXPECT_FALSE(APFloat(APFloat::IEEEdouble, 0.0).isDenormal()); APFloat Val2(APFloat::IEEEdouble, 2.0e0); APFloat T(APFloat::IEEEdouble, MinNormalStr); T.divide(Val2, rdmd); EXPECT_TRUE(T.isDenormal()); } // Test Intel double-ext { const char *MinNormalStr = "3.36210314311209350626e-4932"; EXPECT_FALSE(APFloat(APFloat::x87DoubleExtended, MinNormalStr).isDenormal()); EXPECT_FALSE(APFloat(APFloat::x87DoubleExtended, 0.0).isDenormal()); APFloat Val2(APFloat::x87DoubleExtended, 2.0e0); APFloat T(APFloat::x87DoubleExtended, MinNormalStr); T.divide(Val2, rdmd); EXPECT_TRUE(T.isDenormal()); } // Test quadruple precision { const char *MinNormalStr = "3.36210314311209350626267781732175260e-4932"; EXPECT_FALSE(APFloat(APFloat::IEEEquad, MinNormalStr).isDenormal()); EXPECT_FALSE(APFloat(APFloat::IEEEquad, 0.0).isDenormal()); APFloat Val2(APFloat::IEEEquad, 2.0e0); APFloat T(APFloat::IEEEquad, MinNormalStr); T.divide(Val2, rdmd); EXPECT_TRUE(T.isDenormal()); } } TEST(APFloatTest, Zero) { EXPECT_EQ(0.0f, APFloat(0.0f).convertToFloat()); EXPECT_EQ(-0.0f, APFloat(-0.0f).convertToFloat()); EXPECT_TRUE(APFloat(-0.0f).isNegative()); EXPECT_EQ(0.0, APFloat(0.0).convertToDouble()); EXPECT_EQ(-0.0, APFloat(-0.0).convertToDouble()); EXPECT_TRUE(APFloat(-0.0).isNegative()); } TEST(APFloatTest, DecimalStringsWithoutNullTerminators) { // Make sure that we can parse strings without null terminators. // rdar://14323230. APFloat Val(APFloat::IEEEdouble); Val.convertFromString(StringRef("0.00", 3), llvm::APFloat::rmNearestTiesToEven); EXPECT_EQ(Val.convertToDouble(), 0.0); Val.convertFromString(StringRef("0.01", 3), llvm::APFloat::rmNearestTiesToEven); EXPECT_EQ(Val.convertToDouble(), 0.0); Val.convertFromString(StringRef("0.09", 3), llvm::APFloat::rmNearestTiesToEven); EXPECT_EQ(Val.convertToDouble(), 0.0); Val.convertFromString(StringRef("0.095", 4), llvm::APFloat::rmNearestTiesToEven); EXPECT_EQ(Val.convertToDouble(), 0.09); Val.convertFromString(StringRef("0.00e+3", 7), llvm::APFloat::rmNearestTiesToEven); EXPECT_EQ(Val.convertToDouble(), 0.00); Val.convertFromString(StringRef("0e+3", 4), llvm::APFloat::rmNearestTiesToEven); EXPECT_EQ(Val.convertToDouble(), 0.00); } TEST(APFloatTest, fromZeroDecimalString) { EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble, "0").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble, "+0").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble, "-0").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble, "0.").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble, "+0.").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble, "-0.").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble, ".0").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble, "+.0").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble, "-.0").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble, "0.0").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble, "+0.0").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble, "-0.0").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble, "00000.").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble, "+00000.").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble, "-00000.").convertToDouble()); EXPECT_EQ(0.0, APFloat(APFloat::IEEEdouble, ".00000").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble, "+.00000").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble, "-.00000").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble, "0000.00000").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble, "+0000.00000").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble, "-0000.00000").convertToDouble()); } TEST(APFloatTest, fromZeroDecimalSingleExponentString) { EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble, "0e1").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble, "+0e1").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble, "-0e1").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble, "0e+1").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble, "+0e+1").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble, "-0e+1").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble, "0e-1").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble, "+0e-1").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble, "-0e-1").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble, "0.e1").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble, "+0.e1").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble, "-0.e1").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble, "0.e+1").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble, "+0.e+1").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble, "-0.e+1").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble, "0.e-1").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble, "+0.e-1").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble, "-0.e-1").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble, ".0e1").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble, "+.0e1").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble, "-.0e1").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble, ".0e+1").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble, "+.0e+1").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble, "-.0e+1").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble, ".0e-1").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble, "+.0e-1").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble, "-.0e-1").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble, "0.0e1").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble, "+0.0e1").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble, "-0.0e1").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble, "0.0e+1").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble, "+0.0e+1").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble, "-0.0e+1").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble, "0.0e-1").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble, "+0.0e-1").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble, "-0.0e-1").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble, "000.0000e1").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble, "+000.0000e+1").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble, "-000.0000e+1").convertToDouble()); } TEST(APFloatTest, fromZeroDecimalLargeExponentString) { EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble, "0e1234").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble, "+0e1234").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble, "-0e1234").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble, "0e+1234").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble, "+0e+1234").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble, "-0e+1234").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble, "0e-1234").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble, "+0e-1234").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble, "-0e-1234").convertToDouble()); EXPECT_EQ(0.0, APFloat(APFloat::IEEEdouble, "000.0000e1234").convertToDouble()); EXPECT_EQ(0.0, APFloat(APFloat::IEEEdouble, "000.0000e-1234").convertToDouble()); EXPECT_EQ(0.0, APFloat(APFloat::IEEEdouble, StringRef("0e1234\02", 6)).convertToDouble()); } TEST(APFloatTest, fromZeroHexadecimalString) { EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble, "0x0p1").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble, "+0x0p1").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble, "-0x0p1").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble, "0x0p+1").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble, "+0x0p+1").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble, "-0x0p+1").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble, "0x0p-1").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble, "+0x0p-1").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble, "-0x0p-1").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble, "0x0.p1").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble, "+0x0.p1").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble, "-0x0.p1").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble, "0x0.p+1").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble, "+0x0.p+1").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble, "-0x0.p+1").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble, "0x0.p-1").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble, "+0x0.p-1").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble, "-0x0.p-1").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble, "0x.0p1").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble, "+0x.0p1").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble, "-0x.0p1").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble, "0x.0p+1").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble, "+0x.0p+1").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble, "-0x.0p+1").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble, "0x.0p-1").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble, "+0x.0p-1").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble, "-0x.0p-1").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble, "0x0.0p1").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble, "+0x0.0p1").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble, "-0x0.0p1").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble, "0x0.0p+1").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble, "+0x0.0p+1").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble, "-0x0.0p+1").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble, "0x0.0p-1").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble, "+0x0.0p-1").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble, "-0x0.0p-1").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble, "0x00000.p1").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble, "0x0000.00000p1").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble, "0x.00000p1").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble, "0x0.p1").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble, "0x0p1234").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble, "-0x0p1234").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble, "0x00000.p1234").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble, "0x0000.00000p1234").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble, "0x.00000p1234").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble, "0x0.p1234").convertToDouble()); } TEST(APFloatTest, fromDecimalString) { EXPECT_EQ(1.0, APFloat(APFloat::IEEEdouble, "1").convertToDouble()); EXPECT_EQ(2.0, APFloat(APFloat::IEEEdouble, "2.").convertToDouble()); EXPECT_EQ(0.5, APFloat(APFloat::IEEEdouble, ".5").convertToDouble()); EXPECT_EQ(1.0, APFloat(APFloat::IEEEdouble, "1.0").convertToDouble()); EXPECT_EQ(-2.0, APFloat(APFloat::IEEEdouble, "-2").convertToDouble()); EXPECT_EQ(-4.0, APFloat(APFloat::IEEEdouble, "-4.").convertToDouble()); EXPECT_EQ(-0.5, APFloat(APFloat::IEEEdouble, "-.5").convertToDouble()); EXPECT_EQ(-1.5, APFloat(APFloat::IEEEdouble, "-1.5").convertToDouble()); EXPECT_EQ(1.25e12, APFloat(APFloat::IEEEdouble, "1.25e12").convertToDouble()); EXPECT_EQ(1.25e+12, APFloat(APFloat::IEEEdouble, "1.25e+12").convertToDouble()); EXPECT_EQ(1.25e-12, APFloat(APFloat::IEEEdouble, "1.25e-12").convertToDouble()); EXPECT_EQ(1024.0, APFloat(APFloat::IEEEdouble, "1024.").convertToDouble()); EXPECT_EQ(1024.05, APFloat(APFloat::IEEEdouble, "1024.05000").convertToDouble()); EXPECT_EQ(0.05, APFloat(APFloat::IEEEdouble, ".05000").convertToDouble()); EXPECT_EQ(2.0, APFloat(APFloat::IEEEdouble, "2.").convertToDouble()); EXPECT_EQ(2.0e2, APFloat(APFloat::IEEEdouble, "2.e2").convertToDouble()); EXPECT_EQ(2.0e+2, APFloat(APFloat::IEEEdouble, "2.e+2").convertToDouble()); EXPECT_EQ(2.0e-2, APFloat(APFloat::IEEEdouble, "2.e-2").convertToDouble()); EXPECT_EQ(2.05e2, APFloat(APFloat::IEEEdouble, "002.05000e2").convertToDouble()); EXPECT_EQ(2.05e+2, APFloat(APFloat::IEEEdouble, "002.05000e+2").convertToDouble()); EXPECT_EQ(2.05e-2, APFloat(APFloat::IEEEdouble, "002.05000e-2").convertToDouble()); EXPECT_EQ(2.05e12, APFloat(APFloat::IEEEdouble, "002.05000e12").convertToDouble()); EXPECT_EQ(2.05e+12, APFloat(APFloat::IEEEdouble, "002.05000e+12").convertToDouble()); EXPECT_EQ(2.05e-12, APFloat(APFloat::IEEEdouble, "002.05000e-12").convertToDouble()); // These are "carefully selected" to overflow the fast log-base // calculations in APFloat.cpp EXPECT_TRUE(APFloat(APFloat::IEEEdouble, "99e99999").isInfinity()); EXPECT_TRUE(APFloat(APFloat::IEEEdouble, "-99e99999").isInfinity()); EXPECT_TRUE(APFloat(APFloat::IEEEdouble, "1e-99999").isPosZero()); EXPECT_TRUE(APFloat(APFloat::IEEEdouble, "-1e-99999").isNegZero()); EXPECT_EQ(2.71828, convertToDoubleFromString("2.71828")); } TEST(APFloatTest, fromHexadecimalString) { EXPECT_EQ( 1.0, APFloat(APFloat::IEEEdouble, "0x1p0").convertToDouble()); EXPECT_EQ(+1.0, APFloat(APFloat::IEEEdouble, "+0x1p0").convertToDouble()); EXPECT_EQ(-1.0, APFloat(APFloat::IEEEdouble, "-0x1p0").convertToDouble()); EXPECT_EQ( 1.0, APFloat(APFloat::IEEEdouble, "0x1p+0").convertToDouble()); EXPECT_EQ(+1.0, APFloat(APFloat::IEEEdouble, "+0x1p+0").convertToDouble()); EXPECT_EQ(-1.0, APFloat(APFloat::IEEEdouble, "-0x1p+0").convertToDouble()); EXPECT_EQ( 1.0, APFloat(APFloat::IEEEdouble, "0x1p-0").convertToDouble()); EXPECT_EQ(+1.0, APFloat(APFloat::IEEEdouble, "+0x1p-0").convertToDouble()); EXPECT_EQ(-1.0, APFloat(APFloat::IEEEdouble, "-0x1p-0").convertToDouble()); EXPECT_EQ( 2.0, APFloat(APFloat::IEEEdouble, "0x1p1").convertToDouble()); EXPECT_EQ(+2.0, APFloat(APFloat::IEEEdouble, "+0x1p1").convertToDouble()); EXPECT_EQ(-2.0, APFloat(APFloat::IEEEdouble, "-0x1p1").convertToDouble()); EXPECT_EQ( 2.0, APFloat(APFloat::IEEEdouble, "0x1p+1").convertToDouble()); EXPECT_EQ(+2.0, APFloat(APFloat::IEEEdouble, "+0x1p+1").convertToDouble()); EXPECT_EQ(-2.0, APFloat(APFloat::IEEEdouble, "-0x1p+1").convertToDouble()); EXPECT_EQ( 0.5, APFloat(APFloat::IEEEdouble, "0x1p-1").convertToDouble()); EXPECT_EQ(+0.5, APFloat(APFloat::IEEEdouble, "+0x1p-1").convertToDouble()); EXPECT_EQ(-0.5, APFloat(APFloat::IEEEdouble, "-0x1p-1").convertToDouble()); EXPECT_EQ( 3.0, APFloat(APFloat::IEEEdouble, "0x1.8p1").convertToDouble()); EXPECT_EQ(+3.0, APFloat(APFloat::IEEEdouble, "+0x1.8p1").convertToDouble()); EXPECT_EQ(-3.0, APFloat(APFloat::IEEEdouble, "-0x1.8p1").convertToDouble()); EXPECT_EQ( 3.0, APFloat(APFloat::IEEEdouble, "0x1.8p+1").convertToDouble()); EXPECT_EQ(+3.0, APFloat(APFloat::IEEEdouble, "+0x1.8p+1").convertToDouble()); EXPECT_EQ(-3.0, APFloat(APFloat::IEEEdouble, "-0x1.8p+1").convertToDouble()); EXPECT_EQ( 0.75, APFloat(APFloat::IEEEdouble, "0x1.8p-1").convertToDouble()); EXPECT_EQ(+0.75, APFloat(APFloat::IEEEdouble, "+0x1.8p-1").convertToDouble()); EXPECT_EQ(-0.75, APFloat(APFloat::IEEEdouble, "-0x1.8p-1").convertToDouble()); EXPECT_EQ( 8192.0, APFloat(APFloat::IEEEdouble, "0x1000.000p1").convertToDouble()); EXPECT_EQ(+8192.0, APFloat(APFloat::IEEEdouble, "+0x1000.000p1").convertToDouble()); EXPECT_EQ(-8192.0, APFloat(APFloat::IEEEdouble, "-0x1000.000p1").convertToDouble()); EXPECT_EQ( 8192.0, APFloat(APFloat::IEEEdouble, "0x1000.000p+1").convertToDouble()); EXPECT_EQ(+8192.0, APFloat(APFloat::IEEEdouble, "+0x1000.000p+1").convertToDouble()); EXPECT_EQ(-8192.0, APFloat(APFloat::IEEEdouble, "-0x1000.000p+1").convertToDouble()); EXPECT_EQ( 2048.0, APFloat(APFloat::IEEEdouble, "0x1000.000p-1").convertToDouble()); EXPECT_EQ(+2048.0, APFloat(APFloat::IEEEdouble, "+0x1000.000p-1").convertToDouble()); EXPECT_EQ(-2048.0, APFloat(APFloat::IEEEdouble, "-0x1000.000p-1").convertToDouble()); EXPECT_EQ( 8192.0, APFloat(APFloat::IEEEdouble, "0x1000p1").convertToDouble()); EXPECT_EQ(+8192.0, APFloat(APFloat::IEEEdouble, "+0x1000p1").convertToDouble()); EXPECT_EQ(-8192.0, APFloat(APFloat::IEEEdouble, "-0x1000p1").convertToDouble()); EXPECT_EQ( 8192.0, APFloat(APFloat::IEEEdouble, "0x1000p+1").convertToDouble()); EXPECT_EQ(+8192.0, APFloat(APFloat::IEEEdouble, "+0x1000p+1").convertToDouble()); EXPECT_EQ(-8192.0, APFloat(APFloat::IEEEdouble, "-0x1000p+1").convertToDouble()); EXPECT_EQ( 2048.0, APFloat(APFloat::IEEEdouble, "0x1000p-1").convertToDouble()); EXPECT_EQ(+2048.0, APFloat(APFloat::IEEEdouble, "+0x1000p-1").convertToDouble()); EXPECT_EQ(-2048.0, APFloat(APFloat::IEEEdouble, "-0x1000p-1").convertToDouble()); EXPECT_EQ( 16384.0, APFloat(APFloat::IEEEdouble, "0x10p10").convertToDouble()); EXPECT_EQ(+16384.0, APFloat(APFloat::IEEEdouble, "+0x10p10").convertToDouble()); EXPECT_EQ(-16384.0, APFloat(APFloat::IEEEdouble, "-0x10p10").convertToDouble()); EXPECT_EQ( 16384.0, APFloat(APFloat::IEEEdouble, "0x10p+10").convertToDouble()); EXPECT_EQ(+16384.0, APFloat(APFloat::IEEEdouble, "+0x10p+10").convertToDouble()); EXPECT_EQ(-16384.0, APFloat(APFloat::IEEEdouble, "-0x10p+10").convertToDouble()); EXPECT_EQ( 0.015625, APFloat(APFloat::IEEEdouble, "0x10p-10").convertToDouble()); EXPECT_EQ(+0.015625, APFloat(APFloat::IEEEdouble, "+0x10p-10").convertToDouble()); EXPECT_EQ(-0.015625, APFloat(APFloat::IEEEdouble, "-0x10p-10").convertToDouble()); EXPECT_EQ(1.0625, APFloat(APFloat::IEEEdouble, "0x1.1p0").convertToDouble()); EXPECT_EQ(1.0, APFloat(APFloat::IEEEdouble, "0x1p0").convertToDouble()); EXPECT_EQ(convertToDoubleFromString("0x1p-150"), convertToDoubleFromString("+0x800000000000000001.p-221")); EXPECT_EQ(2251799813685248.5, convertToDoubleFromString("0x80000000000004000000.010p-28")); } TEST(APFloatTest, toString) { ASSERT_EQ("10", convertToString(10.0, 6, 3)); ASSERT_EQ("1.0E+1", convertToString(10.0, 6, 0)); ASSERT_EQ("10100", convertToString(1.01E+4, 5, 2)); ASSERT_EQ("1.01E+4", convertToString(1.01E+4, 4, 2)); ASSERT_EQ("1.01E+4", convertToString(1.01E+4, 5, 1)); ASSERT_EQ("0.0101", convertToString(1.01E-2, 5, 2)); ASSERT_EQ("0.0101", convertToString(1.01E-2, 4, 2)); ASSERT_EQ("1.01E-2", convertToString(1.01E-2, 5, 1)); ASSERT_EQ("0.78539816339744828", convertToString(0.78539816339744830961, 0, 3)); ASSERT_EQ("4.9406564584124654E-324", convertToString(4.9406564584124654e-324, 0, 3)); ASSERT_EQ("873.18340000000001", convertToString(873.1834, 0, 1)); ASSERT_EQ("8.7318340000000001E+2", convertToString(873.1834, 0, 0)); ASSERT_EQ("1.7976931348623157E+308", convertToString(1.7976931348623157E+308, 0, 0)); } TEST(APFloatTest, toInteger) { bool isExact = false; APSInt result(5, /*isUnsigned=*/true); EXPECT_EQ(APFloat::opOK, APFloat(APFloat::IEEEdouble, "10") .convertToInteger(result, APFloat::rmTowardZero, &isExact)); EXPECT_TRUE(isExact); EXPECT_EQ(APSInt(APInt(5, 10), true), result); EXPECT_EQ(APFloat::opInvalidOp, APFloat(APFloat::IEEEdouble, "-10") .convertToInteger(result, APFloat::rmTowardZero, &isExact)); EXPECT_FALSE(isExact); EXPECT_EQ(APSInt::getMinValue(5, true), result); EXPECT_EQ(APFloat::opInvalidOp, APFloat(APFloat::IEEEdouble, "32") .convertToInteger(result, APFloat::rmTowardZero, &isExact)); EXPECT_FALSE(isExact); EXPECT_EQ(APSInt::getMaxValue(5, true), result); EXPECT_EQ(APFloat::opInexact, APFloat(APFloat::IEEEdouble, "7.9") .convertToInteger(result, APFloat::rmTowardZero, &isExact)); EXPECT_FALSE(isExact); EXPECT_EQ(APSInt(APInt(5, 7), true), result); result.setIsUnsigned(false); EXPECT_EQ(APFloat::opOK, APFloat(APFloat::IEEEdouble, "-10") .convertToInteger(result, APFloat::rmTowardZero, &isExact)); EXPECT_TRUE(isExact); EXPECT_EQ(APSInt(APInt(5, -10, true), false), result); EXPECT_EQ(APFloat::opInvalidOp, APFloat(APFloat::IEEEdouble, "-17") .convertToInteger(result, APFloat::rmTowardZero, &isExact)); EXPECT_FALSE(isExact); EXPECT_EQ(APSInt::getMinValue(5, false), result); EXPECT_EQ(APFloat::opInvalidOp, APFloat(APFloat::IEEEdouble, "16") .convertToInteger(result, APFloat::rmTowardZero, &isExact)); EXPECT_FALSE(isExact); EXPECT_EQ(APSInt::getMaxValue(5, false), result); } static APInt nanbits(const fltSemantics &Sem, bool SNaN, bool Negative, uint64_t fill) { APInt apfill(64, fill); if (SNaN) return APFloat::getSNaN(Sem, Negative, &apfill).bitcastToAPInt(); else return APFloat::getQNaN(Sem, Negative, &apfill).bitcastToAPInt(); } TEST(APFloatTest, makeNaN) { ASSERT_EQ(0x7fc00000, nanbits(APFloat::IEEEsingle, false, false, 0)); ASSERT_EQ(0xffc00000, nanbits(APFloat::IEEEsingle, false, true, 0)); ASSERT_EQ(0x7fc0ae72, nanbits(APFloat::IEEEsingle, false, false, 0xae72)); ASSERT_EQ(0x7fffae72, nanbits(APFloat::IEEEsingle, false, false, 0xffffae72)); ASSERT_EQ(0x7fa00000, nanbits(APFloat::IEEEsingle, true, false, 0)); ASSERT_EQ(0xffa00000, nanbits(APFloat::IEEEsingle, true, true, 0)); ASSERT_EQ(0x7f80ae72, nanbits(APFloat::IEEEsingle, true, false, 0xae72)); ASSERT_EQ(0x7fbfae72, nanbits(APFloat::IEEEsingle, true, false, 0xffffae72)); ASSERT_EQ(0x7ff8000000000000ULL, nanbits(APFloat::IEEEdouble, false, false, 0)); ASSERT_EQ(0xfff8000000000000ULL, nanbits(APFloat::IEEEdouble, false, true, 0)); ASSERT_EQ(0x7ff800000000ae72ULL, nanbits(APFloat::IEEEdouble, false, false, 0xae72)); ASSERT_EQ(0x7fffffffffffae72ULL, nanbits(APFloat::IEEEdouble, false, false, 0xffffffffffffae72ULL)); ASSERT_EQ(0x7ff4000000000000ULL, nanbits(APFloat::IEEEdouble, true, false, 0)); ASSERT_EQ(0xfff4000000000000ULL, nanbits(APFloat::IEEEdouble, true, true, 0)); ASSERT_EQ(0x7ff000000000ae72ULL, nanbits(APFloat::IEEEdouble, true, false, 0xae72)); ASSERT_EQ(0x7ff7ffffffffae72ULL, nanbits(APFloat::IEEEdouble, true, false, 0xffffffffffffae72ULL)); } #ifdef GTEST_HAS_DEATH_TEST #ifndef NDEBUG TEST(APFloatTest, SemanticsDeath) { EXPECT_DEATH(APFloat(APFloat::IEEEsingle, 0.0f).convertToDouble(), "Float semantics are not IEEEdouble"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, 0.0 ).convertToFloat(), "Float semantics are not IEEEsingle"); } TEST(APFloatTest, StringDecimalDeath) { EXPECT_DEATH(APFloat(APFloat::IEEEdouble, ""), "Invalid string length"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "+"), "String has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "-"), "String has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, StringRef("\0", 1)), "Invalid character in significand"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, StringRef("1\0", 2)), "Invalid character in significand"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, StringRef("1\02", 3)), "Invalid character in significand"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, StringRef("1\02e1", 5)), "Invalid character in significand"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, StringRef("1e\0", 3)), "Invalid character in exponent"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, StringRef("1e1\0", 4)), "Invalid character in exponent"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, StringRef("1e1\02", 5)), "Invalid character in exponent"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "1.0f"), "Invalid character in significand"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, ".."), "String contains multiple dots"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "..0"), "String contains multiple dots"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "1.0.0"), "String contains multiple dots"); } TEST(APFloatTest, StringDecimalSignificandDeath) { EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "."), "Significand has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "+."), "Significand has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "-."), "Significand has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "e"), "Significand has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "+e"), "Significand has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "-e"), "Significand has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "e1"), "Significand has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "+e1"), "Significand has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "-e1"), "Significand has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, ".e1"), "Significand has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "+.e1"), "Significand has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "-.e1"), "Significand has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, ".e"), "Significand has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "+.e"), "Significand has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "-.e"), "Significand has no digits"); } TEST(APFloatTest, StringDecimalExponentDeath) { EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "1e"), "Exponent has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "+1e"), "Exponent has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "-1e"), "Exponent has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "1.e"), "Exponent has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "+1.e"), "Exponent has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "-1.e"), "Exponent has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, ".1e"), "Exponent has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "+.1e"), "Exponent has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "-.1e"), "Exponent has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "1.1e"), "Exponent has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "+1.1e"), "Exponent has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "-1.1e"), "Exponent has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "1e+"), "Exponent has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "1e-"), "Exponent has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, ".1e"), "Exponent has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, ".1e+"), "Exponent has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, ".1e-"), "Exponent has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "1.0e"), "Exponent has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "1.0e+"), "Exponent has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "1.0e-"), "Exponent has no digits"); } TEST(APFloatTest, StringHexadecimalDeath) { EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "0x"), "Invalid string"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "+0x"), "Invalid string"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "-0x"), "Invalid string"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "0x0"), "Hex strings require an exponent"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "+0x0"), "Hex strings require an exponent"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "-0x0"), "Hex strings require an exponent"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "0x0."), "Hex strings require an exponent"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "+0x0."), "Hex strings require an exponent"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "-0x0."), "Hex strings require an exponent"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "0x.0"), "Hex strings require an exponent"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "+0x.0"), "Hex strings require an exponent"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "-0x.0"), "Hex strings require an exponent"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "0x0.0"), "Hex strings require an exponent"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "+0x0.0"), "Hex strings require an exponent"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "-0x0.0"), "Hex strings require an exponent"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, StringRef("0x\0", 3)), "Invalid character in significand"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, StringRef("0x1\0", 4)), "Invalid character in significand"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, StringRef("0x1\02", 5)), "Invalid character in significand"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, StringRef("0x1\02p1", 7)), "Invalid character in significand"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, StringRef("0x1p\0", 5)), "Invalid character in exponent"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, StringRef("0x1p1\0", 6)), "Invalid character in exponent"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, StringRef("0x1p1\02", 7)), "Invalid character in exponent"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "0x1p0f"), "Invalid character in exponent"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "0x..p1"), "String contains multiple dots"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "0x..0p1"), "String contains multiple dots"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "0x1.0.0p1"), "String contains multiple dots"); } TEST(APFloatTest, StringHexadecimalSignificandDeath) { EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "0x."), "Significand has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "+0x."), "Significand has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "-0x."), "Significand has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "0xp"), "Significand has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "+0xp"), "Significand has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "-0xp"), "Significand has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "0xp+"), "Significand has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "+0xp+"), "Significand has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "-0xp+"), "Significand has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "0xp-"), "Significand has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "+0xp-"), "Significand has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "-0xp-"), "Significand has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "0x.p"), "Significand has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "+0x.p"), "Significand has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "-0x.p"), "Significand has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "0x.p+"), "Significand has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "+0x.p+"), "Significand has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "-0x.p+"), "Significand has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "0x.p-"), "Significand has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "+0x.p-"), "Significand has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "-0x.p-"), "Significand has no digits"); } TEST(APFloatTest, StringHexadecimalExponentDeath) { EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "0x1p"), "Exponent has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "+0x1p"), "Exponent has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "-0x1p"), "Exponent has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "0x1p+"), "Exponent has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "+0x1p+"), "Exponent has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "-0x1p+"), "Exponent has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "0x1p-"), "Exponent has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "+0x1p-"), "Exponent has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "-0x1p-"), "Exponent has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "0x1.p"), "Exponent has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "+0x1.p"), "Exponent has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "-0x1.p"), "Exponent has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "0x1.p+"), "Exponent has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "+0x1.p+"), "Exponent has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "-0x1.p+"), "Exponent has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "0x1.p-"), "Exponent has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "+0x1.p-"), "Exponent has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "-0x1.p-"), "Exponent has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "0x.1p"), "Exponent has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "+0x.1p"), "Exponent has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "-0x.1p"), "Exponent has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "0x.1p+"), "Exponent has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "+0x.1p+"), "Exponent has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "-0x.1p+"), "Exponent has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "0x.1p-"), "Exponent has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "+0x.1p-"), "Exponent has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "-0x.1p-"), "Exponent has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "0x1.1p"), "Exponent has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "+0x1.1p"), "Exponent has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "-0x1.1p"), "Exponent has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "0x1.1p+"), "Exponent has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "+0x1.1p+"), "Exponent has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "-0x1.1p+"), "Exponent has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "0x1.1p-"), "Exponent has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "+0x1.1p-"), "Exponent has no digits"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble, "-0x1.1p-"), "Exponent has no digits"); } #endif #endif TEST(APFloatTest, exactInverse) { APFloat inv(0.0f); // Trivial operation. EXPECT_TRUE(APFloat(2.0).getExactInverse(&inv)); EXPECT_TRUE(inv.bitwiseIsEqual(APFloat(0.5))); EXPECT_TRUE(APFloat(2.0f).getExactInverse(&inv)); EXPECT_TRUE(inv.bitwiseIsEqual(APFloat(0.5f))); EXPECT_TRUE(APFloat(APFloat::IEEEquad, "2.0").getExactInverse(&inv)); EXPECT_TRUE(inv.bitwiseIsEqual(APFloat(APFloat::IEEEquad, "0.5"))); EXPECT_TRUE(APFloat(APFloat::PPCDoubleDouble, "2.0").getExactInverse(&inv)); EXPECT_TRUE(inv.bitwiseIsEqual(APFloat(APFloat::PPCDoubleDouble, "0.5"))); EXPECT_TRUE(APFloat(APFloat::x87DoubleExtended, "2.0").getExactInverse(&inv)); EXPECT_TRUE(inv.bitwiseIsEqual(APFloat(APFloat::x87DoubleExtended, "0.5"))); // FLT_MIN EXPECT_TRUE(APFloat(1.17549435e-38f).getExactInverse(&inv)); EXPECT_TRUE(inv.bitwiseIsEqual(APFloat(8.5070592e+37f))); // Large float, inverse is a denormal. EXPECT_FALSE(APFloat(1.7014118e38f).getExactInverse(nullptr)); // Zero EXPECT_FALSE(APFloat(0.0).getExactInverse(nullptr)); // Denormalized float EXPECT_FALSE(APFloat(1.40129846e-45f).getExactInverse(nullptr)); } TEST(APFloatTest, roundToIntegral) { APFloat T(-0.5), S(3.14), R(APFloat::getLargest(APFloat::IEEEdouble)), P(0.0); P = T; P.roundToIntegral(APFloat::rmTowardZero); EXPECT_EQ(-0.0, P.convertToDouble()); P = T; P.roundToIntegral(APFloat::rmTowardNegative); EXPECT_EQ(-1.0, P.convertToDouble()); P = T; P.roundToIntegral(APFloat::rmTowardPositive); EXPECT_EQ(-0.0, P.convertToDouble()); P = T; P.roundToIntegral(APFloat::rmNearestTiesToEven); EXPECT_EQ(-0.0, P.convertToDouble()); P = S; P.roundToIntegral(APFloat::rmTowardZero); EXPECT_EQ(3.0, P.convertToDouble()); P = S; P.roundToIntegral(APFloat::rmTowardNegative); EXPECT_EQ(3.0, P.convertToDouble()); P = S; P.roundToIntegral(APFloat::rmTowardPositive); EXPECT_EQ(4.0, P.convertToDouble()); P = S; P.roundToIntegral(APFloat::rmNearestTiesToEven); EXPECT_EQ(3.0, P.convertToDouble()); P = R; P.roundToIntegral(APFloat::rmTowardZero); EXPECT_EQ(R.convertToDouble(), P.convertToDouble()); P = R; P.roundToIntegral(APFloat::rmTowardNegative); EXPECT_EQ(R.convertToDouble(), P.convertToDouble()); P = R; P.roundToIntegral(APFloat::rmTowardPositive); EXPECT_EQ(R.convertToDouble(), P.convertToDouble()); P = R; P.roundToIntegral(APFloat::rmNearestTiesToEven); EXPECT_EQ(R.convertToDouble(), P.convertToDouble()); P = APFloat::getZero(APFloat::IEEEdouble); P.roundToIntegral(APFloat::rmTowardZero); EXPECT_EQ(0.0, P.convertToDouble()); P = APFloat::getZero(APFloat::IEEEdouble, true); P.roundToIntegral(APFloat::rmTowardZero); EXPECT_EQ(-0.0, P.convertToDouble()); P = APFloat::getNaN(APFloat::IEEEdouble); P.roundToIntegral(APFloat::rmTowardZero); EXPECT_TRUE(std::isnan(P.convertToDouble())); P = APFloat::getInf(APFloat::IEEEdouble); P.roundToIntegral(APFloat::rmTowardZero); EXPECT_TRUE(std::isinf(P.convertToDouble()) && P.convertToDouble() > 0.0); P = APFloat::getInf(APFloat::IEEEdouble, true); P.roundToIntegral(APFloat::rmTowardZero); EXPECT_TRUE(std::isinf(P.convertToDouble()) && P.convertToDouble() < 0.0); } TEST(APFloatTest, getLargest) { EXPECT_EQ(3.402823466e+38f, APFloat::getLargest(APFloat::IEEEsingle).convertToFloat()); EXPECT_EQ(1.7976931348623158e+308, APFloat::getLargest(APFloat::IEEEdouble).convertToDouble()); } TEST(APFloatTest, getSmallest) { APFloat test = APFloat::getSmallest(APFloat::IEEEsingle, false); APFloat expected = APFloat(APFloat::IEEEsingle, "0x0.000002p-126"); EXPECT_FALSE(test.isNegative()); EXPECT_TRUE(test.isFiniteNonZero()); EXPECT_TRUE(test.isDenormal()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); test = APFloat::getSmallest(APFloat::IEEEsingle, true); expected = APFloat(APFloat::IEEEsingle, "-0x0.000002p-126"); EXPECT_TRUE(test.isNegative()); EXPECT_TRUE(test.isFiniteNonZero()); EXPECT_TRUE(test.isDenormal()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); test = APFloat::getSmallest(APFloat::IEEEquad, false); expected = APFloat(APFloat::IEEEquad, "0x0.0000000000000000000000000001p-16382"); EXPECT_FALSE(test.isNegative()); EXPECT_TRUE(test.isFiniteNonZero()); EXPECT_TRUE(test.isDenormal()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); test = APFloat::getSmallest(APFloat::IEEEquad, true); expected = APFloat(APFloat::IEEEquad, "-0x0.0000000000000000000000000001p-16382"); EXPECT_TRUE(test.isNegative()); EXPECT_TRUE(test.isFiniteNonZero()); EXPECT_TRUE(test.isDenormal()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); } TEST(APFloatTest, getSmallestNormalized) { APFloat test = APFloat::getSmallestNormalized(APFloat::IEEEsingle, false); APFloat expected = APFloat(APFloat::IEEEsingle, "0x1p-126"); EXPECT_FALSE(test.isNegative()); EXPECT_TRUE(test.isFiniteNonZero()); EXPECT_FALSE(test.isDenormal()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); test = APFloat::getSmallestNormalized(APFloat::IEEEsingle, true); expected = APFloat(APFloat::IEEEsingle, "-0x1p-126"); EXPECT_TRUE(test.isNegative()); EXPECT_TRUE(test.isFiniteNonZero()); EXPECT_FALSE(test.isDenormal()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); test = APFloat::getSmallestNormalized(APFloat::IEEEquad, false); expected = APFloat(APFloat::IEEEquad, "0x1p-16382"); EXPECT_FALSE(test.isNegative()); EXPECT_TRUE(test.isFiniteNonZero()); EXPECT_FALSE(test.isDenormal()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); test = APFloat::getSmallestNormalized(APFloat::IEEEquad, true); expected = APFloat(APFloat::IEEEquad, "-0x1p-16382"); EXPECT_TRUE(test.isNegative()); EXPECT_TRUE(test.isFiniteNonZero()); EXPECT_FALSE(test.isDenormal()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); } TEST(APFloatTest, getZero) { struct { const fltSemantics *semantics; const bool sign; const unsigned long long bitPattern[2]; const unsigned bitPatternLength; } const GetZeroTest[] = { { &APFloat::IEEEhalf, false, {0, 0}, 1}, { &APFloat::IEEEhalf, true, {0x8000ULL, 0}, 1}, { &APFloat::IEEEsingle, false, {0, 0}, 1}, { &APFloat::IEEEsingle, true, {0x80000000ULL, 0}, 1}, { &APFloat::IEEEdouble, false, {0, 0}, 1}, { &APFloat::IEEEdouble, true, {0x8000000000000000ULL, 0}, 1}, { &APFloat::IEEEquad, false, {0, 0}, 2}, { &APFloat::IEEEquad, true, {0, 0x8000000000000000ULL}, 2}, { &APFloat::PPCDoubleDouble, false, {0, 0}, 2}, { &APFloat::PPCDoubleDouble, true, {0x8000000000000000ULL, 0}, 2}, { &APFloat::x87DoubleExtended, false, {0, 0}, 2}, { &APFloat::x87DoubleExtended, true, {0, 0x8000ULL}, 2}, }; const unsigned NumGetZeroTests = 12; for (unsigned i = 0; i < NumGetZeroTests; ++i) { APFloat test = APFloat::getZero(*GetZeroTest[i].semantics, GetZeroTest[i].sign); const char *pattern = GetZeroTest[i].sign? "-0x0p+0" : "0x0p+0"; APFloat expected = APFloat(*GetZeroTest[i].semantics, pattern); EXPECT_TRUE(test.isZero()); EXPECT_TRUE(GetZeroTest[i].sign? test.isNegative() : !test.isNegative()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); for (unsigned j = 0, je = GetZeroTest[i].bitPatternLength; j < je; ++j) { EXPECT_EQ(GetZeroTest[i].bitPattern[j], test.bitcastToAPInt().getRawData()[j]); } } } TEST(APFloatTest, copySign) { EXPECT_TRUE(APFloat(-42.0).bitwiseIsEqual( APFloat::copySign(APFloat(42.0), APFloat(-1.0)))); EXPECT_TRUE(APFloat(42.0).bitwiseIsEqual( APFloat::copySign(APFloat(-42.0), APFloat(1.0)))); EXPECT_TRUE(APFloat(-42.0).bitwiseIsEqual( APFloat::copySign(APFloat(-42.0), APFloat(-1.0)))); EXPECT_TRUE(APFloat(42.0).bitwiseIsEqual( APFloat::copySign(APFloat(42.0), APFloat(1.0)))); } TEST(APFloatTest, convert) { bool losesInfo; APFloat test(APFloat::IEEEdouble, "1.0"); test.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo); EXPECT_EQ(1.0f, test.convertToFloat()); EXPECT_FALSE(losesInfo); test = APFloat(APFloat::x87DoubleExtended, "0x1p-53"); test.add(APFloat(APFloat::x87DoubleExtended, "1.0"), APFloat::rmNearestTiesToEven); test.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo); EXPECT_EQ(1.0, test.convertToDouble()); EXPECT_TRUE(losesInfo); test = APFloat(APFloat::IEEEquad, "0x1p-53"); test.add(APFloat(APFloat::IEEEquad, "1.0"), APFloat::rmNearestTiesToEven); test.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo); EXPECT_EQ(1.0, test.convertToDouble()); EXPECT_TRUE(losesInfo); test = APFloat(APFloat::x87DoubleExtended, "0xf.fffffffp+28"); test.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo); EXPECT_EQ(4294967295.0, test.convertToDouble()); EXPECT_FALSE(losesInfo); test = APFloat::getSNaN(APFloat::IEEEsingle); APFloat X87SNaN = APFloat::getSNaN(APFloat::x87DoubleExtended); test.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven, &losesInfo); EXPECT_TRUE(test.bitwiseIsEqual(X87SNaN)); EXPECT_FALSE(losesInfo); test = APFloat::getQNaN(APFloat::IEEEsingle); APFloat X87QNaN = APFloat::getQNaN(APFloat::x87DoubleExtended); test.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven, &losesInfo); EXPECT_TRUE(test.bitwiseIsEqual(X87QNaN)); EXPECT_FALSE(losesInfo); test = APFloat::getSNaN(APFloat::x87DoubleExtended); test.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven, &losesInfo); EXPECT_TRUE(test.bitwiseIsEqual(X87SNaN)); EXPECT_FALSE(losesInfo); test = APFloat::getQNaN(APFloat::x87DoubleExtended); test.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven, &losesInfo); EXPECT_TRUE(test.bitwiseIsEqual(X87QNaN)); EXPECT_FALSE(losesInfo); } TEST(APFloatTest, PPCDoubleDouble) { APFloat test(APFloat::PPCDoubleDouble, "1.0"); EXPECT_EQ(0x3ff0000000000000ull, test.bitcastToAPInt().getRawData()[0]); EXPECT_EQ(0x0000000000000000ull, test.bitcastToAPInt().getRawData()[1]); test.divide(APFloat(APFloat::PPCDoubleDouble, "3.0"), APFloat::rmNearestTiesToEven); EXPECT_EQ(0x3fd5555555555555ull, test.bitcastToAPInt().getRawData()[0]); EXPECT_EQ(0x3c75555555555556ull, test.bitcastToAPInt().getRawData()[1]); // LDBL_MAX test = APFloat(APFloat::PPCDoubleDouble, "1.79769313486231580793728971405301e+308"); EXPECT_EQ(0x7fefffffffffffffull, test.bitcastToAPInt().getRawData()[0]); EXPECT_EQ(0x7c8ffffffffffffeull, test.bitcastToAPInt().getRawData()[1]); // LDBL_MIN test = APFloat(APFloat::PPCDoubleDouble, "2.00416836000897277799610805135016e-292"); EXPECT_EQ(0x0360000000000000ull, test.bitcastToAPInt().getRawData()[0]); EXPECT_EQ(0x0000000000000000ull, test.bitcastToAPInt().getRawData()[1]); test = APFloat(APFloat::PPCDoubleDouble, "1.0"); test.add(APFloat(APFloat::PPCDoubleDouble, "0x1p-105"), APFloat::rmNearestTiesToEven); EXPECT_EQ(0x3ff0000000000000ull, test.bitcastToAPInt().getRawData()[0]); EXPECT_EQ(0x3960000000000000ull, test.bitcastToAPInt().getRawData()[1]); test = APFloat(APFloat::PPCDoubleDouble, "1.0"); test.add(APFloat(APFloat::PPCDoubleDouble, "0x1p-106"), APFloat::rmNearestTiesToEven); EXPECT_EQ(0x3ff0000000000000ull, test.bitcastToAPInt().getRawData()[0]); #if 0 // XFAIL // This is what we would expect with a true double-double implementation EXPECT_EQ(0x3950000000000000ull, test.bitcastToAPInt().getRawData()[1]); #else // This is what we get with our 106-bit mantissa approximation EXPECT_EQ(0x0000000000000000ull, test.bitcastToAPInt().getRawData()[1]); #endif } TEST(APFloatTest, isNegative) { APFloat t(APFloat::IEEEsingle, "0x1p+0"); EXPECT_FALSE(t.isNegative()); t = APFloat(APFloat::IEEEsingle, "-0x1p+0"); EXPECT_TRUE(t.isNegative()); EXPECT_FALSE(APFloat::getInf(APFloat::IEEEsingle, false).isNegative()); EXPECT_TRUE(APFloat::getInf(APFloat::IEEEsingle, true).isNegative()); EXPECT_FALSE(APFloat::getZero(APFloat::IEEEsingle, false).isNegative()); EXPECT_TRUE(APFloat::getZero(APFloat::IEEEsingle, true).isNegative()); EXPECT_FALSE(APFloat::getNaN(APFloat::IEEEsingle, false).isNegative()); EXPECT_TRUE(APFloat::getNaN(APFloat::IEEEsingle, true).isNegative()); EXPECT_FALSE(APFloat::getSNaN(APFloat::IEEEsingle, false).isNegative()); EXPECT_TRUE(APFloat::getSNaN(APFloat::IEEEsingle, true).isNegative()); } TEST(APFloatTest, isNormal) { APFloat t(APFloat::IEEEsingle, "0x1p+0"); EXPECT_TRUE(t.isNormal()); EXPECT_FALSE(APFloat::getInf(APFloat::IEEEsingle, false).isNormal()); EXPECT_FALSE(APFloat::getZero(APFloat::IEEEsingle, false).isNormal()); EXPECT_FALSE(APFloat::getNaN(APFloat::IEEEsingle, false).isNormal()); EXPECT_FALSE(APFloat::getSNaN(APFloat::IEEEsingle, false).isNormal()); EXPECT_FALSE(APFloat(APFloat::IEEEsingle, "0x1p-149").isNormal()); } TEST(APFloatTest, isFinite) { APFloat t(APFloat::IEEEsingle, "0x1p+0"); EXPECT_TRUE(t.isFinite()); EXPECT_FALSE(APFloat::getInf(APFloat::IEEEsingle, false).isFinite()); EXPECT_TRUE(APFloat::getZero(APFloat::IEEEsingle, false).isFinite()); EXPECT_FALSE(APFloat::getNaN(APFloat::IEEEsingle, false).isFinite()); EXPECT_FALSE(APFloat::getSNaN(APFloat::IEEEsingle, false).isFinite()); EXPECT_TRUE(APFloat(APFloat::IEEEsingle, "0x1p-149").isFinite()); } TEST(APFloatTest, isInfinity) { APFloat t(APFloat::IEEEsingle, "0x1p+0"); EXPECT_FALSE(t.isInfinity()); EXPECT_TRUE(APFloat::getInf(APFloat::IEEEsingle, false).isInfinity()); EXPECT_FALSE(APFloat::getZero(APFloat::IEEEsingle, false).isInfinity()); EXPECT_FALSE(APFloat::getNaN(APFloat::IEEEsingle, false).isInfinity()); EXPECT_FALSE(APFloat::getSNaN(APFloat::IEEEsingle, false).isInfinity()); EXPECT_FALSE(APFloat(APFloat::IEEEsingle, "0x1p-149").isInfinity()); } TEST(APFloatTest, isNaN) { APFloat t(APFloat::IEEEsingle, "0x1p+0"); EXPECT_FALSE(t.isNaN()); EXPECT_FALSE(APFloat::getInf(APFloat::IEEEsingle, false).isNaN()); EXPECT_FALSE(APFloat::getZero(APFloat::IEEEsingle, false).isNaN()); EXPECT_TRUE(APFloat::getNaN(APFloat::IEEEsingle, false).isNaN()); EXPECT_TRUE(APFloat::getSNaN(APFloat::IEEEsingle, false).isNaN()); EXPECT_FALSE(APFloat(APFloat::IEEEsingle, "0x1p-149").isNaN()); } TEST(APFloatTest, isFiniteNonZero) { // Test positive/negative normal value. EXPECT_TRUE(APFloat(APFloat::IEEEsingle, "0x1p+0").isFiniteNonZero()); EXPECT_TRUE(APFloat(APFloat::IEEEsingle, "-0x1p+0").isFiniteNonZero()); // Test positive/negative denormal value. EXPECT_TRUE(APFloat(APFloat::IEEEsingle, "0x1p-149").isFiniteNonZero()); EXPECT_TRUE(APFloat(APFloat::IEEEsingle, "-0x1p-149").isFiniteNonZero()); // Test +/- Infinity. EXPECT_FALSE(APFloat::getInf(APFloat::IEEEsingle, false).isFiniteNonZero()); EXPECT_FALSE(APFloat::getInf(APFloat::IEEEsingle, true).isFiniteNonZero()); // Test +/- Zero. EXPECT_FALSE(APFloat::getZero(APFloat::IEEEsingle, false).isFiniteNonZero()); EXPECT_FALSE(APFloat::getZero(APFloat::IEEEsingle, true).isFiniteNonZero()); // Test +/- qNaN. +/- dont mean anything with qNaN but paranoia can't hurt in // this instance. EXPECT_FALSE(APFloat::getNaN(APFloat::IEEEsingle, false).isFiniteNonZero()); EXPECT_FALSE(APFloat::getNaN(APFloat::IEEEsingle, true).isFiniteNonZero()); // Test +/- sNaN. +/- dont mean anything with sNaN but paranoia can't hurt in // this instance. EXPECT_FALSE(APFloat::getSNaN(APFloat::IEEEsingle, false).isFiniteNonZero()); EXPECT_FALSE(APFloat::getSNaN(APFloat::IEEEsingle, true).isFiniteNonZero()); } TEST(APFloatTest, add) { // Test Special Cases against each other and normal values. // TODOS/NOTES: // 1. Since we perform only default exception handling all operations with // signaling NaNs should have a result that is a quiet NaN. Currently they // return sNaN. APFloat PInf = APFloat::getInf(APFloat::IEEEsingle, false); APFloat MInf = APFloat::getInf(APFloat::IEEEsingle, true); APFloat PZero = APFloat::getZero(APFloat::IEEEsingle, false); APFloat MZero = APFloat::getZero(APFloat::IEEEsingle, true); APFloat QNaN = APFloat::getNaN(APFloat::IEEEsingle, false); APFloat SNaN = APFloat::getSNaN(APFloat::IEEEsingle, false); APFloat PNormalValue = APFloat(APFloat::IEEEsingle, "0x1p+0"); APFloat MNormalValue = APFloat(APFloat::IEEEsingle, "-0x1p+0"); APFloat PLargestValue = APFloat::getLargest(APFloat::IEEEsingle, false); APFloat MLargestValue = APFloat::getLargest(APFloat::IEEEsingle, true); APFloat PSmallestValue = APFloat::getSmallest(APFloat::IEEEsingle, false); APFloat MSmallestValue = APFloat::getSmallest(APFloat::IEEEsingle, true); APFloat PSmallestNormalized = APFloat::getSmallestNormalized(APFloat::IEEEsingle, false); APFloat MSmallestNormalized = APFloat::getSmallestNormalized(APFloat::IEEEsingle, true); const int OverflowStatus = APFloat::opOverflow | APFloat::opInexact; const unsigned NumTests = 169; struct { APFloat x; APFloat y; const char *result; int status; int category; } SpecialCaseTests[NumTests] = { { PInf, PInf, "inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, MInf, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { PInf, PZero, "inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, MZero, "inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { PInf, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { PInf, PNormalValue, "inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, MNormalValue, "inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, PLargestValue, "inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, MLargestValue, "inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, PSmallestValue, "inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, MSmallestValue, "inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, PSmallestNormalized, "inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, MSmallestNormalized, "inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, PInf, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { MInf, MInf, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, PZero, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, MZero, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { MInf, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { MInf, PNormalValue, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, MNormalValue, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, PLargestValue, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, MLargestValue, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, PSmallestValue, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, MSmallestValue, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, PSmallestNormalized, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, MSmallestNormalized, "-inf", APFloat::opOK, APFloat::fcInfinity }, { PZero, PInf, "inf", APFloat::opOK, APFloat::fcInfinity }, { PZero, MInf, "-inf", APFloat::opOK, APFloat::fcInfinity }, { PZero, PZero, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { PZero, MZero, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { PZero, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { PZero, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { PZero, PNormalValue, "0x1p+0", APFloat::opOK, APFloat::fcNormal }, { PZero, MNormalValue, "-0x1p+0", APFloat::opOK, APFloat::fcNormal }, { PZero, PLargestValue, "0x1.fffffep+127", APFloat::opOK, APFloat::fcNormal }, { PZero, MLargestValue, "-0x1.fffffep+127", APFloat::opOK, APFloat::fcNormal }, { PZero, PSmallestValue, "0x1p-149", APFloat::opOK, APFloat::fcNormal }, { PZero, MSmallestValue, "-0x1p-149", APFloat::opOK, APFloat::fcNormal }, { PZero, PSmallestNormalized, "0x1p-126", APFloat::opOK, APFloat::fcNormal }, { PZero, MSmallestNormalized, "-0x1p-126", APFloat::opOK, APFloat::fcNormal }, { MZero, PInf, "inf", APFloat::opOK, APFloat::fcInfinity }, { MZero, MInf, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MZero, PZero, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { MZero, MZero, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { MZero, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { MZero, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { MZero, PNormalValue, "0x1p+0", APFloat::opOK, APFloat::fcNormal }, { MZero, MNormalValue, "-0x1p+0", APFloat::opOK, APFloat::fcNormal }, { MZero, PLargestValue, "0x1.fffffep+127", APFloat::opOK, APFloat::fcNormal }, { MZero, MLargestValue, "-0x1.fffffep+127", APFloat::opOK, APFloat::fcNormal }, { MZero, PSmallestValue, "0x1p-149", APFloat::opOK, APFloat::fcNormal }, { MZero, MSmallestValue, "-0x1p-149", APFloat::opOK, APFloat::fcNormal }, { MZero, PSmallestNormalized, "0x1p-126", APFloat::opOK, APFloat::fcNormal }, { MZero, MSmallestNormalized, "-0x1p-126", APFloat::opOK, APFloat::fcNormal }, { QNaN, PInf, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, MInf, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, PZero, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, MZero, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { QNaN, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { QNaN, PNormalValue, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, MNormalValue, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, PLargestValue, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, MLargestValue, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, PSmallestValue, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, MSmallestValue, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, PSmallestNormalized, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, MSmallestNormalized, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { SNaN, PInf, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, MInf, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, PZero, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, MZero, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, QNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, PNormalValue, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, MNormalValue, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, PLargestValue, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, MLargestValue, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, PSmallestValue, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, MSmallestValue, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, PSmallestNormalized, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, MSmallestNormalized, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { PNormalValue, PInf, "inf", APFloat::opOK, APFloat::fcInfinity }, { PNormalValue, MInf, "-inf", APFloat::opOK, APFloat::fcInfinity }, { PNormalValue, PZero, "0x1p+0", APFloat::opOK, APFloat::fcNormal }, { PNormalValue, MZero, "0x1p+0", APFloat::opOK, APFloat::fcNormal }, { PNormalValue, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { PNormalValue, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { PNormalValue, PNormalValue, "0x1p+1", APFloat::opOK, APFloat::fcNormal }, { PNormalValue, MNormalValue, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { PNormalValue, PLargestValue, "0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { PNormalValue, MLargestValue, "-0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { PNormalValue, PSmallestValue, "0x1p+0", APFloat::opInexact, APFloat::fcNormal }, { PNormalValue, MSmallestValue, "0x1p+0", APFloat::opInexact, APFloat::fcNormal }, { PNormalValue, PSmallestNormalized, "0x1p+0", APFloat::opInexact, APFloat::fcNormal }, { PNormalValue, MSmallestNormalized, "0x1p+0", APFloat::opInexact, APFloat::fcNormal }, { MNormalValue, PInf, "inf", APFloat::opOK, APFloat::fcInfinity }, { MNormalValue, MInf, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MNormalValue, PZero, "-0x1p+0", APFloat::opOK, APFloat::fcNormal }, { MNormalValue, MZero, "-0x1p+0", APFloat::opOK, APFloat::fcNormal }, { MNormalValue, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { MNormalValue, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { MNormalValue, PNormalValue, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { MNormalValue, MNormalValue, "-0x1p+1", APFloat::opOK, APFloat::fcNormal }, { MNormalValue, PLargestValue, "0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { MNormalValue, MLargestValue, "-0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { MNormalValue, PSmallestValue, "-0x1p+0", APFloat::opInexact, APFloat::fcNormal }, { MNormalValue, MSmallestValue, "-0x1p+0", APFloat::opInexact, APFloat::fcNormal }, { MNormalValue, PSmallestNormalized, "-0x1p+0", APFloat::opInexact, APFloat::fcNormal }, { MNormalValue, MSmallestNormalized, "-0x1p+0", APFloat::opInexact, APFloat::fcNormal }, { PLargestValue, PInf, "inf", APFloat::opOK, APFloat::fcInfinity }, { PLargestValue, MInf, "-inf", APFloat::opOK, APFloat::fcInfinity }, { PLargestValue, PZero, "0x1.fffffep+127", APFloat::opOK, APFloat::fcNormal }, { PLargestValue, MZero, "0x1.fffffep+127", APFloat::opOK, APFloat::fcNormal }, { PLargestValue, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { PLargestValue, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { PLargestValue, PNormalValue, "0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { PLargestValue, MNormalValue, "0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { PLargestValue, PLargestValue, "inf", OverflowStatus, APFloat::fcInfinity }, { PLargestValue, MLargestValue, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { PLargestValue, PSmallestValue, "0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { PLargestValue, MSmallestValue, "0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { PLargestValue, PSmallestNormalized, "0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { PLargestValue, MSmallestNormalized, "0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { MLargestValue, PInf, "inf", APFloat::opOK, APFloat::fcInfinity }, { MLargestValue, MInf, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MLargestValue, PZero, "-0x1.fffffep+127", APFloat::opOK, APFloat::fcNormal }, { MLargestValue, MZero, "-0x1.fffffep+127", APFloat::opOK, APFloat::fcNormal }, { MLargestValue, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { MLargestValue, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { MLargestValue, PNormalValue, "-0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { MLargestValue, MNormalValue, "-0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { MLargestValue, PLargestValue, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { MLargestValue, MLargestValue, "-inf", OverflowStatus, APFloat::fcInfinity }, { MLargestValue, PSmallestValue, "-0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { MLargestValue, MSmallestValue, "-0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { MLargestValue, PSmallestNormalized, "-0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { MLargestValue, MSmallestNormalized, "-0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { PSmallestValue, PInf, "inf", APFloat::opOK, APFloat::fcInfinity }, { PSmallestValue, MInf, "-inf", APFloat::opOK, APFloat::fcInfinity }, { PSmallestValue, PZero, "0x1p-149", APFloat::opOK, APFloat::fcNormal }, { PSmallestValue, MZero, "0x1p-149", APFloat::opOK, APFloat::fcNormal }, { PSmallestValue, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { PSmallestValue, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { PSmallestValue, PNormalValue, "0x1p+0", APFloat::opInexact, APFloat::fcNormal }, { PSmallestValue, MNormalValue, "-0x1p+0", APFloat::opInexact, APFloat::fcNormal }, { PSmallestValue, PLargestValue, "0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { PSmallestValue, MLargestValue, "-0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { PSmallestValue, PSmallestValue, "0x1p-148", APFloat::opOK, APFloat::fcNormal }, { PSmallestValue, MSmallestValue, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { PSmallestValue, PSmallestNormalized, "0x1.000002p-126", APFloat::opOK, APFloat::fcNormal }, { PSmallestValue, MSmallestNormalized, "-0x1.fffffcp-127", APFloat::opOK, APFloat::fcNormal }, { MSmallestValue, PInf, "inf", APFloat::opOK, APFloat::fcInfinity }, { MSmallestValue, MInf, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MSmallestValue, PZero, "-0x1p-149", APFloat::opOK, APFloat::fcNormal }, { MSmallestValue, MZero, "-0x1p-149", APFloat::opOK, APFloat::fcNormal }, { MSmallestValue, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { MSmallestValue, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { MSmallestValue, PNormalValue, "0x1p+0", APFloat::opInexact, APFloat::fcNormal }, { MSmallestValue, MNormalValue, "-0x1p+0", APFloat::opInexact, APFloat::fcNormal }, { MSmallestValue, PLargestValue, "0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { MSmallestValue, MLargestValue, "-0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { MSmallestValue, PSmallestValue, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { MSmallestValue, MSmallestValue, "-0x1p-148", APFloat::opOK, APFloat::fcNormal }, { MSmallestValue, PSmallestNormalized, "0x1.fffffcp-127", APFloat::opOK, APFloat::fcNormal }, { MSmallestValue, MSmallestNormalized, "-0x1.000002p-126", APFloat::opOK, APFloat::fcNormal }, { PSmallestNormalized, PInf, "inf", APFloat::opOK, APFloat::fcInfinity }, { PSmallestNormalized, MInf, "-inf", APFloat::opOK, APFloat::fcInfinity }, { PSmallestNormalized, PZero, "0x1p-126", APFloat::opOK, APFloat::fcNormal }, { PSmallestNormalized, MZero, "0x1p-126", APFloat::opOK, APFloat::fcNormal }, { PSmallestNormalized, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { PSmallestNormalized, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { PSmallestNormalized, PNormalValue, "0x1p+0", APFloat::opInexact, APFloat::fcNormal }, { PSmallestNormalized, MNormalValue, "-0x1p+0", APFloat::opInexact, APFloat::fcNormal }, { PSmallestNormalized, PLargestValue, "0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { PSmallestNormalized, MLargestValue, "-0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { PSmallestNormalized, PSmallestValue, "0x1.000002p-126", APFloat::opOK, APFloat::fcNormal }, { PSmallestNormalized, MSmallestValue, "0x1.fffffcp-127", APFloat::opOK, APFloat::fcNormal }, { PSmallestNormalized, PSmallestNormalized, "0x1p-125", APFloat::opOK, APFloat::fcNormal }, { PSmallestNormalized, MSmallestNormalized, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { MSmallestNormalized, PInf, "inf", APFloat::opOK, APFloat::fcInfinity }, { MSmallestNormalized, MInf, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MSmallestNormalized, PZero, "-0x1p-126", APFloat::opOK, APFloat::fcNormal }, { MSmallestNormalized, MZero, "-0x1p-126", APFloat::opOK, APFloat::fcNormal }, { MSmallestNormalized, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { MSmallestNormalized, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { MSmallestNormalized, PNormalValue, "0x1p+0", APFloat::opInexact, APFloat::fcNormal }, { MSmallestNormalized, MNormalValue, "-0x1p+0", APFloat::opInexact, APFloat::fcNormal }, { MSmallestNormalized, PLargestValue, "0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { MSmallestNormalized, MLargestValue, "-0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { MSmallestNormalized, PSmallestValue, "-0x1.fffffcp-127", APFloat::opOK, APFloat::fcNormal }, { MSmallestNormalized, MSmallestValue, "-0x1.000002p-126", APFloat::opOK, APFloat::fcNormal }, { MSmallestNormalized, PSmallestNormalized, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { MSmallestNormalized, MSmallestNormalized, "-0x1p-125", APFloat::opOK, APFloat::fcNormal } }; for (size_t i = 0; i < NumTests; ++i) { APFloat x(SpecialCaseTests[i].x); APFloat y(SpecialCaseTests[i].y); APFloat::opStatus status = x.add(y, APFloat::rmNearestTiesToEven); APFloat result(APFloat::IEEEsingle, SpecialCaseTests[i].result); EXPECT_TRUE(result.bitwiseIsEqual(x)); EXPECT_TRUE((int)status == SpecialCaseTests[i].status); EXPECT_TRUE((int)x.getCategory() == SpecialCaseTests[i].category); } } TEST(APFloatTest, subtract) { // Test Special Cases against each other and normal values. // TODOS/NOTES: // 1. Since we perform only default exception handling all operations with // signaling NaNs should have a result that is a quiet NaN. Currently they // return sNaN. APFloat PInf = APFloat::getInf(APFloat::IEEEsingle, false); APFloat MInf = APFloat::getInf(APFloat::IEEEsingle, true); APFloat PZero = APFloat::getZero(APFloat::IEEEsingle, false); APFloat MZero = APFloat::getZero(APFloat::IEEEsingle, true); APFloat QNaN = APFloat::getNaN(APFloat::IEEEsingle, false); APFloat SNaN = APFloat::getSNaN(APFloat::IEEEsingle, false); APFloat PNormalValue = APFloat(APFloat::IEEEsingle, "0x1p+0"); APFloat MNormalValue = APFloat(APFloat::IEEEsingle, "-0x1p+0"); APFloat PLargestValue = APFloat::getLargest(APFloat::IEEEsingle, false); APFloat MLargestValue = APFloat::getLargest(APFloat::IEEEsingle, true); APFloat PSmallestValue = APFloat::getSmallest(APFloat::IEEEsingle, false); APFloat MSmallestValue = APFloat::getSmallest(APFloat::IEEEsingle, true); APFloat PSmallestNormalized = APFloat::getSmallestNormalized(APFloat::IEEEsingle, false); APFloat MSmallestNormalized = APFloat::getSmallestNormalized(APFloat::IEEEsingle, true); const int OverflowStatus = APFloat::opOverflow | APFloat::opInexact; const unsigned NumTests = 169; struct { APFloat x; APFloat y; const char *result; int status; int category; } SpecialCaseTests[NumTests] = { { PInf, PInf, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { PInf, MInf, "inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, PZero, "inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, MZero, "inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, QNaN, "-nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { PInf, SNaN, "-nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { PInf, PNormalValue, "inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, MNormalValue, "inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, PLargestValue, "inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, MLargestValue, "inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, PSmallestValue, "inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, MSmallestValue, "inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, PSmallestNormalized, "inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, MSmallestNormalized, "inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, PInf, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, MInf, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { MInf, PZero, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, MZero, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, QNaN, "-nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { MInf, SNaN, "-nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { MInf, PNormalValue, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, MNormalValue, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, PLargestValue, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, MLargestValue, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, PSmallestValue, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, MSmallestValue, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, PSmallestNormalized, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, MSmallestNormalized, "-inf", APFloat::opOK, APFloat::fcInfinity }, { PZero, PInf, "-inf", APFloat::opOK, APFloat::fcInfinity }, { PZero, MInf, "inf", APFloat::opOK, APFloat::fcInfinity }, { PZero, PZero, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { PZero, MZero, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { PZero, QNaN, "-nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { PZero, SNaN, "-nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { PZero, PNormalValue, "-0x1p+0", APFloat::opOK, APFloat::fcNormal }, { PZero, MNormalValue, "0x1p+0", APFloat::opOK, APFloat::fcNormal }, { PZero, PLargestValue, "-0x1.fffffep+127", APFloat::opOK, APFloat::fcNormal }, { PZero, MLargestValue, "0x1.fffffep+127", APFloat::opOK, APFloat::fcNormal }, { PZero, PSmallestValue, "-0x1p-149", APFloat::opOK, APFloat::fcNormal }, { PZero, MSmallestValue, "0x1p-149", APFloat::opOK, APFloat::fcNormal }, { PZero, PSmallestNormalized, "-0x1p-126", APFloat::opOK, APFloat::fcNormal }, { PZero, MSmallestNormalized, "0x1p-126", APFloat::opOK, APFloat::fcNormal }, { MZero, PInf, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MZero, MInf, "inf", APFloat::opOK, APFloat::fcInfinity }, { MZero, PZero, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { MZero, MZero, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { MZero, QNaN, "-nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { MZero, SNaN, "-nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { MZero, PNormalValue, "-0x1p+0", APFloat::opOK, APFloat::fcNormal }, { MZero, MNormalValue, "0x1p+0", APFloat::opOK, APFloat::fcNormal }, { MZero, PLargestValue, "-0x1.fffffep+127", APFloat::opOK, APFloat::fcNormal }, { MZero, MLargestValue, "0x1.fffffep+127", APFloat::opOK, APFloat::fcNormal }, { MZero, PSmallestValue, "-0x1p-149", APFloat::opOK, APFloat::fcNormal }, { MZero, MSmallestValue, "0x1p-149", APFloat::opOK, APFloat::fcNormal }, { MZero, PSmallestNormalized, "-0x1p-126", APFloat::opOK, APFloat::fcNormal }, { MZero, MSmallestNormalized, "0x1p-126", APFloat::opOK, APFloat::fcNormal }, { QNaN, PInf, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, MInf, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, PZero, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, MZero, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { QNaN, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { QNaN, PNormalValue, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, MNormalValue, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, PLargestValue, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, MLargestValue, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, PSmallestValue, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, MSmallestValue, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, PSmallestNormalized, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, MSmallestNormalized, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { SNaN, PInf, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, MInf, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, PZero, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, MZero, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, QNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, PNormalValue, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, MNormalValue, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, PLargestValue, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, MLargestValue, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, PSmallestValue, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, MSmallestValue, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, PSmallestNormalized, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, MSmallestNormalized, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { PNormalValue, PInf, "-inf", APFloat::opOK, APFloat::fcInfinity }, { PNormalValue, MInf, "inf", APFloat::opOK, APFloat::fcInfinity }, { PNormalValue, PZero, "0x1p+0", APFloat::opOK, APFloat::fcNormal }, { PNormalValue, MZero, "0x1p+0", APFloat::opOK, APFloat::fcNormal }, { PNormalValue, QNaN, "-nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { PNormalValue, SNaN, "-nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { PNormalValue, PNormalValue, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { PNormalValue, MNormalValue, "0x1p+1", APFloat::opOK, APFloat::fcNormal }, { PNormalValue, PLargestValue, "-0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { PNormalValue, MLargestValue, "0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { PNormalValue, PSmallestValue, "0x1p+0", APFloat::opInexact, APFloat::fcNormal }, { PNormalValue, MSmallestValue, "0x1p+0", APFloat::opInexact, APFloat::fcNormal }, { PNormalValue, PSmallestNormalized, "0x1p+0", APFloat::opInexact, APFloat::fcNormal }, { PNormalValue, MSmallestNormalized, "0x1p+0", APFloat::opInexact, APFloat::fcNormal }, { MNormalValue, PInf, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MNormalValue, MInf, "inf", APFloat::opOK, APFloat::fcInfinity }, { MNormalValue, PZero, "-0x1p+0", APFloat::opOK, APFloat::fcNormal }, { MNormalValue, MZero, "-0x1p+0", APFloat::opOK, APFloat::fcNormal }, { MNormalValue, QNaN, "-nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { MNormalValue, SNaN, "-nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { MNormalValue, PNormalValue, "-0x1p+1", APFloat::opOK, APFloat::fcNormal }, { MNormalValue, MNormalValue, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { MNormalValue, PLargestValue, "-0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { MNormalValue, MLargestValue, "0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { MNormalValue, PSmallestValue, "-0x1p+0", APFloat::opInexact, APFloat::fcNormal }, { MNormalValue, MSmallestValue, "-0x1p+0", APFloat::opInexact, APFloat::fcNormal }, { MNormalValue, PSmallestNormalized, "-0x1p+0", APFloat::opInexact, APFloat::fcNormal }, { MNormalValue, MSmallestNormalized, "-0x1p+0", APFloat::opInexact, APFloat::fcNormal }, { PLargestValue, PInf, "-inf", APFloat::opOK, APFloat::fcInfinity }, { PLargestValue, MInf, "inf", APFloat::opOK, APFloat::fcInfinity }, { PLargestValue, PZero, "0x1.fffffep+127", APFloat::opOK, APFloat::fcNormal }, { PLargestValue, MZero, "0x1.fffffep+127", APFloat::opOK, APFloat::fcNormal }, { PLargestValue, QNaN, "-nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { PLargestValue, SNaN, "-nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { PLargestValue, PNormalValue, "0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { PLargestValue, MNormalValue, "0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { PLargestValue, PLargestValue, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { PLargestValue, MLargestValue, "inf", OverflowStatus, APFloat::fcInfinity }, { PLargestValue, PSmallestValue, "0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { PLargestValue, MSmallestValue, "0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { PLargestValue, PSmallestNormalized, "0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { PLargestValue, MSmallestNormalized, "0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { MLargestValue, PInf, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MLargestValue, MInf, "inf", APFloat::opOK, APFloat::fcInfinity }, { MLargestValue, PZero, "-0x1.fffffep+127", APFloat::opOK, APFloat::fcNormal }, { MLargestValue, MZero, "-0x1.fffffep+127", APFloat::opOK, APFloat::fcNormal }, { MLargestValue, QNaN, "-nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { MLargestValue, SNaN, "-nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { MLargestValue, PNormalValue, "-0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { MLargestValue, MNormalValue, "-0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { MLargestValue, PLargestValue, "-inf", OverflowStatus, APFloat::fcInfinity }, { MLargestValue, MLargestValue, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { MLargestValue, PSmallestValue, "-0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { MLargestValue, MSmallestValue, "-0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { MLargestValue, PSmallestNormalized, "-0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { MLargestValue, MSmallestNormalized, "-0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { PSmallestValue, PInf, "-inf", APFloat::opOK, APFloat::fcInfinity }, { PSmallestValue, MInf, "inf", APFloat::opOK, APFloat::fcInfinity }, { PSmallestValue, PZero, "0x1p-149", APFloat::opOK, APFloat::fcNormal }, { PSmallestValue, MZero, "0x1p-149", APFloat::opOK, APFloat::fcNormal }, { PSmallestValue, QNaN, "-nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { PSmallestValue, SNaN, "-nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { PSmallestValue, PNormalValue, "-0x1p+0", APFloat::opInexact, APFloat::fcNormal }, { PSmallestValue, MNormalValue, "0x1p+0", APFloat::opInexact, APFloat::fcNormal }, { PSmallestValue, PLargestValue, "-0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { PSmallestValue, MLargestValue, "0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { PSmallestValue, PSmallestValue, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { PSmallestValue, MSmallestValue, "0x1p-148", APFloat::opOK, APFloat::fcNormal }, { PSmallestValue, PSmallestNormalized, "-0x1.fffffcp-127", APFloat::opOK, APFloat::fcNormal }, { PSmallestValue, MSmallestNormalized, "0x1.000002p-126", APFloat::opOK, APFloat::fcNormal }, { MSmallestValue, PInf, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MSmallestValue, MInf, "inf", APFloat::opOK, APFloat::fcInfinity }, { MSmallestValue, PZero, "-0x1p-149", APFloat::opOK, APFloat::fcNormal }, { MSmallestValue, MZero, "-0x1p-149", APFloat::opOK, APFloat::fcNormal }, { MSmallestValue, QNaN, "-nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { MSmallestValue, SNaN, "-nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { MSmallestValue, PNormalValue, "-0x1p+0", APFloat::opInexact, APFloat::fcNormal }, { MSmallestValue, MNormalValue, "0x1p+0", APFloat::opInexact, APFloat::fcNormal }, { MSmallestValue, PLargestValue, "-0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { MSmallestValue, MLargestValue, "0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { MSmallestValue, PSmallestValue, "-0x1p-148", APFloat::opOK, APFloat::fcNormal }, { MSmallestValue, MSmallestValue, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { MSmallestValue, PSmallestNormalized, "-0x1.000002p-126", APFloat::opOK, APFloat::fcNormal }, { MSmallestValue, MSmallestNormalized, "0x1.fffffcp-127", APFloat::opOK, APFloat::fcNormal }, { PSmallestNormalized, PInf, "-inf", APFloat::opOK, APFloat::fcInfinity }, { PSmallestNormalized, MInf, "inf", APFloat::opOK, APFloat::fcInfinity }, { PSmallestNormalized, PZero, "0x1p-126", APFloat::opOK, APFloat::fcNormal }, { PSmallestNormalized, MZero, "0x1p-126", APFloat::opOK, APFloat::fcNormal }, { PSmallestNormalized, QNaN, "-nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { PSmallestNormalized, SNaN, "-nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { PSmallestNormalized, PNormalValue, "-0x1p+0", APFloat::opInexact, APFloat::fcNormal }, { PSmallestNormalized, MNormalValue, "0x1p+0", APFloat::opInexact, APFloat::fcNormal }, { PSmallestNormalized, PLargestValue, "-0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { PSmallestNormalized, MLargestValue, "0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { PSmallestNormalized, PSmallestValue, "0x1.fffffcp-127", APFloat::opOK, APFloat::fcNormal }, { PSmallestNormalized, MSmallestValue, "0x1.000002p-126", APFloat::opOK, APFloat::fcNormal }, { PSmallestNormalized, PSmallestNormalized, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { PSmallestNormalized, MSmallestNormalized, "0x1p-125", APFloat::opOK, APFloat::fcNormal }, { MSmallestNormalized, PInf, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MSmallestNormalized, MInf, "inf", APFloat::opOK, APFloat::fcInfinity }, { MSmallestNormalized, PZero, "-0x1p-126", APFloat::opOK, APFloat::fcNormal }, { MSmallestNormalized, MZero, "-0x1p-126", APFloat::opOK, APFloat::fcNormal }, { MSmallestNormalized, QNaN, "-nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { MSmallestNormalized, SNaN, "-nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { MSmallestNormalized, PNormalValue, "-0x1p+0", APFloat::opInexact, APFloat::fcNormal }, { MSmallestNormalized, MNormalValue, "0x1p+0", APFloat::opInexact, APFloat::fcNormal }, { MSmallestNormalized, PLargestValue, "-0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { MSmallestNormalized, MLargestValue, "0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { MSmallestNormalized, PSmallestValue, "-0x1.000002p-126", APFloat::opOK, APFloat::fcNormal }, { MSmallestNormalized, MSmallestValue, "-0x1.fffffcp-127", APFloat::opOK, APFloat::fcNormal }, { MSmallestNormalized, PSmallestNormalized, "-0x1p-125", APFloat::opOK, APFloat::fcNormal }, { MSmallestNormalized, MSmallestNormalized, "0x0p+0", APFloat::opOK, APFloat::fcZero } }; for (size_t i = 0; i < NumTests; ++i) { APFloat x(SpecialCaseTests[i].x); APFloat y(SpecialCaseTests[i].y); APFloat::opStatus status = x.subtract(y, APFloat::rmNearestTiesToEven); APFloat result(APFloat::IEEEsingle, SpecialCaseTests[i].result); EXPECT_TRUE(result.bitwiseIsEqual(x)); EXPECT_TRUE((int)status == SpecialCaseTests[i].status); EXPECT_TRUE((int)x.getCategory() == SpecialCaseTests[i].category); } } TEST(APFloatTest, multiply) { // Test Special Cases against each other and normal values. // TODOS/NOTES: // 1. Since we perform only default exception handling all operations with // signaling NaNs should have a result that is a quiet NaN. Currently they // return sNaN. APFloat PInf = APFloat::getInf(APFloat::IEEEsingle, false); APFloat MInf = APFloat::getInf(APFloat::IEEEsingle, true); APFloat PZero = APFloat::getZero(APFloat::IEEEsingle, false); APFloat MZero = APFloat::getZero(APFloat::IEEEsingle, true); APFloat QNaN = APFloat::getNaN(APFloat::IEEEsingle, false); APFloat SNaN = APFloat::getSNaN(APFloat::IEEEsingle, false); APFloat PNormalValue = APFloat(APFloat::IEEEsingle, "0x1p+0"); APFloat MNormalValue = APFloat(APFloat::IEEEsingle, "-0x1p+0"); APFloat PLargestValue = APFloat::getLargest(APFloat::IEEEsingle, false); APFloat MLargestValue = APFloat::getLargest(APFloat::IEEEsingle, true); APFloat PSmallestValue = APFloat::getSmallest(APFloat::IEEEsingle, false); APFloat MSmallestValue = APFloat::getSmallest(APFloat::IEEEsingle, true); APFloat PSmallestNormalized = APFloat::getSmallestNormalized(APFloat::IEEEsingle, false); APFloat MSmallestNormalized = APFloat::getSmallestNormalized(APFloat::IEEEsingle, true); const int OverflowStatus = APFloat::opOverflow | APFloat::opInexact; const int UnderflowStatus = APFloat::opUnderflow | APFloat::opInexact; const unsigned NumTests = 169; struct { APFloat x; APFloat y; const char *result; int status; int category; } SpecialCaseTests[NumTests] = { { PInf, PInf, "inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, MInf, "-inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, PZero, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { PInf, MZero, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { PInf, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { PInf, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { PInf, PNormalValue, "inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, MNormalValue, "-inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, PLargestValue, "inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, MLargestValue, "-inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, PSmallestValue, "inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, MSmallestValue, "-inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, PSmallestNormalized, "inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, MSmallestNormalized, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, PInf, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, MInf, "inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, PZero, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { MInf, MZero, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { MInf, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { MInf, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { MInf, PNormalValue, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, MNormalValue, "inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, PLargestValue, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, MLargestValue, "inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, PSmallestValue, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, MSmallestValue, "inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, PSmallestNormalized, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, MSmallestNormalized, "inf", APFloat::opOK, APFloat::fcInfinity }, { PZero, PInf, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { PZero, MInf, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { PZero, PZero, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { PZero, MZero, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { PZero, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { PZero, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { PZero, PNormalValue, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { PZero, MNormalValue, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { PZero, PLargestValue, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { PZero, MLargestValue, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { PZero, PSmallestValue, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { PZero, MSmallestValue, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { PZero, PSmallestNormalized, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { PZero, MSmallestNormalized, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { MZero, PInf, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { MZero, MInf, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { MZero, PZero, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { MZero, MZero, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { MZero, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { MZero, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { MZero, PNormalValue, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { MZero, MNormalValue, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { MZero, PLargestValue, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { MZero, MLargestValue, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { MZero, PSmallestValue, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { MZero, MSmallestValue, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { MZero, PSmallestNormalized, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { MZero, MSmallestNormalized, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { QNaN, PInf, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, MInf, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, PZero, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, MZero, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { QNaN, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { QNaN, PNormalValue, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, MNormalValue, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, PLargestValue, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, MLargestValue, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, PSmallestValue, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, MSmallestValue, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, PSmallestNormalized, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, MSmallestNormalized, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { SNaN, PInf, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, MInf, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, PZero, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, MZero, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, QNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, PNormalValue, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, MNormalValue, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, PLargestValue, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, MLargestValue, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, PSmallestValue, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, MSmallestValue, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, PSmallestNormalized, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, MSmallestNormalized, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { PNormalValue, PInf, "inf", APFloat::opOK, APFloat::fcInfinity }, { PNormalValue, MInf, "-inf", APFloat::opOK, APFloat::fcInfinity }, { PNormalValue, PZero, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { PNormalValue, MZero, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { PNormalValue, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { PNormalValue, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { PNormalValue, PNormalValue, "0x1p+0", APFloat::opOK, APFloat::fcNormal }, { PNormalValue, MNormalValue, "-0x1p+0", APFloat::opOK, APFloat::fcNormal }, { PNormalValue, PLargestValue, "0x1.fffffep+127", APFloat::opOK, APFloat::fcNormal }, { PNormalValue, MLargestValue, "-0x1.fffffep+127", APFloat::opOK, APFloat::fcNormal }, { PNormalValue, PSmallestValue, "0x1p-149", APFloat::opOK, APFloat::fcNormal }, { PNormalValue, MSmallestValue, "-0x1p-149", APFloat::opOK, APFloat::fcNormal }, { PNormalValue, PSmallestNormalized, "0x1p-126", APFloat::opOK, APFloat::fcNormal }, { PNormalValue, MSmallestNormalized, "-0x1p-126", APFloat::opOK, APFloat::fcNormal }, { MNormalValue, PInf, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MNormalValue, MInf, "inf", APFloat::opOK, APFloat::fcInfinity }, { MNormalValue, PZero, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { MNormalValue, MZero, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { MNormalValue, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { MNormalValue, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { MNormalValue, PNormalValue, "-0x1p+0", APFloat::opOK, APFloat::fcNormal }, { MNormalValue, MNormalValue, "0x1p+0", APFloat::opOK, APFloat::fcNormal }, { MNormalValue, PLargestValue, "-0x1.fffffep+127", APFloat::opOK, APFloat::fcNormal }, { MNormalValue, MLargestValue, "0x1.fffffep+127", APFloat::opOK, APFloat::fcNormal }, { MNormalValue, PSmallestValue, "-0x1p-149", APFloat::opOK, APFloat::fcNormal }, { MNormalValue, MSmallestValue, "0x1p-149", APFloat::opOK, APFloat::fcNormal }, { MNormalValue, PSmallestNormalized, "-0x1p-126", APFloat::opOK, APFloat::fcNormal }, { MNormalValue, MSmallestNormalized, "0x1p-126", APFloat::opOK, APFloat::fcNormal }, { PLargestValue, PInf, "inf", APFloat::opOK, APFloat::fcInfinity }, { PLargestValue, MInf, "-inf", APFloat::opOK, APFloat::fcInfinity }, { PLargestValue, PZero, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { PLargestValue, MZero, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { PLargestValue, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { PLargestValue, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { PLargestValue, PNormalValue, "0x1.fffffep+127", APFloat::opOK, APFloat::fcNormal }, { PLargestValue, MNormalValue, "-0x1.fffffep+127", APFloat::opOK, APFloat::fcNormal }, { PLargestValue, PLargestValue, "inf", OverflowStatus, APFloat::fcInfinity }, { PLargestValue, MLargestValue, "-inf", OverflowStatus, APFloat::fcInfinity }, { PLargestValue, PSmallestValue, "0x1.fffffep-22", APFloat::opOK, APFloat::fcNormal }, { PLargestValue, MSmallestValue, "-0x1.fffffep-22", APFloat::opOK, APFloat::fcNormal }, { PLargestValue, PSmallestNormalized, "0x1.fffffep+1", APFloat::opOK, APFloat::fcNormal }, { PLargestValue, MSmallestNormalized, "-0x1.fffffep+1", APFloat::opOK, APFloat::fcNormal }, { MLargestValue, PInf, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MLargestValue, MInf, "inf", APFloat::opOK, APFloat::fcInfinity }, { MLargestValue, PZero, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { MLargestValue, MZero, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { MLargestValue, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { MLargestValue, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { MLargestValue, PNormalValue, "-0x1.fffffep+127", APFloat::opOK, APFloat::fcNormal }, { MLargestValue, MNormalValue, "0x1.fffffep+127", APFloat::opOK, APFloat::fcNormal }, { MLargestValue, PLargestValue, "-inf", OverflowStatus, APFloat::fcInfinity }, { MLargestValue, MLargestValue, "inf", OverflowStatus, APFloat::fcInfinity }, { MLargestValue, PSmallestValue, "-0x1.fffffep-22", APFloat::opOK, APFloat::fcNormal }, { MLargestValue, MSmallestValue, "0x1.fffffep-22", APFloat::opOK, APFloat::fcNormal }, { MLargestValue, PSmallestNormalized, "-0x1.fffffep+1", APFloat::opOK, APFloat::fcNormal }, { MLargestValue, MSmallestNormalized, "0x1.fffffep+1", APFloat::opOK, APFloat::fcNormal }, { PSmallestValue, PInf, "inf", APFloat::opOK, APFloat::fcInfinity }, { PSmallestValue, MInf, "-inf", APFloat::opOK, APFloat::fcInfinity }, { PSmallestValue, PZero, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { PSmallestValue, MZero, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { PSmallestValue, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { PSmallestValue, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { PSmallestValue, PNormalValue, "0x1p-149", APFloat::opOK, APFloat::fcNormal }, { PSmallestValue, MNormalValue, "-0x1p-149", APFloat::opOK, APFloat::fcNormal }, { PSmallestValue, PLargestValue, "0x1.fffffep-22", APFloat::opOK, APFloat::fcNormal }, { PSmallestValue, MLargestValue, "-0x1.fffffep-22", APFloat::opOK, APFloat::fcNormal }, { PSmallestValue, PSmallestValue, "0x0p+0", UnderflowStatus, APFloat::fcZero }, { PSmallestValue, MSmallestValue, "-0x0p+0", UnderflowStatus, APFloat::fcZero }, { PSmallestValue, PSmallestNormalized, "0x0p+0", UnderflowStatus, APFloat::fcZero }, { PSmallestValue, MSmallestNormalized, "-0x0p+0", UnderflowStatus, APFloat::fcZero }, { MSmallestValue, PInf, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MSmallestValue, MInf, "inf", APFloat::opOK, APFloat::fcInfinity }, { MSmallestValue, PZero, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { MSmallestValue, MZero, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { MSmallestValue, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { MSmallestValue, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { MSmallestValue, PNormalValue, "-0x1p-149", APFloat::opOK, APFloat::fcNormal }, { MSmallestValue, MNormalValue, "0x1p-149", APFloat::opOK, APFloat::fcNormal }, { MSmallestValue, PLargestValue, "-0x1.fffffep-22", APFloat::opOK, APFloat::fcNormal }, { MSmallestValue, MLargestValue, "0x1.fffffep-22", APFloat::opOK, APFloat::fcNormal }, { MSmallestValue, PSmallestValue, "-0x0p+0", UnderflowStatus, APFloat::fcZero }, { MSmallestValue, MSmallestValue, "0x0p+0", UnderflowStatus, APFloat::fcZero }, { MSmallestValue, PSmallestNormalized, "-0x0p+0", UnderflowStatus, APFloat::fcZero }, { MSmallestValue, MSmallestNormalized, "0x0p+0", UnderflowStatus, APFloat::fcZero }, { PSmallestNormalized, PInf, "inf", APFloat::opOK, APFloat::fcInfinity }, { PSmallestNormalized, MInf, "-inf", APFloat::opOK, APFloat::fcInfinity }, { PSmallestNormalized, PZero, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { PSmallestNormalized, MZero, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { PSmallestNormalized, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { PSmallestNormalized, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { PSmallestNormalized, PNormalValue, "0x1p-126", APFloat::opOK, APFloat::fcNormal }, { PSmallestNormalized, MNormalValue, "-0x1p-126", APFloat::opOK, APFloat::fcNormal }, { PSmallestNormalized, PLargestValue, "0x1.fffffep+1", APFloat::opOK, APFloat::fcNormal }, { PSmallestNormalized, MLargestValue, "-0x1.fffffep+1", APFloat::opOK, APFloat::fcNormal }, { PSmallestNormalized, PSmallestValue, "0x0p+0", UnderflowStatus, APFloat::fcZero }, { PSmallestNormalized, MSmallestValue, "-0x0p+0", UnderflowStatus, APFloat::fcZero }, { PSmallestNormalized, PSmallestNormalized, "0x0p+0", UnderflowStatus, APFloat::fcZero }, { PSmallestNormalized, MSmallestNormalized, "-0x0p+0", UnderflowStatus, APFloat::fcZero }, { MSmallestNormalized, PInf, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MSmallestNormalized, MInf, "inf", APFloat::opOK, APFloat::fcInfinity }, { MSmallestNormalized, PZero, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { MSmallestNormalized, MZero, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { MSmallestNormalized, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { MSmallestNormalized, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { MSmallestNormalized, PNormalValue, "-0x1p-126", APFloat::opOK, APFloat::fcNormal }, { MSmallestNormalized, MNormalValue, "0x1p-126", APFloat::opOK, APFloat::fcNormal }, { MSmallestNormalized, PLargestValue, "-0x1.fffffep+1", APFloat::opOK, APFloat::fcNormal }, { MSmallestNormalized, MLargestValue, "0x1.fffffep+1", APFloat::opOK, APFloat::fcNormal }, { MSmallestNormalized, PSmallestValue, "-0x0p+0", UnderflowStatus, APFloat::fcZero }, { MSmallestNormalized, MSmallestValue, "0x0p+0", UnderflowStatus, APFloat::fcZero }, { MSmallestNormalized, PSmallestNormalized, "-0x0p+0", UnderflowStatus, APFloat::fcZero }, { MSmallestNormalized, MSmallestNormalized, "0x0p+0", UnderflowStatus, APFloat::fcZero } }; for (size_t i = 0; i < NumTests; ++i) { APFloat x(SpecialCaseTests[i].x); APFloat y(SpecialCaseTests[i].y); APFloat::opStatus status = x.multiply(y, APFloat::rmNearestTiesToEven); APFloat result(APFloat::IEEEsingle, SpecialCaseTests[i].result); EXPECT_TRUE(result.bitwiseIsEqual(x)); EXPECT_TRUE((int)status == SpecialCaseTests[i].status); EXPECT_TRUE((int)x.getCategory() == SpecialCaseTests[i].category); } } TEST(APFloatTest, divide) { // Test Special Cases against each other and normal values. // TODOS/NOTES: // 1. Since we perform only default exception handling all operations with // signaling NaNs should have a result that is a quiet NaN. Currently they // return sNaN. APFloat PInf = APFloat::getInf(APFloat::IEEEsingle, false); APFloat MInf = APFloat::getInf(APFloat::IEEEsingle, true); APFloat PZero = APFloat::getZero(APFloat::IEEEsingle, false); APFloat MZero = APFloat::getZero(APFloat::IEEEsingle, true); APFloat QNaN = APFloat::getNaN(APFloat::IEEEsingle, false); APFloat SNaN = APFloat::getSNaN(APFloat::IEEEsingle, false); APFloat PNormalValue = APFloat(APFloat::IEEEsingle, "0x1p+0"); APFloat MNormalValue = APFloat(APFloat::IEEEsingle, "-0x1p+0"); APFloat PLargestValue = APFloat::getLargest(APFloat::IEEEsingle, false); APFloat MLargestValue = APFloat::getLargest(APFloat::IEEEsingle, true); APFloat PSmallestValue = APFloat::getSmallest(APFloat::IEEEsingle, false); APFloat MSmallestValue = APFloat::getSmallest(APFloat::IEEEsingle, true); APFloat PSmallestNormalized = APFloat::getSmallestNormalized(APFloat::IEEEsingle, false); APFloat MSmallestNormalized = APFloat::getSmallestNormalized(APFloat::IEEEsingle, true); const int OverflowStatus = APFloat::opOverflow | APFloat::opInexact; const int UnderflowStatus = APFloat::opUnderflow | APFloat::opInexact; const unsigned NumTests = 169; struct { APFloat x; APFloat y; const char *result; int status; int category; } SpecialCaseTests[NumTests] = { { PInf, PInf, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { PInf, MInf, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { PInf, PZero, "inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, MZero, "-inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { PInf, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { PInf, PNormalValue, "inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, MNormalValue, "-inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, PLargestValue, "inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, MLargestValue, "-inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, PSmallestValue, "inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, MSmallestValue, "-inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, PSmallestNormalized, "inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, MSmallestNormalized, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, PInf, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { MInf, MInf, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { MInf, PZero, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, MZero, "inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { MInf, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { MInf, PNormalValue, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, MNormalValue, "inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, PLargestValue, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, MLargestValue, "inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, PSmallestValue, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, MSmallestValue, "inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, PSmallestNormalized, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, MSmallestNormalized, "inf", APFloat::opOK, APFloat::fcInfinity }, { PZero, PInf, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { PZero, MInf, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { PZero, PZero, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { PZero, MZero, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { PZero, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { PZero, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { PZero, PNormalValue, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { PZero, MNormalValue, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { PZero, PLargestValue, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { PZero, MLargestValue, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { PZero, PSmallestValue, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { PZero, MSmallestValue, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { PZero, PSmallestNormalized, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { PZero, MSmallestNormalized, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { MZero, PInf, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { MZero, MInf, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { MZero, PZero, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { MZero, MZero, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { MZero, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { MZero, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { MZero, PNormalValue, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { MZero, MNormalValue, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { MZero, PLargestValue, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { MZero, MLargestValue, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { MZero, PSmallestValue, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { MZero, MSmallestValue, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { MZero, PSmallestNormalized, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { MZero, MSmallestNormalized, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { QNaN, PInf, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, MInf, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, PZero, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, MZero, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { QNaN, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { QNaN, PNormalValue, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, MNormalValue, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, PLargestValue, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, MLargestValue, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, PSmallestValue, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, MSmallestValue, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, PSmallestNormalized, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, MSmallestNormalized, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { SNaN, PInf, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, MInf, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, PZero, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, MZero, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, QNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, PNormalValue, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, MNormalValue, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, PLargestValue, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, MLargestValue, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, PSmallestValue, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, MSmallestValue, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, PSmallestNormalized, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, MSmallestNormalized, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { PNormalValue, PInf, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { PNormalValue, MInf, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { PNormalValue, PZero, "inf", APFloat::opDivByZero, APFloat::fcInfinity }, { PNormalValue, MZero, "-inf", APFloat::opDivByZero, APFloat::fcInfinity }, { PNormalValue, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { PNormalValue, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { PNormalValue, PNormalValue, "0x1p+0", APFloat::opOK, APFloat::fcNormal }, { PNormalValue, MNormalValue, "-0x1p+0", APFloat::opOK, APFloat::fcNormal }, { PNormalValue, PLargestValue, "0x1p-128", UnderflowStatus, APFloat::fcNormal }, { PNormalValue, MLargestValue, "-0x1p-128", UnderflowStatus, APFloat::fcNormal }, { PNormalValue, PSmallestValue, "inf", OverflowStatus, APFloat::fcInfinity }, { PNormalValue, MSmallestValue, "-inf", OverflowStatus, APFloat::fcInfinity }, { PNormalValue, PSmallestNormalized, "0x1p+126", APFloat::opOK, APFloat::fcNormal }, { PNormalValue, MSmallestNormalized, "-0x1p+126", APFloat::opOK, APFloat::fcNormal }, { MNormalValue, PInf, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { MNormalValue, MInf, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { MNormalValue, PZero, "-inf", APFloat::opDivByZero, APFloat::fcInfinity }, { MNormalValue, MZero, "inf", APFloat::opDivByZero, APFloat::fcInfinity }, { MNormalValue, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { MNormalValue, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { MNormalValue, PNormalValue, "-0x1p+0", APFloat::opOK, APFloat::fcNormal }, { MNormalValue, MNormalValue, "0x1p+0", APFloat::opOK, APFloat::fcNormal }, { MNormalValue, PLargestValue, "-0x1p-128", UnderflowStatus, APFloat::fcNormal }, { MNormalValue, MLargestValue, "0x1p-128", UnderflowStatus, APFloat::fcNormal }, { MNormalValue, PSmallestValue, "-inf", OverflowStatus, APFloat::fcInfinity }, { MNormalValue, MSmallestValue, "inf", OverflowStatus, APFloat::fcInfinity }, { MNormalValue, PSmallestNormalized, "-0x1p+126", APFloat::opOK, APFloat::fcNormal }, { MNormalValue, MSmallestNormalized, "0x1p+126", APFloat::opOK, APFloat::fcNormal }, { PLargestValue, PInf, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { PLargestValue, MInf, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { PLargestValue, PZero, "inf", APFloat::opDivByZero, APFloat::fcInfinity }, { PLargestValue, MZero, "-inf", APFloat::opDivByZero, APFloat::fcInfinity }, { PLargestValue, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { PLargestValue, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { PLargestValue, PNormalValue, "0x1.fffffep+127", APFloat::opOK, APFloat::fcNormal }, { PLargestValue, MNormalValue, "-0x1.fffffep+127", APFloat::opOK, APFloat::fcNormal }, { PLargestValue, PLargestValue, "0x1p+0", APFloat::opOK, APFloat::fcNormal }, { PLargestValue, MLargestValue, "-0x1p+0", APFloat::opOK, APFloat::fcNormal }, { PLargestValue, PSmallestValue, "inf", OverflowStatus, APFloat::fcInfinity }, { PLargestValue, MSmallestValue, "-inf", OverflowStatus, APFloat::fcInfinity }, { PLargestValue, PSmallestNormalized, "inf", OverflowStatus, APFloat::fcInfinity }, { PLargestValue, MSmallestNormalized, "-inf", OverflowStatus, APFloat::fcInfinity }, { MLargestValue, PInf, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { MLargestValue, MInf, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { MLargestValue, PZero, "-inf", APFloat::opDivByZero, APFloat::fcInfinity }, { MLargestValue, MZero, "inf", APFloat::opDivByZero, APFloat::fcInfinity }, { MLargestValue, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { MLargestValue, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { MLargestValue, PNormalValue, "-0x1.fffffep+127", APFloat::opOK, APFloat::fcNormal }, { MLargestValue, MNormalValue, "0x1.fffffep+127", APFloat::opOK, APFloat::fcNormal }, { MLargestValue, PLargestValue, "-0x1p+0", APFloat::opOK, APFloat::fcNormal }, { MLargestValue, MLargestValue, "0x1p+0", APFloat::opOK, APFloat::fcNormal }, { MLargestValue, PSmallestValue, "-inf", OverflowStatus, APFloat::fcInfinity }, { MLargestValue, MSmallestValue, "inf", OverflowStatus, APFloat::fcInfinity }, { MLargestValue, PSmallestNormalized, "-inf", OverflowStatus, APFloat::fcInfinity }, { MLargestValue, MSmallestNormalized, "inf", OverflowStatus, APFloat::fcInfinity }, { PSmallestValue, PInf, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { PSmallestValue, MInf, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { PSmallestValue, PZero, "inf", APFloat::opDivByZero, APFloat::fcInfinity }, { PSmallestValue, MZero, "-inf", APFloat::opDivByZero, APFloat::fcInfinity }, { PSmallestValue, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { PSmallestValue, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { PSmallestValue, PNormalValue, "0x1p-149", APFloat::opOK, APFloat::fcNormal }, { PSmallestValue, MNormalValue, "-0x1p-149", APFloat::opOK, APFloat::fcNormal }, { PSmallestValue, PLargestValue, "0x0p+0", UnderflowStatus, APFloat::fcZero }, { PSmallestValue, MLargestValue, "-0x0p+0", UnderflowStatus, APFloat::fcZero }, { PSmallestValue, PSmallestValue, "0x1p+0", APFloat::opOK, APFloat::fcNormal }, { PSmallestValue, MSmallestValue, "-0x1p+0", APFloat::opOK, APFloat::fcNormal }, { PSmallestValue, PSmallestNormalized, "0x1p-23", APFloat::opOK, APFloat::fcNormal }, { PSmallestValue, MSmallestNormalized, "-0x1p-23", APFloat::opOK, APFloat::fcNormal }, { MSmallestValue, PInf, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { MSmallestValue, MInf, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { MSmallestValue, PZero, "-inf", APFloat::opDivByZero, APFloat::fcInfinity }, { MSmallestValue, MZero, "inf", APFloat::opDivByZero, APFloat::fcInfinity }, { MSmallestValue, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { MSmallestValue, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { MSmallestValue, PNormalValue, "-0x1p-149", APFloat::opOK, APFloat::fcNormal }, { MSmallestValue, MNormalValue, "0x1p-149", APFloat::opOK, APFloat::fcNormal }, { MSmallestValue, PLargestValue, "-0x0p+0", UnderflowStatus, APFloat::fcZero }, { MSmallestValue, MLargestValue, "0x0p+0", UnderflowStatus, APFloat::fcZero }, { MSmallestValue, PSmallestValue, "-0x1p+0", APFloat::opOK, APFloat::fcNormal }, { MSmallestValue, MSmallestValue, "0x1p+0", APFloat::opOK, APFloat::fcNormal }, { MSmallestValue, PSmallestNormalized, "-0x1p-23", APFloat::opOK, APFloat::fcNormal }, { MSmallestValue, MSmallestNormalized, "0x1p-23", APFloat::opOK, APFloat::fcNormal }, { PSmallestNormalized, PInf, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { PSmallestNormalized, MInf, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { PSmallestNormalized, PZero, "inf", APFloat::opDivByZero, APFloat::fcInfinity }, { PSmallestNormalized, MZero, "-inf", APFloat::opDivByZero, APFloat::fcInfinity }, { PSmallestNormalized, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { PSmallestNormalized, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { PSmallestNormalized, PNormalValue, "0x1p-126", APFloat::opOK, APFloat::fcNormal }, { PSmallestNormalized, MNormalValue, "-0x1p-126", APFloat::opOK, APFloat::fcNormal }, { PSmallestNormalized, PLargestValue, "0x0p+0", UnderflowStatus, APFloat::fcZero }, { PSmallestNormalized, MLargestValue, "-0x0p+0", UnderflowStatus, APFloat::fcZero }, { PSmallestNormalized, PSmallestValue, "0x1p+23", APFloat::opOK, APFloat::fcNormal }, { PSmallestNormalized, MSmallestValue, "-0x1p+23", APFloat::opOK, APFloat::fcNormal }, { PSmallestNormalized, PSmallestNormalized, "0x1p+0", APFloat::opOK, APFloat::fcNormal }, { PSmallestNormalized, MSmallestNormalized, "-0x1p+0", APFloat::opOK, APFloat::fcNormal }, { MSmallestNormalized, PInf, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { MSmallestNormalized, MInf, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { MSmallestNormalized, PZero, "-inf", APFloat::opDivByZero, APFloat::fcInfinity }, { MSmallestNormalized, MZero, "inf", APFloat::opDivByZero, APFloat::fcInfinity }, { MSmallestNormalized, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { MSmallestNormalized, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { MSmallestNormalized, PNormalValue, "-0x1p-126", APFloat::opOK, APFloat::fcNormal }, { MSmallestNormalized, MNormalValue, "0x1p-126", APFloat::opOK, APFloat::fcNormal }, { MSmallestNormalized, PLargestValue, "-0x0p+0", UnderflowStatus, APFloat::fcZero }, { MSmallestNormalized, MLargestValue, "0x0p+0", UnderflowStatus, APFloat::fcZero }, { MSmallestNormalized, PSmallestValue, "-0x1p+23", APFloat::opOK, APFloat::fcNormal }, { MSmallestNormalized, MSmallestValue, "0x1p+23", APFloat::opOK, APFloat::fcNormal }, { MSmallestNormalized, PSmallestNormalized, "-0x1p+0", APFloat::opOK, APFloat::fcNormal }, { MSmallestNormalized, MSmallestNormalized, "0x1p+0", APFloat::opOK, APFloat::fcNormal }, }; for (size_t i = 0; i < NumTests; ++i) { APFloat x(SpecialCaseTests[i].x); APFloat y(SpecialCaseTests[i].y); APFloat::opStatus status = x.divide(y, APFloat::rmNearestTiesToEven); APFloat result(APFloat::IEEEsingle, SpecialCaseTests[i].result); EXPECT_TRUE(result.bitwiseIsEqual(x)); EXPECT_TRUE((int)status == SpecialCaseTests[i].status); EXPECT_TRUE((int)x.getCategory() == SpecialCaseTests[i].category); } } TEST(APFloatTest, operatorOverloads) { // This is mostly testing that these operator overloads compile. APFloat One = APFloat(APFloat::IEEEsingle, "0x1p+0"); APFloat Two = APFloat(APFloat::IEEEsingle, "0x2p+0"); EXPECT_TRUE(Two.bitwiseIsEqual(One + One)); EXPECT_TRUE(One.bitwiseIsEqual(Two - One)); EXPECT_TRUE(Two.bitwiseIsEqual(One * Two)); EXPECT_TRUE(One.bitwiseIsEqual(Two / Two)); } TEST(APFloatTest, abs) { APFloat PInf = APFloat::getInf(APFloat::IEEEsingle, false); APFloat MInf = APFloat::getInf(APFloat::IEEEsingle, true); APFloat PZero = APFloat::getZero(APFloat::IEEEsingle, false); APFloat MZero = APFloat::getZero(APFloat::IEEEsingle, true); APFloat PQNaN = APFloat::getNaN(APFloat::IEEEsingle, false); APFloat MQNaN = APFloat::getNaN(APFloat::IEEEsingle, true); APFloat PSNaN = APFloat::getSNaN(APFloat::IEEEsingle, false); APFloat MSNaN = APFloat::getSNaN(APFloat::IEEEsingle, true); APFloat PNormalValue = APFloat(APFloat::IEEEsingle, "0x1p+0"); APFloat MNormalValue = APFloat(APFloat::IEEEsingle, "-0x1p+0"); APFloat PLargestValue = APFloat::getLargest(APFloat::IEEEsingle, false); APFloat MLargestValue = APFloat::getLargest(APFloat::IEEEsingle, true); APFloat PSmallestValue = APFloat::getSmallest(APFloat::IEEEsingle, false); APFloat MSmallestValue = APFloat::getSmallest(APFloat::IEEEsingle, true); APFloat PSmallestNormalized = APFloat::getSmallestNormalized(APFloat::IEEEsingle, false); APFloat MSmallestNormalized = APFloat::getSmallestNormalized(APFloat::IEEEsingle, true); EXPECT_TRUE(PInf.bitwiseIsEqual(abs(PInf))); EXPECT_TRUE(PInf.bitwiseIsEqual(abs(MInf))); EXPECT_TRUE(PZero.bitwiseIsEqual(abs(PZero))); EXPECT_TRUE(PZero.bitwiseIsEqual(abs(MZero))); EXPECT_TRUE(PQNaN.bitwiseIsEqual(abs(PQNaN))); EXPECT_TRUE(PQNaN.bitwiseIsEqual(abs(MQNaN))); EXPECT_TRUE(PSNaN.bitwiseIsEqual(abs(PSNaN))); EXPECT_TRUE(PSNaN.bitwiseIsEqual(abs(MSNaN))); EXPECT_TRUE(PNormalValue.bitwiseIsEqual(abs(PNormalValue))); EXPECT_TRUE(PNormalValue.bitwiseIsEqual(abs(MNormalValue))); EXPECT_TRUE(PLargestValue.bitwiseIsEqual(abs(PLargestValue))); EXPECT_TRUE(PLargestValue.bitwiseIsEqual(abs(MLargestValue))); EXPECT_TRUE(PSmallestValue.bitwiseIsEqual(abs(PSmallestValue))); EXPECT_TRUE(PSmallestValue.bitwiseIsEqual(abs(MSmallestValue))); EXPECT_TRUE(PSmallestNormalized.bitwiseIsEqual(abs(PSmallestNormalized))); EXPECT_TRUE(PSmallestNormalized.bitwiseIsEqual(abs(MSmallestNormalized))); } TEST(APFloatTest, ilogb) { EXPECT_EQ(0, ilogb(APFloat(APFloat::IEEEsingle, "0x1p+0"))); EXPECT_EQ(0, ilogb(APFloat(APFloat::IEEEsingle, "-0x1p+0"))); EXPECT_EQ(42, ilogb(APFloat(APFloat::IEEEsingle, "0x1p+42"))); EXPECT_EQ(-42, ilogb(APFloat(APFloat::IEEEsingle, "0x1p-42"))); EXPECT_EQ(APFloat::IEK_Inf, ilogb(APFloat::getInf(APFloat::IEEEsingle, false))); EXPECT_EQ(APFloat::IEK_Inf, ilogb(APFloat::getInf(APFloat::IEEEsingle, true))); EXPECT_EQ(APFloat::IEK_Zero, ilogb(APFloat::getZero(APFloat::IEEEsingle, false))); EXPECT_EQ(APFloat::IEK_Zero, ilogb(APFloat::getZero(APFloat::IEEEsingle, true))); EXPECT_EQ(APFloat::IEK_NaN, ilogb(APFloat::getNaN(APFloat::IEEEsingle, false))); EXPECT_EQ(APFloat::IEK_NaN, ilogb(APFloat::getSNaN(APFloat::IEEEsingle, false))); EXPECT_EQ(127, ilogb(APFloat::getLargest(APFloat::IEEEsingle, false))); EXPECT_EQ(127, ilogb(APFloat::getLargest(APFloat::IEEEsingle, true))); EXPECT_EQ(-126, ilogb(APFloat::getSmallest(APFloat::IEEEsingle, false))); EXPECT_EQ(-126, ilogb(APFloat::getSmallest(APFloat::IEEEsingle, true))); EXPECT_EQ(-126, ilogb(APFloat::getSmallestNormalized(APFloat::IEEEsingle, false))); EXPECT_EQ(-126, ilogb(APFloat::getSmallestNormalized(APFloat::IEEEsingle, true))); } TEST(APFloatTest, scalbn) { EXPECT_TRUE( APFloat(APFloat::IEEEsingle, "0x1p+0") .bitwiseIsEqual(scalbn(APFloat(APFloat::IEEEsingle, "0x1p+0"), 0))); EXPECT_TRUE( APFloat(APFloat::IEEEsingle, "0x1p+42") .bitwiseIsEqual(scalbn(APFloat(APFloat::IEEEsingle, "0x1p+0"), 42))); EXPECT_TRUE( APFloat(APFloat::IEEEsingle, "0x1p-42") .bitwiseIsEqual(scalbn(APFloat(APFloat::IEEEsingle, "0x1p+0"), -42))); APFloat PInf = APFloat::getInf(APFloat::IEEEsingle, false); APFloat MInf = APFloat::getInf(APFloat::IEEEsingle, true); APFloat PZero = APFloat::getZero(APFloat::IEEEsingle, false); APFloat MZero = APFloat::getZero(APFloat::IEEEsingle, true); APFloat QPNaN = APFloat::getNaN(APFloat::IEEEsingle, false); APFloat QMNaN = APFloat::getNaN(APFloat::IEEEsingle, true); APFloat SNaN = APFloat::getSNaN(APFloat::IEEEsingle, false); EXPECT_TRUE(PInf.bitwiseIsEqual(scalbn(PInf, 0))); EXPECT_TRUE(MInf.bitwiseIsEqual(scalbn(MInf, 0))); EXPECT_TRUE(PZero.bitwiseIsEqual(scalbn(PZero, 0))); EXPECT_TRUE(MZero.bitwiseIsEqual(scalbn(MZero, 0))); EXPECT_TRUE(QPNaN.bitwiseIsEqual(scalbn(QPNaN, 0))); EXPECT_TRUE(QMNaN.bitwiseIsEqual(scalbn(QMNaN, 0))); EXPECT_TRUE(SNaN.bitwiseIsEqual(scalbn(SNaN, 0))); EXPECT_TRUE( PInf.bitwiseIsEqual(scalbn(APFloat(APFloat::IEEEsingle, "0x1p+0"), 128))); EXPECT_TRUE(MInf.bitwiseIsEqual( scalbn(APFloat(APFloat::IEEEsingle, "-0x1p+0"), 128))); EXPECT_TRUE( PInf.bitwiseIsEqual(scalbn(APFloat(APFloat::IEEEsingle, "0x1p+127"), 1))); EXPECT_TRUE(PZero.bitwiseIsEqual( scalbn(APFloat(APFloat::IEEEsingle, "0x1p+0"), -127))); EXPECT_TRUE(MZero.bitwiseIsEqual( scalbn(APFloat(APFloat::IEEEsingle, "-0x1p+0"), -127))); EXPECT_TRUE(PZero.bitwiseIsEqual( scalbn(APFloat(APFloat::IEEEsingle, "0x1p-126"), -1))); EXPECT_TRUE(PZero.bitwiseIsEqual( scalbn(APFloat(APFloat::IEEEsingle, "0x1p-126"), -1))); } }
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/ADT/PointerIntPairTest.cpp
//===- llvm/unittest/ADT/PointerIntPairTest.cpp - Unit tests --------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "gtest/gtest.h" #include "llvm/ADT/PointerIntPair.h" #include <limits> using namespace llvm; namespace { // Test fixture class PointerIntPairTest : public testing::Test { }; TEST_F(PointerIntPairTest, GetSet) { PointerIntPair<PointerIntPairTest *, 2> Pair(this, 1U); EXPECT_EQ(this, Pair.getPointer()); EXPECT_EQ(1U, Pair.getInt()); Pair.setInt(2); EXPECT_EQ(this, Pair.getPointer()); EXPECT_EQ(2U, Pair.getInt()); Pair.setPointer(nullptr); EXPECT_EQ(nullptr, Pair.getPointer()); EXPECT_EQ(2U, Pair.getInt()); Pair.setPointerAndInt(this, 3U); EXPECT_EQ(this, Pair.getPointer()); EXPECT_EQ(3U, Pair.getInt()); } TEST_F(PointerIntPairTest, DefaultInitialize) { PointerIntPair<PointerIntPairTest *, 2> Pair; EXPECT_EQ(nullptr, Pair.getPointer()); EXPECT_EQ(0U, Pair.getInt()); } TEST_F(PointerIntPairTest, ManyUnusedBits) { // In real code this would be a word-sized integer limited to 31 bits. struct Fixnum31 { uintptr_t Value; }; class FixnumPointerTraits { public: static inline void *getAsVoidPointer(Fixnum31 Num) { return reinterpret_cast<void *>(Num.Value << NumLowBitsAvailable); } static inline Fixnum31 getFromVoidPointer(void *P) { // In real code this would assert that the value is in range. return { reinterpret_cast<uintptr_t>(P) >> NumLowBitsAvailable }; } enum { NumLowBitsAvailable = std::numeric_limits<uintptr_t>::digits - 31 }; }; PointerIntPair<Fixnum31, 1, bool, FixnumPointerTraits> pair; EXPECT_EQ((uintptr_t)0, pair.getPointer().Value); EXPECT_FALSE(pair.getInt()); pair.setPointerAndInt({ 0x7FFFFFFF }, true ); EXPECT_EQ((uintptr_t)0x7FFFFFFF, pair.getPointer().Value); EXPECT_TRUE(pair.getInt()); EXPECT_EQ(FixnumPointerTraits::NumLowBitsAvailable - 1, PointerLikeTypeTraits<decltype(pair)>::NumLowBitsAvailable); } } // end anonymous namespace
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/ADT/SmallPtrSetTest.cpp
//===- llvm/unittest/ADT/SmallPtrSetTest.cpp ------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // SmallPtrSet unit tests. // //===----------------------------------------------------------------------===// #include "gtest/gtest.h" #include "llvm/ADT/SmallPtrSet.h" using namespace llvm; TEST(SmallPtrSetTest, Assignment) { int buf[8]; for (int i = 0; i < 8; ++i) buf[i] = 0; SmallPtrSet<int *, 4> s1; s1.insert(&buf[0]); s1.insert(&buf[1]); SmallPtrSet<int *, 4> s2; (s2 = s1).insert(&buf[2]); // Self assign as well. // HLSL Change - silence warning (s2 = static_cast<SmallPtrSet<int *, 4> &>(s2)).insert(&buf[3]); s1 = s2; EXPECT_EQ(4U, s1.size()); for (int i = 0; i < 8; ++i) if (i < 4) EXPECT_TRUE(s1.count(&buf[i])); else EXPECT_FALSE(s1.count(&buf[i])); } TEST(SmallPtrSetTest, GrowthTest) { int i; int buf[8]; for(i=0; i<8; ++i) buf[i]=0; SmallPtrSet<int *, 4> s; typedef SmallPtrSet<int *, 4>::iterator iter; s.insert(&buf[0]); s.insert(&buf[1]); s.insert(&buf[2]); s.insert(&buf[3]); EXPECT_EQ(4U, s.size()); i = 0; for(iter I=s.begin(), E=s.end(); I!=E; ++I, ++i) (**I)++; EXPECT_EQ(4, i); for(i=0; i<8; ++i) EXPECT_EQ(i<4?1:0,buf[i]); s.insert(&buf[4]); s.insert(&buf[5]); s.insert(&buf[6]); s.insert(&buf[7]); i = 0; for(iter I=s.begin(), E=s.end(); I!=E; ++I, ++i) (**I)++; EXPECT_EQ(8, i); s.erase(&buf[4]); s.erase(&buf[5]); s.erase(&buf[6]); s.erase(&buf[7]); EXPECT_EQ(4U, s.size()); i = 0; for(iter I=s.begin(), E=s.end(); I!=E; ++I, ++i) (**I)++; EXPECT_EQ(4, i); for(i=0; i<8; ++i) EXPECT_EQ(i<4?3:1,buf[i]); s.clear(); for(i=0; i<8; ++i) buf[i]=0; for(i=0; i<128; ++i) s.insert(&buf[i%8]); // test repeated entires EXPECT_EQ(8U, s.size()); for(iter I=s.begin(), E=s.end(); I!=E; ++I, ++i) (**I)++; for(i=0; i<8; ++i) EXPECT_EQ(1,buf[i]); } TEST(SmallPtrSetTest, CopyAndMoveTest) { int buf[8]; for (int i = 0; i < 8; ++i) buf[i] = 0; SmallPtrSet<int *, 4> s1; s1.insert(&buf[0]); s1.insert(&buf[1]); s1.insert(&buf[2]); s1.insert(&buf[3]); EXPECT_EQ(4U, s1.size()); for (int i = 0; i < 8; ++i) if (i < 4) EXPECT_TRUE(s1.count(&buf[i])); else EXPECT_FALSE(s1.count(&buf[i])); SmallPtrSet<int *, 4> s2(s1); EXPECT_EQ(4U, s2.size()); for (int i = 0; i < 8; ++i) if (i < 4) EXPECT_TRUE(s2.count(&buf[i])); else EXPECT_FALSE(s2.count(&buf[i])); s1 = s2; EXPECT_EQ(4U, s1.size()); EXPECT_EQ(4U, s2.size()); for (int i = 0; i < 8; ++i) if (i < 4) EXPECT_TRUE(s1.count(&buf[i])); else EXPECT_FALSE(s1.count(&buf[i])); SmallPtrSet<int *, 4> s3(std::move(s1)); EXPECT_EQ(4U, s3.size()); EXPECT_TRUE(s1.empty()); for (int i = 0; i < 8; ++i) if (i < 4) EXPECT_TRUE(s3.count(&buf[i])); else EXPECT_FALSE(s3.count(&buf[i])); // Move assign into the moved-from object. Also test move of a non-small // container. s3.insert(&buf[4]); s3.insert(&buf[5]); s3.insert(&buf[6]); s3.insert(&buf[7]); s1 = std::move(s3); EXPECT_EQ(8U, s1.size()); EXPECT_TRUE(s3.empty()); for (int i = 0; i < 8; ++i) EXPECT_TRUE(s1.count(&buf[i])); // Copy assign into a moved-from object. s3 = s1; EXPECT_EQ(8U, s3.size()); EXPECT_EQ(8U, s1.size()); for (int i = 0; i < 8; ++i) EXPECT_TRUE(s3.count(&buf[i])); } TEST(SmallPtrSetTest, SwapTest) { int buf[10]; SmallPtrSet<int *, 2> a; SmallPtrSet<int *, 2> b; a.insert(&buf[0]); a.insert(&buf[1]); b.insert(&buf[2]); std::swap(a, b); EXPECT_EQ(1U, a.size()); EXPECT_EQ(2U, b.size()); EXPECT_TRUE(a.count(&buf[2])); EXPECT_TRUE(b.count(&buf[0])); EXPECT_TRUE(b.count(&buf[1])); b.insert(&buf[3]); std::swap(a, b); EXPECT_EQ(3U, a.size()); EXPECT_EQ(1U, b.size()); EXPECT_TRUE(a.count(&buf[0])); EXPECT_TRUE(a.count(&buf[1])); EXPECT_TRUE(a.count(&buf[3])); EXPECT_TRUE(b.count(&buf[2])); std::swap(a, b); EXPECT_EQ(1U, a.size()); EXPECT_EQ(3U, b.size()); EXPECT_TRUE(a.count(&buf[2])); EXPECT_TRUE(b.count(&buf[0])); EXPECT_TRUE(b.count(&buf[1])); EXPECT_TRUE(b.count(&buf[3])); a.insert(&buf[4]); a.insert(&buf[5]); a.insert(&buf[6]); std::swap(b, a); EXPECT_EQ(3U, a.size()); EXPECT_EQ(4U, b.size()); EXPECT_TRUE(b.count(&buf[2])); EXPECT_TRUE(b.count(&buf[4])); EXPECT_TRUE(b.count(&buf[5])); EXPECT_TRUE(b.count(&buf[6])); EXPECT_TRUE(a.count(&buf[0])); EXPECT_TRUE(a.count(&buf[1])); EXPECT_TRUE(a.count(&buf[3])); }
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/ADT/DAGDeltaAlgorithmTest.cpp
//===- llvm/unittest/ADT/DAGDeltaAlgorithmTest.cpp ------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "gtest/gtest.h" #include "llvm/ADT/DAGDeltaAlgorithm.h" #include <algorithm> #include <cstdarg> using namespace llvm; namespace { typedef DAGDeltaAlgorithm::edge_ty edge_ty; class FixedDAGDeltaAlgorithm : public DAGDeltaAlgorithm { changeset_ty FailingSet; unsigned NumTests; protected: bool ExecuteOneTest(const changeset_ty &Changes) override { ++NumTests; return std::includes(Changes.begin(), Changes.end(), FailingSet.begin(), FailingSet.end()); } public: FixedDAGDeltaAlgorithm(const changeset_ty &_FailingSet) : FailingSet(_FailingSet), NumTests(0) {} unsigned getNumTests() const { return NumTests; } }; std::set<unsigned> fixed_set(unsigned N, ...) { std::set<unsigned> S; va_list ap; va_start(ap, N); for (unsigned i = 0; i != N; ++i) S.insert(va_arg(ap, unsigned)); va_end(ap); return S; } std::set<unsigned> range(unsigned Start, unsigned End) { std::set<unsigned> S; while (Start != End) S.insert(Start++); return S; } std::set<unsigned> range(unsigned N) { return range(0, N); } TEST(DAGDeltaAlgorithmTest, Basic) { std::vector<edge_ty> Deps; // Dependencies: // 1 - 3 Deps.clear(); Deps.push_back(std::make_pair(3, 1)); // P = {3,5,7} \in S, // [0, 20), // should minimize to {1,3,5,7} in a reasonable number of tests. FixedDAGDeltaAlgorithm FDA(fixed_set(3, 3, 5, 7)); EXPECT_EQ(fixed_set(4, 1, 3, 5, 7), FDA.Run(range(20), Deps)); EXPECT_GE(46U, FDA.getNumTests()); // Dependencies: // 0 - 1 // \- 2 - 3 // \- 4 Deps.clear(); Deps.push_back(std::make_pair(1, 0)); Deps.push_back(std::make_pair(2, 0)); Deps.push_back(std::make_pair(4, 0)); Deps.push_back(std::make_pair(3, 2)); // This is a case where we must hold required changes. // // P = {1,3} \in S, // [0, 5), // should minimize to {0,1,2,3} in a small number of tests. FixedDAGDeltaAlgorithm FDA2(fixed_set(2, 1, 3)); EXPECT_EQ(fixed_set(4, 0, 1, 2, 3), FDA2.Run(range(5), Deps)); EXPECT_GE(9U, FDA2.getNumTests()); // This is a case where we should quickly prune part of the tree. // // P = {4} \in S, // [0, 5), // should minimize to {0,4} in a small number of tests. FixedDAGDeltaAlgorithm FDA3(fixed_set(1, 4)); EXPECT_EQ(fixed_set(2, 0, 4), FDA3.Run(range(5), Deps)); EXPECT_GE(6U, FDA3.getNumTests()); } }
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/ADT/DeltaAlgorithmTest.cpp
//===- llvm/unittest/ADT/DeltaAlgorithmTest.cpp ---------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "gtest/gtest.h" #include "llvm/ADT/DeltaAlgorithm.h" #include <algorithm> #include <cstdarg> using namespace llvm; namespace std { std::ostream &operator<<(std::ostream &OS, const std::set<unsigned> &S) { OS << "{"; for (std::set<unsigned>::const_iterator it = S.begin(), ie = S.end(); it != ie; ++it) { if (it != S.begin()) OS << ","; OS << *it; } OS << "}"; return OS; } } namespace { class FixedDeltaAlgorithm final : public DeltaAlgorithm { changeset_ty FailingSet; unsigned NumTests; protected: bool ExecuteOneTest(const changeset_ty &Changes) override { ++NumTests; return std::includes(Changes.begin(), Changes.end(), FailingSet.begin(), FailingSet.end()); } public: FixedDeltaAlgorithm(const changeset_ty &_FailingSet) : FailingSet(_FailingSet), NumTests(0) {} unsigned getNumTests() const { return NumTests; } }; std::set<unsigned> fixed_set(unsigned N, ...) { std::set<unsigned> S; va_list ap; va_start(ap, N); for (unsigned i = 0; i != N; ++i) S.insert(va_arg(ap, unsigned)); va_end(ap); return S; } std::set<unsigned> range(unsigned Start, unsigned End) { std::set<unsigned> S; while (Start != End) S.insert(Start++); return S; } std::set<unsigned> range(unsigned N) { return range(0, N); } TEST(DeltaAlgorithmTest, Basic) { // P = {3,5,7} \in S // [0, 20) should minimize to {3,5,7} in a reasonable number of tests. std::set<unsigned> Fails = fixed_set(3, 3, 5, 7); FixedDeltaAlgorithm FDA(Fails); EXPECT_EQ(fixed_set(3, 3, 5, 7), FDA.Run(range(20))); EXPECT_GE(33U, FDA.getNumTests()); // P = {3,5,7} \in S // [10, 20) should minimize to [10,20) EXPECT_EQ(range(10,20), FDA.Run(range(10,20))); // P = [0,4) \in S // [0, 4) should minimize to [0,4) in 11 tests. // // 11 = |{ {}, // {0}, {1}, {2}, {3}, // {1, 2, 3}, {0, 2, 3}, {0, 1, 3}, {0, 1, 2}, // {0, 1}, {2, 3} }| FDA = FixedDeltaAlgorithm(range(10)); EXPECT_EQ(range(4), FDA.Run(range(4))); EXPECT_EQ(11U, FDA.getNumTests()); } }
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/ADT/IntEqClassesTest.cpp
//===---- ADT/IntEqClassesTest.cpp - IntEqClasses unit tests ----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/ADT/IntEqClasses.h" #include "gtest/gtest.h" using namespace llvm; namespace { TEST(IntEqClasses, Simple) { IntEqClasses ec(10); ec.join(0, 1); ec.join(3, 2); ec.join(4, 5); ec.join(7, 6); EXPECT_EQ(0u, ec.findLeader(0)); EXPECT_EQ(0u, ec.findLeader(1)); EXPECT_EQ(2u, ec.findLeader(2)); EXPECT_EQ(2u, ec.findLeader(3)); EXPECT_EQ(4u, ec.findLeader(4)); EXPECT_EQ(4u, ec.findLeader(5)); EXPECT_EQ(6u, ec.findLeader(6)); EXPECT_EQ(6u, ec.findLeader(7)); EXPECT_EQ(8u, ec.findLeader(8)); EXPECT_EQ(9u, ec.findLeader(9)); // join two non-leaders. ec.join(1, 3); EXPECT_EQ(0u, ec.findLeader(0)); EXPECT_EQ(0u, ec.findLeader(1)); EXPECT_EQ(0u, ec.findLeader(2)); EXPECT_EQ(0u, ec.findLeader(3)); EXPECT_EQ(4u, ec.findLeader(4)); EXPECT_EQ(4u, ec.findLeader(5)); EXPECT_EQ(6u, ec.findLeader(6)); EXPECT_EQ(6u, ec.findLeader(7)); EXPECT_EQ(8u, ec.findLeader(8)); EXPECT_EQ(9u, ec.findLeader(9)); // join two leaders. ec.join(4, 8); EXPECT_EQ(0u, ec.findLeader(0)); EXPECT_EQ(0u, ec.findLeader(1)); EXPECT_EQ(0u, ec.findLeader(2)); EXPECT_EQ(0u, ec.findLeader(3)); EXPECT_EQ(4u, ec.findLeader(4)); EXPECT_EQ(4u, ec.findLeader(5)); EXPECT_EQ(6u, ec.findLeader(6)); EXPECT_EQ(6u, ec.findLeader(7)); EXPECT_EQ(4u, ec.findLeader(8)); EXPECT_EQ(9u, ec.findLeader(9)); // join mixed. ec.join(9, 1); EXPECT_EQ(0u, ec.findLeader(0)); EXPECT_EQ(0u, ec.findLeader(1)); EXPECT_EQ(0u, ec.findLeader(2)); EXPECT_EQ(0u, ec.findLeader(3)); EXPECT_EQ(4u, ec.findLeader(4)); EXPECT_EQ(4u, ec.findLeader(5)); EXPECT_EQ(6u, ec.findLeader(6)); EXPECT_EQ(6u, ec.findLeader(7)); EXPECT_EQ(4u, ec.findLeader(8)); EXPECT_EQ(0u, ec.findLeader(9)); // compressed map. ec.compress(); EXPECT_EQ(3u, ec.getNumClasses()); EXPECT_EQ(0u, ec[0]); EXPECT_EQ(0u, ec[1]); EXPECT_EQ(0u, ec[2]); EXPECT_EQ(0u, ec[3]); EXPECT_EQ(1u, ec[4]); EXPECT_EQ(1u, ec[5]); EXPECT_EQ(2u, ec[6]); EXPECT_EQ(2u, ec[7]); EXPECT_EQ(1u, ec[8]); EXPECT_EQ(0u, ec[9]); // uncompressed map. ec.uncompress(); EXPECT_EQ(0u, ec.findLeader(0)); EXPECT_EQ(0u, ec.findLeader(1)); EXPECT_EQ(0u, ec.findLeader(2)); EXPECT_EQ(0u, ec.findLeader(3)); EXPECT_EQ(4u, ec.findLeader(4)); EXPECT_EQ(4u, ec.findLeader(5)); EXPECT_EQ(6u, ec.findLeader(6)); EXPECT_EQ(6u, ec.findLeader(7)); EXPECT_EQ(4u, ec.findLeader(8)); EXPECT_EQ(0u, ec.findLeader(9)); } } // end anonymous namespace
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/ADT/SmallVectorTest.cpp
//===- llvm/unittest/ADT/SmallVectorTest.cpp ------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // SmallVector unit tests. // //===----------------------------------------------------------------------===// #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Support/Compiler.h" #include "gtest/gtest.h" #include <list> #include <stdarg.h> using namespace llvm; namespace { /// A helper class that counts the total number of constructor and /// destructor calls. class Constructable { private: static int numConstructorCalls; static int numMoveConstructorCalls; static int numCopyConstructorCalls; static int numDestructorCalls; static int numAssignmentCalls; static int numMoveAssignmentCalls; static int numCopyAssignmentCalls; bool constructed; int value; public: Constructable() : constructed(true), value(0) { ++numConstructorCalls; } Constructable(int val) : constructed(true), value(val) { ++numConstructorCalls; } Constructable(const Constructable & src) : constructed(true) { value = src.value; ++numConstructorCalls; ++numCopyConstructorCalls; } Constructable(Constructable && src) : constructed(true) { value = src.value; ++numConstructorCalls; ++numMoveConstructorCalls; } ~Constructable() { EXPECT_TRUE(constructed); ++numDestructorCalls; constructed = false; } Constructable & operator=(const Constructable & src) { EXPECT_TRUE(constructed); value = src.value; ++numAssignmentCalls; ++numCopyAssignmentCalls; return *this; } Constructable & operator=(Constructable && src) { EXPECT_TRUE(constructed); value = src.value; ++numAssignmentCalls; ++numMoveAssignmentCalls; return *this; } int getValue() const { return abs(value); } static void reset() { numConstructorCalls = 0; numMoveConstructorCalls = 0; numCopyConstructorCalls = 0; numDestructorCalls = 0; numAssignmentCalls = 0; numMoveAssignmentCalls = 0; numCopyAssignmentCalls = 0; } static int getNumConstructorCalls() { return numConstructorCalls; } static int getNumMoveConstructorCalls() { return numMoveConstructorCalls; } static int getNumCopyConstructorCalls() { return numCopyConstructorCalls; } static int getNumDestructorCalls() { return numDestructorCalls; } static int getNumAssignmentCalls() { return numAssignmentCalls; } static int getNumMoveAssignmentCalls() { return numMoveAssignmentCalls; } static int getNumCopyAssignmentCalls() { return numCopyAssignmentCalls; } friend bool operator==(const Constructable & c0, const Constructable & c1) { return c0.getValue() == c1.getValue(); } friend bool LLVM_ATTRIBUTE_UNUSED operator!=(const Constructable & c0, const Constructable & c1) { return c0.getValue() != c1.getValue(); } }; int Constructable::numConstructorCalls; int Constructable::numCopyConstructorCalls; int Constructable::numMoveConstructorCalls; int Constructable::numDestructorCalls; int Constructable::numAssignmentCalls; int Constructable::numCopyAssignmentCalls; int Constructable::numMoveAssignmentCalls; struct NonCopyable { NonCopyable() {} NonCopyable(NonCopyable &&) {} NonCopyable &operator=(NonCopyable &&) { return *this; } private: NonCopyable(const NonCopyable &) = delete; NonCopyable &operator=(const NonCopyable &) = delete; }; LLVM_ATTRIBUTE_USED void CompileTest() { SmallVector<NonCopyable, 0> V; V.resize(42); } class SmallVectorTestBase : public testing::Test { protected: void SetUp() override { Constructable::reset(); } template <typename VectorT> void assertEmpty(VectorT & v) { // Size tests EXPECT_EQ(0u, v.size()); EXPECT_TRUE(v.empty()); // Iterator tests EXPECT_TRUE(v.begin() == v.end()); } // Assert that v contains the specified values, in order. template <typename VectorT> void assertValuesInOrder(VectorT & v, size_t size, ...) { EXPECT_EQ(size, v.size()); va_list ap; va_start(ap, size); for (size_t i = 0; i < size; ++i) { int value = va_arg(ap, int); EXPECT_EQ(value, v[i].getValue()); } va_end(ap); } // Generate a sequence of values to initialize the vector. template <typename VectorT> void makeSequence(VectorT & v, int start, int end) { for (int i = start; i <= end; ++i) { v.push_back(Constructable(i)); } } }; // Test fixture class template <typename VectorT> class SmallVectorTest : public SmallVectorTestBase { protected: VectorT theVector; VectorT otherVector; }; typedef ::testing::Types<SmallVector<Constructable, 0>, SmallVector<Constructable, 1>, SmallVector<Constructable, 2>, SmallVector<Constructable, 4>, SmallVector<Constructable, 5> > SmallVectorTestTypes; TYPED_TEST_CASE(SmallVectorTest, SmallVectorTestTypes); // New vector test. TYPED_TEST(SmallVectorTest, EmptyVectorTest) { SCOPED_TRACE("EmptyVectorTest"); this->assertEmpty(this->theVector); EXPECT_TRUE(this->theVector.rbegin() == this->theVector.rend()); EXPECT_EQ(0, Constructable::getNumConstructorCalls()); EXPECT_EQ(0, Constructable::getNumDestructorCalls()); } // Simple insertions and deletions. TYPED_TEST(SmallVectorTest, PushPopTest) { SCOPED_TRACE("PushPopTest"); // Track whether the vector will potentially have to grow. bool RequiresGrowth = this->theVector.capacity() < 3; // Push an element this->theVector.push_back(Constructable(1)); // Size tests this->assertValuesInOrder(this->theVector, 1u, 1); EXPECT_FALSE(this->theVector.begin() == this->theVector.end()); EXPECT_FALSE(this->theVector.empty()); // Push another element this->theVector.push_back(Constructable(2)); this->assertValuesInOrder(this->theVector, 2u, 1, 2); // Insert at beginning this->theVector.insert(this->theVector.begin(), this->theVector[1]); this->assertValuesInOrder(this->theVector, 3u, 2, 1, 2); // Pop one element this->theVector.pop_back(); this->assertValuesInOrder(this->theVector, 2u, 2, 1); // Pop remaining elements this->theVector.pop_back(); this->theVector.pop_back(); this->assertEmpty(this->theVector); // Check number of constructor calls. Should be 2 for each list element, // one for the argument to push_back, one for the argument to insert, // and one for the list element itself. if (!RequiresGrowth) { EXPECT_EQ(5, Constructable::getNumConstructorCalls()); EXPECT_EQ(5, Constructable::getNumDestructorCalls()); } else { // If we had to grow the vector, these only have a lower bound, but should // always be equal. EXPECT_LE(5, Constructable::getNumConstructorCalls()); EXPECT_EQ(Constructable::getNumConstructorCalls(), Constructable::getNumDestructorCalls()); } } // Clear test. TYPED_TEST(SmallVectorTest, ClearTest) { SCOPED_TRACE("ClearTest"); this->theVector.reserve(2); this->makeSequence(this->theVector, 1, 2); this->theVector.clear(); this->assertEmpty(this->theVector); EXPECT_EQ(4, Constructable::getNumConstructorCalls()); EXPECT_EQ(4, Constructable::getNumDestructorCalls()); } // Resize smaller test. TYPED_TEST(SmallVectorTest, ResizeShrinkTest) { SCOPED_TRACE("ResizeShrinkTest"); this->theVector.reserve(3); this->makeSequence(this->theVector, 1, 3); this->theVector.resize(1); this->assertValuesInOrder(this->theVector, 1u, 1); EXPECT_EQ(6, Constructable::getNumConstructorCalls()); EXPECT_EQ(5, Constructable::getNumDestructorCalls()); } // Resize bigger test. TYPED_TEST(SmallVectorTest, ResizeGrowTest) { SCOPED_TRACE("ResizeGrowTest"); this->theVector.resize(2); EXPECT_EQ(2, Constructable::getNumConstructorCalls()); EXPECT_EQ(0, Constructable::getNumDestructorCalls()); EXPECT_EQ(2u, this->theVector.size()); } TYPED_TEST(SmallVectorTest, ResizeWithElementsTest) { this->theVector.resize(2); Constructable::reset(); this->theVector.resize(4); size_t Ctors = Constructable::getNumConstructorCalls(); EXPECT_TRUE(Ctors == 2 || Ctors == 4); size_t MoveCtors = Constructable::getNumMoveConstructorCalls(); EXPECT_TRUE(MoveCtors == 0 || MoveCtors == 2); size_t Dtors = Constructable::getNumDestructorCalls(); EXPECT_TRUE(Dtors == 0 || Dtors == 2); } // Resize with fill value. TYPED_TEST(SmallVectorTest, ResizeFillTest) { SCOPED_TRACE("ResizeFillTest"); this->theVector.resize(3, Constructable(77)); this->assertValuesInOrder(this->theVector, 3u, 77, 77, 77); } // Overflow past fixed size. TYPED_TEST(SmallVectorTest, OverflowTest) { SCOPED_TRACE("OverflowTest"); // Push more elements than the fixed size. this->makeSequence(this->theVector, 1, 10); // Test size and values. EXPECT_EQ(10u, this->theVector.size()); for (int i = 0; i < 10; ++i) { EXPECT_EQ(i+1, this->theVector[i].getValue()); } // Now resize back to fixed size. this->theVector.resize(1); this->assertValuesInOrder(this->theVector, 1u, 1); } // Iteration tests. TYPED_TEST(SmallVectorTest, IterationTest) { this->makeSequence(this->theVector, 1, 2); // Forward Iteration typename TypeParam::iterator it = this->theVector.begin(); EXPECT_TRUE(*it == this->theVector.front()); EXPECT_TRUE(*it == this->theVector[0]); EXPECT_EQ(1, it->getValue()); ++it; EXPECT_TRUE(*it == this->theVector[1]); EXPECT_TRUE(*it == this->theVector.back()); EXPECT_EQ(2, it->getValue()); ++it; EXPECT_TRUE(it == this->theVector.end()); --it; EXPECT_TRUE(*it == this->theVector[1]); EXPECT_EQ(2, it->getValue()); --it; EXPECT_TRUE(*it == this->theVector[0]); EXPECT_EQ(1, it->getValue()); // Reverse Iteration typename TypeParam::reverse_iterator rit = this->theVector.rbegin(); EXPECT_TRUE(*rit == this->theVector[1]); EXPECT_EQ(2, rit->getValue()); ++rit; EXPECT_TRUE(*rit == this->theVector[0]); EXPECT_EQ(1, rit->getValue()); ++rit; EXPECT_TRUE(rit == this->theVector.rend()); --rit; EXPECT_TRUE(*rit == this->theVector[0]); EXPECT_EQ(1, rit->getValue()); --rit; EXPECT_TRUE(*rit == this->theVector[1]); EXPECT_EQ(2, rit->getValue()); } // Swap test. TYPED_TEST(SmallVectorTest, SwapTest) { SCOPED_TRACE("SwapTest"); this->makeSequence(this->theVector, 1, 2); std::swap(this->theVector, this->otherVector); this->assertEmpty(this->theVector); this->assertValuesInOrder(this->otherVector, 2u, 1, 2); } // Append test TYPED_TEST(SmallVectorTest, AppendTest) { SCOPED_TRACE("AppendTest"); this->makeSequence(this->otherVector, 2, 3); this->theVector.push_back(Constructable(1)); this->theVector.append(this->otherVector.begin(), this->otherVector.end()); this->assertValuesInOrder(this->theVector, 3u, 1, 2, 3); } // Append repeated test TYPED_TEST(SmallVectorTest, AppendRepeatedTest) { SCOPED_TRACE("AppendRepeatedTest"); this->theVector.push_back(Constructable(1)); this->theVector.append(2, Constructable(77)); this->assertValuesInOrder(this->theVector, 3u, 1, 77, 77); } // Assign test TYPED_TEST(SmallVectorTest, AssignTest) { SCOPED_TRACE("AssignTest"); this->theVector.push_back(Constructable(1)); this->theVector.assign(2, Constructable(77)); this->assertValuesInOrder(this->theVector, 2u, 77, 77); } // Move-assign test TYPED_TEST(SmallVectorTest, MoveAssignTest) { SCOPED_TRACE("MoveAssignTest"); // Set up our vector with a single element, but enough capacity for 4. this->theVector.reserve(4); this->theVector.push_back(Constructable(1)); // Set up the other vector with 2 elements. this->otherVector.push_back(Constructable(2)); this->otherVector.push_back(Constructable(3)); // Move-assign from the other vector. this->theVector = std::move(this->otherVector); // Make sure we have the right result. this->assertValuesInOrder(this->theVector, 2u, 2, 3); // Make sure the # of constructor/destructor calls line up. There // are two live objects after clearing the other vector. this->otherVector.clear(); EXPECT_EQ(Constructable::getNumConstructorCalls()-2, Constructable::getNumDestructorCalls()); // There shouldn't be any live objects any more. this->theVector.clear(); EXPECT_EQ(Constructable::getNumConstructorCalls(), Constructable::getNumDestructorCalls()); } // Erase a single element TYPED_TEST(SmallVectorTest, EraseTest) { SCOPED_TRACE("EraseTest"); this->makeSequence(this->theVector, 1, 3); this->theVector.erase(this->theVector.begin()); this->assertValuesInOrder(this->theVector, 2u, 2, 3); } // Erase a range of elements TYPED_TEST(SmallVectorTest, EraseRangeTest) { SCOPED_TRACE("EraseRangeTest"); this->makeSequence(this->theVector, 1, 3); this->theVector.erase(this->theVector.begin(), this->theVector.begin() + 2); this->assertValuesInOrder(this->theVector, 1u, 3); } // Insert a single element. TYPED_TEST(SmallVectorTest, InsertTest) { SCOPED_TRACE("InsertTest"); this->makeSequence(this->theVector, 1, 3); typename TypeParam::iterator I = this->theVector.insert(this->theVector.begin() + 1, Constructable(77)); EXPECT_EQ(this->theVector.begin() + 1, I); this->assertValuesInOrder(this->theVector, 4u, 1, 77, 2, 3); } // Insert a copy of a single element. TYPED_TEST(SmallVectorTest, InsertCopy) { SCOPED_TRACE("InsertTest"); this->makeSequence(this->theVector, 1, 3); Constructable C(77); typename TypeParam::iterator I = this->theVector.insert(this->theVector.begin() + 1, C); EXPECT_EQ(this->theVector.begin() + 1, I); this->assertValuesInOrder(this->theVector, 4u, 1, 77, 2, 3); } // Insert repeated elements. TYPED_TEST(SmallVectorTest, InsertRepeatedTest) { SCOPED_TRACE("InsertRepeatedTest"); this->makeSequence(this->theVector, 1, 4); Constructable::reset(); auto I = this->theVector.insert(this->theVector.begin() + 1, 2, Constructable(16)); // Move construct the top element into newly allocated space, and optionally // reallocate the whole buffer, move constructing into it. // FIXME: This is inefficient, we shouldn't move things into newly allocated // space, then move them up/around, there should only be 2 or 4 move // constructions here. EXPECT_TRUE(Constructable::getNumMoveConstructorCalls() == 2 || Constructable::getNumMoveConstructorCalls() == 6); // Move assign the next two to shift them up and make a gap. EXPECT_EQ(1, Constructable::getNumMoveAssignmentCalls()); // Copy construct the two new elements from the parameter. EXPECT_EQ(2, Constructable::getNumCopyAssignmentCalls()); // All without any copy construction. EXPECT_EQ(0, Constructable::getNumCopyConstructorCalls()); EXPECT_EQ(this->theVector.begin() + 1, I); this->assertValuesInOrder(this->theVector, 6u, 1, 16, 16, 2, 3, 4); } TYPED_TEST(SmallVectorTest, InsertRepeatedAtEndTest) { SCOPED_TRACE("InsertRepeatedTest"); this->makeSequence(this->theVector, 1, 4); Constructable::reset(); auto I = this->theVector.insert(this->theVector.end(), 2, Constructable(16)); // Just copy construct them into newly allocated space EXPECT_EQ(2, Constructable::getNumCopyConstructorCalls()); // Move everything across if reallocation is needed. EXPECT_TRUE(Constructable::getNumMoveConstructorCalls() == 0 || Constructable::getNumMoveConstructorCalls() == 4); // Without ever moving or copying anything else. EXPECT_EQ(0, Constructable::getNumCopyAssignmentCalls()); EXPECT_EQ(0, Constructable::getNumMoveAssignmentCalls()); EXPECT_EQ(this->theVector.begin() + 4, I); this->assertValuesInOrder(this->theVector, 6u, 1, 2, 3, 4, 16, 16); } TYPED_TEST(SmallVectorTest, InsertRepeatedEmptyTest) { SCOPED_TRACE("InsertRepeatedTest"); this->makeSequence(this->theVector, 10, 15); // Empty insert. EXPECT_EQ(this->theVector.end(), this->theVector.insert(this->theVector.end(), 0, Constructable(42))); EXPECT_EQ(this->theVector.begin() + 1, this->theVector.insert(this->theVector.begin() + 1, 0, Constructable(42))); } // Insert range. TYPED_TEST(SmallVectorTest, InsertRangeTest) { SCOPED_TRACE("InsertRangeTest"); Constructable Arr[3] = { Constructable(77), Constructable(77), Constructable(77) }; this->makeSequence(this->theVector, 1, 3); Constructable::reset(); auto I = this->theVector.insert(this->theVector.begin() + 1, Arr, Arr + 3); // Move construct the top 3 elements into newly allocated space. // Possibly move the whole sequence into new space first. // FIXME: This is inefficient, we shouldn't move things into newly allocated // space, then move them up/around, there should only be 2 or 3 move // constructions here. EXPECT_TRUE(Constructable::getNumMoveConstructorCalls() == 2 || Constructable::getNumMoveConstructorCalls() == 5); // Copy assign the lower 2 new elements into existing space. EXPECT_EQ(2, Constructable::getNumCopyAssignmentCalls()); // Copy construct the third element into newly allocated space. EXPECT_EQ(1, Constructable::getNumCopyConstructorCalls()); EXPECT_EQ(this->theVector.begin() + 1, I); this->assertValuesInOrder(this->theVector, 6u, 1, 77, 77, 77, 2, 3); } TYPED_TEST(SmallVectorTest, InsertRangeAtEndTest) { SCOPED_TRACE("InsertRangeTest"); Constructable Arr[3] = { Constructable(77), Constructable(77), Constructable(77) }; this->makeSequence(this->theVector, 1, 3); // Insert at end. Constructable::reset(); auto I = this->theVector.insert(this->theVector.end(), Arr, Arr+3); // Copy construct the 3 elements into new space at the top. EXPECT_EQ(3, Constructable::getNumCopyConstructorCalls()); // Don't copy/move anything else. EXPECT_EQ(0, Constructable::getNumCopyAssignmentCalls()); // Reallocation might occur, causing all elements to be moved into the new // buffer. EXPECT_TRUE(Constructable::getNumMoveConstructorCalls() == 0 || Constructable::getNumMoveConstructorCalls() == 3); EXPECT_EQ(0, Constructable::getNumMoveAssignmentCalls()); EXPECT_EQ(this->theVector.begin() + 3, I); this->assertValuesInOrder(this->theVector, 6u, 1, 2, 3, 77, 77, 77); } TYPED_TEST(SmallVectorTest, InsertEmptyRangeTest) { SCOPED_TRACE("InsertRangeTest"); this->makeSequence(this->theVector, 1, 3); // Empty insert. EXPECT_EQ(this->theVector.end(), this->theVector.insert(this->theVector.end(), this->theVector.begin(), this->theVector.begin())); EXPECT_EQ(this->theVector.begin() + 1, this->theVector.insert(this->theVector.begin() + 1, this->theVector.begin(), this->theVector.begin())); } // Comparison tests. TYPED_TEST(SmallVectorTest, ComparisonTest) { SCOPED_TRACE("ComparisonTest"); this->makeSequence(this->theVector, 1, 3); this->makeSequence(this->otherVector, 1, 3); EXPECT_TRUE(this->theVector == this->otherVector); EXPECT_FALSE(this->theVector != this->otherVector); this->otherVector.clear(); this->makeSequence(this->otherVector, 2, 4); EXPECT_FALSE(this->theVector == this->otherVector); EXPECT_TRUE(this->theVector != this->otherVector); } // Constant vector tests. TYPED_TEST(SmallVectorTest, ConstVectorTest) { const TypeParam constVector; EXPECT_EQ(0u, constVector.size()); EXPECT_TRUE(constVector.empty()); EXPECT_TRUE(constVector.begin() == constVector.end()); } // Direct array access. TYPED_TEST(SmallVectorTest, DirectVectorTest) { EXPECT_EQ(0u, this->theVector.size()); this->theVector.reserve(4); EXPECT_LE(4u, this->theVector.capacity()); EXPECT_EQ(0, Constructable::getNumConstructorCalls()); this->theVector.push_back(1); this->theVector.push_back(2); this->theVector.push_back(3); this->theVector.push_back(4); EXPECT_EQ(4u, this->theVector.size()); EXPECT_EQ(8, Constructable::getNumConstructorCalls()); EXPECT_EQ(1, this->theVector[0].getValue()); EXPECT_EQ(2, this->theVector[1].getValue()); EXPECT_EQ(3, this->theVector[2].getValue()); EXPECT_EQ(4, this->theVector[3].getValue()); } TYPED_TEST(SmallVectorTest, IteratorTest) { std::list<int> L; this->theVector.insert(this->theVector.end(), L.begin(), L.end()); } template <typename InvalidType> class DualSmallVectorsTest; template <typename VectorT1, typename VectorT2> class DualSmallVectorsTest<std::pair<VectorT1, VectorT2>> : public SmallVectorTestBase { protected: VectorT1 theVector; VectorT2 otherVector; template <typename T, unsigned N> static unsigned NumBuiltinElts(const SmallVector<T, N>&) { return N; } }; typedef ::testing::Types< // Small mode -> Small mode. std::pair<SmallVector<Constructable, 4>, SmallVector<Constructable, 4>>, // Small mode -> Big mode. std::pair<SmallVector<Constructable, 4>, SmallVector<Constructable, 2>>, // Big mode -> Small mode. std::pair<SmallVector<Constructable, 2>, SmallVector<Constructable, 4>>, // Big mode -> Big mode. std::pair<SmallVector<Constructable, 2>, SmallVector<Constructable, 2>> > DualSmallVectorTestTypes; TYPED_TEST_CASE(DualSmallVectorsTest, DualSmallVectorTestTypes); TYPED_TEST(DualSmallVectorsTest, MoveAssignment) { SCOPED_TRACE("MoveAssignTest-DualVectorTypes"); // Set up our vector with four elements. for (unsigned I = 0; I < 4; ++I) this->otherVector.push_back(Constructable(I)); const Constructable *OrigDataPtr = this->otherVector.data(); // Move-assign from the other vector. this->theVector = std::move(static_cast<SmallVectorImpl<Constructable>&>(this->otherVector)); // Make sure we have the right result. this->assertValuesInOrder(this->theVector, 4u, 0, 1, 2, 3); // Make sure the # of constructor/destructor calls line up. There // are two live objects after clearing the other vector. this->otherVector.clear(); EXPECT_EQ(Constructable::getNumConstructorCalls()-4, Constructable::getNumDestructorCalls()); // If the source vector (otherVector) was in small-mode, assert that we just // moved the data pointer over. EXPECT_TRUE(this->NumBuiltinElts(this->otherVector) == 4 || this->theVector.data() == OrigDataPtr); // There shouldn't be any live objects any more. this->theVector.clear(); EXPECT_EQ(Constructable::getNumConstructorCalls(), Constructable::getNumDestructorCalls()); // We shouldn't have copied anything in this whole process. EXPECT_EQ(Constructable::getNumCopyConstructorCalls(), 0); } struct notassignable { int &x; notassignable(int &x) : x(x) {} }; TEST(SmallVectorCustomTest, NoAssignTest) { int x = 0; SmallVector<notassignable, 2> vec; vec.push_back(notassignable(x)); x = 42; EXPECT_EQ(42, vec.pop_back_val().x); } struct MovedFrom { bool hasValue; MovedFrom() : hasValue(true) { } MovedFrom(MovedFrom&& m) : hasValue(m.hasValue) { m.hasValue = false; } MovedFrom &operator=(MovedFrom&& m) { hasValue = m.hasValue; m.hasValue = false; return *this; } }; TEST(SmallVectorTest, MidInsert) { SmallVector<MovedFrom, 3> v; v.push_back(MovedFrom()); v.insert(v.begin(), MovedFrom()); for (MovedFrom &m : v) EXPECT_TRUE(m.hasValue); } enum EmplaceableArgState { EAS_Defaulted, EAS_Arg, EAS_LValue, EAS_RValue, EAS_Failure }; template <int I> struct EmplaceableArg { EmplaceableArgState State; EmplaceableArg() : State(EAS_Defaulted) {} EmplaceableArg(EmplaceableArg &&X) : State(X.State == EAS_Arg ? EAS_RValue : EAS_Failure) {} EmplaceableArg(EmplaceableArg &X) : State(X.State == EAS_Arg ? EAS_LValue : EAS_Failure) {} explicit EmplaceableArg(bool) : State(EAS_Arg) {} private: EmplaceableArg &operator=(EmplaceableArg &&) = delete; EmplaceableArg &operator=(const EmplaceableArg &) = delete; }; enum EmplaceableState { ES_Emplaced, ES_Moved }; struct Emplaceable { EmplaceableArg<0> A0; EmplaceableArg<1> A1; EmplaceableArg<2> A2; EmplaceableArg<3> A3; EmplaceableState State; Emplaceable() : State(ES_Emplaced) {} template <class A0Ty> explicit Emplaceable(A0Ty &&A0) : A0(std::forward<A0Ty>(A0)), State(ES_Emplaced) {} template <class A0Ty, class A1Ty> Emplaceable(A0Ty &&A0, A1Ty &&A1) : A0(std::forward<A0Ty>(A0)), A1(std::forward<A1Ty>(A1)), State(ES_Emplaced) {} template <class A0Ty, class A1Ty, class A2Ty> Emplaceable(A0Ty &&A0, A1Ty &&A1, A2Ty &&A2) : A0(std::forward<A0Ty>(A0)), A1(std::forward<A1Ty>(A1)), A2(std::forward<A2Ty>(A2)), State(ES_Emplaced) {} template <class A0Ty, class A1Ty, class A2Ty, class A3Ty> Emplaceable(A0Ty &&A0, A1Ty &&A1, A2Ty &&A2, A3Ty &&A3) : A0(std::forward<A0Ty>(A0)), A1(std::forward<A1Ty>(A1)), A2(std::forward<A2Ty>(A2)), A3(std::forward<A3Ty>(A3)), State(ES_Emplaced) {} Emplaceable(Emplaceable &&) : State(ES_Moved) {} Emplaceable &operator=(Emplaceable &&) { State = ES_Moved; return *this; } private: Emplaceable(const Emplaceable &) = delete; Emplaceable &operator=(const Emplaceable &) = delete; }; TEST(SmallVectorTest, EmplaceBack) { EmplaceableArg<0> A0(true); EmplaceableArg<1> A1(true); EmplaceableArg<2> A2(true); EmplaceableArg<3> A3(true); { SmallVector<Emplaceable, 3> V; V.emplace_back(); EXPECT_TRUE(V.size() == 1); EXPECT_TRUE(V.back().State == ES_Emplaced); EXPECT_TRUE(V.back().A0.State == EAS_Defaulted); EXPECT_TRUE(V.back().A1.State == EAS_Defaulted); EXPECT_TRUE(V.back().A2.State == EAS_Defaulted); EXPECT_TRUE(V.back().A3.State == EAS_Defaulted); } { SmallVector<Emplaceable, 3> V; V.emplace_back(std::move(A0)); EXPECT_TRUE(V.size() == 1); EXPECT_TRUE(V.back().State == ES_Emplaced); EXPECT_TRUE(V.back().A0.State == EAS_RValue); EXPECT_TRUE(V.back().A1.State == EAS_Defaulted); EXPECT_TRUE(V.back().A2.State == EAS_Defaulted); EXPECT_TRUE(V.back().A3.State == EAS_Defaulted); } { SmallVector<Emplaceable, 3> V; V.emplace_back(A0); EXPECT_TRUE(V.size() == 1); EXPECT_TRUE(V.back().State == ES_Emplaced); EXPECT_TRUE(V.back().A0.State == EAS_LValue); EXPECT_TRUE(V.back().A1.State == EAS_Defaulted); EXPECT_TRUE(V.back().A2.State == EAS_Defaulted); EXPECT_TRUE(V.back().A3.State == EAS_Defaulted); } { SmallVector<Emplaceable, 3> V; V.emplace_back(A0, A1); EXPECT_TRUE(V.size() == 1); EXPECT_TRUE(V.back().State == ES_Emplaced); EXPECT_TRUE(V.back().A0.State == EAS_LValue); EXPECT_TRUE(V.back().A1.State == EAS_LValue); EXPECT_TRUE(V.back().A2.State == EAS_Defaulted); EXPECT_TRUE(V.back().A3.State == EAS_Defaulted); } { SmallVector<Emplaceable, 3> V; V.emplace_back(std::move(A0), std::move(A1)); EXPECT_TRUE(V.size() == 1); EXPECT_TRUE(V.back().State == ES_Emplaced); EXPECT_TRUE(V.back().A0.State == EAS_RValue); EXPECT_TRUE(V.back().A1.State == EAS_RValue); EXPECT_TRUE(V.back().A2.State == EAS_Defaulted); EXPECT_TRUE(V.back().A3.State == EAS_Defaulted); } { SmallVector<Emplaceable, 3> V; V.emplace_back(std::move(A0), A1, std::move(A2), A3); EXPECT_TRUE(V.size() == 1); EXPECT_TRUE(V.back().State == ES_Emplaced); EXPECT_TRUE(V.back().A0.State == EAS_RValue); EXPECT_TRUE(V.back().A1.State == EAS_LValue); EXPECT_TRUE(V.back().A2.State == EAS_RValue); EXPECT_TRUE(V.back().A3.State == EAS_LValue); } { SmallVector<int, 1> V; V.emplace_back(); V.emplace_back(42); EXPECT_EQ(2U, V.size()); EXPECT_EQ(0, V[0]); EXPECT_EQ(42, V[1]); } } TEST(SmallVectorTest, InitializerList) { SmallVector<int, 2> V1 = {}; EXPECT_TRUE(V1.empty()); V1 = {0, 0}; EXPECT_TRUE(makeArrayRef(V1).equals({0, 0})); V1 = {-1, -1}; EXPECT_TRUE(makeArrayRef(V1).equals({-1, -1})); SmallVector<int, 2> V2 = {1, 2, 3, 4}; EXPECT_TRUE(makeArrayRef(V2).equals({1, 2, 3, 4})); V2.assign({4}); EXPECT_TRUE(makeArrayRef(V2).equals({4})); V2.append({3, 2}); EXPECT_TRUE(makeArrayRef(V2).equals({4, 3, 2})); V2.insert(V2.begin() + 1, 5); EXPECT_TRUE(makeArrayRef(V2).equals({4, 5, 3, 2})); } } // end namespace
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/ADT/OptionalTest.cpp
//===- llvm/unittest/ADT/OptionalTest.cpp - Optional unit tests -----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "gtest/gtest.h" #include "llvm/ADT/Optional.h" using namespace llvm; namespace { struct NonDefaultConstructible { static unsigned CopyConstructions; static unsigned Destructions; static unsigned CopyAssignments; explicit NonDefaultConstructible(int) { } NonDefaultConstructible(const NonDefaultConstructible&) { ++CopyConstructions; } NonDefaultConstructible &operator=(const NonDefaultConstructible&) { ++CopyAssignments; return *this; } ~NonDefaultConstructible() { ++Destructions; } static void ResetCounts() { CopyConstructions = 0; Destructions = 0; CopyAssignments = 0; } }; unsigned NonDefaultConstructible::CopyConstructions = 0; unsigned NonDefaultConstructible::Destructions = 0; unsigned NonDefaultConstructible::CopyAssignments = 0; // Test fixture class OptionalTest : public testing::Test { }; TEST_F(OptionalTest, NonDefaultConstructibleTest) { Optional<NonDefaultConstructible> O; EXPECT_FALSE(O); } TEST_F(OptionalTest, ResetTest) { NonDefaultConstructible::ResetCounts(); Optional<NonDefaultConstructible> O(NonDefaultConstructible(3)); EXPECT_EQ(1u, NonDefaultConstructible::CopyConstructions); EXPECT_EQ(0u, NonDefaultConstructible::CopyAssignments); EXPECT_EQ(1u, NonDefaultConstructible::Destructions); NonDefaultConstructible::ResetCounts(); O.reset(); EXPECT_EQ(0u, NonDefaultConstructible::CopyConstructions); EXPECT_EQ(0u, NonDefaultConstructible::CopyAssignments); EXPECT_EQ(1u, NonDefaultConstructible::Destructions); } TEST_F(OptionalTest, InitializationLeakTest) { NonDefaultConstructible::ResetCounts(); Optional<NonDefaultConstructible>(NonDefaultConstructible(3)); EXPECT_EQ(1u, NonDefaultConstructible::CopyConstructions); EXPECT_EQ(0u, NonDefaultConstructible::CopyAssignments); EXPECT_EQ(2u, NonDefaultConstructible::Destructions); } TEST_F(OptionalTest, CopyConstructionTest) { NonDefaultConstructible::ResetCounts(); { Optional<NonDefaultConstructible> A(NonDefaultConstructible(3)); EXPECT_EQ(1u, NonDefaultConstructible::CopyConstructions); EXPECT_EQ(0u, NonDefaultConstructible::CopyAssignments); EXPECT_EQ(1u, NonDefaultConstructible::Destructions); NonDefaultConstructible::ResetCounts(); Optional<NonDefaultConstructible> B(A); EXPECT_EQ(1u, NonDefaultConstructible::CopyConstructions); EXPECT_EQ(0u, NonDefaultConstructible::CopyAssignments); EXPECT_EQ(0u, NonDefaultConstructible::Destructions); NonDefaultConstructible::ResetCounts(); } EXPECT_EQ(0u, NonDefaultConstructible::CopyConstructions); EXPECT_EQ(0u, NonDefaultConstructible::CopyAssignments); EXPECT_EQ(2u, NonDefaultConstructible::Destructions); } TEST_F(OptionalTest, ConstructingCopyAssignmentTest) { NonDefaultConstructible::ResetCounts(); { Optional<NonDefaultConstructible> A(NonDefaultConstructible(3)); Optional<NonDefaultConstructible> B; EXPECT_EQ(1u, NonDefaultConstructible::CopyConstructions); EXPECT_EQ(0u, NonDefaultConstructible::CopyAssignments); EXPECT_EQ(1u, NonDefaultConstructible::Destructions); NonDefaultConstructible::ResetCounts(); B = A; EXPECT_EQ(1u, NonDefaultConstructible::CopyConstructions); EXPECT_EQ(0u, NonDefaultConstructible::CopyAssignments); EXPECT_EQ(0u, NonDefaultConstructible::Destructions); NonDefaultConstructible::ResetCounts(); } EXPECT_EQ(0u, NonDefaultConstructible::CopyConstructions); EXPECT_EQ(0u, NonDefaultConstructible::CopyAssignments); EXPECT_EQ(2u, NonDefaultConstructible::Destructions); } TEST_F(OptionalTest, CopyingCopyAssignmentTest) { NonDefaultConstructible::ResetCounts(); { Optional<NonDefaultConstructible> A(NonDefaultConstructible(3)); Optional<NonDefaultConstructible> B(NonDefaultConstructible(4)); EXPECT_EQ(2u, NonDefaultConstructible::CopyConstructions); EXPECT_EQ(0u, NonDefaultConstructible::CopyAssignments); EXPECT_EQ(2u, NonDefaultConstructible::Destructions); NonDefaultConstructible::ResetCounts(); B = A; EXPECT_EQ(0u, NonDefaultConstructible::CopyConstructions); EXPECT_EQ(1u, NonDefaultConstructible::CopyAssignments); EXPECT_EQ(0u, NonDefaultConstructible::Destructions); NonDefaultConstructible::ResetCounts(); } EXPECT_EQ(0u, NonDefaultConstructible::CopyConstructions); EXPECT_EQ(0u, NonDefaultConstructible::CopyAssignments); EXPECT_EQ(2u, NonDefaultConstructible::Destructions); } TEST_F(OptionalTest, DeletingCopyAssignmentTest) { NonDefaultConstructible::ResetCounts(); { Optional<NonDefaultConstructible> A; Optional<NonDefaultConstructible> B(NonDefaultConstructible(3)); EXPECT_EQ(1u, NonDefaultConstructible::CopyConstructions); EXPECT_EQ(0u, NonDefaultConstructible::CopyAssignments); EXPECT_EQ(1u, NonDefaultConstructible::Destructions); NonDefaultConstructible::ResetCounts(); B = A; EXPECT_EQ(0u, NonDefaultConstructible::CopyConstructions); EXPECT_EQ(0u, NonDefaultConstructible::CopyAssignments); EXPECT_EQ(1u, NonDefaultConstructible::Destructions); NonDefaultConstructible::ResetCounts(); } EXPECT_EQ(0u, NonDefaultConstructible::CopyConstructions); EXPECT_EQ(0u, NonDefaultConstructible::CopyAssignments); EXPECT_EQ(0u, NonDefaultConstructible::Destructions); } TEST_F(OptionalTest, NullCopyConstructionTest) { NonDefaultConstructible::ResetCounts(); { Optional<NonDefaultConstructible> A; Optional<NonDefaultConstructible> B; EXPECT_EQ(0u, NonDefaultConstructible::CopyConstructions); EXPECT_EQ(0u, NonDefaultConstructible::CopyAssignments); EXPECT_EQ(0u, NonDefaultConstructible::Destructions); NonDefaultConstructible::ResetCounts(); B = A; EXPECT_EQ(0u, NonDefaultConstructible::CopyConstructions); EXPECT_EQ(0u, NonDefaultConstructible::CopyAssignments); EXPECT_EQ(0u, NonDefaultConstructible::Destructions); NonDefaultConstructible::ResetCounts(); } EXPECT_EQ(0u, NonDefaultConstructible::CopyConstructions); EXPECT_EQ(0u, NonDefaultConstructible::CopyAssignments); EXPECT_EQ(0u, NonDefaultConstructible::Destructions); } TEST_F(OptionalTest, GetValueOr) { Optional<int> A; EXPECT_EQ(42, A.getValueOr(42)); A = 5; EXPECT_EQ(5, A.getValueOr(42)); } struct MultiArgConstructor { int x, y; MultiArgConstructor(int x, int y) : x(x), y(y) {} explicit MultiArgConstructor(int x, bool positive) : x(x), y(positive ? x : -x) {} MultiArgConstructor(const MultiArgConstructor &) = delete; MultiArgConstructor(MultiArgConstructor &&) = delete; MultiArgConstructor &operator=(const MultiArgConstructor &) = delete; MultiArgConstructor &operator=(MultiArgConstructor &&) = delete; static unsigned Destructions; ~MultiArgConstructor() { ++Destructions; } static void ResetCounts() { Destructions = 0; } }; unsigned MultiArgConstructor::Destructions = 0; TEST_F(OptionalTest, Emplace) { MultiArgConstructor::ResetCounts(); Optional<MultiArgConstructor> A; A.emplace(1, 2); EXPECT_TRUE(A.hasValue()); EXPECT_EQ(1, A->x); EXPECT_EQ(2, A->y); EXPECT_EQ(0u, MultiArgConstructor::Destructions); A.emplace(5, false); EXPECT_TRUE(A.hasValue()); EXPECT_EQ(5, A->x); EXPECT_EQ(-5, A->y); EXPECT_EQ(1u, MultiArgConstructor::Destructions); } struct MoveOnly { static unsigned MoveConstructions; static unsigned Destructions; static unsigned MoveAssignments; int val; explicit MoveOnly(int val) : val(val) { } MoveOnly(MoveOnly&& other) { val = other.val; ++MoveConstructions; } MoveOnly &operator=(MoveOnly&& other) { val = other.val; ++MoveAssignments; return *this; } ~MoveOnly() { ++Destructions; } static void ResetCounts() { MoveConstructions = 0; Destructions = 0; MoveAssignments = 0; } }; unsigned MoveOnly::MoveConstructions = 0; unsigned MoveOnly::Destructions = 0; unsigned MoveOnly::MoveAssignments = 0; TEST_F(OptionalTest, MoveOnlyNull) { MoveOnly::ResetCounts(); Optional<MoveOnly> O; EXPECT_EQ(0u, MoveOnly::MoveConstructions); EXPECT_EQ(0u, MoveOnly::MoveAssignments); EXPECT_EQ(0u, MoveOnly::Destructions); } TEST_F(OptionalTest, MoveOnlyConstruction) { MoveOnly::ResetCounts(); Optional<MoveOnly> O(MoveOnly(3)); EXPECT_TRUE((bool)O); EXPECT_EQ(3, O->val); EXPECT_EQ(1u, MoveOnly::MoveConstructions); EXPECT_EQ(0u, MoveOnly::MoveAssignments); EXPECT_EQ(1u, MoveOnly::Destructions); } TEST_F(OptionalTest, MoveOnlyMoveConstruction) { Optional<MoveOnly> A(MoveOnly(3)); MoveOnly::ResetCounts(); Optional<MoveOnly> B(std::move(A)); EXPECT_FALSE((bool)A); EXPECT_TRUE((bool)B); EXPECT_EQ(3, B->val); EXPECT_EQ(1u, MoveOnly::MoveConstructions); EXPECT_EQ(0u, MoveOnly::MoveAssignments); EXPECT_EQ(1u, MoveOnly::Destructions); } TEST_F(OptionalTest, MoveOnlyAssignment) { MoveOnly::ResetCounts(); Optional<MoveOnly> O; O = MoveOnly(3); EXPECT_TRUE((bool)O); EXPECT_EQ(3, O->val); EXPECT_EQ(1u, MoveOnly::MoveConstructions); EXPECT_EQ(0u, MoveOnly::MoveAssignments); EXPECT_EQ(1u, MoveOnly::Destructions); } TEST_F(OptionalTest, MoveOnlyInitializingAssignment) { Optional<MoveOnly> A(MoveOnly(3)); Optional<MoveOnly> B; MoveOnly::ResetCounts(); B = std::move(A); EXPECT_FALSE((bool)A); EXPECT_TRUE((bool)B); EXPECT_EQ(3, B->val); EXPECT_EQ(1u, MoveOnly::MoveConstructions); EXPECT_EQ(0u, MoveOnly::MoveAssignments); EXPECT_EQ(1u, MoveOnly::Destructions); } TEST_F(OptionalTest, MoveOnlyNullingAssignment) { Optional<MoveOnly> A; Optional<MoveOnly> B(MoveOnly(3)); MoveOnly::ResetCounts(); B = std::move(A); EXPECT_FALSE((bool)A); EXPECT_FALSE((bool)B); EXPECT_EQ(0u, MoveOnly::MoveConstructions); EXPECT_EQ(0u, MoveOnly::MoveAssignments); EXPECT_EQ(1u, MoveOnly::Destructions); } TEST_F(OptionalTest, MoveOnlyAssigningAssignment) { Optional<MoveOnly> A(MoveOnly(3)); Optional<MoveOnly> B(MoveOnly(4)); MoveOnly::ResetCounts(); B = std::move(A); EXPECT_FALSE((bool)A); EXPECT_TRUE((bool)B); EXPECT_EQ(3, B->val); EXPECT_EQ(0u, MoveOnly::MoveConstructions); EXPECT_EQ(1u, MoveOnly::MoveAssignments); EXPECT_EQ(1u, MoveOnly::Destructions); } struct Immovable { static unsigned Constructions; static unsigned Destructions; int val; explicit Immovable(int val) : val(val) { ++Constructions; } ~Immovable() { ++Destructions; } static void ResetCounts() { Constructions = 0; Destructions = 0; } private: // This should disable all move/copy operations. Immovable(Immovable&& other) = delete; }; unsigned Immovable::Constructions = 0; unsigned Immovable::Destructions = 0; TEST_F(OptionalTest, ImmovableEmplace) { Optional<Immovable> A; Immovable::ResetCounts(); A.emplace(4); EXPECT_TRUE((bool)A); EXPECT_EQ(4, A->val); EXPECT_EQ(1u, Immovable::Constructions); EXPECT_EQ(0u, Immovable::Destructions); } #if LLVM_HAS_RVALUE_REFERENCE_THIS TEST_F(OptionalTest, MoveGetValueOr) { Optional<MoveOnly> A; MoveOnly::ResetCounts(); EXPECT_EQ(42, std::move(A).getValueOr(MoveOnly(42)).val); EXPECT_EQ(1u, MoveOnly::MoveConstructions); EXPECT_EQ(0u, MoveOnly::MoveAssignments); EXPECT_EQ(2u, MoveOnly::Destructions); A = MoveOnly(5); MoveOnly::ResetCounts(); EXPECT_EQ(5, std::move(A).getValueOr(MoveOnly(42)).val); EXPECT_EQ(1u, MoveOnly::MoveConstructions); EXPECT_EQ(0u, MoveOnly::MoveAssignments); EXPECT_EQ(2u, MoveOnly::Destructions); } #endif // LLVM_HAS_RVALUE_REFERENCE_THIS } // end anonymous namespace
0
repos/DirectXShaderCompiler
repos/DirectXShaderCompiler/test/lit.site.cfg.in
import sys ## Autogenerated by LLVM/Clang configuration. # Do not edit! config.host_triple = "@LLVM_HOST_TRIPLE@" config.target_triple = "@TARGET_TRIPLE@" config.llvm_src_root = "@LLVM_SOURCE_DIR@" config.llvm_obj_root = "@LLVM_BINARY_DIR@" config.llvm_tools_dir = "@LLVM_TOOLS_DIR@" config.llvm_lib_dir = "@LLVM_LIBRARY_DIR@" config.llvm_shlib_dir = "@SHLIBDIR@" config.llvm_shlib_ext = "@SHLIBEXT@" config.llvm_exe_ext = "@EXEEXT@" config.lit_tools_dir = "@LLVM_LIT_TOOLS_DIR@" config.python_executable = "@PYTHON_EXECUTABLE@" config.gold_executable = "@GOLD_EXECUTABLE@" config.ld64_executable = "@LD64_EXECUTABLE@" config.ocamlfind_executable = "@OCAMLFIND@" config.have_ocamlopt = "@HAVE_OCAMLOPT@" config.have_ocaml_ounit = "@HAVE_OCAML_OUNIT@" config.ocaml_flags = "@OCAMLFLAGS@" config.go_executable = "@GO_EXECUTABLE@" config.enable_shared = @ENABLE_SHARED@ config.enable_assertions = @ENABLE_ASSERTIONS@ config.targets_to_build = "@TARGETS_TO_BUILD@" config.llvm_bindings = "@LLVM_BINDINGS@".split(' ') config.host_os = "@HOST_OS@" config.host_arch = "@HOST_ARCH@" config.host_cc = "@HOST_CC@" config.host_cxx = "@HOST_CXX@" config.host_ldflags = "@HOST_LDFLAGS@" config.llvm_use_intel_jitevents = "@LLVM_USE_INTEL_JITEVENTS@" config.llvm_use_sanitizer = "@LLVM_USE_SANITIZER@" config.have_zlib = "@HAVE_LIBZ@" config.have_dia_sdk = @HAVE_DIA_SDK@ config.enable_ffi = "@LLVM_ENABLE_FFI@" # Support substitution of the tools_dir with user parameters. This is # used when we can't determine the tool dir at configuration time. try: config.llvm_tools_dir = config.llvm_tools_dir % lit_config.params config.llvm_shlib_dir = config.llvm_shlib_dir % lit_config.params except KeyError: e = sys.exc_info()[1] key, = e.args lit_config.fatal("unable to find %r parameter, use '--param=%s=VALUE'" % (key,key)) # Let the main config do the real work. lit_config.load_config(config, "@LLVM_SOURCE_DIR@/test/lit.cfg")
0
repos/DirectXShaderCompiler
repos/DirectXShaderCompiler/test/CMakeLists.txt
configure_lit_site_cfg( ${CMAKE_CURRENT_SOURCE_DIR}/lit.site.cfg.in ${CMAKE_CURRENT_BINARY_DIR}/lit.site.cfg ) configure_lit_site_cfg( ${CMAKE_CURRENT_SOURCE_DIR}/Unit/lit.site.cfg.in ${CMAKE_CURRENT_BINARY_DIR}/Unit/lit.site.cfg ) # Don't include check-llvm into check-all without LLVM_BUILD_TOOLS. if(NOT LLVM_BUILD_TOOLS) set(EXCLUDE_FROM_ALL ON) endif() # Set the depends list as a variable so that it can grow conditionally. # NOTE: Sync the substitutions in test/lit.cfg when adding to this list. set(LLVM_TEST_DEPENDS llvm-config UnitTests #BugpointPasses #LLVMHello #bugpoint #llc #lli #lli-child-target #llvm-ar llvm-as llvm-bcanalyzer #llvm-c-test #llvm-cov #llvm-cxxdump llvm-diff llvm-dis #llvm-dsymutil #llvm-dwarfdump llvm-extract #llvm-lib llvm-link #llvm-lto #llvm-mc #llvm-mcmarkup #llvm-nm #llvm-objdump #llvm-profdata #llvm-ranlib #llvm-readobj #llvm-rtdyld #llvm-size #llvm-symbolizer llvm-tblgen #macho-dump opt FileCheck count not yaml-bench #yaml2obj #obj2yaml verify-uselistorder ) # If Intel JIT events are supported, depend on a tool that tests the listener. if( LLVM_USE_INTEL_JITEVENTS ) set(LLVM_TEST_DEPENDS ${LLVM_TEST_DEPENDS} llvm-jitlistener) endif( LLVM_USE_INTEL_JITEVENTS ) if(TARGET LLVMgold) set(LLVM_TEST_DEPENDS ${LLVM_TEST_DEPENDS} LLVMgold) endif() if(TARGET llvm-go) set(LLVM_TEST_DEPENDS ${LLVM_TEST_DEPENDS} llvm-go) endif() if(APPLE) #set(LLVM_TEST_DEPENDS ${LLVM_TEST_DEPENDS} LTO) endif() if(TARGET ocaml_llvm) set(LLVM_TEST_DEPENDS ${LLVM_TEST_DEPENDS} ocaml_llvm ocaml_llvm_all_backends ocaml_llvm_analysis ocaml_llvm_bitreader ocaml_llvm_bitwriter ocaml_llvm_executionengine ocaml_llvm_irreader ocaml_llvm_linker ocaml_llvm_target ocaml_llvm_ipo ocaml_llvm_passmgr_builder ocaml_llvm_scalar_opts ocaml_llvm_transform_utils ocaml_llvm_vectorize ) endif() add_custom_target(llvm-test-depends DEPENDS ${LLVM_TEST_DEPENDS}) set_target_properties(llvm-test-depends PROPERTIES FOLDER "Tests") add_lit_testsuite(check-llvm "Running the LLVM regression tests" ${CMAKE_CURRENT_BINARY_DIR} PARAMS llvm_site_config=${CMAKE_CURRENT_BINARY_DIR}/lit.site.cfg llvm_unit_site_config=${CMAKE_CURRENT_BINARY_DIR}/Unit/lit.site.cfg DEPENDS llvm-test-depends ) set_target_properties(check-llvm PROPERTIES FOLDER "Tests") add_lit_testsuites(LLVM ${CMAKE_CURRENT_SOURCE_DIR} PARAMS llvm_site_config=${CMAKE_CURRENT_BINARY_DIR}/lit.site.cfg llvm_unit_site_config=${CMAKE_CURRENT_BINARY_DIR}/Unit/lit.site.cfg DEPENDS llvm-test-depends ) # HLSL Change Begin - When building IDE configurations, generate the unit test config if (CMAKE_CONFIGURATION_TYPES) add_lit_target(check-llvm-unit "Running lit suite llvm-unit" ${CMAKE_CURRENT_BINARY_DIR}/Unit PARAMS llvm_site_config=${CMAKE_CURRENT_BINARY_DIR}/lit.site.cfg llvm_unit_site_config=${CMAKE_CURRENT_BINARY_DIR}/Unit/lit.site.cfg DEPENDS UnitTests ) endif() # HLSL Change End - Add a separate target for clang unit tests # Setup a legacy alias for 'check-llvm'. This will likely change to be an # alias for 'check-all' at some point in the future. add_custom_target(check) add_dependencies(check check-llvm) set_target_properties(check PROPERTIES FOLDER "Tests")
0
repos/DirectXShaderCompiler
repos/DirectXShaderCompiler/test/TestRunner.sh
#!/bin/sh # Deprecated, use 'llvm-lit'. echo "warning: '$0' is deprecated, use 'llvm-lit' instead." exec llvm-lit "$@"
0
repos/DirectXShaderCompiler/test/MC
repos/DirectXShaderCompiler/test/MC/AsmParser/dot-symbol-assignment-backwards.s
# RUN: not llvm-mc -filetype=obj -triple i386-unknown-unknown %s 2> %t # RUN: FileCheck -input-file %t %s . = 0x10 .byte 1 . = . + 10 .byte 2 # CHECK: LLVM ERROR: invalid .org offset '24' (at offset '28') . = 0x18 .byte 3
0
repos/DirectXShaderCompiler/test/MC
repos/DirectXShaderCompiler/test/MC/AsmParser/directive_file.s
# RUN: llvm-mc -triple i386-unknown-unknown %s | FileCheck %s # RUN: llvm-mc -triple i386-unknown-unknown %s -filetype=null .file "hello" .file 1 "worl\144" # "\144" is "d" .file 2 "directory" "file" # CHECK: .file "hello" # CHECK: .file 1 "world" # CHECK: .file 2 "directory" "file"
0
repos/DirectXShaderCompiler/test/MC
repos/DirectXShaderCompiler/test/MC/AsmParser/directive_lcomm.s
# RUN: llvm-mc -triple i386-apple-darwin10 %s | FileCheck %s # RUN: llvm-mc -triple i386-pc-mingw32 %s | FileCheck %s # RUN: not llvm-mc -triple i386-linux-gnu %s 2>&1 | FileCheck %s -check-prefix=ERROR # CHECK: TEST0: # CHECK: .lcomm a,7,4 # CHECK: .lcomm b,8 # CHECK: .lcomm c,0 # ELF doesn't like alignment on .lcomm. # ERROR: alignment not supported on this target TEST0: .lcomm a, 8-1, 4 .lcomm b,8 .lcomm c, 0
0
repos/DirectXShaderCompiler/test/MC
repos/DirectXShaderCompiler/test/MC/AsmParser/macro-err1.s
// RUN: not llvm-mc -triple x86_64-unknown-unknown %s 2> %t // RUN: FileCheck < %t %s .macro foo bar .long \bar .endm foo 42, 42 // CHECK: too many positional arguments
0
repos/DirectXShaderCompiler/test/MC
repos/DirectXShaderCompiler/test/MC/AsmParser/directive_include.s
# RUN: llvm-mc -triple i386-unknown-unknown %s -I %p | FileCheck %s # CHECK: TESTA: # CHECK: TEST0: # CHECK: a = 0 # CHECK: TESTB: TESTA: .include "directive\137set.s" # "\137" is underscore "_" TESTB:
0
repos/DirectXShaderCompiler/test/MC
repos/DirectXShaderCompiler/test/MC/AsmParser/extern.s
# RUN: llvm-mc -triple i386-unknown-unknown %s | FileCheck %s # CHECK-NOT: foo .extern foo
0
repos/DirectXShaderCompiler/test/MC
repos/DirectXShaderCompiler/test/MC/AsmParser/ifc.s
# RUN: llvm-mc -triple i386-unknown-unknown %s | FileCheck %s # CHECK-NOT: .byte 0 # CHECK: .byte 1 .ifc foo, foo .byte 1 .else .byte 0 .endif # CHECK-NOT: .byte 0 # CHECK: .byte 1 .ifc "foo space", "foo space" .byte 1 .else .byte 0 .endif # CHECK-NOT: .byte 0 # CHECK: .byte 1 .ifc foo space, foo space .byte 1 .else .byte 0 .endif # CHECK-NOT: .byte 0 # CHECK: .byte 1 .ifc unequal, unEqual .byte 0 .else .byte 1 .endif # CHECK-NOT: .byte 0 # CHECK: .byte 1 .ifnc foo, foo .byte 0 .else .byte 1 .endif # CHECK-NOT: .byte 0 # CHECK: .byte 1 .ifnc "foo space", "foo space" .byte 0 .else .byte 1 .endif # CHECK-NOT: .byte 0 # CHECK: .byte 1 .ifnc foo space, foo space .byte 0 .else .byte 1 .endif # CHECK-NOT: .byte 0 # CHECK: .byte 1 .ifnc unequal, unEqual .byte 1 .else .byte 0 .endif # CHECK-NOT: .byte 0 # CHECK: .byte 1 .ifnc equal, equal ; .byte 0 ; .else ; .byte 1 ; .endif
0
repos/DirectXShaderCompiler/test/MC
repos/DirectXShaderCompiler/test/MC/AsmParser/cfi-unfinished-frame.s
// RUN: not llvm-mc -filetype=asm -triple x86_64-pc-linux-gnu %s -o %t 2>%t.out // RUN: FileCheck -input-file=%t.out %s .cfi_startproc // CHECK: Unfinished frame
0
repos/DirectXShaderCompiler/test/MC
repos/DirectXShaderCompiler/test/MC/AsmParser/line_with_hash.s
# RUN: llvm-mc -triple i386-unknown-unknown %s | FileCheck %s // We used to incorrectly parse a line with only a # in it .zero 42 # .ifndef FOO .zero 2 .else .endif .zero 24 // CHECK: .zero 42 // CHECK-NEXT: .zero 2 // CHECK-NEXT: .zero 24
0
repos/DirectXShaderCompiler/test/MC
repos/DirectXShaderCompiler/test/MC/AsmParser/directive_ascii.s
# RUN: llvm-mc -triple i386-unknown-unknown %s | FileCheck %s .data # CHECK: TEST0: TEST0: .ascii # CHECK: TEST1: TEST1: .asciz # CHECK: TEST2: # CHECK: .byte 65 TEST2: .ascii "A" # CHECK: TEST3: # CHECK: .byte 66 # CHECK: .byte 0 # CHECK: .byte 67 # CHECK: .byte 0 TEST3: .asciz "B", "C" # CHECK: TEST4: # CHECK: .asciz "\001\001\007\0008\001\0001\200" TEST4: .ascii "\1\01\07\08\001\0001\200\0" # CHECK: TEST5: # CHECK: .ascii "\b\f\n\r\t\\\"" TEST5: .ascii "\b\f\n\r\t\\\"" # CHECK: TEST6: # CHECK: .byte 66 # CHECK: .byte 0 # CHECK: .byte 67 # CHECK: .byte 0 TEST6: .string "B", "C"
0
repos/DirectXShaderCompiler/test/MC
repos/DirectXShaderCompiler/test/MC/AsmParser/directive-warning.s
// RUN: llvm-mc -triple i386 %s 2>&1 | FileCheck %s .warning // CHECK: warning: .warning directive invoked in source file // CHECK-NEXT: .warning // CHECK-NEXT: ^ .ifc a,a .warning .endif // CHECK: warning: .warning directive invoked in source file // CHECK-NEXT: .warning // CHECK-NEXT: ^ .ifnc a,a .warning .endif // CHECK-NOT: warning: .warning directive invoked in source file .warning "here be dragons" // CHECK: warning: here be dragons .ifc one, two .warning "dragons, i say" .endif // CHECK-NOT: warning: dragons, i say
0
repos/DirectXShaderCompiler/test/MC
repos/DirectXShaderCompiler/test/MC/AsmParser/directive_thread_init_func.s
# RUN: llvm-mc -triple x86_64-unknown-darwin %s | FileCheck %s # CHECK: __DATA,__thread_init,thread_local_init_function_pointers # CHECK: .quad 0 .thread_init_func .quad 0
0
repos/DirectXShaderCompiler/test/MC
repos/DirectXShaderCompiler/test/MC/AsmParser/directive_values.s
# RUN: llvm-mc -triple i386-unknown-unknown %s | FileCheck %s # CHECK: TEST0: # CHECK: .byte 0 TEST0: .byte 0 # CHECK: TEST1: # CHECK: .short 3 TEST1: .short 3 # CHECK: TEST2: # CHECK: .long 8 TEST2: .long 8 # CHECK: TEST3: # CHECK: .quad 9 TEST3: .quad 9 # rdar://7997827 TEST4: .quad 0b0100 .quad 4294967295 .quad 4294967295+1 .quad 4294967295LL+1 .quad 0b10LL + 07ULL + 0x42AULL # CHECK: TEST4 # CHECK: .quad 4 # CHECK: .quad 4294967295 # CHECK: .quad 4294967296 # CHECK: .quad 4294967296 # CHECK: .quad 1075 TEST5: .value 8 # CHECK: TEST5: # CHECK: .short 8 TEST6: .byte 'c' .byte '\'' .byte '\\' .byte '\#' .byte '\t' .byte '\n' # CHECK: TEST6 # CHECK: .byte 99 # CHECK: .byte 39 # CHECK: .byte 92 # CHECK: .byte 35 # CHECK: .byte 9 # CHECK: .byte 10 TEST7: .byte 1, 2, 3, 4 # CHECK: .byte 1 # CHECK-NEXT: .byte 2 # CHECK-NEXT: .byte 3 # CHECK-NEXT: .byte 4 TEST8: .long 0x200000UL+1 .long 0x200000L+1 # CHECK: .long 2097153 # CHECK: .long 2097153 TEST9: .octa 0x1234567812345678abcdef, 340282366920938463463374607431768211455 .octa 0b00111010010110100101101001011010010110100101101001011010010110100101101001011010010110100101101001011010010110100101101001011010 # CHECK: TEST9 # CHECK: .quad 8652035380128501231 # CHECK: .quad 1193046 # CHECK: .quad -1 # CHECK: .quad -1 # CHECK: .quad 6510615555426900570 # CHECK: .quad 4204772546213206618
0
repos/DirectXShaderCompiler/test/MC
repos/DirectXShaderCompiler/test/MC/AsmParser/directive_rept-diagnostics.s
# RUN: not llvm-mc -triple i686-elf -filetype asm -o /dev/null %s 2>&1 \ # RUN: | FileCheck %s .data .global invalid_expression .type invalid_expression,@object invalid_expression: .rept * # CHECK: error: unknown token in expression # CHECK: .rept * # CHECK: ^ .global bad_token .type bad_token,@object bad_token: .rept bad_token # CHECK: error: unexpected token in '.rept' directive # CHECK: .rept bad_token # CHECK: ^ .global negative .type negative,@object negative: .rept -32 # CHECK: error: Count is negative # CHECK: .rept -32 # CHECK: ^ .global trailer .type trailer,@object trailer: .rep 0 trailer # CHECK: error: unexpected token in '.rep' directive # CHECK: .rep 0 trailer # CHECK: ^
0
repos/DirectXShaderCompiler/test/MC
repos/DirectXShaderCompiler/test/MC/AsmParser/assignment.s
# RUN: llvm-mc -triple i386-unknown-unknown %s | FileCheck %s # CHECK: TEST0: # CHECK: a = 0 TEST0: a = 0 # CHECK: .globl _f1 # CHECK: _f1 = 0 .globl _f1 _f1 = 0
0
repos/DirectXShaderCompiler/test/MC
repos/DirectXShaderCompiler/test/MC/AsmParser/directive_tbss.s
# RUN: llvm-mc -triple x86_64-unknown-darwin %s | FileCheck %s # CHECK: .tbss _a$tlv$init, 4 # CHECK: .tbss _b$tlv$init, 4, 3 .tbss _a$tlv$init, 4 .tbss _b$tlv$init, 4, 3
0
repos/DirectXShaderCompiler/test/MC
repos/DirectXShaderCompiler/test/MC/AsmParser/variables.s
// RUN: llvm-mc -triple i386-unknown-unknown %s .data t0_v0 = 1 t0_v1 = t0_v0 .if t0_v1 != 1 .abort "invalid value" .endif t1_v0 = 1 t1_v1 = t0_v0 t1_v0 = 2 .if t0_v1 != 1 .abort "invalid value" .endif
0
repos/DirectXShaderCompiler/test/MC
repos/DirectXShaderCompiler/test/MC/AsmParser/macro-exitm.s
// RUN: llvm-mc -triple i386-unknown-unknown %s | FileCheck %s // .exitm is encountered in a normal macro expansion .macro REP .rept 3 .long 0 .exitm .endr .endm REP // Only the output from the first rept expansion should make it through: // CHECK: .long 0 // CHECK-NOT: .long 0 // .exitm is in a true branch .macro A .if 1 .long 1 .exitm .endif .long 1 .endm A // CHECK: .long 1 // CHECK-NOT: .long 1 // .exitm is in a false branch .macro B .if 1 .long 2 .else .exitm .endif .long 2 .endm B // CHECK: .long 2 // CHECK: .long 2 // .exitm is in a false branch that is encountered prior to the true branch .macro C .if 0 .exitm .else .long 3 .endif .long 3 .endm C // CHECK: .long 3 // CHECK: .long 3 // .exitm is in a macro that's expanded in a conditional block. .macro D .long 4 .exitm .long 4 .endm .if 1 D .endif // CHECK: .long 4 // CHECK-NOT: .long 4
0
repos/DirectXShaderCompiler/test/MC
repos/DirectXShaderCompiler/test/MC/AsmParser/directive_symbol_attrs.s
# RUN: llvm-mc -triple i386-unknown-unknown %s | FileCheck %s # CHECK: TEST0: # CHECK: .globl a # CHECK: .globl b TEST0: .globl a, b
0
repos/DirectXShaderCompiler/test/MC
repos/DirectXShaderCompiler/test/MC/AsmParser/macros-gas.s
// RUN: not llvm-mc -triple i386-linux-gnu %s 2> %t.err | FileCheck %s // RUN: FileCheck --check-prefix=CHECK-ERRORS %s < %t.err .macro .test0 .macrobody0 .endm .macro .test1 .test0 .endm .test1 // CHECK-ERRORS: <instantiation>:1:1: error: unknown directive // CHECK-ERRORS-NEXT: macrobody0 // CHECK-ERRORS-NEXT: ^ // CHECK-ERRORS: <instantiation>:1:1: note: while in macro instantiation // CHECK-ERRORS-NEXT: .test0 // CHECK-ERRORS-NEXT: ^ // CHECK-ERRORS: 11:1: note: while in macro instantiation // CHECK-ERRORS-NEXT: .test1 // CHECK-ERRORS-NEXT: ^ .macro test2 _a .byte \_a .endm // CHECK: .byte 10 test2 10 .macro test3 _a _b _c .ascii "\_a \_b \_c \\_c" .endm // CHECK: .ascii "1 2 3 \003" test3 1, 2, 3 // CHECK: .ascii "1 2 3 \003" test3 1, 2 3 .macro test3_prime _a _b _c .ascii "\_a \_b \_c" .endm // CHECK: .ascii "1 (23) " test3_prime 1, (2 3) // CHECK: .ascii "1 (23) " test3_prime 1 (2 3) // CHECK: .ascii "1 2 " test3_prime 1 2 .macro test5 _a .globl \_a .endm // CHECK: .globl zed1 test5 zed1 .macro test6 $a .globl \$a .endm // CHECK: .globl zed2 test6 zed2 .macro test7 .a .globl \.a .endm // CHECK: .globl zed3 test7 zed3 .macro test8 _a, _b, _c .ascii "\_a,\_b,\_c" .endm .macro test9 _a _b _c .ascii "\_a \_b \_c" .endm // CHECK: .ascii "a,b,c" test8 a, b, c // CHECK: .ascii "%1,%2,%3" test8 %1 %2 %3 #a comment // CHECK: .ascii "x-y,z,1" test8 x - y z 1 // CHECK: .ascii "1 2 3" test9 1, 2,3 // CHECK: .ascii "1,2,3" test8 1,2 3 // CHECK: .ascii "1,2,3" test8 1 2, 3 .macro test10 .ascii "$20" .endm test10 // CHECK: .ascii "$20" test10 42 // CHECK-ERRORS: 102:10: error: Wrong number of arguments // CHECK-ERRORS-NEXT: test10 42 // CHECK-ERRORS-NEXT: ^