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