| 1 | //===----------------------------------------------------------------------===// |
| 2 | // |
| 3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 | // See https://llvm.org/LICENSE.txt for license information. |
| 5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 6 | // |
| 7 | //===----------------------------------------------------------------------===// |
| 8 | |
| 9 | // void* operator new(std::size_t, std::align_val_t); |
| 10 | |
| 11 | // Test that we can replace the operator by defining our own. |
| 12 | |
| 13 | // UNSUPPORTED: c++03, c++11, c++14 |
| 14 | // UNSUPPORTED: sanitizer-new-delete |
| 15 | |
| 16 | // Libc++ when built for z/OS doesn't contain the aligned allocation functions, |
| 17 | // nor does the dynamic library shipped with z/OS. |
| 18 | // XFAIL: target={{.+}}-zos{{.*}} |
| 19 | |
| 20 | #include <new> |
| 21 | #include <cstddef> |
| 22 | #include <cstdlib> |
| 23 | #include <cstdint> |
| 24 | #include <cassert> |
| 25 | #include <limits> |
| 26 | |
| 27 | #include "test_macros.h" |
| 28 | #include "../types.h" |
| 29 | |
| 30 | int new_called = 0; |
| 31 | int delete_called = 0; |
| 32 | |
| 33 | alignas(OverAligned) char DummyData[alignof(OverAligned)]; |
| 34 | |
| 35 | void* operator new(std::size_t s, std::align_val_t a) { |
| 36 | assert(s <= sizeof(DummyData)); |
| 37 | assert(static_cast<std::size_t>(a) == alignof(OverAligned)); |
| 38 | ++new_called; |
| 39 | return DummyData; |
| 40 | } |
| 41 | |
| 42 | void operator delete(void*, std::align_val_t) noexcept { |
| 43 | ++delete_called; |
| 44 | // nothing to delete, we didn't actually allocate in `operator new` |
| 45 | } |
| 46 | |
| 47 | int main(int, char**) { |
| 48 | // Test with an overaligned type |
| 49 | { |
| 50 | new_called = delete_called = 0; |
| 51 | OverAligned* dummy_data_block = new OverAligned; |
| 52 | OverAligned* x = DoNotOptimize(dummy_data_block); |
| 53 | assert(static_cast<void*>(x) == DummyData); |
| 54 | assert(new_called == 1); |
| 55 | |
| 56 | delete dummy_data_block; |
| 57 | assert(delete_called == 1); |
| 58 | } |
| 59 | |
| 60 | // Test with a type that is right on the verge of being overaligned |
| 61 | { |
| 62 | new_called = delete_called = 0; |
| 63 | MaxAligned* x = new MaxAligned; |
| 64 | assert(x != nullptr); |
| 65 | assert(new_called == 0); |
| 66 | |
| 67 | delete x; |
| 68 | assert(delete_called == 0); |
| 69 | } |
| 70 | |
| 71 | // Test with a type that is clearly not overaligned |
| 72 | { |
| 73 | new_called = delete_called = 0; |
| 74 | int* x = new int; |
| 75 | assert(x != nullptr); |
| 76 | assert(new_called == 0); |
| 77 | |
| 78 | delete x; |
| 79 | assert(delete_called == 0); |
| 80 | } |
| 81 | |
| 82 | return 0; |
| 83 | } |
| 84 | |