SpillPlacement.cpp 13 KB

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