aboutsummaryrefslogtreecommitdiff
path: root/backend/unittests/CodeGen/TargetFunctionStateTest.cpp
blob: 2286400a577a9155ef167c7cc00d5dfc442de77f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
// SPDX-License-Identifier: GPL-3.0-or-later

#include "rcc/CodeGen/TargetFunctionState.h"

#include "Target/TestTarget.h"
#include "rcc/CodeGen/InstructionDescriptor.h"
#include "rcc/CodeGen/MachineFunction.h"
#include "rcc/CodeGen/MachineFunctionCloner.h"
#include "rcc/CodeGen/MachineVerifier.h"

#include <cstddef>
#include <cstdint>
#include <iostream>
#include <span>
#include <string>
#include <string_view>
#include <utility>
#include <vector>

namespace {

class TestContext final {
public:
  void expect(bool Condition, std::string_view Message) {
    if (Condition)
      return;
    std::cerr << Message << '\n';
    ++FailureCount;
  }

  [[nodiscard]] int result() const noexcept {
    return FailureCount == 0 ? 0 : 1;
  }

private:
  int FailureCount = 0;
};

struct TestFunctionInfo final {
  std::uint64_t StackProbeSize = 0;
  bool UsesShadowCallStack = false;
  std::string CallingConvention;

  [[nodiscard]] static constexpr rcc::TargetFunctionStateTypeID stableTypeID() noexcept {
    return rcc::TargetFunctionStateTypeID::fromValue(0x5243435446530001ULL);
  }

  [[nodiscard]] static constexpr std::uint32_t schemaVersion() noexcept {
    return 3;
  }

  [[nodiscard]] rcc::Expected<void> verify() const {
    if (StackProbeSize == 0 || CallingConvention.empty()) {
      return rcc::makeUnexpected(rcc::ErrorCode::VerificationError,
                                 "test function info is incomplete");
    }
    return {};
  }

  [[nodiscard]] rcc::Expected<TestFunctionInfo>
  clone(const rcc::MachineFunctionCloneContext &) const {
    return TestFunctionInfo{StackProbeSize, UsesShadowCallStack, CallingConvention};
  }

  [[nodiscard]] std::string print() const {
    return CallingConvention + ":" + std::to_string(StackProbeSize) + ":" +
           (UsesShadowCallStack ? "shadow" : "plain");
  }

  [[nodiscard]] rcc::Expected<std::vector<std::byte>> encode() const {
    std::vector<std::byte> Payload;
    Payload.reserve(9 + CallingConvention.size());
    for (std::size_t Index = 0; Index < 8; ++Index) {
      Payload.push_back(static_cast<std::byte>((StackProbeSize >> (Index * 8U)) & 0xffU));
    }
    Payload.push_back(static_cast<std::byte>(UsesShadowCallStack ? 1 : 0));
    for (const char RawCharacter : CallingConvention) {
      Payload.push_back(static_cast<std::byte>(static_cast<unsigned char>(RawCharacter)));
    }
    return Payload;
  }

  [[nodiscard]] static rcc::Expected<TestFunctionInfo> decode(std::uint32_t Version,
                                                              std::span<const std::byte> Payload) {
    if (Version != schemaVersion()) {
      return rcc::makeUnexpected(rcc::ErrorCode::ParseError,
                                 "unsupported test function info version");
    }
    if (Payload.size() <= 9 || std::to_integer<unsigned int>(Payload[8]) > 1) {
      return rcc::makeUnexpected(rcc::ErrorCode::ParseError,
                                 "test function info payload is invalid");
    }

    std::uint64_t StackProbeSize = 0;
    for (std::size_t Index = 0; Index < 8; ++Index) {
      StackProbeSize |= std::to_integer<std::uint64_t>(Payload[Index]) << (Index * 8U);
    }
    std::string CallingConvention;
    CallingConvention.reserve(Payload.size() - 9);
    for (const std::byte Character : Payload.subspan(9)) {
      CallingConvention.push_back(static_cast<char>(std::to_integer<unsigned char>(Character)));
    }
    return TestFunctionInfo{StackProbeSize, std::to_integer<unsigned int>(Payload[8]) != 0,
                            std::move(CallingConvention)};
  }

  friend bool operator==(const TestFunctionInfo &Left, const TestFunctionInfo &Right) = default;
};

struct CollidingFunctionInfo final {
  TestFunctionInfo Value;

  [[nodiscard]] static constexpr rcc::TargetFunctionStateTypeID stableTypeID() noexcept {
    return TestFunctionInfo::stableTypeID();
  }

  [[nodiscard]] static constexpr std::uint32_t schemaVersion() noexcept {
    return TestFunctionInfo::schemaVersion();
  }

  [[nodiscard]] rcc::Expected<void> verify() const {
    return Value.verify();
  }

  [[nodiscard]] rcc::Expected<CollidingFunctionInfo>
  clone(const rcc::MachineFunctionCloneContext &) const {
    return CollidingFunctionInfo{Value};
  }

  [[nodiscard]] std::string print() const {
    return Value.print();
  }

  [[nodiscard]] rcc::Expected<std::vector<std::byte>> encode() const {
    return Value.encode();
  }

  [[nodiscard]] static rcc::Expected<CollidingFunctionInfo>
  decode(std::uint32_t Version, std::span<const std::byte> Payload) {
    auto Decoded = TestFunctionInfo::decode(Version, Payload);
    if (!Decoded)
      return std::unexpected(Decoded.error());
    return CollidingFunctionInfo{std::move(*Decoded)};
  }

