RegAllocPBQP.cpp 33 KB

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