1 //===-- ExhaustiveSolver.h - Brute Force PBQP Solver -----------*- 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 // Uses a trivial brute force algorithm to solve a PBQP problem.
11 // PBQP is NP-HARD - This solver should only be used for debugging small
14 //===----------------------------------------------------------------------===//
16 #ifndef LLVM_CODEGEN_PBQP_EXHAUSTIVESOLVER_H
17 #define LLVM_CODEGEN_PBQP_EXHAUSTIVESOLVER_H
23 /// A brute force PBQP solver. This solver takes exponential time. It should
24 /// only be used for debugging purposes.
25 class ExhaustiveSolverImpl
{
30 PBQPNum
getSolutionCost(const Solution
&solution
) const {
33 for (SimpleGraph::ConstNodeIterator
34 nodeItr
= g
.nodesBegin(), nodeEnd
= g
.nodesEnd();
35 nodeItr
!= nodeEnd
; ++nodeItr
) {
37 unsigned nodeId
= g
.getNodeID(nodeItr
);
39 cost
+= g
.getNodeCosts(nodeItr
)[solution
.getSelection(nodeId
)];
42 for (SimpleGraph::ConstEdgeIterator
43 edgeItr
= g
.edgesBegin(), edgeEnd
= g
.edgesEnd();
44 edgeItr
!= edgeEnd
; ++edgeItr
) {
46 SimpleGraph::ConstNodeIterator n1
= g
.getEdgeNode1Itr(edgeItr
),
47 n2
= g
.getEdgeNode2Itr(edgeItr
);
48 unsigned sol1
= solution
.getSelection(g
.getNodeID(n1
)),
49 sol2
= solution
.getSelection(g
.getNodeID(n2
));
51 cost
+= g
.getEdgeCosts(edgeItr
)[sol1
][sol2
];
59 ExhaustiveSolverImpl(const SimpleGraph
&g
) : g(g
) {}
61 Solution
solve() const {
62 Solution
current(g
.getNumNodes(), true), optimal(current
);
64 PBQPNum bestCost
= std::numeric_limits
<PBQPNum
>::infinity();
65 bool finished
= false;
68 PBQPNum currentCost
= getSolutionCost(current
);
70 if (currentCost
< bestCost
) {
72 bestCost
= currentCost
;
78 for (unsigned i
= 0; i
< g
.getNumNodes(); ++i
) {
79 if (current
.getSelection(i
) ==
80 (g
.getNodeCosts(g
.getNodeItr(i
)).getLength() - 1)) {
81 current
.setSelection(i
, 0);
84 current
.setSelection(i
, current
.getSelection(i
) + 1);
92 optimal
.setSolutionCost(bestCost
);
99 class ExhaustiveSolver
: public Solver
{
101 ~ExhaustiveSolver() {}
102 Solution
solve(const SimpleGraph
&g
) const {
103 ExhaustiveSolverImpl
solver(g
);
104 return solver
.solve();
110 #endif // LLVM_CODGEN_PBQP_EXHAUSTIVESOLVER_HPP