1 //===-- RegAllocPBQP.h ------------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the PBQPBuilder interface, for classes which build PBQP
11 // instances to represent register allocation problems, and the RegAllocPBQP
14 //===----------------------------------------------------------------------===//
16 #ifndef LLVM_CODEGEN_REGALLOCPBQP_H
17 #define LLVM_CODEGEN_REGALLOCPBQP_H
19 #include "llvm/CodeGen/MachineFunctionPass.h"
20 #include "llvm/CodeGen/PBQP/CostAllocator.h"
21 #include "llvm/CodeGen/PBQP/ReductionRules.h"
22 #include "llvm/CodeGen/PBQPRAConstraint.h"
23 #include "llvm/Support/ErrorHandling.h"
32 /// @brief Spill option index.
33 inline unsigned getSpillOptionIdx() { return 0; }
35 /// \brief Metadata to speed allocatability test.
37 /// Keeps track of the number of infinities in each row and column.
38 class MatrixMetadata {
40 MatrixMetadata(const MatrixMetadata&);
41 void operator=(const MatrixMetadata&);
43 MatrixMetadata(const Matrix& M)
44 : WorstRow(0), WorstCol(0),
45 UnsafeRows(new bool[M.getRows() - 1]()),
46 UnsafeCols(new bool[M.getCols() - 1]()) {
48 unsigned* ColCounts = new unsigned[M.getCols() - 1]();
50 for (unsigned i = 1; i < M.getRows(); ++i) {
51 unsigned RowCount = 0;
52 for (unsigned j = 1; j < M.getCols(); ++j) {
53 if (M[i][j] == std::numeric_limits<PBQPNum>::infinity()) {
56 UnsafeRows[i - 1] = true;
57 UnsafeCols[j - 1] = true;
60 WorstRow = std::max(WorstRow, RowCount);
62 unsigned WorstColCountForCurRow =
63 *std::max_element(ColCounts, ColCounts + M.getCols() - 1);
64 WorstCol = std::max(WorstCol, WorstColCountForCurRow);
68 unsigned getWorstRow() const { return WorstRow; }
69 unsigned getWorstCol() const { return WorstCol; }
70 const bool* getUnsafeRows() const { return UnsafeRows.get(); }
71 const bool* getUnsafeCols() const { return UnsafeCols.get(); }
74 unsigned WorstRow, WorstCol;
75 std::unique_ptr<bool[]> UnsafeRows;
76 std::unique_ptr<bool[]> UnsafeCols;
79 /// \brief Holds a vector of the allowed physical regs for a vreg.
80 class AllowedRegVector {
81 friend hash_code hash_value(const AllowedRegVector &);
84 AllowedRegVector() : NumOpts(0), Opts(nullptr) {}
86 AllowedRegVector(const std::vector<unsigned> &OptVec)
87 : NumOpts(OptVec.size()), Opts(new unsigned[NumOpts]) {
88 std::copy(OptVec.begin(), OptVec.end(), Opts.get());
91 AllowedRegVector(const AllowedRegVector &Other)
92 : NumOpts(Other.NumOpts), Opts(new unsigned[NumOpts]) {
93 std::copy(Other.Opts.get(), Other.Opts.get() + NumOpts, Opts.get());
96 AllowedRegVector(AllowedRegVector &&Other)
97 : NumOpts(std::move(Other.NumOpts)), Opts(std::move(Other.Opts)) {}
99 AllowedRegVector& operator=(const AllowedRegVector &Other) {
100 NumOpts = Other.NumOpts;
101 Opts.reset(new unsigned[NumOpts]);
102 std::copy(Other.Opts.get(), Other.Opts.get() + NumOpts, Opts.get());
106 AllowedRegVector& operator=(AllowedRegVector &&Other) {
107 NumOpts = std::move(Other.NumOpts);
108 Opts = std::move(Other.Opts);
112 unsigned size() const { return NumOpts; }
113 unsigned operator[](size_t I) const { return Opts[I]; }
115 bool operator==(const AllowedRegVector &Other) const {
116 if (NumOpts != Other.NumOpts)
118 return std::equal(Opts.get(), Opts.get() + NumOpts, Other.Opts.get());
121 bool operator!=(const AllowedRegVector &Other) const {
122 return !(*this == Other);
127 std::unique_ptr<unsigned[]> Opts;
130 inline hash_code hash_value(const AllowedRegVector &OptRegs) {
131 unsigned *OStart = OptRegs.Opts.get();
132 unsigned *OEnd = OptRegs.Opts.get() + OptRegs.NumOpts;
133 return hash_combine(OptRegs.NumOpts,
134 hash_combine_range(OStart, OEnd));
137 /// \brief Holds graph-level metadata relevent to PBQP RA problems.
138 class GraphMetadata {
140 typedef ValuePool<AllowedRegVector> AllowedRegVecPool;
143 typedef AllowedRegVecPool::PoolRef AllowedRegVecRef;
145 GraphMetadata(MachineFunction &MF,
147 MachineBlockFrequencyInfo &MBFI)
148 : MF(MF), LIS(LIS), MBFI(MBFI) {}
152 MachineBlockFrequencyInfo &MBFI;
154 void setNodeIdForVReg(unsigned VReg, GraphBase::NodeId NId) {
155 VRegToNodeId[VReg] = NId;
158 GraphBase::NodeId getNodeIdForVReg(unsigned VReg) const {
159 auto VRegItr = VRegToNodeId.find(VReg);
160 if (VRegItr == VRegToNodeId.end())
161 return GraphBase::invalidNodeId();
162 return VRegItr->second;
165 void eraseNodeIdForVReg(unsigned VReg) {
166 VRegToNodeId.erase(VReg);
169 AllowedRegVecRef getAllowedRegs(AllowedRegVector Allowed) {
170 return AllowedRegVecs.getValue(std::move(Allowed));
174 DenseMap<unsigned, GraphBase::NodeId> VRegToNodeId;
175 AllowedRegVecPool AllowedRegVecs;
178 /// \brief Holds solver state and other metadata relevant to each PBQP RA node.
181 typedef RegAlloc::AllowedRegVector AllowedRegVector;
183 typedef enum { Unprocessed,
185 ConservativelyAllocatable,
186 NotProvablyAllocatable } ReductionState;
189 : RS(Unprocessed), NumOpts(0), DeniedOpts(0), OptUnsafeEdges(nullptr),
192 // FIXME: Re-implementing default behavior to work around MSVC. Remove once
193 // MSVC synthesizes move constructors properly.
194 NodeMetadata(const NodeMetadata &Other)
195 : RS(Other.RS), NumOpts(Other.NumOpts), DeniedOpts(Other.DeniedOpts),
196 OptUnsafeEdges(new unsigned[NumOpts]), VReg(Other.VReg),
197 AllowedRegs(Other.AllowedRegs) {
199 std::copy(&Other.OptUnsafeEdges[0], &Other.OptUnsafeEdges[NumOpts],
204 // FIXME: Re-implementing default behavior to work around MSVC. Remove once
205 // MSVC synthesizes move constructors properly.
206 NodeMetadata(NodeMetadata &&Other)
207 : RS(Other.RS), NumOpts(Other.NumOpts), DeniedOpts(Other.DeniedOpts),
208 OptUnsafeEdges(std::move(Other.OptUnsafeEdges)), VReg(Other.VReg),
209 AllowedRegs(std::move(Other.AllowedRegs)) {}
211 // FIXME: Re-implementing default behavior to work around MSVC. Remove once
212 // MSVC synthesizes move constructors properly.
213 NodeMetadata& operator=(const NodeMetadata &Other) {
215 NumOpts = Other.NumOpts;
216 DeniedOpts = Other.DeniedOpts;
217 OptUnsafeEdges.reset(new unsigned[NumOpts]);
218 std::copy(Other.OptUnsafeEdges.get(), Other.OptUnsafeEdges.get() + NumOpts,
219 OptUnsafeEdges.get());
221 AllowedRegs = Other.AllowedRegs;
225 // FIXME: Re-implementing default behavior to work around MSVC. Remove once
226 // MSVC synthesizes move constructors properly.
227 NodeMetadata& operator=(NodeMetadata &&Other) {
229 NumOpts = Other.NumOpts;
230 DeniedOpts = Other.DeniedOpts;
231 OptUnsafeEdges = std::move(Other.OptUnsafeEdges);
233 AllowedRegs = std::move(Other.AllowedRegs);
237 void setVReg(unsigned VReg) { this->VReg = VReg; }
238 unsigned getVReg() const { return VReg; }
240 void setAllowedRegs(GraphMetadata::AllowedRegVecRef AllowedRegs) {
241 this->AllowedRegs = std::move(AllowedRegs);
243 const AllowedRegVector& getAllowedRegs() const { return *AllowedRegs; }
245 void setup(const Vector& Costs) {
246 NumOpts = Costs.getLength() - 1;
247 OptUnsafeEdges = std::unique_ptr<unsigned[]>(new unsigned[NumOpts]());
250 ReductionState getReductionState() const { return RS; }
251 void setReductionState(ReductionState RS) { this->RS = RS; }
253 void handleAddEdge(const MatrixMetadata& MD, bool Transpose) {
254 DeniedOpts += Transpose ? MD.getWorstRow() : MD.getWorstCol();
255 const bool* UnsafeOpts =
256 Transpose ? MD.getUnsafeCols() : MD.getUnsafeRows();
257 for (unsigned i = 0; i < NumOpts; ++i)
258 OptUnsafeEdges[i] += UnsafeOpts[i];
261 void handleRemoveEdge(const MatrixMetadata& MD, bool Transpose) {
262 DeniedOpts -= Transpose ? MD.getWorstRow() : MD.getWorstCol();
263 const bool* UnsafeOpts =
264 Transpose ? MD.getUnsafeCols() : MD.getUnsafeRows();
265 for (unsigned i = 0; i < NumOpts; ++i)
266 OptUnsafeEdges[i] -= UnsafeOpts[i];
269 bool isConservativelyAllocatable() const {
270 return (DeniedOpts < NumOpts) ||
271 (std::find(&OptUnsafeEdges[0], &OptUnsafeEdges[NumOpts], 0) !=
272 &OptUnsafeEdges[NumOpts]);
279 std::unique_ptr<unsigned[]> OptUnsafeEdges;
281 GraphMetadata::AllowedRegVecRef AllowedRegs;
284 class RegAllocSolverImpl {
286 typedef MDMatrix<MatrixMetadata> RAMatrix;
288 typedef PBQP::Vector RawVector;
289 typedef PBQP::Matrix RawMatrix;
290 typedef PBQP::Vector Vector;
291 typedef RAMatrix Matrix;
292 typedef PBQP::PoolCostAllocator<Vector, Matrix> CostAllocator;
294 typedef GraphBase::NodeId NodeId;
295 typedef GraphBase::EdgeId EdgeId;
297 typedef RegAlloc::NodeMetadata NodeMetadata;
298 struct EdgeMetadata { };
299 typedef RegAlloc::GraphMetadata GraphMetadata;
301 typedef PBQP::Graph<RegAllocSolverImpl> Graph;
303 RegAllocSolverImpl(Graph &G) : G(G) {}
309 S = backpropagate(G, reduce());
314 void handleAddNode(NodeId NId) {
315 assert(G.getNodeCosts(NId).getLength() > 1 &&
316 "PBQP Graph should not contain single or zero-option nodes");
317 G.getNodeMetadata(NId).setup(G.getNodeCosts(NId));
319 void handleRemoveNode(NodeId NId) {}
320 void handleSetNodeCosts(NodeId NId, const Vector& newCosts) {}
322 void handleAddEdge(EdgeId EId) {
323 handleReconnectEdge(EId, G.getEdgeNode1Id(EId));
324 handleReconnectEdge(EId, G.getEdgeNode2Id(EId));
327 void handleRemoveEdge(EdgeId EId) {
328 handleDisconnectEdge(EId, G.getEdgeNode1Id(EId));
329 handleDisconnectEdge(EId, G.getEdgeNode2Id(EId));
332 void handleDisconnectEdge(EdgeId EId, NodeId NId) {
333 NodeMetadata& NMd = G.getNodeMetadata(NId);
334 const MatrixMetadata& MMd = G.getEdgeCosts(EId).getMetadata();
335 NMd.handleRemoveEdge(MMd, NId == G.getEdgeNode2Id(EId));
336 if (G.getNodeDegree(NId) == 3) {
337 // This node is becoming optimally reducible.
338 moveToOptimallyReducibleNodes(NId);
339 } else if (NMd.getReductionState() ==
340 NodeMetadata::NotProvablyAllocatable &&
341 NMd.isConservativelyAllocatable()) {
342 // This node just became conservatively allocatable.
343 moveToConservativelyAllocatableNodes(NId);
347 void handleReconnectEdge(EdgeId EId, NodeId NId) {
348 NodeMetadata& NMd = G.getNodeMetadata(NId);
349 const MatrixMetadata& MMd = G.getEdgeCosts(EId).getMetadata();
350 NMd.handleAddEdge(MMd, NId == G.getEdgeNode2Id(EId));
353 void handleSetEdgeCosts(EdgeId EId, const Matrix& NewCosts) {
354 handleRemoveEdge(EId);
356 NodeId N1Id = G.getEdgeNode1Id(EId);
357 NodeId N2Id = G.getEdgeNode2Id(EId);
358 NodeMetadata& N1Md = G.getNodeMetadata(N1Id);
359 NodeMetadata& N2Md = G.getNodeMetadata(N2Id);
360 const MatrixMetadata& MMd = NewCosts.getMetadata();
361 N1Md.handleAddEdge(MMd, N1Id != G.getEdgeNode1Id(EId));
362 N2Md.handleAddEdge(MMd, N2Id != G.getEdgeNode1Id(EId));
367 void removeFromCurrentSet(NodeId NId) {
368 switch (G.getNodeMetadata(NId).getReductionState()) {
369 case NodeMetadata::Unprocessed: break;
370 case NodeMetadata::OptimallyReducible:
371 assert(OptimallyReducibleNodes.find(NId) !=
372 OptimallyReducibleNodes.end() &&
373 "Node not in optimally reducible set.");
374 OptimallyReducibleNodes.erase(NId);
376 case NodeMetadata::ConservativelyAllocatable:
377 assert(ConservativelyAllocatableNodes.find(NId) !=
378 ConservativelyAllocatableNodes.end() &&
379 "Node not in conservatively allocatable set.");
380 ConservativelyAllocatableNodes.erase(NId);
382 case NodeMetadata::NotProvablyAllocatable:
383 assert(NotProvablyAllocatableNodes.find(NId) !=
384 NotProvablyAllocatableNodes.end() &&
385 "Node not in not-provably-allocatable set.");
386 NotProvablyAllocatableNodes.erase(NId);
391 void moveToOptimallyReducibleNodes(NodeId NId) {
392 removeFromCurrentSet(NId);
393 OptimallyReducibleNodes.insert(NId);
394 G.getNodeMetadata(NId).setReductionState(
395 NodeMetadata::OptimallyReducible);
398 void moveToConservativelyAllocatableNodes(NodeId NId) {
399 removeFromCurrentSet(NId);
400 ConservativelyAllocatableNodes.insert(NId);
401 G.getNodeMetadata(NId).setReductionState(
402 NodeMetadata::ConservativelyAllocatable);
405 void moveToNotProvablyAllocatableNodes(NodeId NId) {
406 removeFromCurrentSet(NId);
407 NotProvablyAllocatableNodes.insert(NId);
408 G.getNodeMetadata(NId).setReductionState(
409 NodeMetadata::NotProvablyAllocatable);
414 for (auto NId : G.nodeIds()) {
415 if (G.getNodeDegree(NId) < 3)
416 moveToOptimallyReducibleNodes(NId);
417 else if (G.getNodeMetadata(NId).isConservativelyAllocatable())
418 moveToConservativelyAllocatableNodes(NId);
420 moveToNotProvablyAllocatableNodes(NId);
424 // Compute a reduction order for the graph by iteratively applying PBQP
425 // reduction rules. Locally optimal rules are applied whenever possible (R0,
426 // R1, R2). If no locally-optimal rules apply then any conservatively
427 // allocatable node is reduced. Finally, if no conservatively allocatable
428 // node exists then the node with the lowest spill-cost:degree ratio is
430 std::vector<GraphBase::NodeId> reduce() {
431 assert(!G.empty() && "Cannot reduce empty graph.");
433 typedef GraphBase::NodeId NodeId;
434 std::vector<NodeId> NodeStack;
436 // Consume worklists.
438 if (!OptimallyReducibleNodes.empty()) {
439 NodeSet::iterator NItr = OptimallyReducibleNodes.begin();
441 OptimallyReducibleNodes.erase(NItr);
442 NodeStack.push_back(NId);
443 switch (G.getNodeDegree(NId)) {
452 default: llvm_unreachable("Not an optimally reducible node.");
454 } else if (!ConservativelyAllocatableNodes.empty()) {
455 // Conservatively allocatable nodes will never spill. For now just
456 // take the first node in the set and push it on the stack. When we
457 // start optimizing more heavily for register preferencing, it may
458 // would be better to push nodes with lower 'expected' or worst-case
459 // register costs first (since early nodes are the most
461 NodeSet::iterator NItr = ConservativelyAllocatableNodes.begin();
463 ConservativelyAllocatableNodes.erase(NItr);
464 NodeStack.push_back(NId);
465 G.disconnectAllNeighborsFromNode(NId);
467 } else if (!NotProvablyAllocatableNodes.empty()) {
468 NodeSet::iterator NItr =
469 std::min_element(NotProvablyAllocatableNodes.begin(),
470 NotProvablyAllocatableNodes.end(),
471 SpillCostComparator(G));
473 NotProvablyAllocatableNodes.erase(NItr);
474 NodeStack.push_back(NId);
475 G.disconnectAllNeighborsFromNode(NId);
483 class SpillCostComparator {
485 SpillCostComparator(const Graph& G) : G(G) {}
486 bool operator()(NodeId N1Id, NodeId N2Id) {
487 PBQPNum N1SC = G.getNodeCosts(N1Id)[0] / G.getNodeDegree(N1Id);
488 PBQPNum N2SC = G.getNodeCosts(N2Id)[0] / G.getNodeDegree(N2Id);
496 typedef std::set<NodeId> NodeSet;
497 NodeSet OptimallyReducibleNodes;
498 NodeSet ConservativelyAllocatableNodes;
499 NodeSet NotProvablyAllocatableNodes;
502 class PBQPRAGraph : public PBQP::Graph<RegAllocSolverImpl> {
504 typedef PBQP::Graph<RegAllocSolverImpl> BaseT;
506 PBQPRAGraph(GraphMetadata Metadata) : BaseT(Metadata) {}
508 /// @brief Dump this graph to dbgs().
511 /// @brief Dump this graph to an output stream.
512 /// @param OS Output stream to print on.
513 void dump(raw_ostream &OS) const;
515 /// @brief Print a representation of this graph in DOT format.
516 /// @param OS Output stream to print on.
517 void printDot(raw_ostream &OS) const;
520 inline Solution solve(PBQPRAGraph& G) {
523 RegAllocSolverImpl RegAllocSolver(G);
524 return RegAllocSolver.solve();
527 } // namespace RegAlloc
530 /// @brief Create a PBQP register allocator instance.
532 createPBQPRegisterAllocator(char *customPassID = nullptr);
536 #endif /* LLVM_CODEGEN_REGALLOCPBQP_H */