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 // The node's reduction state. The order in this enum is important,
184 // as it is assumed nodes can only progress up (i.e. towards being
185 // optimally reducible) when reducing the graph.
188 NotProvablyAllocatable,
189 ConservativelyAllocatable,
194 : RS(Unprocessed), NumOpts(0), DeniedOpts(0), OptUnsafeEdges(nullptr),
197 // FIXME: Re-implementing default behavior to work around MSVC. Remove once
198 // MSVC synthesizes move constructors properly.
199 NodeMetadata(const NodeMetadata &Other)
200 : RS(Other.RS), NumOpts(Other.NumOpts), DeniedOpts(Other.DeniedOpts),
201 OptUnsafeEdges(new unsigned[NumOpts]), VReg(Other.VReg),
202 AllowedRegs(Other.AllowedRegs) {
204 std::copy(&Other.OptUnsafeEdges[0], &Other.OptUnsafeEdges[NumOpts],
209 // FIXME: Re-implementing default behavior to work around MSVC. Remove once
210 // MSVC synthesizes move constructors properly.
211 NodeMetadata(NodeMetadata &&Other)
212 : RS(Other.RS), NumOpts(Other.NumOpts), DeniedOpts(Other.DeniedOpts),
213 OptUnsafeEdges(std::move(Other.OptUnsafeEdges)), VReg(Other.VReg),
214 AllowedRegs(std::move(Other.AllowedRegs)) {}
216 // FIXME: Re-implementing default behavior to work around MSVC. Remove once
217 // MSVC synthesizes move constructors properly.
218 NodeMetadata& operator=(const NodeMetadata &Other) {
220 NumOpts = Other.NumOpts;
221 DeniedOpts = Other.DeniedOpts;
222 OptUnsafeEdges.reset(new unsigned[NumOpts]);
223 std::copy(Other.OptUnsafeEdges.get(), Other.OptUnsafeEdges.get() + NumOpts,
224 OptUnsafeEdges.get());
226 AllowedRegs = Other.AllowedRegs;
230 // FIXME: Re-implementing default behavior to work around MSVC. Remove once
231 // MSVC synthesizes move constructors properly.
232 NodeMetadata& operator=(NodeMetadata &&Other) {
234 NumOpts = Other.NumOpts;
235 DeniedOpts = Other.DeniedOpts;
236 OptUnsafeEdges = std::move(Other.OptUnsafeEdges);
238 AllowedRegs = std::move(Other.AllowedRegs);
242 void setVReg(unsigned VReg) { this->VReg = VReg; }
243 unsigned getVReg() const { return VReg; }
245 void setAllowedRegs(GraphMetadata::AllowedRegVecRef AllowedRegs) {
246 this->AllowedRegs = std::move(AllowedRegs);
248 const AllowedRegVector& getAllowedRegs() const { return *AllowedRegs; }
250 void setup(const Vector& Costs) {
251 NumOpts = Costs.getLength() - 1;
252 OptUnsafeEdges = std::unique_ptr<unsigned[]>(new unsigned[NumOpts]());
255 ReductionState getReductionState() const { return RS; }
256 void setReductionState(ReductionState RS) {
257 assert(RS >= this->RS && "A node's reduction state can not be downgraded");
261 void handleAddEdge(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 void handleRemoveEdge(const MatrixMetadata& MD, bool Transpose) {
270 DeniedOpts -= Transpose ? MD.getWorstRow() : MD.getWorstCol();
271 const bool* UnsafeOpts =
272 Transpose ? MD.getUnsafeCols() : MD.getUnsafeRows();
273 for (unsigned i = 0; i < NumOpts; ++i)
274 OptUnsafeEdges[i] -= UnsafeOpts[i];
277 bool isConservativelyAllocatable() const {
278 return (DeniedOpts < NumOpts) ||
279 (std::find(&OptUnsafeEdges[0], &OptUnsafeEdges[NumOpts], 0) !=
280 &OptUnsafeEdges[NumOpts]);
287 std::unique_ptr<unsigned[]> OptUnsafeEdges;
289 GraphMetadata::AllowedRegVecRef AllowedRegs;
292 class RegAllocSolverImpl {
294 typedef MDMatrix<MatrixMetadata> RAMatrix;
296 typedef PBQP::Vector RawVector;
297 typedef PBQP::Matrix RawMatrix;
298 typedef PBQP::Vector Vector;
299 typedef RAMatrix Matrix;
300 typedef PBQP::PoolCostAllocator<Vector, Matrix> CostAllocator;
302 typedef GraphBase::NodeId NodeId;
303 typedef GraphBase::EdgeId EdgeId;
305 typedef RegAlloc::NodeMetadata NodeMetadata;
306 struct EdgeMetadata { };
307 typedef RegAlloc::GraphMetadata GraphMetadata;
309 typedef PBQP::Graph<RegAllocSolverImpl> Graph;
311 RegAllocSolverImpl(Graph &G) : G(G) {}
317 S = backpropagate(G, reduce());
322 void handleAddNode(NodeId NId) {
323 assert(G.getNodeCosts(NId).getLength() > 1 &&
324 "PBQP Graph should not contain single or zero-option nodes");
325 G.getNodeMetadata(NId).setup(G.getNodeCosts(NId));
327 void handleRemoveNode(NodeId NId) {}
328 void handleSetNodeCosts(NodeId NId, const Vector& newCosts) {}
330 void handleAddEdge(EdgeId EId) {
331 handleReconnectEdge(EId, G.getEdgeNode1Id(EId));
332 handleReconnectEdge(EId, G.getEdgeNode2Id(EId));
335 void handleRemoveEdge(EdgeId EId) {
336 handleDisconnectEdge(EId, G.getEdgeNode1Id(EId));
337 handleDisconnectEdge(EId, G.getEdgeNode2Id(EId));
340 void handleDisconnectEdge(EdgeId EId, NodeId NId) {
341 NodeMetadata& NMd = G.getNodeMetadata(NId);
342 const MatrixMetadata& MMd = G.getEdgeCosts(EId).getMetadata();
343 NMd.handleRemoveEdge(MMd, NId == G.getEdgeNode2Id(EId));
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 handleUpdateCosts(EdgeId EId, const Matrix& NewCosts) {
354 NodeId N1Id = G.getEdgeNode1Id(EId);
355 NodeId N2Id = G.getEdgeNode2Id(EId);
356 NodeMetadata& N1Md = G.getNodeMetadata(N1Id);
357 NodeMetadata& N2Md = G.getNodeMetadata(N2Id);
358 bool Transpose = N1Id != G.getEdgeNode1Id(EId);
360 // Metadata are computed incrementally. First, update them
361 // by removing the old cost.
362 const MatrixMetadata& OldMMd = G.getEdgeCosts(EId).getMetadata();
363 N1Md.handleRemoveEdge(OldMMd, Transpose);
364 N2Md.handleRemoveEdge(OldMMd, !Transpose);
366 // And update now the metadata with the new cost.
367 const MatrixMetadata& MMd = NewCosts.getMetadata();
368 N1Md.handleAddEdge(MMd, Transpose);
369 N2Md.handleAddEdge(MMd, !Transpose);
371 // As the metadata may have changed with the update, the nodes may have
372 // become ConservativelyAllocatable or OptimallyReducible.
379 void promote(NodeId NId, NodeMetadata& NMd) {
380 if (G.getNodeDegree(NId) == 3) {
381 // This node is becoming optimally reducible.
382 moveToOptimallyReducibleNodes(NId);
383 } else if (NMd.getReductionState() ==
384 NodeMetadata::NotProvablyAllocatable &&
385 NMd.isConservativelyAllocatable()) {
386 // This node just became conservatively allocatable.
387 moveToConservativelyAllocatableNodes(NId);
391 void removeFromCurrentSet(NodeId NId) {
392 switch (G.getNodeMetadata(NId).getReductionState()) {
393 case NodeMetadata::Unprocessed: break;
394 case NodeMetadata::OptimallyReducible:
395 assert(OptimallyReducibleNodes.find(NId) !=
396 OptimallyReducibleNodes.end() &&
397 "Node not in optimally reducible set.");
398 OptimallyReducibleNodes.erase(NId);
400 case NodeMetadata::ConservativelyAllocatable:
401 assert(ConservativelyAllocatableNodes.find(NId) !=
402 ConservativelyAllocatableNodes.end() &&
403 "Node not in conservatively allocatable set.");
404 ConservativelyAllocatableNodes.erase(NId);
406 case NodeMetadata::NotProvablyAllocatable:
407 assert(NotProvablyAllocatableNodes.find(NId) !=
408 NotProvablyAllocatableNodes.end() &&
409 "Node not in not-provably-allocatable set.");
410 NotProvablyAllocatableNodes.erase(NId);
415 void moveToOptimallyReducibleNodes(NodeId NId) {
416 removeFromCurrentSet(NId);
417 OptimallyReducibleNodes.insert(NId);
418 G.getNodeMetadata(NId).setReductionState(
419 NodeMetadata::OptimallyReducible);
422 void moveToConservativelyAllocatableNodes(NodeId NId) {
423 removeFromCurrentSet(NId);
424 ConservativelyAllocatableNodes.insert(NId);
425 G.getNodeMetadata(NId).setReductionState(
426 NodeMetadata::ConservativelyAllocatable);
429 void moveToNotProvablyAllocatableNodes(NodeId NId) {
430 removeFromCurrentSet(NId);
431 NotProvablyAllocatableNodes.insert(NId);
432 G.getNodeMetadata(NId).setReductionState(
433 NodeMetadata::NotProvablyAllocatable);
438 for (auto NId : G.nodeIds()) {
439 if (G.getNodeDegree(NId) < 3)
440 moveToOptimallyReducibleNodes(NId);
441 else if (G.getNodeMetadata(NId).isConservativelyAllocatable())
442 moveToConservativelyAllocatableNodes(NId);
444 moveToNotProvablyAllocatableNodes(NId);
448 // Compute a reduction order for the graph by iteratively applying PBQP
449 // reduction rules. Locally optimal rules are applied whenever possible (R0,
450 // R1, R2). If no locally-optimal rules apply then any conservatively
451 // allocatable node is reduced. Finally, if no conservatively allocatable
452 // node exists then the node with the lowest spill-cost:degree ratio is
454 std::vector<GraphBase::NodeId> reduce() {
455 assert(!G.empty() && "Cannot reduce empty graph.");
457 typedef GraphBase::NodeId NodeId;
458 std::vector<NodeId> NodeStack;
460 // Consume worklists.
462 if (!OptimallyReducibleNodes.empty()) {
463 NodeSet::iterator NItr = OptimallyReducibleNodes.begin();
465 OptimallyReducibleNodes.erase(NItr);
466 NodeStack.push_back(NId);
467 switch (G.getNodeDegree(NId)) {
476 default: llvm_unreachable("Not an optimally reducible node.");
478 } else if (!ConservativelyAllocatableNodes.empty()) {
479 // Conservatively allocatable nodes will never spill. For now just
480 // take the first node in the set and push it on the stack. When we
481 // start optimizing more heavily for register preferencing, it may
482 // would be better to push nodes with lower 'expected' or worst-case
483 // register costs first (since early nodes are the most
485 NodeSet::iterator NItr = ConservativelyAllocatableNodes.begin();
487 ConservativelyAllocatableNodes.erase(NItr);
488 NodeStack.push_back(NId);
489 G.disconnectAllNeighborsFromNode(NId);
491 } else if (!NotProvablyAllocatableNodes.empty()) {
492 NodeSet::iterator NItr =
493 std::min_element(NotProvablyAllocatableNodes.begin(),
494 NotProvablyAllocatableNodes.end(),
495 SpillCostComparator(G));
497 NotProvablyAllocatableNodes.erase(NItr);
498 NodeStack.push_back(NId);
499 G.disconnectAllNeighborsFromNode(NId);
507 class SpillCostComparator {
509 SpillCostComparator(const Graph& G) : G(G) {}
510 bool operator()(NodeId N1Id, NodeId N2Id) {
511 PBQPNum N1SC = G.getNodeCosts(N1Id)[0] / G.getNodeDegree(N1Id);
512 PBQPNum N2SC = G.getNodeCosts(N2Id)[0] / G.getNodeDegree(N2Id);
520 typedef std::set<NodeId> NodeSet;
521 NodeSet OptimallyReducibleNodes;
522 NodeSet ConservativelyAllocatableNodes;
523 NodeSet NotProvablyAllocatableNodes;
526 class PBQPRAGraph : public PBQP::Graph<RegAllocSolverImpl> {
528 typedef PBQP::Graph<RegAllocSolverImpl> BaseT;
530 PBQPRAGraph(GraphMetadata Metadata) : BaseT(Metadata) {}
532 /// @brief Dump this graph to dbgs().
535 /// @brief Dump this graph to an output stream.
536 /// @param OS Output stream to print on.
537 void dump(raw_ostream &OS) const;
539 /// @brief Print a representation of this graph in DOT format.
540 /// @param OS Output stream to print on.
541 void printDot(raw_ostream &OS) const;
544 inline Solution solve(PBQPRAGraph& G) {
547 RegAllocSolverImpl RegAllocSolver(G);
548 return RegAllocSolver.solve();
551 } // namespace RegAlloc
554 /// @brief Create a PBQP register allocator instance.
556 createPBQPRegisterAllocator(char *customPassID = nullptr);
560 #endif /* LLVM_CODEGEN_REGALLOCPBQP_H */