  friend bool operator==(const CollidingFunctionInfo &Left,
                         const CollidingFunctionInfo &Right) = default;
};

[[nodiscard]] rcc::Expected<rcc::TargetDescription> createTarget() {
  rcc::InstructionDescriptor Descriptor;
  Descriptor.InstructionOpcode = rcc::Opcode::fromValue(1);
  Descriptor.Name = "TEST_NOP";
  Descriptor.Flags = {rcc::InstructionFlag::ProducesCode};
  std::vector<rcc::InstructionDescriptor> Descriptors;
  Descriptors.push_back(std::move(Descriptor));
  auto Instructions = rcc::InstructionSet::create(std::move(Descriptors));
  if (!Instructions)
    return std::unexpected(Instructions.error());
  return rcc::test::createTestTargetDescription(std::move(*Instructions));
}

void testTargetFunctionStateContract(TestContext &Context) {
  auto State = rcc::TargetFunctionState::create(TestFunctionInfo{4096, true, "lp64d"});
  Context.expect(State.has_value(), "valid target function state must be type-erased");
  if (!State)
    return;

  Context.expect(State->typeID() == TestFunctionInfo::stableTypeID() &&
                     State->schemaVersion() == TestFunctionInfo::schemaVersion() &&
                     State->getIf<TestFunctionInfo>() != nullptr &&
                     State->getIf<CollidingFunctionInfo>() == nullptr,
                 "strong query must require stable and local type identity");
  auto Printed = State->print();
  Context.expect(State->verify().has_value() && Printed && *Printed == "lp64d:4096:shadow",
                 "type-erased target state must preserve its semantic hooks");

  auto Encoded = State->encode();
  if (!Encoded)
    return;
  auto Decoded = rcc::TargetFunctionState::decode<TestFunctionInfo>(*Encoded);
  Context.expect(Decoded && State->equals(*Decoded) &&
                     State->getIf<TestFunctionInfo>() != Decoded->getIf<TestFunctionInfo>(),
                 "versioned target function state must round-trip losslessly");

  auto Collision = rcc::TargetFunctionState::create(
      CollidingFunctionInfo{TestFunctionInfo{4096, true, "lp64d"}});
  Context.expect(Collision && !State->equals(*Collision),
                 "colliding stable TypeIDs must not defeat local type safety");
}

void testTargetFunctionStateFailures(TestContext &Context) {
  rcc::TargetFunctionState Empty;
  Context.expect(!Empty.verify() && !Empty.print() && !Empty.encode(),
                 "empty target function state must reject semantic operations");
  Context.expect(!rcc::TargetFunctionState::create(TestFunctionInfo{0, false, ""}),
                 "target function state creation must verify its concrete value");

  auto State = rcc::TargetFunctionState::create(TestFunctionInfo{2048, false, "lp64"});
  if (!State)
    return;
  auto Encoded = State->encode();
  if (!Encoded)
    return;

  Encoded->Version = 0;
  Context.expect(!rcc::TargetFunctionState::decode<TestFunctionInfo>(*Encoded),
                 "target function state decode must reject version zero");
  Encoded->Version = 99;
  Context.expect(!rcc::TargetFunctionState::decode<TestFunctionInfo>(*Encoded),
                 "target function state decode must reject unsupported versions");
  Encoded->Version = TestFunctionInfo::schemaVersion();
  Encoded->TypeID = rcc::TargetFunctionStateTypeID::fromValue(1);
  Context.expect(!rcc::TargetFunctionState::decode<TestFunctionInfo>(*Encoded),
                 "target function state decode must reject a mismatched TypeID");
}

void testMachineFunctionOwnershipAndVerification(TestContext &Context) {
  auto Target = createTarget();
  auto Function =
      rcc::MachineFunction::create("target_state", rcc::MachineFunctionStableID::fromValue(1));
  if (!Target || !Function)
    return;

  Context.expect(!(*Function)->setTargetState(rcc::TargetFunctionState{}),
                 "machine function must reject an empty target state");
  auto State = rcc::TargetFunctionState::create(TestFunctionInfo{4096, false, "lp64d"});
  Context.expect(State && (*Function)->setTargetState(std::move(*State)).has_value(),
                 "machine function must accept one verified target state");
  Context.expect((*Function)->getTargetInfo<TestFunctionInfo>() != nullptr &&
                     (*Function)->getTargetInfo<CollidingFunctionInfo>() == nullptr &&
                     rcc::MachineVerifier::verify(**Function, *Target).has_value(),
                 "machine function must expose and verify its strong target state");

  auto Replacement = rcc::TargetFunctionState::create(TestFunctionInfo{8192, true, "lp64d"});
  Context.expect(Replacement && !(*Function)->setTargetState(std::move(*Replacement)),
                 "machine function must not accept a second current target state");

  TestFunctionInfo *Info = (*Function)->getTargetInfo<TestFunctionInfo>();
  if (Info == nullptr)
    return;
  Info->CallingConvention.clear();
  Context.expect(!rcc::MachineVerifier::verify(**Function, *Target),
                 "machine verifier must reject invalid concrete target state");
}

} // namespace

int main() {
  TestContext Context;
  testTargetFunctionStateContract(Context);
  testTargetFunctionStateFailures(Context);
  testMachineFunctionOwnershipAndVerification(Context);
  return Context.result();
}