SafeStackColoring.cpp 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. //===- SafeStackColoring.cpp - SafeStack frame coloring -------------------===//
  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. #include "SafeStackColoring.h"
  9. #include "llvm/ADT/BitVector.h"
  10. #include "llvm/ADT/DenseMap.h"
  11. #include "llvm/ADT/DepthFirstIterator.h"
  12. #include "llvm/ADT/SmallVector.h"
  13. #include "llvm/Config/llvm-config.h"
  14. #include "llvm/IR/BasicBlock.h"
  15. #include "llvm/IR/CFG.h"
  16. #include "llvm/IR/Instruction.h"
  17. #include "llvm/IR/Instructions.h"
  18. #include "llvm/IR/IntrinsicInst.h"
  19. #include "llvm/IR/Intrinsics.h"
  20. #include "llvm/IR/User.h"
  21. #include "llvm/Support/Casting.h"
  22. #include "llvm/Support/CommandLine.h"
  23. #include "llvm/Support/Compiler.h"
  24. #include "llvm/Support/Debug.h"
  25. #include "llvm/Support/raw_ostream.h"
  26. #include <cassert>
  27. #include <tuple>
  28. #include <utility>
  29. using namespace llvm;
  30. using namespace llvm::safestack;
  31. #define DEBUG_TYPE "safestackcoloring"
  32. // Disabled by default due to PR32143.
  33. static cl::opt<bool> ClColoring("safe-stack-coloring",
  34. cl::desc("enable safe stack coloring"),
  35. cl::Hidden, cl::init(false));
  36. const StackColoring::LiveRange &StackColoring::getLiveRange(AllocaInst *AI) {
  37. const auto IT = AllocaNumbering.find(AI);
  38. assert(IT != AllocaNumbering.end());
  39. return LiveRanges[IT->second];
  40. }
  41. bool StackColoring::readMarker(Instruction *I, bool *IsStart) {
  42. if (!I->isLifetimeStartOrEnd())
  43. return false;
  44. auto *II = cast<IntrinsicInst>(I);
  45. *IsStart = II->getIntrinsicID() == Intrinsic::lifetime_start;
  46. return true;
  47. }
  48. void StackColoring::removeAllMarkers() {
  49. for (auto *I : Markers) {
  50. auto *Op = dyn_cast<Instruction>(I->getOperand(1));
  51. I->eraseFromParent();
  52. // Remove the operand bitcast, too, if it has no more uses left.
  53. if (Op && Op->use_empty())
  54. Op->eraseFromParent();
  55. }
  56. }
  57. void StackColoring::collectMarkers() {
  58. InterestingAllocas.resize(NumAllocas);
  59. DenseMap<BasicBlock *, SmallDenseMap<Instruction *, Marker>> BBMarkerSet;
  60. // Compute the set of start/end markers per basic block.
  61. for (unsigned AllocaNo = 0; AllocaNo < NumAllocas; ++AllocaNo) {
  62. AllocaInst *AI = Allocas[AllocaNo];
  63. SmallVector<Instruction *, 8> WorkList;
  64. WorkList.push_back(AI);
  65. while (!WorkList.empty()) {
  66. Instruction *I = WorkList.pop_back_val();
  67. for (User *U : I->users()) {
  68. if (auto *BI = dyn_cast<BitCastInst>(U)) {
  69. WorkList.push_back(BI);
  70. continue;
  71. }
  72. auto *UI = dyn_cast<Instruction>(U);
  73. if (!UI)
  74. continue;
  75. bool IsStart;
  76. if (!readMarker(UI, &IsStart))
  77. continue;
  78. if (IsStart)
  79. InterestingAllocas.set(AllocaNo);
  80. BBMarkerSet[UI->getParent()][UI] = {AllocaNo, IsStart};
  81. Markers.push_back(UI);
  82. }
  83. }
  84. }
  85. // Compute instruction numbering. Only the following instructions are
  86. // considered:
  87. // * Basic block entries
  88. // * Lifetime markers
  89. // For each basic block, compute
  90. // * the list of markers in the instruction order
  91. // * the sets of allocas whose lifetime starts or ends in this BB
  92. LLVM_DEBUG(dbgs() << "Instructions:\n");
  93. unsigned InstNo = 0;
  94. for (BasicBlock *BB : depth_first(&F)) {
  95. LLVM_DEBUG(dbgs() << " " << InstNo << ": BB " << BB->getName() << "\n");
  96. unsigned BBStart = InstNo++;
  97. BlockLifetimeInfo &BlockInfo = BlockLiveness[BB];
  98. BlockInfo.Begin.resize(NumAllocas);
  99. BlockInfo.End.resize(NumAllocas);
  100. BlockInfo.LiveIn.resize(NumAllocas);
  101. BlockInfo.LiveOut.resize(NumAllocas);
  102. auto &BlockMarkerSet = BBMarkerSet[BB];
  103. if (BlockMarkerSet.empty()) {
  104. unsigned BBEnd = InstNo;
  105. BlockInstRange[BB] = std::make_pair(BBStart, BBEnd);
  106. continue;
  107. }
  108. auto ProcessMarker = [&](Instruction *I, const Marker &M) {
  109. LLVM_DEBUG(dbgs() << " " << InstNo << ": "
  110. << (M.IsStart ? "start " : "end ") << M.AllocaNo
  111. << ", " << *I << "\n");
  112. BBMarkers[BB].push_back({InstNo, M});
  113. InstructionNumbering[I] = InstNo++;
  114. if (M.IsStart) {
  115. if (BlockInfo.End.test(M.AllocaNo))
  116. BlockInfo.End.reset(M.AllocaNo);
  117. BlockInfo.Begin.set(M.AllocaNo);
  118. } else {
  119. if (BlockInfo.Begin.test(M.AllocaNo))
  120. BlockInfo.Begin.reset(M.AllocaNo);
  121. BlockInfo.End.set(M.AllocaNo);
  122. }
  123. };
  124. if (BlockMarkerSet.size() == 1) {
  125. ProcessMarker(BlockMarkerSet.begin()->getFirst(),
  126. BlockMarkerSet.begin()->getSecond());
  127. } else {
  128. // Scan the BB to determine the marker order.
  129. for (Instruction &I : *BB) {
  130. auto It = BlockMarkerSet.find(&I);
  131. if (It == BlockMarkerSet.end())
  132. continue;
  133. ProcessMarker(&I, It->getSecond());
  134. }
  135. }
  136. unsigned BBEnd = InstNo;
  137. BlockInstRange[BB] = std::make_pair(BBStart, BBEnd);
  138. }
  139. NumInst = InstNo;
  140. }
  141. void StackColoring::calculateLocalLiveness() {
  142. bool changed = true;
  143. while (changed) {
  144. changed = false;
  145. for (BasicBlock *BB : depth_first(&F)) {
  146. BlockLifetimeInfo &BlockInfo = BlockLiveness[BB];
  147. // Compute LiveIn by unioning together the LiveOut sets of all preds.
  148. BitVector LocalLiveIn;
  149. for (auto *PredBB : predecessors(BB)) {
  150. LivenessMap::const_iterator I = BlockLiveness.find(PredBB);
  151. // If a predecessor is unreachable, ignore it.
  152. if (I == BlockLiveness.end())
  153. continue;
  154. LocalLiveIn |= I->second.LiveOut;
  155. }
  156. // Compute LiveOut by subtracting out lifetimes that end in this
  157. // block, then adding in lifetimes that begin in this block. If
  158. // we have both BEGIN and END markers in the same basic block
  159. // then we know that the BEGIN marker comes after the END,
  160. // because we already handle the case where the BEGIN comes
  161. // before the END when collecting the markers (and building the
  162. // BEGIN/END vectors).
  163. BitVector LocalLiveOut = LocalLiveIn;
  164. LocalLiveOut.reset(BlockInfo.End);
  165. LocalLiveOut |= BlockInfo.Begin;
  166. // Update block LiveIn set, noting whether it has changed.
  167. if (LocalLiveIn.test(BlockInfo.LiveIn)) {
  168. changed = true;
  169. BlockInfo.LiveIn |= LocalLiveIn;
  170. }
  171. // Update block LiveOut set, noting whether it has changed.
  172. if (LocalLiveOut.test(BlockInfo.LiveOut)) {
  173. changed = true;
  174. BlockInfo.LiveOut |= LocalLiveOut;
  175. }
  176. }
  177. } // while changed.
  178. }
  179. void StackColoring::calculateLiveIntervals() {
  180. for (auto IT : BlockLiveness) {
  181. BasicBlock *BB = IT.getFirst();
  182. BlockLifetimeInfo &BlockInfo = IT.getSecond();
  183. unsigned BBStart, BBEnd;
  184. std::tie(BBStart, BBEnd) = BlockInstRange[BB];
  185. BitVector Started, Ended;
  186. Started.resize(NumAllocas);
  187. Ended.resize(NumAllocas);
  188. SmallVector<unsigned, 8> Start;
  189. Start.resize(NumAllocas);
  190. // LiveIn ranges start at the first instruction.
  191. for (unsigned AllocaNo = 0; AllocaNo < NumAllocas; ++AllocaNo) {
  192. if (BlockInfo.LiveIn.test(AllocaNo)) {
  193. Started.set(AllocaNo);
  194. Start[AllocaNo] = BBStart;
  195. }
  196. }
  197. for (auto &It : BBMarkers[BB]) {
  198. unsigned InstNo = It.first;
  199. bool IsStart = It.second.IsStart;
  200. unsigned AllocaNo = It.second.AllocaNo;
  201. if (IsStart) {
  202. assert(!Started.test(AllocaNo) || Start[AllocaNo] == BBStart);
  203. if (!Started.test(AllocaNo)) {
  204. Started.set(AllocaNo);
  205. Ended.reset(AllocaNo);
  206. Start[AllocaNo] = InstNo;
  207. }
  208. } else {
  209. assert(!Ended.test(AllocaNo));
  210. if (Started.test(AllocaNo)) {
  211. LiveRanges[AllocaNo].AddRange(Start[AllocaNo], InstNo);
  212. Started.reset(AllocaNo);
  213. }
  214. Ended.set(AllocaNo);
  215. }
  216. }
  217. for (unsigned AllocaNo = 0; AllocaNo < NumAllocas; ++AllocaNo)
  218. if (Started.test(AllocaNo))
  219. LiveRanges[AllocaNo].AddRange(Start[AllocaNo], BBEnd);
  220. }
  221. }
  222. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  223. LLVM_DUMP_METHOD void StackColoring::dumpAllocas() {
  224. dbgs() << "Allocas:\n";
  225. for (unsigned AllocaNo = 0; AllocaNo < NumAllocas; ++AllocaNo)
  226. dbgs() << " " << AllocaNo << ": " << *Allocas[AllocaNo] << "\n";
  227. }
  228. LLVM_DUMP_METHOD void StackColoring::dumpBlockLiveness() {
  229. dbgs() << "Block liveness:\n";
  230. for (auto IT : BlockLiveness) {
  231. BasicBlock *BB = IT.getFirst();
  232. BlockLifetimeInfo &BlockInfo = BlockLiveness[BB];
  233. auto BlockRange = BlockInstRange[BB];
  234. dbgs() << " BB [" << BlockRange.first << ", " << BlockRange.second
  235. << "): begin " << BlockInfo.Begin << ", end " << BlockInfo.End
  236. << ", livein " << BlockInfo.LiveIn << ", liveout "
  237. << BlockInfo.LiveOut << "\n";
  238. }
  239. }
  240. LLVM_DUMP_METHOD void StackColoring::dumpLiveRanges() {
  241. dbgs() << "Alloca liveness:\n";
  242. for (unsigned AllocaNo = 0; AllocaNo < NumAllocas; ++AllocaNo) {
  243. LiveRange &Range = LiveRanges[AllocaNo];
  244. dbgs() << " " << AllocaNo << ": " << Range << "\n";
  245. }
  246. }
  247. #endif
  248. void StackColoring::run() {
  249. LLVM_DEBUG(dumpAllocas());
  250. for (unsigned I = 0; I < NumAllocas; ++I)
  251. AllocaNumbering[Allocas[I]] = I;
  252. LiveRanges.resize(NumAllocas);
  253. collectMarkers();
  254. if (!ClColoring) {
  255. for (auto &R : LiveRanges) {
  256. R.SetMaximum(1);
  257. R.AddRange(0, 1);
  258. }
  259. return;
  260. }
  261. for (auto &R : LiveRanges)
  262. R.SetMaximum(NumInst);
  263. for (unsigned I = 0; I < NumAllocas; ++I)
  264. if (!InterestingAllocas.test(I))
  265. LiveRanges[I] = getFullLiveRange();
  266. calculateLocalLiveness();
  267. LLVM_DEBUG(dumpBlockLiveness());
  268. calculateLiveIntervals();
  269. LLVM_DEBUG(dumpLiveRanges());
  270. }