SafeStackColoring.cpp 9.6 KB

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