1 //===- RegAllocPBQP.cpp ---- PBQP Register Allocator ----------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains a Partitioned Boolean Quadratic Programming (PBQP) based
10 // register allocator for LLVM. This allocator works by constructing a PBQP
11 // problem representing the register allocation problem under consideration,
12 // solving this using a PBQP solver, and mapping the solution back to a
13 // register assignment. If any variables are selected for spilling then spill
14 // code is inserted and the process repeated.
15 //
16 // The PBQP solver (pbqp.c) provided for this allocator uses a heuristic tuned
17 // for register allocation. For more information on PBQP for register
18 // allocation, see the following papers:
19 //
20 //   (1) Hames, L. and Scholz, B. 2006. Nearly optimal register allocation with
21 //   PBQP. In Proceedings of the 7th Joint Modular Languages Conference
22 //   (JMLC'06). LNCS, vol. 4228. Springer, New York, NY, USA. 346-361.
23 //
24 //   (2) Scholz, B., Eckstein, E. 2002. Register allocation for irregular
25 //   architectures. In Proceedings of the Joint Conference on Languages,
26 //   Compilers and Tools for Embedded Systems (LCTES'02), ACM Press, New York,
27 //   NY, USA, 139-148.
28 //
29 //===----------------------------------------------------------------------===//
30 
31 #include "llvm/CodeGen/RegAllocPBQP.h"
32 #include "RegisterCoalescer.h"
33 #include "llvm/ADT/ArrayRef.h"
34 #include "llvm/ADT/BitVector.h"
35 #include "llvm/ADT/DenseMap.h"
36 #include "llvm/ADT/DenseSet.h"
37 #include "llvm/ADT/STLExtras.h"
38 #include "llvm/ADT/SmallPtrSet.h"
39 #include "llvm/ADT/SmallVector.h"
40 #include "llvm/ADT/StringRef.h"
41 #include "llvm/Analysis/AliasAnalysis.h"
42 #include "llvm/CodeGen/CalcSpillWeights.h"
43 #include "llvm/CodeGen/LiveInterval.h"
44 #include "llvm/CodeGen/LiveIntervals.h"
45 #include "llvm/CodeGen/LiveRangeEdit.h"
46 #include "llvm/CodeGen/LiveStacks.h"
47 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
48 #include "llvm/CodeGen/MachineDominators.h"
49 #include "llvm/CodeGen/MachineFunction.h"
50 #include "llvm/CodeGen/MachineFunctionPass.h"
51 #include "llvm/CodeGen/MachineInstr.h"
52 #include "llvm/CodeGen/MachineLoopInfo.h"
53 #include "llvm/CodeGen/MachineRegisterInfo.h"
54 #include "llvm/CodeGen/PBQP/Graph.h"
55 #include "llvm/CodeGen/PBQP/Math.h"
56 #include "llvm/CodeGen/PBQP/Solution.h"
57 #include "llvm/CodeGen/PBQPRAConstraint.h"
58 #include "llvm/CodeGen/RegAllocRegistry.h"
59 #include "llvm/CodeGen/SlotIndexes.h"
60 #include "llvm/CodeGen/Spiller.h"
61 #include "llvm/CodeGen/TargetRegisterInfo.h"
62 #include "llvm/CodeGen/TargetSubtargetInfo.h"
63 #include "llvm/CodeGen/VirtRegMap.h"
64 #include "llvm/Config/llvm-config.h"
65 #include "llvm/IR/Function.h"
66 #include "llvm/IR/Module.h"
67 #include "llvm/MC/MCRegisterInfo.h"
68 #include "llvm/Pass.h"
69 #include "llvm/Support/CommandLine.h"
70 #include "llvm/Support/Compiler.h"
71 #include "llvm/Support/Debug.h"
72 #include "llvm/Support/FileSystem.h"
73 #include "llvm/Support/Printable.h"
74 #include "llvm/Support/raw_ostream.h"
75 #include <algorithm>
76 #include <cassert>
77 #include <cstddef>
78 #include <limits>
79 #include <map>
80 #include <memory>
81 #include <queue>
82 #include <set>
83 #include <sstream>
84 #include <string>
85 #include <system_error>
86 #include <tuple>
87 #include <utility>
88 #include <vector>
89 
90 using namespace llvm;
91 
92 #define DEBUG_TYPE "regalloc"
93 
94 static RegisterRegAlloc
95 RegisterPBQPRepAlloc("pbqp", "PBQP register allocator",
96                        createDefaultPBQPRegisterAllocator);
97 
98 static cl::opt<bool>
99 PBQPCoalescing("pbqp-coalescing",
100                 cl::desc("Attempt coalescing during PBQP register allocation."),
101                 cl::init(false), cl::Hidden);
102 
103 #ifndef NDEBUG
104 static cl::opt<bool>
105 PBQPDumpGraphs("pbqp-dump-graphs",
106                cl::desc("Dump graphs for each function/round in the compilation unit."),
107                cl::init(false), cl::Hidden);
108 #endif
109 
110 namespace {
111 
112 ///
113 /// PBQP based allocators solve the register allocation problem by mapping
114 /// register allocation problems to Partitioned Boolean Quadratic
115 /// Programming problems.
116 class RegAllocPBQP : public MachineFunctionPass {
117 public:
118   static char ID;
119 
120   /// Construct a PBQP register allocator.
121   RegAllocPBQP(char *cPassID = nullptr)
122       : MachineFunctionPass(ID), customPassID(cPassID) {
123     initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
124     initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
125     initializeLiveStacksPass(*PassRegistry::getPassRegistry());
126     initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
127   }
128 
129   /// Return the pass name.
130   StringRef getPassName() const override { return "PBQP Register Allocator"; }
131 
132   /// PBQP analysis usage.
133   void getAnalysisUsage(AnalysisUsage &au) const override;
134 
135   /// Perform register allocation
136   bool runOnMachineFunction(MachineFunction &MF) override;
137 
138   MachineFunctionProperties getRequiredProperties() const override {
139     return MachineFunctionProperties().set(
140         MachineFunctionProperties::Property::NoPHIs);
141   }
142 
143   MachineFunctionProperties getClearedProperties() const override {
144     return MachineFunctionProperties().set(
145       MachineFunctionProperties::Property::IsSSA);
146   }
147 
148 private:
149   using LI2NodeMap = std::map<const LiveInterval *, unsigned>;
150   using Node2LIMap = std::vector<const LiveInterval *>;
151   using AllowedSet = std::vector<unsigned>;
152   using AllowedSetMap = std::vector<AllowedSet>;
153   using RegPair = std::pair<unsigned, unsigned>;
154   using CoalesceMap = std::map<RegPair, PBQP::PBQPNum>;
155   using RegSet = std::set<Register>;
156 
157   char *customPassID;
158 
159   RegSet VRegsToAlloc, EmptyIntervalVRegs;
160 
161   /// Inst which is a def of an original reg and whose defs are already all
162   /// dead after remat is saved in DeadRemats. The deletion of such inst is
163   /// postponed till all the allocations are done, so its remat expr is
164   /// always available for the remat of all the siblings of the original reg.
165   SmallPtrSet<MachineInstr *, 32> DeadRemats;
166 
167   /// Finds the initial set of vreg intervals to allocate.
168   void findVRegIntervalsToAlloc(const MachineFunction &MF, LiveIntervals &LIS);
169 
170   /// Constructs an initial graph.
171   void initializeGraph(PBQPRAGraph &G, VirtRegMap &VRM, Spiller &VRegSpiller);
172 
173   /// Spill the given VReg.
174   void spillVReg(Register VReg, SmallVectorImpl<Register> &NewIntervals,
175                  MachineFunction &MF, LiveIntervals &LIS, VirtRegMap &VRM,
176                  Spiller &VRegSpiller);
177 
178   /// Given a solved PBQP problem maps this solution back to a register
179   /// assignment.
180   bool mapPBQPToRegAlloc(const PBQPRAGraph &G,
181                          const PBQP::Solution &Solution,
182                          VirtRegMap &VRM,
183                          Spiller &VRegSpiller);
184 
185   /// Postprocessing before final spilling. Sets basic block "live in"
186   /// variables.
187   void finalizeAlloc(MachineFunction &MF, LiveIntervals &LIS,
188                      VirtRegMap &VRM) const;
189 
190   void postOptimization(Spiller &VRegSpiller, LiveIntervals &LIS);
191 };
192 
193 char RegAllocPBQP::ID = 0;
194 
195 /// Set spill costs for each node in the PBQP reg-alloc graph.
196 class SpillCosts : public PBQPRAConstraint {
197 public:
198   void apply(PBQPRAGraph &G) override {
199     LiveIntervals &LIS = G.getMetadata().LIS;
200 
201     // A minimum spill costs, so that register constraints can can be set
202     // without normalization in the [0.0:MinSpillCost( interval.
203     const PBQP::PBQPNum MinSpillCost = 10.0;
204 
205     for (auto NId : G.nodeIds()) {
206       PBQP::PBQPNum SpillCost =
207           LIS.getInterval(G.getNodeMetadata(NId).getVReg()).weight();
208       if (SpillCost == 0.0)
209         SpillCost = std::numeric_limits<PBQP::PBQPNum>::min();
210       else
211         SpillCost += MinSpillCost;
212       PBQPRAGraph::RawVector NodeCosts(G.getNodeCosts(NId));
213       NodeCosts[PBQP::RegAlloc::getSpillOptionIdx()] = SpillCost;
214       G.setNodeCosts(NId, std::move(NodeCosts));
215     }
216   }
217 };
218 
219 /// Add interference edges between overlapping vregs.
220 class Interference : public PBQPRAConstraint {
221 private:
222   using AllowedRegVecPtr = const PBQP::RegAlloc::AllowedRegVector *;
223   using IKey = std::pair<AllowedRegVecPtr, AllowedRegVecPtr>;
224   using IMatrixCache = DenseMap<IKey, PBQPRAGraph::MatrixPtr>;
225   using DisjointAllowedRegsCache = DenseSet<IKey>;
226   using IEdgeKey = std::pair<PBQP::GraphBase::NodeId, PBQP::GraphBase::NodeId>;
227   using IEdgeCache = DenseSet<IEdgeKey>;
228 
229   bool haveDisjointAllowedRegs(const PBQPRAGraph &G, PBQPRAGraph::NodeId NId,
230                                PBQPRAGraph::NodeId MId,
231                                const DisjointAllowedRegsCache &D) const {
232     const auto *NRegs = &G.getNodeMetadata(NId).getAllowedRegs();
233     const auto *MRegs = &G.getNodeMetadata(MId).getAllowedRegs();
234 
235     if (NRegs == MRegs)
236       return false;
237 
238     if (NRegs < MRegs)
239       return D.count(IKey(NRegs, MRegs)) > 0;
240 
241     return D.count(IKey(MRegs, NRegs)) > 0;
242   }
243 
244   void setDisjointAllowedRegs(const PBQPRAGraph &G, PBQPRAGraph::NodeId NId,
245                               PBQPRAGraph::NodeId MId,
246                               DisjointAllowedRegsCache &D) {
247     const auto *NRegs = &G.getNodeMetadata(NId).getAllowedRegs();
248     const auto *MRegs = &G.getNodeMetadata(MId).getAllowedRegs();
249 
250     assert(NRegs != MRegs && "AllowedRegs can not be disjoint with itself");
251 
252     if (NRegs < MRegs)
253       D.insert(IKey(NRegs, MRegs));
254     else
255       D.insert(IKey(MRegs, NRegs));
256   }
257 
258   // Holds (Interval, CurrentSegmentID, and NodeId). The first two are required
259   // for the fast interference graph construction algorithm. The last is there
260   // to save us from looking up node ids via the VRegToNode map in the graph
261   // metadata.
262   using IntervalInfo =
263       std::tuple<LiveInterval*, size_t, PBQP::GraphBase::NodeId>;
264 
265   static SlotIndex getStartPoint(const IntervalInfo &I) {
266     return std::get<0>(I)->segments[std::get<1>(I)].start;
267   }
268 
269   static SlotIndex getEndPoint(const IntervalInfo &I) {
270     return std::get<0>(I)->segments[std::get<1>(I)].end;
271   }
272 
273   static PBQP::GraphBase::NodeId getNodeId(const IntervalInfo &I) {
274     return std::get<2>(I);
275   }
276 
277   static bool lowestStartPoint(const IntervalInfo &I1,
278                                const IntervalInfo &I2) {
279     // Condition reversed because priority queue has the *highest* element at
280     // the front, rather than the lowest.
281     return getStartPoint(I1) > getStartPoint(I2);
282   }
283 
284   static bool lowestEndPoint(const IntervalInfo &I1,
285                              const IntervalInfo &I2) {
286     SlotIndex E1 = getEndPoint(I1);
287     SlotIndex E2 = getEndPoint(I2);
288 
289     if (E1 < E2)
290       return true;
291 
292     if (E1 > E2)
293       return false;
294 
295     // If two intervals end at the same point, we need a way to break the tie or
296     // the set will assume they're actually equal and refuse to insert a
297     // "duplicate". Just compare the vregs - fast and guaranteed unique.
298     return std::get<0>(I1)->reg() < std::get<0>(I2)->reg();
299   }
300 
301   static bool isAtLastSegment(const IntervalInfo &I) {
302     return std::get<1>(I) == std::get<0>(I)->size() - 1;
303   }
304 
305   static IntervalInfo nextSegment(const IntervalInfo &I) {
306     return std::make_tuple(std::get<0>(I), std::get<1>(I) + 1, std::get<2>(I));
307   }
308 
309 public:
310   void apply(PBQPRAGraph &G) override {
311     // The following is loosely based on the linear scan algorithm introduced in
312     // "Linear Scan Register Allocation" by Poletto and Sarkar. This version
313     // isn't linear, because the size of the active set isn't bound by the
314     // number of registers, but rather the size of the largest clique in the
315     // graph. Still, we expect this to be better than N^2.
316     LiveIntervals &LIS = G.getMetadata().LIS;
317 
318     // Interferenc matrices are incredibly regular - they're only a function of
319     // the allowed sets, so we cache them to avoid the overhead of constructing
320     // and uniquing them.
321     IMatrixCache C;
322 
323     // Finding an edge is expensive in the worst case (O(max_clique(G))). So
324     // cache locally edges we have already seen.
325     IEdgeCache EC;
326 
327     // Cache known disjoint allowed registers pairs
328     DisjointAllowedRegsCache D;
329 
330     using IntervalSet = std::set<IntervalInfo, decltype(&lowestEndPoint)>;
331     using IntervalQueue =
332         std::priority_queue<IntervalInfo, std::vector<IntervalInfo>,
333                             decltype(&lowestStartPoint)>;
334     IntervalSet Active(lowestEndPoint);
335     IntervalQueue Inactive(lowestStartPoint);
336 
337     // Start by building the inactive set.
338     for (auto NId : G.nodeIds()) {
339       Register VReg = G.getNodeMetadata(NId).getVReg();
340       LiveInterval &LI = LIS.getInterval(VReg);
341       assert(!LI.empty() && "PBQP graph contains node for empty interval");
342       Inactive.push(std::make_tuple(&LI, 0, NId));
343     }
344 
345     while (!Inactive.empty()) {
346       // Tentatively grab the "next" interval - this choice may be overriden
347       // below.
348       IntervalInfo Cur = Inactive.top();
349 
350       // Retire any active intervals that end before Cur starts.
351       IntervalSet::iterator RetireItr = Active.begin();
352       while (RetireItr != Active.end() &&
353              (getEndPoint(*RetireItr) <= getStartPoint(Cur))) {
354         // If this interval has subsequent segments, add the next one to the
355         // inactive list.
356         if (!isAtLastSegment(*RetireItr))
357           Inactive.push(nextSegment(*RetireItr));
358 
359         ++RetireItr;
360       }
361       Active.erase(Active.begin(), RetireItr);
362 
363       // One of the newly retired segments may actually start before the
364       // Cur segment, so re-grab the front of the inactive list.
365       Cur = Inactive.top();
366       Inactive.pop();
367 
368       // At this point we know that Cur overlaps all active intervals. Add the
369       // interference edges.
370       PBQP::GraphBase::NodeId NId = getNodeId(Cur);
371       for (const auto &A : Active) {
372         PBQP::GraphBase::NodeId MId = getNodeId(A);
373 
374         // Do not add an edge when the nodes' allowed registers do not
375         // intersect: there is obviously no interference.
376         if (haveDisjointAllowedRegs(G, NId, MId, D))
377           continue;
378 
379         // Check that we haven't already added this edge
380         IEdgeKey EK(std::min(NId, MId), std::max(NId, MId));
381         if (EC.count(EK))
382           continue;
383 
384         // This is a new edge - add it to the graph.
385         if (!createInterferenceEdge(G, NId, MId, C))
386           setDisjointAllowedRegs(G, NId, MId, D);
387         else
388           EC.insert(EK);
389       }
390 
391       // Finally, add Cur to the Active set.
392       Active.insert(Cur);
393     }
394   }
395 
396 private:
397   // Create an Interference edge and add it to the graph, unless it is
398   // a null matrix, meaning the nodes' allowed registers do not have any
399   // interference. This case occurs frequently between integer and floating
400   // point registers for example.
401   // return true iff both nodes interferes.
402   bool createInterferenceEdge(PBQPRAGraph &G,
403                               PBQPRAGraph::NodeId NId, PBQPRAGraph::NodeId MId,
404                               IMatrixCache &C) {
405     const TargetRegisterInfo &TRI =
406         *G.getMetadata().MF.getSubtarget().getRegisterInfo();
407     const auto &NRegs = G.getNodeMetadata(NId).getAllowedRegs();
408     const auto &MRegs = G.getNodeMetadata(MId).getAllowedRegs();
409 
410     // Try looking the edge costs up in the IMatrixCache first.
411     IKey K(&NRegs, &MRegs);
412     IMatrixCache::iterator I = C.find(K);
413     if (I != C.end()) {
414       G.addEdgeBypassingCostAllocator(NId, MId, I->second);
415       return true;
416     }
417 
418     PBQPRAGraph::RawMatrix M(NRegs.size() + 1, MRegs.size() + 1, 0);
419     bool NodesInterfere = false;
420     for (unsigned I = 0; I != NRegs.size(); ++I) {
421       MCRegister PRegN = NRegs[I];
422       for (unsigned J = 0; J != MRegs.size(); ++J) {
423         MCRegister PRegM = MRegs[J];
424         if (TRI.regsOverlap(PRegN, PRegM)) {
425           M[I + 1][J + 1] = std::numeric_limits<PBQP::PBQPNum>::infinity();
426           NodesInterfere = true;
427         }
428       }
429     }
430 
431     if (!NodesInterfere)
432       return false;
433 
434     PBQPRAGraph::EdgeId EId = G.addEdge(NId, MId, std::move(M));
435     C[K] = G.getEdgeCostsPtr(EId);
436 
437     return true;
438   }
439 };
440 
441 class Coalescing : public PBQPRAConstraint {
442 public:
443   void apply(PBQPRAGraph &G) override {
444     MachineFunction &MF = G.getMetadata().MF;
445     MachineBlockFrequencyInfo &MBFI = G.getMetadata().MBFI;
446     CoalescerPair CP(*MF.getSubtarget().getRegisterInfo());
447 
448     // Scan the machine function and add a coalescing cost whenever CoalescerPair
449     // gives the Ok.
450     for (const auto &MBB : MF) {
451       for (const auto &MI : MBB) {
452         // Skip not-coalescable or already coalesced copies.
453         if (!CP.setRegisters(&MI) || CP.getSrcReg() == CP.getDstReg())
454           continue;
455 
456         Register DstReg = CP.getDstReg();
457         Register SrcReg = CP.getSrcReg();
458 
459         PBQP::PBQPNum CBenefit = MBFI.getBlockFreqRelativeToEntryBlock(&MBB);
460 
461         if (CP.isPhys()) {
462           if (!MF.getRegInfo().isAllocatable(DstReg))
463             continue;
464 
465           PBQPRAGraph::NodeId NId = G.getMetadata().getNodeIdForVReg(SrcReg);
466 
467           const PBQPRAGraph::NodeMetadata::AllowedRegVector &Allowed =
468             G.getNodeMetadata(NId).getAllowedRegs();
469 
470           unsigned PRegOpt = 0;
471           while (PRegOpt < Allowed.size() && Allowed[PRegOpt].id() != DstReg)
472             ++PRegOpt;
473 
474           if (PRegOpt < Allowed.size()) {
475             PBQPRAGraph::RawVector NewCosts(G.getNodeCosts(NId));
476             NewCosts[PRegOpt + 1] -= CBenefit;
477             G.setNodeCosts(NId, std::move(NewCosts));
478           }
479         } else {
480           PBQPRAGraph::NodeId N1Id = G.getMetadata().getNodeIdForVReg(DstReg);
481           PBQPRAGraph::NodeId N2Id = G.getMetadata().getNodeIdForVReg(SrcReg);
482           const PBQPRAGraph::NodeMetadata::AllowedRegVector *Allowed1 =
483             &G.getNodeMetadata(N1Id).getAllowedRegs();
484           const PBQPRAGraph::NodeMetadata::AllowedRegVector *Allowed2 =
485             &G.getNodeMetadata(N2Id).getAllowedRegs();
486 
487           PBQPRAGraph::EdgeId EId = G.findEdge(N1Id, N2Id);
488           if (EId == G.invalidEdgeId()) {
489             PBQPRAGraph::RawMatrix Costs(Allowed1->size() + 1,
490                                          Allowed2->size() + 1, 0);
491             addVirtRegCoalesce(Costs, *Allowed1, *Allowed2, CBenefit);
492             G.addEdge(N1Id, N2Id, std::move(Costs));
493           } else {
494             if (G.getEdgeNode1Id(EId) == N2Id) {
495               std::swap(N1Id, N2Id);
496               std::swap(Allowed1, Allowed2);
497             }
498             PBQPRAGraph::RawMatrix Costs(G.getEdgeCosts(EId));
499             addVirtRegCoalesce(Costs, *Allowed1, *Allowed2, CBenefit);
500             G.updateEdgeCosts(EId, std::move(Costs));
501           }
502         }
503       }
504     }
505   }
506 
507 private:
508   void addVirtRegCoalesce(
509                     PBQPRAGraph::RawMatrix &CostMat,
510                     const PBQPRAGraph::NodeMetadata::AllowedRegVector &Allowed1,
511                     const PBQPRAGraph::NodeMetadata::AllowedRegVector &Allowed2,
512                     PBQP::PBQPNum Benefit) {
513     assert(CostMat.getRows() == Allowed1.size() + 1 && "Size mismatch.");
514     assert(CostMat.getCols() == Allowed2.size() + 1 && "Size mismatch.");
515     for (unsigned I = 0; I != Allowed1.size(); ++I) {
516       MCRegister PReg1 = Allowed1[I];
517       for (unsigned J = 0; J != Allowed2.size(); ++J) {
518         MCRegister PReg2 = Allowed2[J];
519         if (PReg1 == PReg2)
520           CostMat[I + 1][J + 1] -= Benefit;
521       }
522     }
523   }
524 };
525 
526 /// PBQP-specific implementation of weight normalization.
527 class PBQPVirtRegAuxInfo final : public VirtRegAuxInfo {
528   float normalize(float UseDefFreq, unsigned Size, unsigned NumInstr) override {
529     // All intervals have a spill weight that is mostly proportional to the
530     // number of uses, with uses in loops having a bigger weight.
531     return NumInstr * VirtRegAuxInfo::normalize(UseDefFreq, Size, 1);
532   }
533 
534 public:
535   PBQPVirtRegAuxInfo(MachineFunction &MF, LiveIntervals &LIS, VirtRegMap &VRM,
536                      const MachineLoopInfo &Loops,
537                      const MachineBlockFrequencyInfo &MBFI)
538       : VirtRegAuxInfo(MF, LIS, VRM, Loops, MBFI) {}
539 };
540 } // end anonymous namespace
541 
542 // Out-of-line destructor/anchor for PBQPRAConstraint.
543 PBQPRAConstraint::~PBQPRAConstraint() = default;
544 
545 void PBQPRAConstraint::anchor() {}
546 
547 void PBQPRAConstraintList::anchor() {}
548 
549 void RegAllocPBQP::getAnalysisUsage(AnalysisUsage &au) const {
550   au.setPreservesCFG();
551   au.addRequired<AAResultsWrapperPass>();
552   au.addPreserved<AAResultsWrapperPass>();
553   au.addRequired<SlotIndexes>();
554   au.addPreserved<SlotIndexes>();
555   au.addRequired<LiveIntervals>();
556   au.addPreserved<LiveIntervals>();
557   //au.addRequiredID(SplitCriticalEdgesID);
558   if (customPassID)
559     au.addRequiredID(*customPassID);
560   au.addRequired<LiveStacks>();
561   au.addPreserved<LiveStacks>();
562   au.addRequired<MachineBlockFrequencyInfo>();
563   au.addPreserved<MachineBlockFrequencyInfo>();
564   au.addRequired<MachineLoopInfo>();
565   au.addPreserved<MachineLoopInfo>();
566   au.addRequired<MachineDominatorTree>();
567   au.addPreserved<MachineDominatorTree>();
568   au.addRequired<VirtRegMap>();
569   au.addPreserved<VirtRegMap>();
570   MachineFunctionPass::getAnalysisUsage(au);
571 }
572 
573 void RegAllocPBQP::findVRegIntervalsToAlloc(const MachineFunction &MF,
574                                             LiveIntervals &LIS) {
575   const MachineRegisterInfo &MRI = MF.getRegInfo();
576 
577   // Iterate over all live ranges.
578   for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
579     Register Reg = Register::index2VirtReg(I);
580     if (MRI.reg_nodbg_empty(Reg))
581       continue;
582     VRegsToAlloc.insert(Reg);
583   }
584 }
585 
586 static bool isACalleeSavedRegister(MCRegister Reg,
587                                    const TargetRegisterInfo &TRI,
588                                    const MachineFunction &MF) {
589   const MCPhysReg *CSR = MF.getRegInfo().getCalleeSavedRegs();
590   for (unsigned i = 0; CSR[i] != 0; ++i)
591     if (TRI.regsOverlap(Reg, CSR[i]))
592       return true;
593   return false;
594 }
595 
596 void RegAllocPBQP::initializeGraph(PBQPRAGraph &G, VirtRegMap &VRM,
597                                    Spiller &VRegSpiller) {
598   MachineFunction &MF = G.getMetadata().MF;
599 
600   LiveIntervals &LIS = G.getMetadata().LIS;
601   const MachineRegisterInfo &MRI = G.getMetadata().MF.getRegInfo();
602   const TargetRegisterInfo &TRI =
603       *G.getMetadata().MF.getSubtarget().getRegisterInfo();
604 
605   std::vector<Register> Worklist(VRegsToAlloc.begin(), VRegsToAlloc.end());
606 
607   std::map<Register, std::vector<MCRegister>> VRegAllowedMap;
608 
609   while (!Worklist.empty()) {
610     Register VReg = Worklist.back();
611     Worklist.pop_back();
612 
613     LiveInterval &VRegLI = LIS.getInterval(VReg);
614 
615     // If this is an empty interval move it to the EmptyIntervalVRegs set then
616     // continue.
617     if (VRegLI.empty()) {
618       EmptyIntervalVRegs.insert(VRegLI.reg());
619       VRegsToAlloc.erase(VRegLI.reg());
620       continue;
621     }
622 
623     const TargetRegisterClass *TRC = MRI.getRegClass(VReg);
624 
625     // Record any overlaps with regmask operands.
626     BitVector RegMaskOverlaps;
627     LIS.checkRegMaskInterference(VRegLI, RegMaskOverlaps);
628 
629     // Compute an initial allowed set for the current vreg.
630     std::vector<MCRegister> VRegAllowed;
631     ArrayRef<MCPhysReg> RawPRegOrder = TRC->getRawAllocationOrder(MF);
632     for (unsigned I = 0; I != RawPRegOrder.size(); ++I) {
633       MCRegister PReg(RawPRegOrder[I]);
634       if (MRI.isReserved(PReg))
635         continue;
636 
637       // vregLI crosses a regmask operand that clobbers preg.
638       if (!RegMaskOverlaps.empty() && !RegMaskOverlaps.test(PReg))
639         continue;
640 
641       // vregLI overlaps fixed regunit interference.
642       bool Interference = false;
643       for (MCRegUnitIterator Units(PReg, &TRI); Units.isValid(); ++Units) {
644         if (VRegLI.overlaps(LIS.getRegUnit(*Units))) {
645           Interference = true;
646           break;
647         }
648       }
649       if (Interference)
650         continue;
651 
652       // preg is usable for this virtual register.
653       VRegAllowed.push_back(PReg);
654     }
655 
656     // Check for vregs that have no allowed registers. These should be
657     // pre-spilled and the new vregs added to the worklist.
658     if (VRegAllowed.empty()) {
659       SmallVector<Register, 8> NewVRegs;
660       spillVReg(VReg, NewVRegs, MF, LIS, VRM, VRegSpiller);
661       Worklist.insert(Worklist.end(), NewVRegs.begin(), NewVRegs.end());
662       continue;
663     } else
664       VRegAllowedMap[VReg] = std::move(VRegAllowed);
665   }
666 
667   for (auto &KV : VRegAllowedMap) {
668     auto VReg = KV.first;
669 
670     // Move empty intervals to the EmptyIntervalVReg set.
671     if (LIS.getInterval(VReg).empty()) {
672       EmptyIntervalVRegs.insert(VReg);
673       VRegsToAlloc.erase(VReg);
674       continue;
675     }
676 
677     auto &VRegAllowed = KV.second;
678 
679     PBQPRAGraph::RawVector NodeCosts(VRegAllowed.size() + 1, 0);
680 
681     // Tweak cost of callee saved registers, as using then force spilling and
682     // restoring them. This would only happen in the prologue / epilogue though.
683     for (unsigned i = 0; i != VRegAllowed.size(); ++i)
684       if (isACalleeSavedRegister(VRegAllowed[i], TRI, MF))
685         NodeCosts[1 + i] += 1.0;
686 
687     PBQPRAGraph::NodeId NId = G.addNode(std::move(NodeCosts));
688     G.getNodeMetadata(NId).setVReg(VReg);
689     G.getNodeMetadata(NId).setAllowedRegs(
690       G.getMetadata().getAllowedRegs(std::move(VRegAllowed)));
691     G.getMetadata().setNodeIdForVReg(VReg, NId);
692   }
693 }
694 
695 void RegAllocPBQP::spillVReg(Register VReg,
696                              SmallVectorImpl<Register> &NewIntervals,
697                              MachineFunction &MF, LiveIntervals &LIS,
698                              VirtRegMap &VRM, Spiller &VRegSpiller) {
699   VRegsToAlloc.erase(VReg);
700   LiveRangeEdit LRE(&LIS.getInterval(VReg), NewIntervals, MF, LIS, &VRM,
701                     nullptr, &DeadRemats);
702   VRegSpiller.spill(LRE);
703 
704   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
705   (void)TRI;
706   LLVM_DEBUG(dbgs() << "VREG " << printReg(VReg, &TRI) << " -> SPILLED (Cost: "
707                     << LRE.getParent().weight() << ", New vregs: ");
708 
709   // Copy any newly inserted live intervals into the list of regs to
710   // allocate.
711   for (LiveRangeEdit::iterator I = LRE.begin(), E = LRE.end();
712        I != E; ++I) {
713     const LiveInterval &LI = LIS.getInterval(*I);
714     assert(!LI.empty() && "Empty spill range.");
715     LLVM_DEBUG(dbgs() << printReg(LI.reg(), &TRI) << " ");
716     VRegsToAlloc.insert(LI.reg());
717   }
718 
719   LLVM_DEBUG(dbgs() << ")\n");
720 }
721 
722 bool RegAllocPBQP::mapPBQPToRegAlloc(const PBQPRAGraph &G,
723                                      const PBQP::Solution &Solution,
724                                      VirtRegMap &VRM,
725                                      Spiller &VRegSpiller) {
726   MachineFunction &MF = G.getMetadata().MF;
727   LiveIntervals &LIS = G.getMetadata().LIS;
728   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
729   (void)TRI;
730 
731   // Set to true if we have any spills
732   bool AnotherRoundNeeded = false;
733 
734   // Clear the existing allocation.
735   VRM.clearAllVirt();
736 
737   // Iterate over the nodes mapping the PBQP solution to a register
738   // assignment.
739   for (auto NId : G.nodeIds()) {
740     Register VReg = G.getNodeMetadata(NId).getVReg();
741     unsigned AllocOpt = Solution.getSelection(NId);
742 
743     if (AllocOpt != PBQP::RegAlloc::getSpillOptionIdx()) {
744       MCRegister PReg = G.getNodeMetadata(NId).getAllowedRegs()[AllocOpt - 1];
745       LLVM_DEBUG(dbgs() << "VREG " << printReg(VReg, &TRI) << " -> "
746                         << TRI.getName(PReg) << "\n");
747       assert(PReg != 0 && "Invalid preg selected.");
748       VRM.assignVirt2Phys(VReg, PReg);
749     } else {
750       // Spill VReg. If this introduces new intervals we'll need another round
751       // of allocation.
752       SmallVector<Register, 8> NewVRegs;
753       spillVReg(VReg, NewVRegs, MF, LIS, VRM, VRegSpiller);
754       AnotherRoundNeeded |= !NewVRegs.empty();
755     }
756   }
757 
758   return !AnotherRoundNeeded;
759 }
760 
761 void RegAllocPBQP::finalizeAlloc(MachineFunction &MF,
762                                  LiveIntervals &LIS,
763                                  VirtRegMap &VRM) const {
764   MachineRegisterInfo &MRI = MF.getRegInfo();
765 
766   // First allocate registers for the empty intervals.
767   for (RegSet::const_iterator
768          I = EmptyIntervalVRegs.begin(), E = EmptyIntervalVRegs.end();
769          I != E; ++I) {
770     LiveInterval &LI = LIS.getInterval(*I);
771 
772     Register PReg = MRI.getSimpleHint(LI.reg());
773 
774     if (PReg == 0) {
775       const TargetRegisterClass &RC = *MRI.getRegClass(LI.reg());
776       const ArrayRef<MCPhysReg> RawPRegOrder = RC.getRawAllocationOrder(MF);
777       for (unsigned CandidateReg : RawPRegOrder) {
778         if (!VRM.getRegInfo().isReserved(CandidateReg)) {
779           PReg = CandidateReg;
780           break;
781         }
782       }
783       assert(PReg &&
784              "No un-reserved physical registers in this register class");
785     }
786 
787     VRM.assignVirt2Phys(LI.reg(), PReg);
788   }
789 }
790 
791 void RegAllocPBQP::postOptimization(Spiller &VRegSpiller, LiveIntervals &LIS) {
792   VRegSpiller.postOptimization();
793   /// Remove dead defs because of rematerialization.
794   for (auto DeadInst : DeadRemats) {
795     LIS.RemoveMachineInstrFromMaps(*DeadInst);
796     DeadInst->eraseFromParent();
797   }
798   DeadRemats.clear();
799 }
800 
801 bool RegAllocPBQP::runOnMachineFunction(MachineFunction &MF) {
802   LiveIntervals &LIS = getAnalysis<LiveIntervals>();
803   MachineBlockFrequencyInfo &MBFI =
804     getAnalysis<MachineBlockFrequencyInfo>();
805 
806   VirtRegMap &VRM = getAnalysis<VirtRegMap>();
807 
808   PBQPVirtRegAuxInfo VRAI(MF, LIS, VRM, getAnalysis<MachineLoopInfo>(), MBFI);
809   VRAI.calculateSpillWeightsAndHints();
810 
811   std::unique_ptr<Spiller> VRegSpiller(createInlineSpiller(*this, MF, VRM));
812 
813   MF.getRegInfo().freezeReservedRegs(MF);
814 
815   LLVM_DEBUG(dbgs() << "PBQP Register Allocating for " << MF.getName() << "\n");
816 
817   // Allocator main loop:
818   //
819   // * Map current regalloc problem to a PBQP problem
820   // * Solve the PBQP problem
821   // * Map the solution back to a register allocation
822   // * Spill if necessary
823   //
824   // This process is continued till no more spills are generated.
825 
826   // Find the vreg intervals in need of allocation.
827   findVRegIntervalsToAlloc(MF, LIS);
828 
829 #ifndef NDEBUG
830   const Function &F = MF.getFunction();
831   std::string FullyQualifiedName =
832     F.getParent()->getModuleIdentifier() + "." + F.getName().str();
833 #endif
834 
835   // If there are non-empty intervals allocate them using pbqp.
836   if (!VRegsToAlloc.empty()) {
837     const TargetSubtargetInfo &Subtarget = MF.getSubtarget();
838     std::unique_ptr<PBQPRAConstraintList> ConstraintsRoot =
839       std::make_unique<PBQPRAConstraintList>();
840     ConstraintsRoot->addConstraint(std::make_unique<SpillCosts>());
841     ConstraintsRoot->addConstraint(std::make_unique<Interference>());
842     if (PBQPCoalescing)
843       ConstraintsRoot->addConstraint(std::make_unique<Coalescing>());
844     ConstraintsRoot->addConstraint(Subtarget.getCustomPBQPConstraints());
845 
846     bool PBQPAllocComplete = false;
847     unsigned Round = 0;
848 
849     while (!PBQPAllocComplete) {
850       LLVM_DEBUG(dbgs() << "  PBQP Regalloc round " << Round << ":\n");
851 
852       PBQPRAGraph G(PBQPRAGraph::GraphMetadata(MF, LIS, MBFI));
853       initializeGraph(G, VRM, *VRegSpiller);
854       ConstraintsRoot->apply(G);
855 
856 #ifndef NDEBUG
857       if (PBQPDumpGraphs) {
858         std::ostringstream RS;
859         RS << Round;
860         std::string GraphFileName = FullyQualifiedName + "." + RS.str() +
861                                     ".pbqpgraph";
862         std::error_code EC;
863         raw_fd_ostream OS(GraphFileName, EC, sys::fs::OF_Text);
864         LLVM_DEBUG(dbgs() << "Dumping graph for round " << Round << " to \""
865                           << GraphFileName << "\"\n");
866         G.dump(OS);
867       }
868 #endif
869 
870       PBQP::Solution Solution = PBQP::RegAlloc::solve(G);
871       PBQPAllocComplete = mapPBQPToRegAlloc(G, Solution, VRM, *VRegSpiller);
872       ++Round;
873     }
874   }
875 
876   // Finalise allocation, allocate empty ranges.
877   finalizeAlloc(MF, LIS, VRM);
878   postOptimization(*VRegSpiller, LIS);
879   VRegsToAlloc.clear();
880   EmptyIntervalVRegs.clear();
881 
882   LLVM_DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << VRM << "\n");
883 
884   return true;
885 }
886 
887 /// Create Printable object for node and register info.
888 static Printable PrintNodeInfo(PBQP::RegAlloc::PBQPRAGraph::NodeId NId,
889                                const PBQP::RegAlloc::PBQPRAGraph &G) {
890   return Printable([NId, &G](raw_ostream &OS) {
891     const MachineRegisterInfo &MRI = G.getMetadata().MF.getRegInfo();
892     const TargetRegisterInfo *TRI = MRI.getTargetRegisterInfo();
893     Register VReg = G.getNodeMetadata(NId).getVReg();
894     const char *RegClassName = TRI->getRegClassName(MRI.getRegClass(VReg));
895     OS << NId << " (" << RegClassName << ':' << printReg(VReg, TRI) << ')';
896   });
897 }
898 
899 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
900 LLVM_DUMP_METHOD void PBQP::RegAlloc::PBQPRAGraph::dump(raw_ostream &OS) const {
901   for (auto NId : nodeIds()) {
902     const Vector &Costs = getNodeCosts(NId);
903     assert(Costs.getLength() != 0 && "Empty vector in graph.");
904     OS << PrintNodeInfo(NId, *this) << ": " << Costs << '\n';
905   }
906   OS << '\n';
907 
908   for (auto EId : edgeIds()) {
909     NodeId N1Id = getEdgeNode1Id(EId);
910     NodeId N2Id = getEdgeNode2Id(EId);
911     assert(N1Id != N2Id && "PBQP graphs should not have self-edges.");
912     const Matrix &M = getEdgeCosts(EId);
913     assert(M.getRows() != 0 && "No rows in matrix.");
914     assert(M.getCols() != 0 && "No cols in matrix.");
915     OS << PrintNodeInfo(N1Id, *this) << ' ' << M.getRows() << " rows / ";
916     OS << PrintNodeInfo(N2Id, *this) << ' ' << M.getCols() << " cols:\n";
917     OS << M << '\n';
918   }
919 }
920 
921 LLVM_DUMP_METHOD void PBQP::RegAlloc::PBQPRAGraph::dump() const {
922   dump(dbgs());
923 }
924 #endif
925 
926 void PBQP::RegAlloc::PBQPRAGraph::printDot(raw_ostream &OS) const {
927   OS << "graph {\n";
928   for (auto NId : nodeIds()) {
929     OS << "  node" << NId << " [ label=\""
930        << PrintNodeInfo(NId, *this) << "\\n"
931        << getNodeCosts(NId) << "\" ]\n";
932   }
933 
934   OS << "  edge [ len=" << nodeIds().size() << " ]\n";
935   for (auto EId : edgeIds()) {
936     OS << "  node" << getEdgeNode1Id(EId)
937        << " -- node" << getEdgeNode2Id(EId)
938        << " [ label=\"";
939     const Matrix &EdgeCosts = getEdgeCosts(EId);
940     for (unsigned i = 0; i < EdgeCosts.getRows(); ++i) {
941       OS << EdgeCosts.getRowAsVector(i) << "\\n";
942     }
943     OS << "\" ]\n";
944   }
945   OS << "}\n";
946 }
947 
948 FunctionPass *llvm::createPBQPRegisterAllocator(char *customPassID) {
949   return new RegAllocPBQP(customPassID);
950 }
951 
952 FunctionPass* llvm::createDefaultPBQPRegisterAllocator() {
953   return createPBQPRegisterAllocator();
954 }
955