0d379ea8b226586a7ce059a250895533fc203db3
[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   NodeMetadata(NodeMetadata &&Other)
88     : RS(Other.RS), NumOpts(Other.NumOpts), DeniedOpts(Other.DeniedOpts),
89       OptUnsafeEdges(std::move(Other.OptUnsafeEdges)), VReg(Other.VReg),
90       OptionRegs(std::move(Other.OptionRegs)) {}
91
92   NodeMetadata& operator=(NodeMetadata &&Other) {
93     RS = Other.RS;
94     NumOpts = Other.NumOpts;
95     DeniedOpts = Other.DeniedOpts;
96     OptUnsafeEdges = std::move(Other.OptUnsafeEdges);
97     VReg = Other.VReg;
98     OptionRegs = std::move(Other.OptionRegs);
99     return *this;
100   }
101
102   void setVReg(unsigned VReg) { this->VReg = VReg; }
103   unsigned getVReg() const { return VReg; }
104
105   void setOptionRegs(OptionToRegMap OptionRegs) {
106     this->OptionRegs = std::move(OptionRegs);
107   }
108   const OptionToRegMap& getOptionRegs() const { return OptionRegs; }
109
110   void setup(const Vector& Costs) {
111     NumOpts = Costs.getLength() - 1;
112     OptUnsafeEdges = std::unique_ptr<unsigned[]>(new unsigned[NumOpts]());
113   }
114
115   ReductionState getReductionState() const { return RS; }
116   void setReductionState(ReductionState RS) { this->RS = RS; }
117
118   void handleAddEdge(const MatrixMetadata& MD, bool Transpose) {
119     DeniedOpts += Transpose ? MD.getWorstCol() : MD.getWorstRow();
120     const bool* UnsafeOpts =
121       Transpose ? MD.getUnsafeCols() : MD.getUnsafeRows();
122     for (unsigned i = 0; i < NumOpts; ++i)
123       OptUnsafeEdges[i] += UnsafeOpts[i];
124   }
125
126   void handleRemoveEdge(const MatrixMetadata& MD, bool Transpose) {
127     DeniedOpts -= Transpose ? MD.getWorstCol() : MD.getWorstRow();
128     const bool* UnsafeOpts =
129       Transpose ? MD.getUnsafeCols() : MD.getUnsafeRows();
130     for (unsigned i = 0; i < NumOpts; ++i)
131       OptUnsafeEdges[i] -= UnsafeOpts[i];
132   }
133
134   bool isConservativelyAllocatable() const {
135     return (DeniedOpts < NumOpts) ||
136       (std::find(&OptUnsafeEdges[0], &OptUnsafeEdges[NumOpts], 0) !=
137        &OptUnsafeEdges[NumOpts]);
138   }
139
140 private:
141   NodeMetadata(const NodeMetadata&) LLVM_DELETED_FUNCTION;
142   void operator=(const NodeMetadata&) LLVM_DELETED_FUNCTION;
143
144   ReductionState RS;
145   unsigned NumOpts;
146   unsigned DeniedOpts;
147   std::unique_ptr<unsigned[]> OptUnsafeEdges;
148   unsigned VReg;
149   OptionToRegMap OptionRegs;
150 };
151
152 class RegAllocSolverImpl {
153 private:
154   typedef MDMatrix<MatrixMetadata> RAMatrix;
155 public:
156   typedef PBQP::Vector RawVector;
157   typedef PBQP::Matrix RawMatrix;
158   typedef PBQP::Vector Vector;
159   typedef RAMatrix     Matrix;
160   typedef PBQP::PoolCostAllocator<Vector, Matrix> CostAllocator;
161
162   typedef GraphBase::NodeId NodeId;
163   typedef GraphBase::EdgeId EdgeId;
164
165   typedef RegAlloc::NodeMetadata NodeMetadata;
166
167   struct EdgeMetadata { };
168
169   class GraphMetadata {
170   public:
171     GraphMetadata(MachineFunction &MF,
172                   LiveIntervals &LIS,
173                   MachineBlockFrequencyInfo &MBFI)
174       : MF(MF), LIS(LIS), MBFI(MBFI) {}
175
176     MachineFunction &MF;
177     LiveIntervals &LIS;
178     MachineBlockFrequencyInfo &MBFI;
179
180     void setNodeIdForVReg(unsigned VReg, GraphBase::NodeId NId) {
181       VRegToNodeId[VReg] = NId;
182     }
183
184     GraphBase::NodeId getNodeIdForVReg(unsigned VReg) const {
185       auto VRegItr = VRegToNodeId.find(VReg);
186       if (VRegItr == VRegToNodeId.end())
187         return GraphBase::invalidNodeId();
188       return VRegItr->second;
189     }
190
191     void eraseNodeIdForVReg(unsigned VReg) {
192       VRegToNodeId.erase(VReg);
193     }
194
195   private:
196     DenseMap<unsigned, NodeId> VRegToNodeId;
197   };
198
199   typedef PBQP::Graph<RegAllocSolverImpl> Graph;
200
201   RegAllocSolverImpl(Graph &G) : G(G) {}
202
203   Solution solve() {
204     G.setSolver(*this);
205     Solution S;
206     setup();
207     S = backpropagate(G, reduce());
208     G.unsetSolver();
209     return S;
210   }
211
212   void handleAddNode(NodeId NId) {
213     G.getNodeMetadata(NId).setup(G.getNodeCosts(NId));
214   }
215   void handleRemoveNode(NodeId NId) {}
216   void handleSetNodeCosts(NodeId NId, const Vector& newCosts) {}
217
218   void handleAddEdge(EdgeId EId) {
219     handleReconnectEdge(EId, G.getEdgeNode1Id(EId));
220     handleReconnectEdge(EId, G.getEdgeNode2Id(EId));
221   }
222
223   void handleRemoveEdge(EdgeId EId) {
224     handleDisconnectEdge(EId, G.getEdgeNode1Id(EId));
225     handleDisconnectEdge(EId, G.getEdgeNode2Id(EId));
226   }
227
228   void handleDisconnectEdge(EdgeId EId, NodeId NId) {
229     NodeMetadata& NMd = G.getNodeMetadata(NId);
230     const MatrixMetadata& MMd = G.getEdgeCosts(EId).getMetadata();
231     NMd.handleRemoveEdge(MMd, NId == G.getEdgeNode2Id(EId));
232     if (G.getNodeDegree(NId) == 3) {
233       // This node is becoming optimally reducible.
234       moveToOptimallyReducibleNodes(NId);
235     } else if (NMd.getReductionState() ==
236                NodeMetadata::NotProvablyAllocatable &&
237                NMd.isConservativelyAllocatable()) {
238       // This node just became conservatively allocatable.
239       moveToConservativelyAllocatableNodes(NId);
240     }
241   }
242
243   void handleReconnectEdge(EdgeId EId, NodeId NId) {
244     NodeMetadata& NMd = G.getNodeMetadata(NId);
245     const MatrixMetadata& MMd = G.getEdgeCosts(EId).getMetadata();
246     NMd.handleAddEdge(MMd, NId == G.getEdgeNode2Id(EId));
247   }
248
249   void handleSetEdgeCosts(EdgeId EId, const Matrix& NewCosts) {
250     handleRemoveEdge(EId);
251
252     NodeId N1Id = G.getEdgeNode1Id(EId);
253     NodeId N2Id = G.getEdgeNode2Id(EId);
254     NodeMetadata& N1Md = G.getNodeMetadata(N1Id);
255     NodeMetadata& N2Md = G.getNodeMetadata(N2Id);
256     const MatrixMetadata& MMd = NewCosts.getMetadata();
257     N1Md.handleAddEdge(MMd, N1Id != G.getEdgeNode1Id(EId));
258     N2Md.handleAddEdge(MMd, N2Id != G.getEdgeNode1Id(EId));
259   }
260
261 private:
262
263   void removeFromCurrentSet(NodeId NId) {
264     switch (G.getNodeMetadata(NId).getReductionState()) {
265     case NodeMetadata::Unprocessed: break;
266     case NodeMetadata::OptimallyReducible:
267       assert(OptimallyReducibleNodes.find(NId) !=
268              OptimallyReducibleNodes.end() &&
269              "Node not in optimally reducible set.");
270       OptimallyReducibleNodes.erase(NId);
271       break;
272     case NodeMetadata::ConservativelyAllocatable:
273       assert(ConservativelyAllocatableNodes.find(NId) !=
274              ConservativelyAllocatableNodes.end() &&
275              "Node not in conservatively allocatable set.");
276       ConservativelyAllocatableNodes.erase(NId);
277       break;
278     case NodeMetadata::NotProvablyAllocatable:
279       assert(NotProvablyAllocatableNodes.find(NId) !=
280              NotProvablyAllocatableNodes.end() &&
281              "Node not in not-provably-allocatable set.");
282       NotProvablyAllocatableNodes.erase(NId);
283       break;
284     }
285   }
286
287   void moveToOptimallyReducibleNodes(NodeId NId) {
288     removeFromCurrentSet(NId);
289     OptimallyReducibleNodes.insert(NId);
290     G.getNodeMetadata(NId).setReductionState(
291       NodeMetadata::OptimallyReducible);
292   }
293
294   void moveToConservativelyAllocatableNodes(NodeId NId) {
295     removeFromCurrentSet(NId);
296     ConservativelyAllocatableNodes.insert(NId);
297     G.getNodeMetadata(NId).setReductionState(
298       NodeMetadata::ConservativelyAllocatable);
299   }
300
301   void moveToNotProvablyAllocatableNodes(NodeId NId) {
302     removeFromCurrentSet(NId);
303     NotProvablyAllocatableNodes.insert(NId);
304     G.getNodeMetadata(NId).setReductionState(
305       NodeMetadata::NotProvablyAllocatable);
306   }
307
308   void setup() {
309     // Set up worklists.
310     for (auto NId : G.nodeIds()) {
311       if (G.getNodeDegree(NId) < 3)
312         moveToOptimallyReducibleNodes(NId);
313       else if (G.getNodeMetadata(NId).isConservativelyAllocatable())
314         moveToConservativelyAllocatableNodes(NId);
315       else
316         moveToNotProvablyAllocatableNodes(NId);
317     }
318   }
319
320   // Compute a reduction order for the graph by iteratively applying PBQP
321   // reduction rules. Locally optimal rules are applied whenever possible (R0,
322   // R1, R2). If no locally-optimal rules apply then any conservatively
323   // allocatable node is reduced. Finally, if no conservatively allocatable
324   // node exists then the node with the lowest spill-cost:degree ratio is
325   // selected.
326   std::vector<GraphBase::NodeId> reduce() {
327     assert(!G.empty() && "Cannot reduce empty graph.");
328
329     typedef GraphBase::NodeId NodeId;
330     std::vector<NodeId> NodeStack;
331
332     // Consume worklists.
333     while (true) {
334       if (!OptimallyReducibleNodes.empty()) {
335         NodeSet::iterator NItr = OptimallyReducibleNodes.begin();
336         NodeId NId = *NItr;
337         OptimallyReducibleNodes.erase(NItr);
338         NodeStack.push_back(NId);
339         switch (G.getNodeDegree(NId)) {
340         case 0:
341           break;
342         case 1:
343           applyR1(G, NId);
344           break;
345         case 2:
346           applyR2(G, NId);
347           break;
348         default: llvm_unreachable("Not an optimally reducible node.");
349         }
350       } else if (!ConservativelyAllocatableNodes.empty()) {
351         // Conservatively allocatable nodes will never spill. For now just
352         // take the first node in the set and push it on the stack. When we
353         // start optimizing more heavily for register preferencing, it may
354         // would be better to push nodes with lower 'expected' or worst-case
355         // register costs first (since early nodes are the most
356         // constrained).
357         NodeSet::iterator NItr = ConservativelyAllocatableNodes.begin();
358         NodeId NId = *NItr;
359         ConservativelyAllocatableNodes.erase(NItr);
360         NodeStack.push_back(NId);
361         G.disconnectAllNeighborsFromNode(NId);
362
363       } else if (!NotProvablyAllocatableNodes.empty()) {
364         NodeSet::iterator NItr =
365           std::min_element(NotProvablyAllocatableNodes.begin(),
366                            NotProvablyAllocatableNodes.end(),
367                            SpillCostComparator(G));
368         NodeId NId = *NItr;
369         NotProvablyAllocatableNodes.erase(NItr);
370         NodeStack.push_back(NId);
371         G.disconnectAllNeighborsFromNode(NId);
372       } else
373         break;
374     }
375
376     return NodeStack;
377   }
378
379   class SpillCostComparator {
380   public:
381     SpillCostComparator(const Graph& G) : G(G) {}
382     bool operator()(NodeId N1Id, NodeId N2Id) {
383       PBQPNum N1SC = G.getNodeCosts(N1Id)[0] / G.getNodeDegree(N1Id);
384       PBQPNum N2SC = G.getNodeCosts(N2Id)[0] / G.getNodeDegree(N2Id);
385       return N1SC < N2SC;
386     }
387   private:
388     const Graph& G;
389   };
390
391   Graph& G;
392   typedef std::set<NodeId> NodeSet;
393   NodeSet OptimallyReducibleNodes;
394   NodeSet ConservativelyAllocatableNodes;
395   NodeSet NotProvablyAllocatableNodes;
396 };
397
398 class PBQPRAGraph : public PBQP::Graph<RegAllocSolverImpl> {
399 private:
400   typedef PBQP::Graph<RegAllocSolverImpl> BaseT;
401 public:
402   PBQPRAGraph(GraphMetadata Metadata) : BaseT(Metadata) {}
403 };
404
405 inline Solution solve(PBQPRAGraph& G) {
406   if (G.empty())
407     return Solution();
408   RegAllocSolverImpl RegAllocSolver(G);
409   return RegAllocSolver.solve();
410 }
411
412 } // namespace RegAlloc
413 } // namespace PBQP
414
415 /// @brief Create a PBQP register allocator instance.
416 FunctionPass *
417 createPBQPRegisterAllocator(char *customPassID = nullptr);
418
419 } // namespace llvm
420
421 #endif /* LLVM_CODEGEN_REGALLOCPBQP_H */