aboutsummaryrefslogtreecommitdiff
path: root/backend/lib/CodeGen/TargetCallLowering.cpp
blob: d6a14b78452da49a8f551919846a21889ab2bc85 (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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
// SPDX-License-Identifier: GPL-3.0-or-later

#include "rcc/CodeGen/TargetCallLowering.h"

#include "rcc/CodeGen/MachineIRBuilder.h"

#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <limits>
#include <string>
#include <unordered_set>
#include <utility>
#include <vector>

namespace rcc {
namespace {

[[nodiscard]] bool isKnownExtension(ABIExtensionKind Extension) noexcept {
  return Extension < ABIExtensionKind::Count;
}

[[nodiscard]] bool isKnownLocationKind(CCLocationKind Kind) noexcept {
  return Kind <= CCLocationKind::Custom;
}

[[nodiscard]] bool isKnownTailCallKind(TailCallKind Kind) noexcept {
  return Kind <= TailCallKind::MustTail;
}

[[nodiscard]] bool addOverflows(std::uint64_t Left, std::uint64_t Right) noexcept {
  return Left > std::numeric_limits<std::uint64_t>::max() - Right;
}

[[nodiscard]] Expected<void> verifyAssignment(const CCAssignment &Assignment,
                                              bool AllowNoRegister) {
  if (Assignment.OriginalValue.isNoRegister() && !AllowNoRegister) {
    return makeUnexpected(ErrorCode::InvalidArgument,
                          "call-lowering assignment requires a machine register value");
  }
  if (!Assignment.ValueType.isValid() || !Assignment.LocationType.isValid() ||
      !Assignment.ValueType.isScalarValue() || !Assignment.LocationType.isScalarValue()) {
    return makeUnexpected(ErrorCode::InvalidArgument,
                          "call-lowering assignments require scalar value and location LLTs");
  }
  if (Assignment.FragmentCount == 0 || Assignment.FragmentIndex >= Assignment.FragmentCount) {
    return makeUnexpected(ErrorCode::InvalidArgument,
                          "call-lowering assignment has invalid fragment coordinates");
  }
  if (Assignment.LocationSizeBytes == 0 || Assignment.StackSlotSizeBytes == 0 ||
      Assignment.LocationSizeBytes > Assignment.StackSlotSizeBytes ||
      !isKnownExtension(Assignment.Extension) || !isKnownLocationKind(Assignment.LocationKind)) {
    return makeUnexpected(ErrorCode::InvalidArgument,
                          "call-lowering assignment has invalid size or extension metadata");
  }

  const bool HasRegister = Assignment.LocationRegister.has_value();
  const bool HasStack = Assignment.StackOffsetBytes.has_value();
  if (HasRegister && !Assignment.LocationRegister->isValid()) {
    return makeUnexpected(ErrorCode::InvalidArgument,
                          "call-lowering assignment names an invalid physical register");
  }
  if (HasStack && *Assignment.StackOffsetBytes % Assignment.LocationAlignment.bytes() != 0) {
    return makeUnexpected(ErrorCode::InvalidArgument,
                          "stack assignment offset violates its location alignment");
  }
  switch (Assignment.LocationKind) {
  case CCLocationKind::Register:
    if (!HasRegister || HasStack) {
      return makeUnexpected(ErrorCode::InvalidArgument,
                            "register assignment must name exactly one physical register");
    }
    break;
  case CCLocationKind::Stack:
    if (HasRegister || !HasStack) {
      return makeUnexpected(ErrorCode::InvalidArgument,
                            "stack assignment must name exactly one stack offset");
    }
    break;
  case CCLocationKind::Indirect:
    if (HasRegister == HasStack || !Assignment.CustomFlags.has(CCAssignmentFlag::Indirect)) {
      return makeUnexpected(ErrorCode::InvalidArgument,
                            "indirect assignment must have one transport location and its flag");
    }
    break;
  case CCLocationKind::Custom:
    if (HasRegister && HasStack) {
      return makeUnexpected(ErrorCode::InvalidArgument,
                            "custom assignment cannot use register and stack simultaneously");
    }
    break;
  }
  return {};
}

[[nodiscard]] Expected<void> verifyAssignments(std::span<const CCAssignment> Assignments,
                                               bool AllowNoRegister,
                                               const StackArgumentArea &StackArea) {
  std::unordered_set<PhysicalRegister> Registers;
  std::vector<std::pair<std::uint64_t, std::uint64_t>> StackRanges;
  StackRanges.reserve(Assignments.size());
  for (const CCAssignment &Assignment : Assignments) {
    auto Verification = verifyAssignment(Assignment, AllowNoRegister);
    if (!Verification)
      return std::unexpected(Verification.error());
    if (Assignment.LocationRegister && !Registers.insert(*Assignment.LocationRegister).second) {
      return makeUnexpected(ErrorCode::InvalidArgument,
                            "call-lowering assignments reuse a physical location register");
    }
    if (!Assignment.StackOffsetBytes)
      continue;
    if (addOverflows(*Assignment.StackOffsetBytes, Assignment.StackSlotSizeBytes)) {
      return makeUnexpected(ErrorCode::InvalidArgument,
                            "call-lowering stack assignment range overflows uint64");
    }
    const std::uint64_t End = *Assignment.StackOffsetBytes + Assignment.StackSlotSizeBytes;
    if (End > StackArea.SizeBytes) {
      return makeUnexpected(ErrorCode::InvalidArgument,
                            "call-lowering stack assignment exceeds its argument area");
    }
    StackRanges.emplace_back(*Assignment.StackOffsetBytes, End);
  }

  std::ranges::sort(StackRanges);
  for (std::size_t Index = 1; Index < StackRanges.size(); ++Index) {
    if (StackRanges[Index].first < StackRanges[Index - 1].second) {
      return makeUnexpected(ErrorCode::InvalidArgument, "call-lowering stack assignments overlap");
    }
  }
  return {};
}

[[nodiscard]] Expected<void> verifyVarArgs(const VarArgLoweringState &State) {
  if (!State.IsVariadic) {
    if (State.FixedArgumentCount != 0 || State.FirstUnallocatedIntegerRegister != 0 ||
        State.OverflowAreaOffsetBytes != 0 || State.RegisterSaveAreaOffsetBytes != 0 ||
        State.RegisterSaveAreaSizeBytes != 0 || State.RegisterSavePaddingBytes != 0 ||
        !State.RegistersToSave.empty()) {
      return makeUnexpected(ErrorCode::InvalidArgument,
                            "non-variadic plan contains variadic lowering state");
    }
    return {};
  }

  if (State.RegisterSaveAreaSizeBytes == 0 && !State.RegistersToSave.empty()) {
    return makeUnexpected(ErrorCode::InvalidArgument,
                          "variadic register saves require a nonempty save area");
  }
  if (State.RegisterSaveAreaSizeBytes % 8 != 0 || State.RegisterSavePaddingBytes % 8 != 0) {
    return makeUnexpected(ErrorCode::InvalidArgument,
                          "variadic register-save size and padding must be XLEN aligned");
  }
  std::unordered_set<PhysicalRegister> SavedRegisters;
  std::unordered_set<std::uint64_t> SavedOffsets;
  for (const VarArgRegisterSave Save : State.RegistersToSave) {
    if (!Save.Reg.isValid() || !SavedRegisters.insert(Save.Reg).second ||
        Save.OffsetBytes % 8 != 0 || !SavedOffsets.insert(Save.OffsetBytes).second ||
        addOverflows(Save.OffsetBytes, std::uint64_t{8}) ||
        Save.OffsetBytes + 8 > State.RegisterSaveAreaSizeBytes) {
      return makeUnexpected(ErrorCode::InvalidArgument,
                            "variadic register-save entry is invalid or outside its area");
    }
  }
  return {};
}

} // namespace

ABIValueFlags::ABIValueFlags(std::initializer_list<ABIValueFlag> Flags) noexcept {
  for (const ABIValueFlag Flag : Flags)
    set(Flag);
}

CCAssignmentFlags::CCAssignmentFlags(std::initializer_list<CCAssignmentFlag> Flags) noexcept {
  for (const CCAssignmentFlag Flag : Flags)
    set(Flag);
}

Expected<MachineCallTarget> MachineCallTarget::globalSymbol(std::string Name,
                                                            std::uint32_t TargetFlags) {
  if (Name.empty())
    return makeUnexpected(ErrorCode::InvalidArgument, "global call target name cannot be empty");
  return MachineCallTarget(MachineCallTargetKind::GlobalSymbol, std::move(Name), TargetFlags);
}

Expected<MachineCallTarget> MachineCallTarget::externalSymbol(std::string Name,
                                                              std::uint32_t TargetFlags) {
  if (Name.empty())
    return makeUnexpected(ErrorCode::InvalidArgument, "external call target name cannot be empty");
  return MachineCallTarget(MachineCallTargetKind::ExternalSymbol, std::move(Name), TargetFlags);
}

Expected<MachineCallTarget> MachineCallTarget::indirect(Register Callee,
                                                        std::uint32_t TargetFlags) {
  if (Callee.isNoRegister()) {
    return makeUnexpected(ErrorCode::InvalidArgument,
                          "indirect call target requires a machine register");
  }
  return MachineCallTarget(MachineCallTargetKind::IndirectRegister, Callee, TargetFlags);
}

std::string_view MachineCallTarget::symbolName() const noexcept {
  const auto *Name = std::get_if<std::string>(&Value);
  return Name == nullptr ? std::string_view{} : std::string_view(*Name);
}

Register MachineCallTarget::indirectRegister() const noexcept {
  const auto *Reg = std::get_if<Register>(&Value);
  return Reg == nullptr ? Register{} : *Reg;
}

Expected<CallLoweringPlan> CallLoweringPlan::create(CallLoweringPlanDesc Description) {
  if (Description.Target.empty() || Description.Convention.value() == 0) {
    return makeUnexpected(ErrorCode::InvalidArgument,
                          "call-lowering plan requires target and calling-convention identities");
  }
  if (Description.Kind > CallLoweringPlanKind::Return ||
      !isKnownTailCallKind(Description.TailDecision)) {
    return makeUnexpected(ErrorCode::InvalidArgument, "call-lowering plan kind is invalid");
  }
  if (Description.StackArguments.ShadowSpaceBytes > Description.StackArguments.SizeBytes ||
      Description.StackArguments.SizeBytes % Description.StackArguments.Align.bytes() != 0) {
    return makeUnexpected(ErrorCode::InvalidArgument,
                          "call-lowering stack argument area is malformed");
  }
  if (Description.CallFrame.SizeBytes % Description.CallFrame.Align.bytes() != 0 ||
      Description.CallFrame.EmitSetup != Description.CallFrame.EmitDestroy) {
    return makeUnexpected(ErrorCode::InvalidArgument,
                          "call-lowering call-frame requirements are inconsistent");
  }

  auto ArgumentVerification =
      verifyAssignments(Description.ArgumentAssignments, false, Description.StackArguments);
  if (!ArgumentVerification)
    return std::unexpected(ArgumentVerification.error());
  const bool AllowNoReturnRegister = Description.Kind == CallLoweringPlanKind::Call &&
                                     Description.TailDecision != TailCallKind::NotTail;
  auto ReturnVerification = verifyAssignments(Description.ReturnAssignments, AllowNoReturnRegister,
                                              StackArgumentArea{0, 0, Alignment{}});
  if (!ReturnVerification)
    return std::unexpected(ReturnVerification.error());
  auto VarArgVerification = verifyVarArgs(Description.VarArgs);
  if (!VarArgVerification)
    return std::unexpected(VarArgVerification.error());

  switch (Description.Kind) {
  case CallLoweringPlanKind::FormalArguments:
    if (!Description.ReturnAssignments.empty() || Description.Callee || Description.PreservedMask ||
        Description.CallSiteID != 0 || Description.TailDecision != TailCallKind::NotTail ||
        Description.CallFrame.EmitSetup || Description.CallFrame.ReusesIncomingArea ||
        !Description.ByValCopies.empty() || !Description.TailRejectionReason.empty()) {
      return makeUnexpected(ErrorCode::InvalidArgument,
                            "formal-argument plan contains call or return state");
    }
    break;
  case CallLoweringPlanKind::Return:
    if (!Description.ArgumentAssignments.empty() || Description.Callee ||
        Description.PreservedMask || Description.CallSiteID != 0 ||
        Description.TailDecision != TailCallKind::NotTail || Description.CallFrame.EmitSetup ||
        Description.CallFrame.ReusesIncomingArea || !Description.ByValCopies.empty() ||
        Description.VarArgs.IsVariadic || !Description.TailRejectionReason.empty()) {
      return makeUnexpected(ErrorCode::InvalidArgument,
                            "return plan contains formal-argument or call state");
    }
    break;
  case CallLoweringPlanKind::Call:
    if (!Description.Callee || !Description.Callee->isValid() || !Description.PreservedMask ||
        Description.CallSiteID == 0) {
      return makeUnexpected(ErrorCode::InvalidArgument,
                            "call plan requires a callee, call-site ID, and preserved mask");
    }
    if (Description.TailDecision == TailCallKind::NotTail) {
      if (!Description.CallFrame.EmitSetup || Description.CallFrame.ReusesIncomingArea) {
        return makeUnexpected(ErrorCode::InvalidArgument,
                              "ordinary call plan requires a private call frame");
      }
    } else if (Description.CallFrame.EmitSetup || !Description.CallFrame.ReusesIncomingArea ||
               !Description.TailRejectionReason.empty()) {
      return makeUnexpected(ErrorCode::InvalidArgument,
                            "tail-call plan must reuse the caller's incoming argument area");
    }
    if (Description.CallFrame.SizeBytes < Description.StackArguments.SizeBytes) {
      return makeUnexpected(ErrorCode::InvalidArgument,
                            "call frame does not contain the stack-argument area");
    }
    break;
  }

  std::unordered_set<std::size_t> ByValAssignments;
  std::vector<std::pair<std::uint64_t, std::uint64_t>> ByValRanges;
  for (const ByValCopyAssignment &Copy : Description.ByValCopies) {
    if (Copy.ArgumentAssignmentIndex >= Description.ArgumentAssignments.size() ||
        !ByValAssignments.insert(Copy.ArgumentAssignmentIndex).second ||
        Copy.Source.isNoRegister() || !Copy.PointerType.isPointer() || Copy.SizeBytes == 0 ||
        Copy.StackOffsetBytes % Copy.Align.bytes() != 0 ||
        Copy.StackOffsetBytes < Description.StackArguments.SizeBytes ||
        !Description.ArgumentAssignments[Copy.ArgumentAssignmentIndex].CustomFlags.has(
            CCAssignmentFlag::ByVal) ||
        addOverflows(Copy.StackOffsetBytes, Copy.SizeBytes) ||
        Copy.StackOffsetBytes + Copy.SizeBytes > Description.CallFrame.SizeBytes) {
      return makeUnexpected(ErrorCode::InvalidArgument,
                            "call-lowering byval copy is malformed or outside the call frame");
    }
    ByValRanges.emplace_back(Copy.StackOffsetBytes, Copy.StackOffsetBytes + Copy.SizeBytes);
  }
  std::ranges::sort(ByValRanges);
  for (std::size_t Index = 1; Index < ByValRanges.size(); ++Index) {
    if (ByValRanges[Index].first < ByValRanges[Index - 1].second) {
      return makeUnexpected(ErrorCode::InvalidArgument, "call-lowering byval copy ranges overlap");
    }
  }

  return CallLoweringPlan(std::move(Description));
}

Expected<void>
TargetCallLowering::lowerFormalArguments(MachineIRBuilder &Builder,
                                         const FormalArgumentRequest &Request) const {
  auto Plan = planFormalArguments(Request);
  if (!Plan)
    return std::unexpected(Plan.error());
  if (Plan->kind() != CallLoweringPlanKind::FormalArguments) {
    return makeUnexpected(ErrorCode::InternalError,
                          "target returned the wrong call-lowering plan kind for formal arguments");
  }
  return emitPlan(Builder, *Plan);
}

Expected<void> TargetCallLowering::lowerCall(MachineIRBuilder &Builder,
                                             const CallLoweringRequest &Request) const {
  auto Plan = planCall(Request);
  if (!Plan)
    return std::unexpected(Plan.error());
  if (Plan->kind() != CallLoweringPlanKind::Call) {
    return makeUnexpected(ErrorCode::InternalError,
                          "target returned the wrong call-lowering plan kind for a call");
  }
  return emitPlan(Builder, *Plan);
}

Expected<void> TargetCallLowering::lowerReturn(MachineIRBuilder &Builder,
                                               const ReturnLoweringRequest &Request) const {
  auto Plan = planReturn(Request);
  if (!Plan)
    return std::unexpected(Plan.error());
  if (Plan->kind() != CallLoweringPlanKind::Return) {
    return makeUnexpected(ErrorCode::InternalError,
                          "target returned the wrong call-lowering plan kind for a return");
  }
  return emitPlan(Builder, *Plan);
}

} // namespace rcc