StackLifetime.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  1. //===- StackLifetime.cpp - Alloca Lifetime Analysis -----------------------===//
  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 "llvm/Analysis/StackLifetime.h"
  9. #include "llvm/ADT/DepthFirstIterator.h"
  10. #include "llvm/ADT/STLExtras.h"
  11. #include "llvm/ADT/SmallVector.h"
  12. #include "llvm/ADT/StringExtras.h"
  13. #include "llvm/Analysis/ValueTracking.h"
  14. #include "llvm/Config/llvm-config.h"
  15. #include "llvm/IR/AssemblyAnnotationWriter.h"
  16. #include "llvm/IR/BasicBlock.h"
  17. #include "llvm/IR/CFG.h"
  18. #include "llvm/IR/InstIterator.h"
  19. #include "llvm/IR/Instructions.h"
  20. #include "llvm/IR/IntrinsicInst.h"
  21. #include "llvm/IR/Intrinsics.h"
  22. #include "llvm/IR/User.h"
  23. #include "llvm/IR/Value.h"
  24. #include "llvm/Pass.h"
  25. #include "llvm/Support/Casting.h"
  26. #include "llvm/Support/CommandLine.h"
  27. #include "llvm/Support/Compiler.h"
  28. #include "llvm/Support/Debug.h"
  29. #include "llvm/Support/FormattedStream.h"
  30. #include <algorithm>
  31. #include <memory>
  32. #include <tuple>
  33. using namespace llvm;
  34. #define DEBUG_TYPE "stack-lifetime"
  35. const StackLifetime::LiveRange &
  36. StackLifetime::getLiveRange(const AllocaInst *AI) const {
  37. const auto IT = AllocaNumbering.find(AI);
  38. assert(IT != AllocaNumbering.end());
  39. return LiveRanges[IT->second];
  40. }
  41. bool StackLifetime::isReachable(const Instruction *I) const {
  42. return BlockInstRange.find(I->getParent()) != BlockInstRange.end();
  43. }
  44. bool StackLifetime::isAliveAfter(const AllocaInst *AI,
  45. const Instruction *I) const {
  46. const BasicBlock *BB = I->getParent();
  47. auto ItBB = BlockInstRange.find(BB);
  48. assert(ItBB != BlockInstRange.end() && "Unreachable is not expected");
  49. // Search the block for the first instruction following 'I'.
  50. auto It = std::upper_bound(Instructions.begin() + ItBB->getSecond().first + 1,
  51. Instructions.begin() + ItBB->getSecond().second, I,
  52. [](const Instruction *L, const Instruction *R) {
  53. return L->comesBefore(R);
  54. });
  55. --It;
  56. unsigned InstNum = It - Instructions.begin();
  57. return getLiveRange(AI).test(InstNum);
  58. }
  59. // Returns unique alloca annotated by lifetime marker only if
  60. // markers has the same size and points to the alloca start.
  61. static const AllocaInst *findMatchingAlloca(const IntrinsicInst &II,
  62. const DataLayout &DL) {
  63. const AllocaInst *AI = findAllocaForValue(II.getArgOperand(1), true);
  64. if (!AI)
  65. return nullptr;
  66. auto AllocaSizeInBits = AI->getAllocationSizeInBits(DL);
  67. if (!AllocaSizeInBits)
  68. return nullptr;
  69. int64_t AllocaSize = AllocaSizeInBits.getValue() / 8;
  70. auto *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
  71. if (!Size)
  72. return nullptr;
  73. int64_t LifetimeSize = Size->getSExtValue();
  74. if (LifetimeSize != -1 && LifetimeSize != AllocaSize)
  75. return nullptr;
  76. return AI;
  77. }
  78. void StackLifetime::collectMarkers() {
  79. InterestingAllocas.resize(NumAllocas);
  80. DenseMap<const BasicBlock *, SmallDenseMap<const IntrinsicInst *, Marker>>
  81. BBMarkerSet;
  82. const DataLayout &DL = F.getParent()->getDataLayout();
  83. // Compute the set of start/end markers per basic block.
  84. for (const BasicBlock *BB : depth_first(&F)) {
  85. for (const Instruction &I : *BB) {
  86. const IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
  87. if (!II || !II->isLifetimeStartOrEnd())
  88. continue;
  89. const AllocaInst *AI = findMatchingAlloca(*II, DL);
  90. if (!AI) {
  91. HasUnknownLifetimeStartOrEnd = true;
  92. continue;
  93. }
  94. auto It = AllocaNumbering.find(AI);
  95. if (It == AllocaNumbering.end())
  96. continue;
  97. auto AllocaNo = It->second;
  98. bool IsStart = II->getIntrinsicID() == Intrinsic::lifetime_start;
  99. if (IsStart)
  100. InterestingAllocas.set(AllocaNo);
  101. BBMarkerSet[BB][II] = {AllocaNo, IsStart};
  102. }
  103. }
  104. // Compute instruction numbering. Only the following instructions are
  105. // considered:
  106. // * Basic block entries
  107. // * Lifetime markers
  108. // For each basic block, compute
  109. // * the list of markers in the instruction order
  110. // * the sets of allocas whose lifetime starts or ends in this BB
  111. LLVM_DEBUG(dbgs() << "Instructions:\n");
  112. for (const BasicBlock *BB : depth_first(&F)) {
  113. LLVM_DEBUG(dbgs() << " " << Instructions.size() << ": BB " << BB->getName()
  114. << "\n");
  115. auto BBStart = Instructions.size();
  116. Instructions.push_back(nullptr);
  117. BlockLifetimeInfo &BlockInfo =
  118. BlockLiveness.try_emplace(BB, NumAllocas).first->getSecond();
  119. auto &BlockMarkerSet = BBMarkerSet[BB];
  120. if (BlockMarkerSet.empty()) {
  121. BlockInstRange[BB] = std::make_pair(BBStart, Instructions.size());
  122. continue;
  123. }
  124. auto ProcessMarker = [&](const IntrinsicInst *I, const Marker &M) {
  125. LLVM_DEBUG(dbgs() << " " << Instructions.size() << ": "
  126. << (M.IsStart ? "start " : "end ") << M.AllocaNo
  127. << ", " << *I << "\n");
  128. BBMarkers[BB].push_back({Instructions.size(), M});
  129. Instructions.push_back(I);
  130. if (M.IsStart) {
  131. BlockInfo.End.reset(M.AllocaNo);
  132. BlockInfo.Begin.set(M.AllocaNo);
  133. } else {
  134. BlockInfo.Begin.reset(M.AllocaNo);
  135. BlockInfo.End.set(M.AllocaNo);
  136. }
  137. };
  138. if (BlockMarkerSet.size() == 1) {
  139. ProcessMarker(BlockMarkerSet.begin()->getFirst(),
  140. BlockMarkerSet.begin()->getSecond());
  141. } else {
  142. // Scan the BB to determine the marker order.
  143. for (const Instruction &I : *BB) {
  144. const IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
  145. if (!II)
  146. continue;
  147. auto It = BlockMarkerSet.find(II);
  148. if (It == BlockMarkerSet.end())
  149. continue;
  150. ProcessMarker(II, It->getSecond());
  151. }
  152. }
  153. BlockInstRange[BB] = std::make_pair(BBStart, Instructions.size());
  154. }
  155. }
  156. void StackLifetime::calculateLocalLiveness() {
  157. bool Changed = true;
  158. while (Changed) {
  159. Changed = false;
  160. for (const BasicBlock *BB : depth_first(&F)) {
  161. BlockLifetimeInfo &BlockInfo = BlockLiveness.find(BB)->getSecond();
  162. // Compute LiveIn by unioning together the LiveOut sets of all preds.
  163. BitVector LocalLiveIn;
  164. for (auto *PredBB : predecessors(BB)) {
  165. LivenessMap::const_iterator I = BlockLiveness.find(PredBB);
  166. // If a predecessor is unreachable, ignore it.
  167. if (I == BlockLiveness.end())
  168. continue;
  169. switch (Type) {
  170. case LivenessType::May:
  171. LocalLiveIn |= I->second.LiveOut;
  172. break;
  173. case LivenessType::Must:
  174. if (LocalLiveIn.empty())
  175. LocalLiveIn = I->second.LiveOut;
  176. else
  177. LocalLiveIn &= I->second.LiveOut;
  178. break;
  179. }
  180. }
  181. // Compute LiveOut by subtracting out lifetimes that end in this
  182. // block, then adding in lifetimes that begin in this block. If
  183. // we have both BEGIN and END markers in the same basic block
  184. // then we know that the BEGIN marker comes after the END,
  185. // because we already handle the case where the BEGIN comes
  186. // before the END when collecting the markers (and building the
  187. // BEGIN/END vectors).
  188. BitVector LocalLiveOut = LocalLiveIn;
  189. LocalLiveOut.reset(BlockInfo.End);
  190. LocalLiveOut |= BlockInfo.Begin;
  191. // Update block LiveIn set, noting whether it has changed.
  192. if (LocalLiveIn.test(BlockInfo.LiveIn)) {
  193. BlockInfo.LiveIn |= LocalLiveIn;
  194. }
  195. // Update block LiveOut set, noting whether it has changed.
  196. if (LocalLiveOut.test(BlockInfo.LiveOut)) {
  197. Changed = true;
  198. BlockInfo.LiveOut |= LocalLiveOut;
  199. }
  200. }
  201. } // while changed.
  202. }
  203. void StackLifetime::calculateLiveIntervals() {
  204. for (auto IT : BlockLiveness) {
  205. const BasicBlock *BB = IT.getFirst();
  206. BlockLifetimeInfo &BlockInfo = IT.getSecond();
  207. unsigned BBStart, BBEnd;
  208. std::tie(BBStart, BBEnd) = BlockInstRange[BB];
  209. BitVector Started, Ended;
  210. Started.resize(NumAllocas);
  211. Ended.resize(NumAllocas);
  212. SmallVector<unsigned, 8> Start;
  213. Start.resize(NumAllocas);
  214. // LiveIn ranges start at the first instruction.
  215. for (unsigned AllocaNo = 0; AllocaNo < NumAllocas; ++AllocaNo) {
  216. if (BlockInfo.LiveIn.test(AllocaNo)) {
  217. Started.set(AllocaNo);
  218. Start[AllocaNo] = BBStart;
  219. }
  220. }
  221. for (auto &It : BBMarkers[BB]) {
  222. unsigned InstNo = It.first;
  223. bool IsStart = It.second.IsStart;
  224. unsigned AllocaNo = It.second.AllocaNo;
  225. if (IsStart) {
  226. if (!Started.test(AllocaNo)) {
  227. Started.set(AllocaNo);
  228. Ended.reset(AllocaNo);
  229. Start[AllocaNo] = InstNo;
  230. }
  231. } else {
  232. if (Started.test(AllocaNo)) {
  233. LiveRanges[AllocaNo].addRange(Start[AllocaNo], InstNo);
  234. Started.reset(AllocaNo);
  235. }
  236. Ended.set(AllocaNo);
  237. }
  238. }
  239. for (unsigned AllocaNo = 0; AllocaNo < NumAllocas; ++AllocaNo)
  240. if (Started.test(AllocaNo))
  241. LiveRanges[AllocaNo].addRange(Start[AllocaNo], BBEnd);
  242. }
  243. }
  244. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  245. LLVM_DUMP_METHOD void StackLifetime::dumpAllocas() const {
  246. dbgs() << "Allocas:\n";
  247. for (unsigned AllocaNo = 0; AllocaNo < NumAllocas; ++AllocaNo)
  248. dbgs() << " " << AllocaNo << ": " << *Allocas[AllocaNo] << "\n";
  249. }
  250. LLVM_DUMP_METHOD void StackLifetime::dumpBlockLiveness() const {
  251. dbgs() << "Block liveness:\n";
  252. for (auto IT : BlockLiveness) {
  253. const BasicBlock *BB = IT.getFirst();
  254. const BlockLifetimeInfo &BlockInfo = BlockLiveness.find(BB)->getSecond();
  255. auto BlockRange = BlockInstRange.find(BB)->getSecond();
  256. dbgs() << " BB (" << BB->getName() << ") [" << BlockRange.first << ", " << BlockRange.second
  257. << "): begin " << BlockInfo.Begin << ", end " << BlockInfo.End
  258. << ", livein " << BlockInfo.LiveIn << ", liveout "
  259. << BlockInfo.LiveOut << "\n";
  260. }
  261. }
  262. LLVM_DUMP_METHOD void StackLifetime::dumpLiveRanges() const {
  263. dbgs() << "Alloca liveness:\n";
  264. for (unsigned AllocaNo = 0; AllocaNo < NumAllocas; ++AllocaNo)
  265. dbgs() << " " << AllocaNo << ": " << LiveRanges[AllocaNo] << "\n";
  266. }
  267. #endif
  268. StackLifetime::StackLifetime(const Function &F,
  269. ArrayRef<const AllocaInst *> Allocas,
  270. LivenessType Type)
  271. : F(F), Type(Type), Allocas(Allocas), NumAllocas(Allocas.size()) {
  272. LLVM_DEBUG(dumpAllocas());
  273. for (unsigned I = 0; I < NumAllocas; ++I)
  274. AllocaNumbering[Allocas[I]] = I;
  275. collectMarkers();
  276. }
  277. void StackLifetime::run() {
  278. if (HasUnknownLifetimeStartOrEnd) {
  279. // There is marker which we can't assign to a specific alloca, so we
  280. // fallback to the most conservative results for the type.
  281. switch (Type) {
  282. case LivenessType::May:
  283. LiveRanges.resize(NumAllocas, getFullLiveRange());
  284. break;
  285. case LivenessType::Must:
  286. LiveRanges.resize(NumAllocas, LiveRange(Instructions.size()));
  287. break;
  288. }
  289. return;
  290. }
  291. LiveRanges.resize(NumAllocas, LiveRange(Instructions.size()));
  292. for (unsigned I = 0; I < NumAllocas; ++I)
  293. if (!InterestingAllocas.test(I))
  294. LiveRanges[I] = getFullLiveRange();
  295. calculateLocalLiveness();
  296. LLVM_DEBUG(dumpBlockLiveness());
  297. calculateLiveIntervals();
  298. LLVM_DEBUG(dumpLiveRanges());
  299. }
  300. class StackLifetime::LifetimeAnnotationWriter
  301. : public AssemblyAnnotationWriter {
  302. const StackLifetime &SL;
  303. void printInstrAlive(unsigned InstrNo, formatted_raw_ostream &OS) {
  304. SmallVector<StringRef, 16> Names;
  305. for (const auto &KV : SL.AllocaNumbering) {
  306. if (SL.LiveRanges[KV.getSecond()].test(InstrNo))
  307. Names.push_back(KV.getFirst()->getName());
  308. }
  309. llvm::sort(Names);
  310. OS << " ; Alive: <" << llvm::join(Names, " ") << ">\n";
  311. }
  312. void emitBasicBlockStartAnnot(const BasicBlock *BB,
  313. formatted_raw_ostream &OS) override {
  314. auto ItBB = SL.BlockInstRange.find(BB);
  315. if (ItBB == SL.BlockInstRange.end())
  316. return; // Unreachable.
  317. printInstrAlive(ItBB->getSecond().first, OS);
  318. }
  319. void printInfoComment(const Value &V, formatted_raw_ostream &OS) override {
  320. const Instruction *Instr = dyn_cast<Instruction>(&V);
  321. if (!Instr || !SL.isReachable(Instr))
  322. return;
  323. SmallVector<StringRef, 16> Names;
  324. for (const auto &KV : SL.AllocaNumbering) {
  325. if (SL.isAliveAfter(KV.getFirst(), Instr))
  326. Names.push_back(KV.getFirst()->getName());
  327. }
  328. llvm::sort(Names);
  329. OS << "\n ; Alive: <" << llvm::join(Names, " ") << ">\n";
  330. }
  331. public:
  332. LifetimeAnnotationWriter(const StackLifetime &SL) : SL(SL) {}
  333. };
  334. void StackLifetime::print(raw_ostream &OS) {
  335. LifetimeAnnotationWriter AAW(*this);
  336. F.print(OS, &AAW);
  337. }
  338. PreservedAnalyses StackLifetimePrinterPass::run(Function &F,
  339. FunctionAnalysisManager &AM) {
  340. SmallVector<const AllocaInst *, 8> Allocas;
  341. for (auto &I : instructions(F))
  342. if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I))
  343. Allocas.push_back(AI);
  344. StackLifetime SL(F, Allocas, Type);
  345. SL.run();
  346. SL.print(OS);
  347. return PreservedAnalyses::all();
  348. }
  349. void StackLifetimePrinterPass::printPipeline(
  350. raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
  351. static_cast<PassInfoMixin<StackLifetimePrinterPass> *>(this)->printPipeline(
  352. OS, MapClassName2PassName);
  353. OS << "<";
  354. switch (Type) {
  355. case StackLifetime::LivenessType::May:
  356. OS << "may";
  357. break;
  358. case StackLifetime::LivenessType::Must:
  359. OS << "must";
  360. break;
  361. }
  362. OS << ">";
  363. }