SpillPlacement.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. //===-- SpillPlacement.cpp - Optimal Spill Code Placement -----------------===//
  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 implements the spill code placement analysis.
  11. //
  12. // Each edge bundle corresponds to a node in a Hopfield network. Constraints on
  13. // basic blocks are weighted by the block frequency and added to become the node
  14. // bias.
  15. //
  16. // Transparent basic blocks have the variable live through, but don't care if it
  17. // is spilled or in a register. These blocks become connections in the Hopfield
  18. // network, again weighted by block frequency.
  19. //
  20. // The Hopfield network minimizes (possibly locally) its energy function:
  21. //
  22. // E = -sum_n V_n * ( B_n + sum_{n, m linked by b} V_m * F_b )
  23. //
  24. // The energy function represents the expected spill code execution frequency,
  25. // or the cost of spilling. This is a Lyapunov function which never increases
  26. // when a node is updated. It is guaranteed to converge to a local minimum.
  27. //
  28. //===----------------------------------------------------------------------===//
  29. #include "SpillPlacement.h"
  30. #include "llvm/ADT/BitVector.h"
  31. #include "llvm/CodeGen/EdgeBundles.h"
  32. #include "llvm/CodeGen/MachineBasicBlock.h"
  33. #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
  34. #include "llvm/CodeGen/MachineFunction.h"
  35. #include "llvm/CodeGen/MachineLoopInfo.h"
  36. #include "llvm/CodeGen/Passes.h"
  37. #include "llvm/Support/Debug.h"
  38. #include "llvm/Support/Format.h"
  39. #include "llvm/Support/ManagedStatic.h"
  40. using namespace llvm;
  41. #define DEBUG_TYPE "spillplacement"
  42. char SpillPlacement::ID = 0;
  43. INITIALIZE_PASS_BEGIN(SpillPlacement, "spill-code-placement",
  44. "Spill Code Placement Analysis", true, true)
  45. INITIALIZE_PASS_DEPENDENCY(EdgeBundles)
  46. INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
  47. INITIALIZE_PASS_END(SpillPlacement, "spill-code-placement",
  48. "Spill Code Placement Analysis", true, true)
  49. char &llvm::SpillPlacementID = SpillPlacement::ID;
  50. void SpillPlacement::getAnalysisUsage(AnalysisUsage &AU) const {
  51. AU.setPreservesAll();
  52. AU.addRequired<MachineBlockFrequencyInfo>();
  53. AU.addRequiredTransitive<EdgeBundles>();
  54. AU.addRequiredTransitive<MachineLoopInfo>();
  55. MachineFunctionPass::getAnalysisUsage(AU);
  56. }
  57. /// Node - Each edge bundle corresponds to a Hopfield node.
  58. ///
  59. /// The node contains precomputed frequency data that only depends on the CFG,
  60. /// but Bias and Links are computed each time placeSpills is called.
  61. ///
  62. /// The node Value is positive when the variable should be in a register. The
  63. /// value can change when linked nodes change, but convergence is very fast
  64. /// because all weights are positive.
  65. ///
  66. struct SpillPlacement::Node {
  67. /// BiasN - Sum of blocks that prefer a spill.
  68. BlockFrequency BiasN;
  69. /// BiasP - Sum of blocks that prefer a register.
  70. BlockFrequency BiasP;
  71. /// Value - Output value of this node computed from the Bias and links.
  72. /// This is always on of the values {-1, 0, 1}. A positive number means the
  73. /// variable should go in a register through this bundle.
  74. int Value;
  75. typedef SmallVector<std::pair<BlockFrequency, unsigned>, 4> LinkVector;
  76. /// Links - (Weight, BundleNo) for all transparent blocks connecting to other
  77. /// bundles. The weights are all positive block frequencies.
  78. LinkVector Links;
  79. /// SumLinkWeights - Cached sum of the weights of all links + ThresHold.
  80. BlockFrequency SumLinkWeights;
  81. /// preferReg - Return true when this node prefers to be in a register.
  82. bool preferReg() const {
  83. // Undecided nodes (Value==0) go on the stack.
  84. return Value > 0;
  85. }
  86. /// mustSpill - Return True if this node is so biased that it must spill.
  87. bool mustSpill() const {
  88. // We must spill if Bias < -sum(weights) or the MustSpill flag was set.
  89. // BiasN is saturated when MustSpill is set, make sure this still returns
  90. // true when the RHS saturates. Note that SumLinkWeights includes Threshold.
  91. return BiasN >= BiasP + SumLinkWeights;
  92. }
  93. /// clear - Reset per-query data, but preserve frequencies that only depend on
  94. // the CFG.
  95. void clear(const BlockFrequency &Threshold) {
  96. BiasN = BiasP = Value = 0;
  97. SumLinkWeights = Threshold;
  98. Links.clear();
  99. }
  100. /// addLink - Add a link to bundle b with weight w.
  101. void addLink(unsigned b, BlockFrequency w) {
  102. // Update cached sum.
  103. SumLinkWeights += w;
  104. // There can be multiple links to the same bundle, add them up.
  105. for (LinkVector::iterator I = Links.begin(), E = Links.end(); I != E; ++I)
  106. if (I->second == b) {
  107. I->first += w;
  108. return;
  109. }
  110. // This must be the first link to b.
  111. Links.push_back(std::make_pair(w, b));
  112. }
  113. /// addBias - Bias this node.
  114. void addBias(BlockFrequency freq, BorderConstraint direction) {
  115. switch (direction) {
  116. default:
  117. break;
  118. case PrefReg:
  119. BiasP += freq;
  120. break;
  121. case PrefSpill:
  122. BiasN += freq;
  123. break;
  124. case MustSpill:
  125. BiasN = BlockFrequency::getMaxFrequency();
  126. break;
  127. }
  128. }
  129. /// update - Recompute Value from Bias and Links. Return true when node
  130. /// preference changes.
  131. bool update(const Node nodes[], const BlockFrequency &Threshold) {
  132. // Compute the weighted sum of inputs.
  133. BlockFrequency SumN = BiasN;
  134. BlockFrequency SumP = BiasP;
  135. for (LinkVector::iterator I = Links.begin(), E = Links.end(); I != E; ++I) {
  136. if (nodes[I->second].Value == -1)
  137. SumN += I->first;
  138. else if (nodes[I->second].Value == 1)
  139. SumP += I->first;
  140. }
  141. // Each weighted sum is going to be less than the total frequency of the
  142. // bundle. Ideally, we should simply set Value = sign(SumP - SumN), but we
  143. // will add a dead zone around 0 for two reasons:
  144. //
  145. // 1. It avoids arbitrary bias when all links are 0 as is possible during
  146. // initial iterations.
  147. // 2. It helps tame rounding errors when the links nominally sum to 0.
  148. //
  149. bool Before = preferReg();
  150. if (SumN >= SumP + Threshold)
  151. Value = -1;
  152. else if (SumP >= SumN + Threshold)
  153. Value = 1;
  154. else
  155. Value = 0;
  156. return Before != preferReg();
  157. }
  158. };
  159. bool SpillPlacement::runOnMachineFunction(MachineFunction &mf) {
  160. MF = &mf;
  161. bundles = &getAnalysis<EdgeBundles>();
  162. loops = &getAnalysis<MachineLoopInfo>();
  163. assert(!nodes && "Leaking node array");
  164. nodes = new Node[bundles->getNumBundles()];
  165. // Compute total ingoing and outgoing block frequencies for all bundles.
  166. BlockFrequencies.resize(mf.getNumBlockIDs());
  167. MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
  168. setThreshold(MBFI->getEntryFreq());
  169. for (MachineFunction::iterator I = mf.begin(), E = mf.end(); I != E; ++I) {
  170. unsigned Num = I->getNumber();
  171. BlockFrequencies[Num] = MBFI->getBlockFreq(I);
  172. }
  173. // We never change the function.
  174. return false;
  175. }
  176. void SpillPlacement::releaseMemory() {
  177. delete[] nodes;
  178. nodes = nullptr;
  179. }
  180. /// activate - mark node n as active if it wasn't already.
  181. void SpillPlacement::activate(unsigned n) {
  182. if (ActiveNodes->test(n))
  183. return;
  184. ActiveNodes->set(n);
  185. nodes[n].clear(Threshold);
  186. // Very large bundles usually come from big switches, indirect branches,
  187. // landing pads, or loops with many 'continue' statements. It is difficult to
  188. // allocate registers when so many different blocks are involved.
  189. //
  190. // Give a small negative bias to large bundles such that a substantial
  191. // fraction of the connected blocks need to be interested before we consider
  192. // expanding the region through the bundle. This helps compile time by
  193. // limiting the number of blocks visited and the number of links in the
  194. // Hopfield network.
  195. if (bundles->getBlocks(n).size() > 100) {
  196. nodes[n].BiasP = 0;
  197. nodes[n].BiasN = (MBFI->getEntryFreq() / 16);
  198. }
  199. }
  200. /// \brief Set the threshold for a given entry frequency.
  201. ///
  202. /// Set the threshold relative to \c Entry. Since the threshold is used as a
  203. /// bound on the open interval (-Threshold;Threshold), 1 is the minimum
  204. /// threshold.
  205. void SpillPlacement::setThreshold(const BlockFrequency &Entry) {
  206. // Apparently 2 is a good threshold when Entry==2^14, but we need to scale
  207. // it. Divide by 2^13, rounding as appropriate.
  208. uint64_t Freq = Entry.getFrequency();
  209. uint64_t Scaled = (Freq >> 13) + bool(Freq & (1 << 12));
  210. Threshold = std::max(UINT64_C(1), Scaled);
  211. }
  212. /// addConstraints - Compute node biases and weights from a set of constraints.
  213. /// Set a bit in NodeMask for each active node.
  214. void SpillPlacement::addConstraints(ArrayRef<BlockConstraint> LiveBlocks) {
  215. for (ArrayRef<BlockConstraint>::iterator I = LiveBlocks.begin(),
  216. E = LiveBlocks.end(); I != E; ++I) {
  217. BlockFrequency Freq = BlockFrequencies[I->Number];
  218. // Live-in to block?
  219. if (I->Entry != DontCare) {
  220. unsigned ib = bundles->getBundle(I->Number, 0);
  221. activate(ib);
  222. nodes[ib].addBias(Freq, I->Entry);
  223. }
  224. // Live-out from block?
  225. if (I->Exit != DontCare) {
  226. unsigned ob = bundles->getBundle(I->Number, 1);
  227. activate(ob);
  228. nodes[ob].addBias(Freq, I->Exit);
  229. }
  230. }
  231. }
  232. /// addPrefSpill - Same as addConstraints(PrefSpill)
  233. void SpillPlacement::addPrefSpill(ArrayRef<unsigned> Blocks, bool Strong) {
  234. for (ArrayRef<unsigned>::iterator I = Blocks.begin(), E = Blocks.end();
  235. I != E; ++I) {
  236. BlockFrequency Freq = BlockFrequencies[*I];
  237. if (Strong)
  238. Freq += Freq;
  239. unsigned ib = bundles->getBundle(*I, 0);
  240. unsigned ob = bundles->getBundle(*I, 1);
  241. activate(ib);
  242. activate(ob);
  243. nodes[ib].addBias(Freq, PrefSpill);
  244. nodes[ob].addBias(Freq, PrefSpill);
  245. }
  246. }
  247. void SpillPlacement::addLinks(ArrayRef<unsigned> Links) {
  248. for (ArrayRef<unsigned>::iterator I = Links.begin(), E = Links.end(); I != E;
  249. ++I) {
  250. unsigned Number = *I;
  251. unsigned ib = bundles->getBundle(Number, 0);
  252. unsigned ob = bundles->getBundle(Number, 1);
  253. // Ignore self-loops.
  254. if (ib == ob)
  255. continue;
  256. activate(ib);
  257. activate(ob);
  258. if (nodes[ib].Links.empty() && !nodes[ib].mustSpill())
  259. Linked.push_back(ib);
  260. if (nodes[ob].Links.empty() && !nodes[ob].mustSpill())
  261. Linked.push_back(ob);
  262. BlockFrequency Freq = BlockFrequencies[Number];
  263. nodes[ib].addLink(ob, Freq);
  264. nodes[ob].addLink(ib, Freq);
  265. }
  266. }
  267. bool SpillPlacement::scanActiveBundles() {
  268. Linked.clear();
  269. RecentPositive.clear();
  270. for (int n = ActiveNodes->find_first(); n>=0; n = ActiveNodes->find_next(n)) {
  271. nodes[n].update(nodes, Threshold);
  272. // A node that must spill, or a node without any links is not going to
  273. // change its value ever again, so exclude it from iterations.
  274. if (nodes[n].mustSpill())
  275. continue;
  276. if (!nodes[n].Links.empty())
  277. Linked.push_back(n);
  278. if (nodes[n].preferReg())
  279. RecentPositive.push_back(n);
  280. }
  281. return !RecentPositive.empty();
  282. }
  283. /// iterate - Repeatedly update the Hopfield nodes until stability or the
  284. /// maximum number of iterations is reached.
  285. /// @param Linked - Numbers of linked nodes that need updating.
  286. void SpillPlacement::iterate() {
  287. // First update the recently positive nodes. They have likely received new
  288. // negative bias that will turn them off.
  289. while (!RecentPositive.empty())
  290. nodes[RecentPositive.pop_back_val()].update(nodes, Threshold);
  291. if (Linked.empty())
  292. return;
  293. // Run up to 10 iterations. The edge bundle numbering is closely related to
  294. // basic block numbering, so there is a strong tendency towards chains of
  295. // linked nodes with sequential numbers. By scanning the linked nodes
  296. // backwards and forwards, we make it very likely that a single node can
  297. // affect the entire network in a single iteration. That means very fast
  298. // convergence, usually in a single iteration.
  299. for (unsigned iteration = 0; iteration != 10; ++iteration) {
  300. // Scan backwards, skipping the last node when iteration is not zero. When
  301. // iteration is not zero, the last node was just updated.
  302. bool Changed = false;
  303. for (SmallVectorImpl<unsigned>::const_reverse_iterator I =
  304. iteration == 0 ? Linked.rbegin() : std::next(Linked.rbegin()),
  305. E = Linked.rend(); I != E; ++I) {
  306. unsigned n = *I;
  307. if (nodes[n].update(nodes, Threshold)) {
  308. Changed = true;
  309. if (nodes[n].preferReg())
  310. RecentPositive.push_back(n);
  311. }
  312. }
  313. if (!Changed || !RecentPositive.empty())
  314. return;
  315. // Scan forwards, skipping the first node which was just updated.
  316. Changed = false;
  317. for (SmallVectorImpl<unsigned>::const_iterator I =
  318. std::next(Linked.begin()), E = Linked.end(); I != E; ++I) {
  319. unsigned n = *I;
  320. if (nodes[n].update(nodes, Threshold)) {
  321. Changed = true;
  322. if (nodes[n].preferReg())
  323. RecentPositive.push_back(n);
  324. }
  325. }
  326. if (!Changed || !RecentPositive.empty())
  327. return;
  328. }
  329. }
  330. void SpillPlacement::prepare(BitVector &RegBundles) {
  331. Linked.clear();
  332. RecentPositive.clear();
  333. // Reuse RegBundles as our ActiveNodes vector.
  334. ActiveNodes = &RegBundles;
  335. ActiveNodes->clear();
  336. ActiveNodes->resize(bundles->getNumBundles());
  337. }
  338. bool
  339. SpillPlacement::finish() {
  340. assert(ActiveNodes && "Call prepare() first");
  341. // Write preferences back to ActiveNodes.
  342. bool Perfect = true;
  343. for (int n = ActiveNodes->find_first(); n>=0; n = ActiveNodes->find_next(n))
  344. if (!nodes[n].preferReg()) {
  345. ActiveNodes->reset(n);
  346. Perfect = false;
  347. }
  348. ActiveNodes = nullptr;
  349. return Perfect;
  350. }