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
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "rcc/CodeGen/RegAllocPBQP.h"
#include "RegAllocBase.h"
#include "rcc/CodeGen/GenericOpcodes.h"
#include "rcc/CodeGen/LiveIntervals.h"
#include "rcc/CodeGen/LiveRegMatrix.h"
#include "rcc/CodeGen/MachineBasicBlock.h"
#include "rcc/CodeGen/MachineFunction.h"
#include "rcc/CodeGen/MachineInstr.h"
#include "rcc/CodeGen/MachineOperand.h"
#include "rcc/CodeGen/PBQP/Solver.h"
#include <algorithm>
#include <cstdint>
#include <limits>
#include <map>
#include <optional>
#include <ranges>
#include <string>
#include <utility>
#include <vector>
namespace rcc {
namespace {
struct PBQPAllocationNode final {
Register VirtualReg;
pbqp::NodeID Node;
std::vector<std::optional<PhysicalRegister>> Options;
};
[[nodiscard]] std::map<std::pair<std::uint32_t, std::uint32_t>, MachineInstrStableID>
copyRelatedRegisters(const MachineFunction &Function) {
std::map<std::pair<std::uint32_t, std::uint32_t>, MachineInstrStableID> Result;
for (const MachineBasicBlock *Block = Function.firstBlock(); Block != nullptr;
Block = Block->next()) {
for (const MachineInstr *Instruction = Block->firstInstruction(); Instruction != nullptr;
Instruction = Instruction->next()) {
if (Instruction->opcode() != opcode(GenericOpcode::COPY) || Instruction->operandCount() < 2)
continue;
const Register *Destination = Instruction->operands()[0].getIf<Register>();
const Register *Source = Instruction->operands()[1].getIf<Register>();
if (Destination == nullptr || Source == nullptr || !Destination->isVirtual() ||
!Source->isVirtual() || *Destination == *Source)
continue;
std::uint32_t Left = Destination->opaqueValue();
std::uint32_t Right = Source->opaqueValue();
if (Right < Left)
std::swap(Left, Right);
Result.try_emplace({Left, Right}, Instruction->stableID());
}
}
return Result;
}
[[nodiscard]] std::string_view reductionName(pbqp::ReductionKind Kind) noexcept {
switch (Kind) {
case pbqp::ReductionKind::DegreeZero:
return "degree-zero";
case pbqp::ReductionKind::DegreeOne:
return "degree-one";
case pbqp::ReductionKind::DegreeTwo:
return "degree-two";
case pbqp::ReductionKind::Heuristic:
return "heuristic";
}
return "unknown";
}
[[nodiscard]] MachineInstrStableID actionInstructionForRegister(const MachineFunction &Function,
Register Reg) noexcept {
const MachineOperand *Definition = Function.registerInfo().getUniqueVRegDef(Reg);
const MachineInstr *Instruction = Definition == nullptr ? nullptr : Definition->parent();
return Instruction == nullptr ? MachineInstrStableID{} : Instruction->stableID();
}
[[nodiscard]] pbqp::Cost boundedCost(std::uint64_t Value) noexcept {
const std::uint64_t Limit = static_cast<std::uint64_t>(pbqp::InfiniteCost - 1);
return static_cast<pbqp::Cost>(std::min(Value, Limit));
}
class PBQPAllocatorEngine final : public RegAllocBase {
public:
PBQPAllocatorEngine(MachineFunction &Function, const TargetDescription &Target,
const TargetRegisterAllocationInfo &TargetInfo,
MachineFunctionAnalysisManager &Analyses, RegisterAllocationOptions Options)
: RegAllocBase(Function, Target, TargetInfo, Analyses, Options) {}
private:
[[nodiscard]] Expected<AllocationRoundResult>
allocateRound(const LiveIntervalsAnalysis::Result &Intervals, VirtRegMap &Mapping) override {
LiveRegMatrix FixedMatrix(Function, Target, Intervals);
pbqp::Graph Problem;
std::vector<PBQPAllocationNode> Nodes;
for (const LiveInterval *Interval : orderedAllocationIntervals(Intervals, Function)) {
const Register VirtualReg = Interval->Reg;
const bool TerminatorDefined =
regalloc_detail::hasTerminatorDefinition(Function, Target, VirtualReg);
if (TerminatorDefined) {
auto Marked = Mapping.setSpillable(VirtualReg, false);
if (!Marked)
return std::unexpected(Marked.error());
}
auto ClassID = regalloc_detail::registerClassFor(Function, VirtualReg);
if (!ClassID)
return std::unexpected(ClassID.error());
auto Candidates = regalloc_detail::allocationOrder(Function, Target, TargetInfo, VirtualReg);
if (!Candidates)
return std::unexpected(Candidates.error());
std::erase_if(*Candidates, [&](PhysicalRegister Candidate) {
return FixedMatrix.checkInterference(VirtualReg, Candidate).Kind !=
RegisterInterferenceKind::Free;
});
std::vector<std::optional<PhysicalRegister>> NodeOptions;
NodeOptions.reserve(Candidates->size() + 1U);
NodeOptions.push_back(std::nullopt);
for (const PhysicalRegister Candidate : *Candidates)
NodeOptions.push_back(Candidate);
pbqp::CostVector Costs(NodeOptions.size(), 0);
if (!Mapping.isSpillable(VirtualReg)) {
Costs[0] = pbqp::InfiniteCost;
} else {
const std::uint64_t TargetSpillCost = TargetInfo.spillCost(Function, *Interval, *ClassID);
const std::uint64_t Weight = std::max<std::uint64_t>(1, Interval->SpillWeight);
const std::uint64_t Scaled =
TargetSpillCost > std::numeric_limits<std::uint64_t>::max() / Weight
? std::numeric_limits<std::uint64_t>::max()
: TargetSpillCost * Weight;
const std::uint64_t Adjusted =
Scaled == std::numeric_limits<std::uint64_t>::max() ? Scaled : Scaled + 1U;
Costs[0] = boundedCost(Adjusted);
}
auto Info = Function.registerInfo().virtualRegisterInfo(VirtualReg);
if (!Info)
return std::unexpected(Info.error());
for (std::size_t Index = 1; Index < NodeOptions.size(); ++Index) {
const auto CandidateOption = NodeOptions[Index];
if (!CandidateOption) {
return makeUnexpected(ErrorCode::InternalError,
"PBQP allocation node has an unexpected spill option");
}
const PhysicalRegister Candidate = CandidateOption.value();
std::uint64_t Cost =
TargetInfo.physicalRegisterCost(Function, VirtualReg, Candidate, *ClassID, true);
const auto Hint = std::ranges::find(Info->get().AllocationHints, Candidate);
const std::uint64_t HintCost =
Hint == Info->get().AllocationHints.end()
? 2U
: static_cast<std::uint64_t>(Hint - Info->get().AllocationHints.begin());
Cost = Cost > std::numeric_limits<std::uint64_t>::max() - HintCost
? std::numeric_limits<std::uint64_t>::max()
: Cost + HintCost;
Costs[Index] = boundedCost(Cost);
}
auto NodeID = Problem.addNode(std::move(Costs), VirtualReg.opaqueValue());
if (!NodeID)
return std::unexpected(NodeID.error());
Nodes.push_back(PBQPAllocationNode{VirtualReg, *NodeID, std::move(NodeOptions)});
}
const auto CopyPairs = copyRelatedRegisters(Function);
for (std::size_t LeftIndex = 0; LeftIndex < Nodes.size(); ++LeftIndex) {
const PBQPAllocationNode &Left = Nodes[LeftIndex];
const LiveInterval *LeftInterval = Intervals.interval(Left.VirtualReg);
for (std::size_t RightIndex = LeftIndex + 1U; RightIndex < Nodes.size(); ++RightIndex) {
const PBQPAllocationNode &Right = Nodes[RightIndex];
const LiveInterval *RightInterval = Intervals.interval(Right.VirtualReg);
if (LeftInterval == nullptr || RightInterval == nullptr)
continue;
std::uint32_t LeftKey = Left.VirtualReg.opaqueValue();
std::uint32_t RightKey = Right.VirtualReg.opaqueValue();
if (RightKey < LeftKey)
std::swap(LeftKey, RightKey);
const auto CopyPosition = CopyPairs.find({LeftKey, RightKey});
bool CopyRelated = Options.EnableCopyCoalescing && CopyPosition != CopyPairs.end();
if (CopyRelated) {
auto Accepted = Analyses.requestAction("coalesce-copy", Function, CopyPosition->second);
if (!Accepted)
return std::unexpected(Accepted.error());
CopyRelated = *Accepted;
}
pbqp::CostMatrix Costs(Left.Options.size(), Right.Options.size(), 0);
bool HasCost = false;
for (std::size_t LeftOption = 1; LeftOption < Left.Options.size(); ++LeftOption) {
for (std::size_t RightOption = 1; RightOption < Right.Options.size(); ++RightOption) {
const auto LeftRegister = Left.Options[LeftOption];
const auto RightRegister = Right.Options[RightOption];
if (!LeftRegister || !RightRegister) {
return makeUnexpected(ErrorCode::InternalError,
"PBQP edge has an unexpected spill option");
}
const PhysicalRegister LeftReg = LeftRegister.value();
const PhysicalRegister RightReg = RightRegister.value();
if (regalloc_detail::intervalsOverlapOnPhysicalRegisters(
*LeftInterval, LeftReg, *RightInterval, RightReg, Target.registers())) {
Costs.at(LeftOption, RightOption) = pbqp::InfiniteCost;
HasCost = true;
} else if (CopyRelated && LeftReg == RightReg) {
Costs.at(LeftOption, RightOption) = -1;
HasCost = true;
}
}
}
if (!HasCost)
continue;
const std::uint64_t StableKey =
(static_cast<std::uint64_t>(Left.VirtualReg.opaqueValue()) << 32U) |
Right.VirtualReg.opaqueValue();
auto Edge = Problem.addEdge(Left.Node, Right.Node, std::move(Costs), StableKey);
if (!Edge)
return std::unexpected(Edge.error());
}
}
pbqp::DeterministicSolver Solver;
auto Solution = Solver.solve(Problem, [&](const pbqp::SolverAction &Action) -> Expected<bool> {
if (Action.Node.value() >= Nodes.size()) {
return makeUnexpected(ErrorCode::InternalError,
"PBQP action names an unknown allocation node");
}
const Register VirtualReg = Nodes[Action.Node.value()].VirtualReg;
std::string Rule =
Action.Kind == pbqp::SolverActionKind::Reduction ? "pbqp-reduce." : "pbqp-choice.";
Rule.append(reductionName(Action.Reduction));
if (Action.Kind == pbqp::SolverActionKind::Choice) {
Rule.append(".option-");
Rule.append(std::to_string(Action.Value));
}
return Analyses.requestAction(Rule, Function,
actionInstructionForRegister(Function, VirtualReg));
});
if (!Solution)
return std::unexpected(Solution.error());
LiveRegMatrix AssignedMatrix(Function, Target, Intervals);
AllocationRoundResult Result;
for (const PBQPAllocationNode &Node : Nodes) {
const auto Selection = Solution->selection(Node.Node);
if (!Selection)
return makeUnexpected(ErrorCode::InternalError,
"PBQP solver returned an invalid selection");
const std::size_t SelectedOption = Selection.value();
if (SelectedOption >= Node.Options.size()) {
return makeUnexpected(ErrorCode::InternalError,
"PBQP solver selected an out-of-range option");
}
const auto AssignedOption = Node.Options[SelectedOption];
if (!AssignedOption) {
Result.Spilled.push_back(Node.VirtualReg);
continue;
}
const PhysicalRegister Assigned = AssignedOption.value();
auto MatrixAssignment = AssignedMatrix.assign(Node.VirtualReg, Assigned);
if (!MatrixAssignment)
return makeUnexpected(ErrorCode::InternalError,
"PBQP solution violates its encoded interference constraints");
auto MapAssignment = Mapping.assign(Node.VirtualReg, Assigned);
if (!MapAssignment)
return std::unexpected(MapAssignment.error());
}
return Result;
}
};
[[nodiscard]] const MachinePassContract &pbqpContract() {
static const MachinePassContract Contract = [] {
MachinePassContract Value{
.Name = "PBQPAllocator",
.Requires = {MachineFunctionProperty::NoPHIs},
.Sets = {},
.Clears = {MachineFunctionProperty::IsSSA},
.RequiredAnalyses = {MachineFunctionAnalysisManager::id<LiveIntervalsAnalysis>(),
MachineFunctionAnalysisManager::id<VirtRegMapAnalysis>()},
.VerificationStage = std::nullopt,
};
Value.ThreadSafety = PassThreadSafety::ThreadSafe;
return Value;
}();
return Contract;
}
} // namespace
const MachinePassContract &PBQPAllocatorPass::contract() const noexcept {
return pbqpContract();
}
Expected<MachinePassResult> PBQPAllocatorPass::run(MachineFunction &Function,
const TargetDescription &Target,
MachineFunctionAnalysisManager &Analyses) {
if (Info == nullptr)
return makeUnexpected(ErrorCode::InvalidArgument, "PBQPAllocator requires target behavior");
const std::vector<PhysicalRegister> FunctionReserved =
regalloc_detail::functionReservedRegisters(Function, Target, *Info);
auto Reserved = regalloc_detail::reserveFunctionRegisters(Function, FunctionReserved);
if (!Reserved)
return std::unexpected(Reserved.error());
PBQPAllocatorEngine Allocator(Function, Target, *Info, Analyses, Options);
auto Mapping = Analyses.getResult<VirtRegMapAnalysis>(Function, Target);
if (!Mapping)
return std::unexpected(Mapping.error());
auto Allocated = Allocator.run(**Mapping);
if (!Allocated)
return std::unexpected(Allocated.error());
Allocated->Changed |= *Reserved;
MachinePassResult Result = regalloc_detail::passResult(*Allocated);
Result.Preserved.preserve<VirtRegMapAnalysis>();
return Result;
}
} // namespace rcc
|