[PBQP] Unique-ptrify some PBQP Metadata structures. No functional change.
[oota-llvm.git] / include / llvm / CodeGen / RegAllocPBQP.h
1 //===-- RegAllocPBQP.h ------------------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the PBQPBuilder interface, for classes which build PBQP
11 // instances to represent register allocation problems, and the RegAllocPBQP
12 // interface.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #ifndef LLVM_CODEGEN_REGALLOCPBQP_H
17 #define LLVM_CODEGEN_REGALLOCPBQP_H
18
19 #include "llvm/CodeGen/MachineFunctionPass.h"
20 #include "llvm/CodeGen/PBQPRAConstraint.h"
21 #include "llvm/CodeGen/PBQP/CostAllocator.h"
22 #include "llvm/CodeGen/PBQP/ReductionRules.h"
23 #include "llvm/Support/ErrorHandling.h"
24
25 namespace llvm {
26 namespace PBQP {
27 namespace RegAlloc {
28
29 /// @brief Spill option index.
30 inline unsigned getSpillOptionIdx() { return 0; }
31
32 /// \brief Metadata to speed allocatability test.
33 ///
34 /// Keeps track of the number of infinities in each row and column.
35 class MatrixMetadata {
36 private:
37   MatrixMetadata(const MatrixMetadata&);
38   void operator=(const MatrixMetadata&);
39 public:
40   MatrixMetadata(const Matrix& M)
41     : WorstRow(0), WorstCol(0),
42       UnsafeRows(new bool[M.getRows() - 1]()),
43       UnsafeCols(new bool[M.getCols() - 1]()) {
44
45     unsigned* ColCounts = new unsigned[M.getCols() - 1]();
46
47     for (unsigned i = 1; i < M.getRows(); ++i) {
48       unsigned RowCount = 0;
49       for (unsigned j = 1; j < M.getCols(); ++j) {
50         if (M[i][j] == std::numeric_limits<PBQPNum>::infinity()) {
51           ++RowCount;
52           ++ColCounts[j - 1];
53           UnsafeRows[i - 1] = true;
54           UnsafeCols[j - 1] = true;
55         }
56       }
57       WorstRow = std::max(WorstRow, RowCount);
58     }
59     unsigned WorstColCountForCurRow =
60       *std::max_element(ColCounts, ColCounts + M.getCols() - 1);
61     WorstCol = std::max(WorstCol, WorstColCountForCurRow);
62     delete[] ColCounts;
63   }
64
65   unsigned getWorstRow() const { return WorstRow; }
66   unsigned getWorstCol() const { return WorstCol; }
67   const bool* getUnsafeRows() const { return UnsafeRows.get(); }
68   const bool* getUnsafeCols() const { return UnsafeCols.get(); }
69
70 private:
71   unsigned WorstRow, WorstCol;
72   std::unique_ptr<bool[]> UnsafeRows;
73   std::unique_ptr<bool[]> UnsafeCols;
74 };
75
76 class NodeMetadata {
77 public:
78   typedef std::vector<unsigned> OptionToRegMap;
79
80   typedef enum { Unprocessed,
81                  OptimallyReducible,
82                  ConservativelyAllocatable,
83                  NotProvablyAllocatable } ReductionState;
84
85   NodeMetadata() : RS(Unprocessed), DeniedOpts(0), OptUnsafeEdges(nullptr){}
86
87   void setVReg(unsigned VReg) { this->VReg = VReg; }
88   unsigned getVReg() const { return VReg; }
89
90   void setOptionRegs(OptionToRegMap OptionRegs) {
91     this->OptionRegs = std::move(OptionRegs);
92   }
93   const OptionToRegMap& getOptionRegs() const { return OptionRegs; }
94
95   void setup(const Vector& Costs) {
96     NumOpts = Costs.getLength() - 1;
97     OptUnsafeEdges = std::unique_ptr<unsigned[]>(new unsigned[NumOpts]());
98   }
99
100   ReductionState getReductionState() const { return RS; }
101   void setReductionState(ReductionState RS) { this->RS = RS; }
102
103   void handleAddEdge(const MatrixMetadata& MD, bool Transpose) {
104     DeniedOpts += Transpose ? MD.getWorstCol() : MD.getWorstRow();
105     const bool* UnsafeOpts =
106       Transpose ? MD.getUnsafeCols() : MD.getUnsafeRows();
107     for (unsigned i = 0; i < NumOpts; ++i)
108       OptUnsafeEdges[i] += UnsafeOpts[i];
109   }
110
111   void handleRemoveEdge(const MatrixMetadata& MD, bool Transpose) {
112     DeniedOpts -= Transpose ? MD.getWorstCol() : MD.getWorstRow();
113     const bool* UnsafeOpts =
114       Transpose ? MD.getUnsafeCols() : MD.getUnsafeRows();
115     for (unsigned i = 0; i < NumOpts; ++i)
116       OptUnsafeEdges[i] -= UnsafeOpts[i];
117   }
118
119   bool isConservativelyAllocatable() const {
120     return (DeniedOpts < NumOpts) ||
121       (std::find(&OptUnsafeEdges[0], &OptUnsafeEdges[NumOpts], 0) !=
122        &OptUnsafeEdges[NumOpts]);
123   }
124
125 private:
126   ReductionState RS;
127   unsigned NumOpts;
128   unsigned DeniedOpts;
129   std::unique_ptr<unsigned[]> OptUnsafeEdges;
130   unsigned VReg;
131   OptionToRegMap OptionRegs;
132 };
133
134 class RegAllocSolverImpl {
135 private:
136   typedef MDMatrix<MatrixMetadata> RAMatrix;
137 public:
138   typedef PBQP::Vector RawVector;
139   typedef PBQP::Matrix RawMatrix;
140   typedef PBQP::Vector Vector;
141   typedef RAMatrix     Matrix;
142   typedef PBQP::PoolCostAllocator<Vector, Matrix> CostAllocator;
143
144   typedef GraphBase::NodeId NodeId;
145   typedef GraphBase::EdgeId EdgeId;
146
147   typedef RegAlloc::NodeMetadata NodeMetadata;
148
149   struct EdgeMetadata { };
150
151   class GraphMetadata {
152   public:
153     GraphMetadata(MachineFunction &MF,
154                   LiveIntervals &LIS,
155                   MachineBlockFrequencyInfo &MBFI)
156       : MF(MF), LIS(LIS), MBFI(MBFI) {}
157
158     MachineFunction &MF;
159     LiveIntervals &LIS;
160     MachineBlockFrequencyInfo &MBFI;
161
162     void setNodeIdForVReg(unsigned VReg, GraphBase::NodeId NId) {
163       VRegToNodeId[VReg] = NId;
164     }
165
166     GraphBase::NodeId getNodeIdForVReg(unsigned VReg) const {
167       auto VRegItr = VRegToNodeId.find(VReg);
168       if (VRegItr == VRegToNodeId.end())
169         return GraphBase::invalidNodeId();
170       return VRegItr->second;
171     }
172
173     void eraseNodeIdForVReg(unsigned VReg) {
174       VRegToNodeId.erase(VReg);
175     }
176
177   private:
178     DenseMap<unsigned, NodeId> VRegToNodeId;
179   };
180
181   typedef PBQP::Graph<RegAllocSolverImpl> Graph;
182
183   RegAllocSolverImpl(Graph &G) : G(G) {}
184
185   Solution solve() {
186     G.setSolver(*this);
187     Solution S;
188     setup();
189     S = backpropagate(G, reduce());
190     G.unsetSolver();
191     return S;
192   }
193
194   void handleAddNode(NodeId NId) {
195     G.getNodeMetadata(NId).setup(G.getNodeCosts(NId));
196   }
197   void handleRemoveNode(NodeId NId) {}
198   void handleSetNodeCosts(NodeId NId, const Vector& newCosts) {}
199
200   void handleAddEdge(EdgeId EId) {
201     handleReconnectEdge(EId, G.getEdgeNode1Id(EId));
202     handleReconnectEdge(EId, G.getEdgeNode2Id(EId));
203   }
204
205   void handleRemoveEdge(EdgeId EId) {
206     handleDisconnectEdge(EId, G.getEdgeNode1Id(EId));
207     handleDisconnectEdge(EId, G.getEdgeNode2Id(EId));
208   }
209
210   void handleDisconnectEdge(EdgeId EId, NodeId NId) {
211     NodeMetadata& NMd = G.getNodeMetadata(NId);
212     const MatrixMetadata& MMd = G.getEdgeCosts(EId).getMetadata();
213     NMd.handleRemoveEdge(MMd, NId == G.getEdgeNode2Id(EId));
214     if (G.getNodeDegree(NId) == 3) {
215       // This node is becoming optimally reducible.
216       moveToOptimallyReducibleNodes(NId);
217     } else if (NMd.getReductionState() ==
218                NodeMetadata::NotProvablyAllocatable &&
219                NMd.isConservativelyAllocatable()) {
220       // This node just became conservatively allocatable.
221       moveToConservativelyAllocatableNodes(NId);
222     }
223   }
224
225   void handleReconnectEdge(EdgeId EId, NodeId NId) {
226     NodeMetadata& NMd = G.getNodeMetadata(NId);
227     const MatrixMetadata& MMd = G.getEdgeCosts(EId).getMetadata();
228     NMd.handleAddEdge(MMd, NId == G.getEdgeNode2Id(EId));
229   }
230
231   void handleSetEdgeCosts(EdgeId EId, const Matrix& NewCosts) {
232     handleRemoveEdge(EId);
233
234     NodeId N1Id = G.getEdgeNode1Id(EId);
235     NodeId N2Id = G.getEdgeNode2Id(EId);
236     NodeMetadata& N1Md = G.getNodeMetadata(N1Id);
237     NodeMetadata& N2Md = G.getNodeMetadata(N2Id);
238     const MatrixMetadata& MMd = NewCosts.getMetadata();
239     N1Md.handleAddEdge(MMd, N1Id != G.getEdgeNode1Id(EId));
240     N2Md.handleAddEdge(MMd, N2Id != G.getEdgeNode1Id(EId));
241   }
242
243 private:
244
245   void removeFromCurrentSet(NodeId NId) {
246     switch (G.getNodeMetadata(NId).getReductionState()) {
247     case NodeMetadata::Unprocessed: break;
248     case NodeMetadata::OptimallyReducible:
249       assert(OptimallyReducibleNodes.find(NId) !=
250              OptimallyReducibleNodes.end() &&
251              "Node not in optimally reducible set.");
252       OptimallyReducibleNodes.erase(NId);
253       break;
254     case NodeMetadata::ConservativelyAllocatable:
255       assert(ConservativelyAllocatableNodes.find(NId) !=
256              ConservativelyAllocatableNodes.end() &&
257              "Node not in conservatively allocatable set.");
258       ConservativelyAllocatableNodes.erase(NId);
259       break;
260     case NodeMetadata::NotProvablyAllocatable:
261       assert(NotProvablyAllocatableNodes.find(NId) !=
262              NotProvablyAllocatableNodes.end() &&
263              "Node not in not-provably-allocatable set.");
264       NotProvablyAllocatableNodes.erase(NId);
265       break;
266     }
267   }
268
269   void moveToOptimallyReducibleNodes(NodeId NId) {
270     removeFromCurrentSet(NId);
271     OptimallyReducibleNodes.insert(NId);
272     G.getNodeMetadata(NId).setReductionState(
273       NodeMetadata::OptimallyReducible);
274   }
275
276   void moveToConservativelyAllocatableNodes(NodeId NId) {
277     removeFromCurrentSet(NId);
278     ConservativelyAllocatableNodes.insert(NId);
279     G.getNodeMetadata(NId).setReductionState(
280       NodeMetadata::ConservativelyAllocatable);
281   }
282
283   void moveToNotProvablyAllocatableNodes(NodeId NId) {
284     removeFromCurrentSet(NId);
285     NotProvablyAllocatableNodes.insert(NId);
286     G.getNodeMetadata(NId).setReductionState(
287       NodeMetadata::NotProvablyAllocatable);
288   }
289
290   void setup() {
291     // Set up worklists.
292     for (auto NId : G.nodeIds()) {
293       if (G.getNodeDegree(NId) < 3)
294         moveToOptimallyReducibleNodes(NId);
295       else if (G.getNodeMetadata(NId).isConservativelyAllocatable())
296         moveToConservativelyAllocatableNodes(NId);
297       else
298         moveToNotProvablyAllocatableNodes(NId);
299     }
300   }
301
302   // Compute a reduction order for the graph by iteratively applying PBQP
303   // reduction rules. Locally optimal rules are applied whenever possible (R0,
304   // R1, R2). If no locally-optimal rules apply then any conservatively
305   // allocatable node is reduced. Finally, if no conservatively allocatable
306   // node exists then the node with the lowest spill-cost:degree ratio is
307   // selected.
308   std::vector<GraphBase::NodeId> reduce() {
309     assert(!G.empty() && "Cannot reduce empty graph.");
310
311     typedef GraphBase::NodeId NodeId;
312     std::vector<NodeId> NodeStack;
313
314     // Consume worklists.
315     while (true) {
316       if (!OptimallyReducibleNodes.empty()) {
317         NodeSet::iterator NItr = OptimallyReducibleNodes.begin();
318         NodeId NId = *NItr;
319         OptimallyReducibleNodes.erase(NItr);
320         NodeStack.push_back(NId);
321         switch (G.getNodeDegree(NId)) {
322         case 0:
323           break;
324         case 1:
325           applyR1(G, NId);
326           break;
327         case 2:
328           applyR2(G, NId);
329           break;
330         default: llvm_unreachable("Not an optimally reducible node.");
331         }
332       } else if (!ConservativelyAllocatableNodes.empty()) {
333         // Conservatively allocatable nodes will never spill. For now just
334         // take the first node in the set and push it on the stack. When we
335         // start optimizing more heavily for register preferencing, it may
336         // would be better to push nodes with lower 'expected' or worst-case
337         // register costs first (since early nodes are the most
338         // constrained).
339         NodeSet::iterator NItr = ConservativelyAllocatableNodes.begin();
340         NodeId NId = *NItr;
341         ConservativelyAllocatableNodes.erase(NItr);
342         NodeStack.push_back(NId);
343         G.disconnectAllNeighborsFromNode(NId);
344
345       } else if (!NotProvablyAllocatableNodes.empty()) {
346         NodeSet::iterator NItr =
347           std::min_element(NotProvablyAllocatableNodes.begin(),
348                            NotProvablyAllocatableNodes.end(),
349                            SpillCostComparator(G));
350         NodeId NId = *NItr;
351         NotProvablyAllocatableNodes.erase(NItr);
352         NodeStack.push_back(NId);
353         G.disconnectAllNeighborsFromNode(NId);
354       } else
355         break;
356     }
357
358     return NodeStack;
359   }
360
361   class SpillCostComparator {
362   public:
363     SpillCostComparator(const Graph& G) : G(G) {}
364     bool operator()(NodeId N1Id, NodeId N2Id) {
365       PBQPNum N1SC = G.getNodeCosts(N1Id)[0] / G.getNodeDegree(N1Id);
366       PBQPNum N2SC = G.getNodeCosts(N2Id)[0] / G.getNodeDegree(N2Id);
367       return N1SC < N2SC;
368     }
369   private:
370     const Graph& G;
371   };
372
373   Graph& G;
374   typedef std::set<NodeId> NodeSet;
375   NodeSet OptimallyReducibleNodes;
376   NodeSet ConservativelyAllocatableNodes;
377   NodeSet NotProvablyAllocatableNodes;
378 };
379
380 class PBQPRAGraph : public PBQP::Graph<RegAllocSolverImpl> {
381 private:
382   typedef PBQP::Graph<RegAllocSolverImpl> BaseT;
383 public:
384   PBQPRAGraph(GraphMetadata Metadata) : BaseT(Metadata) {}
385 };
386
387 inline Solution solve(PBQPRAGraph& G) {
388   if (G.empty())
389     return Solution();
390   RegAllocSolverImpl RegAllocSolver(G);
391   return RegAllocSolver.solve();
392 }
393
394 } // namespace RegAlloc
395 } // namespace PBQP
396
397 /// @brief Create a PBQP register allocator instance.
398 FunctionPass *
399 createPBQPRegisterAllocator(char *customPassID = nullptr);
400
401 } // namespace llvm
402
403 #endif /* LLVM_CODEGEN_REGALLOCPBQP_H */