LiveVariables.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  1. //=- LiveVariables.cpp - Live Variable Analysis for Source CFGs ----------*-==//
  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. // This file implements Live Variables analysis for source-level CFGs.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/Analysis/Analyses/LiveVariables.h"
  13. #include "clang/AST/Stmt.h"
  14. #include "clang/AST/StmtVisitor.h"
  15. #include "clang/Analysis/AnalysisDeclContext.h"
  16. #include "clang/Analysis/CFG.h"
  17. #include "clang/Analysis/FlowSensitive/DataflowWorklist.h"
  18. #include "llvm/ADT/DenseMap.h"
  19. #include "llvm/Support/raw_ostream.h"
  20. #include <algorithm>
  21. #include <vector>
  22. using namespace clang;
  23. namespace {
  24. class LiveVariablesImpl {
  25. public:
  26. AnalysisDeclContext &analysisContext;
  27. llvm::ImmutableSet<const Expr *>::Factory ESetFact;
  28. llvm::ImmutableSet<const VarDecl *>::Factory DSetFact;
  29. llvm::ImmutableSet<const BindingDecl *>::Factory BSetFact;
  30. llvm::DenseMap<const CFGBlock *, LiveVariables::LivenessValues> blocksEndToLiveness;
  31. llvm::DenseMap<const CFGBlock *, LiveVariables::LivenessValues> blocksBeginToLiveness;
  32. llvm::DenseMap<const Stmt *, LiveVariables::LivenessValues> stmtsToLiveness;
  33. llvm::DenseMap<const DeclRefExpr *, unsigned> inAssignment;
  34. const bool killAtAssign;
  35. LiveVariables::LivenessValues
  36. merge(LiveVariables::LivenessValues valsA,
  37. LiveVariables::LivenessValues valsB);
  38. LiveVariables::LivenessValues
  39. runOnBlock(const CFGBlock *block, LiveVariables::LivenessValues val,
  40. LiveVariables::Observer *obs = nullptr);
  41. void dumpBlockLiveness(const SourceManager& M);
  42. void dumpExprLiveness(const SourceManager& M);
  43. LiveVariablesImpl(AnalysisDeclContext &ac, bool KillAtAssign)
  44. : analysisContext(ac),
  45. ESetFact(false), // Do not canonicalize ImmutableSets by default.
  46. DSetFact(false), // This is a *major* performance win.
  47. BSetFact(false), killAtAssign(KillAtAssign) {}
  48. };
  49. } // namespace
  50. static LiveVariablesImpl &getImpl(void *x) {
  51. return *((LiveVariablesImpl *) x);
  52. }
  53. //===----------------------------------------------------------------------===//
  54. // Operations and queries on LivenessValues.
  55. //===----------------------------------------------------------------------===//
  56. bool LiveVariables::LivenessValues::isLive(const Expr *E) const {
  57. return liveExprs.contains(E);
  58. }
  59. bool LiveVariables::LivenessValues::isLive(const VarDecl *D) const {
  60. if (const auto *DD = dyn_cast<DecompositionDecl>(D)) {
  61. bool alive = false;
  62. for (const BindingDecl *BD : DD->bindings())
  63. alive |= liveBindings.contains(BD);
  64. return alive;
  65. }
  66. return liveDecls.contains(D);
  67. }
  68. namespace {
  69. template <typename SET>
  70. SET mergeSets(SET A, SET B) {
  71. if (A.isEmpty())
  72. return B;
  73. for (typename SET::iterator it = B.begin(), ei = B.end(); it != ei; ++it) {
  74. A = A.add(*it);
  75. }
  76. return A;
  77. }
  78. } // namespace
  79. void LiveVariables::Observer::anchor() { }
  80. LiveVariables::LivenessValues
  81. LiveVariablesImpl::merge(LiveVariables::LivenessValues valsA,
  82. LiveVariables::LivenessValues valsB) {
  83. llvm::ImmutableSetRef<const Expr *> SSetRefA(
  84. valsA.liveExprs.getRootWithoutRetain(), ESetFact.getTreeFactory()),
  85. SSetRefB(valsB.liveExprs.getRootWithoutRetain(),
  86. ESetFact.getTreeFactory());
  87. llvm::ImmutableSetRef<const VarDecl *>
  88. DSetRefA(valsA.liveDecls.getRootWithoutRetain(), DSetFact.getTreeFactory()),
  89. DSetRefB(valsB.liveDecls.getRootWithoutRetain(), DSetFact.getTreeFactory());
  90. llvm::ImmutableSetRef<const BindingDecl *>
  91. BSetRefA(valsA.liveBindings.getRootWithoutRetain(), BSetFact.getTreeFactory()),
  92. BSetRefB(valsB.liveBindings.getRootWithoutRetain(), BSetFact.getTreeFactory());
  93. SSetRefA = mergeSets(SSetRefA, SSetRefB);
  94. DSetRefA = mergeSets(DSetRefA, DSetRefB);
  95. BSetRefA = mergeSets(BSetRefA, BSetRefB);
  96. // asImmutableSet() canonicalizes the tree, allowing us to do an easy
  97. // comparison afterwards.
  98. return LiveVariables::LivenessValues(SSetRefA.asImmutableSet(),
  99. DSetRefA.asImmutableSet(),
  100. BSetRefA.asImmutableSet());
  101. }
  102. bool LiveVariables::LivenessValues::equals(const LivenessValues &V) const {
  103. return liveExprs == V.liveExprs && liveDecls == V.liveDecls;
  104. }
  105. //===----------------------------------------------------------------------===//
  106. // Query methods.
  107. //===----------------------------------------------------------------------===//
  108. static bool isAlwaysAlive(const VarDecl *D) {
  109. return D->hasGlobalStorage();
  110. }
  111. bool LiveVariables::isLive(const CFGBlock *B, const VarDecl *D) {
  112. return isAlwaysAlive(D) || getImpl(impl).blocksEndToLiveness[B].isLive(D);
  113. }
  114. bool LiveVariables::isLive(const Stmt *S, const VarDecl *D) {
  115. return isAlwaysAlive(D) || getImpl(impl).stmtsToLiveness[S].isLive(D);
  116. }
  117. bool LiveVariables::isLive(const Stmt *Loc, const Expr *Val) {
  118. return getImpl(impl).stmtsToLiveness[Loc].isLive(Val);
  119. }
  120. //===----------------------------------------------------------------------===//
  121. // Dataflow computation.
  122. //===----------------------------------------------------------------------===//
  123. namespace {
  124. class TransferFunctions : public StmtVisitor<TransferFunctions> {
  125. LiveVariablesImpl &LV;
  126. LiveVariables::LivenessValues &val;
  127. LiveVariables::Observer *observer;
  128. const CFGBlock *currentBlock;
  129. public:
  130. TransferFunctions(LiveVariablesImpl &im,
  131. LiveVariables::LivenessValues &Val,
  132. LiveVariables::Observer *Observer,
  133. const CFGBlock *CurrentBlock)
  134. : LV(im), val(Val), observer(Observer), currentBlock(CurrentBlock) {}
  135. void VisitBinaryOperator(BinaryOperator *BO);
  136. void VisitBlockExpr(BlockExpr *BE);
  137. void VisitDeclRefExpr(DeclRefExpr *DR);
  138. void VisitDeclStmt(DeclStmt *DS);
  139. void VisitObjCForCollectionStmt(ObjCForCollectionStmt *OS);
  140. void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *UE);
  141. void VisitUnaryOperator(UnaryOperator *UO);
  142. void Visit(Stmt *S);
  143. };
  144. } // namespace
  145. static const VariableArrayType *FindVA(QualType Ty) {
  146. const Type *ty = Ty.getTypePtr();
  147. while (const ArrayType *VT = dyn_cast<ArrayType>(ty)) {
  148. if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(VT))
  149. if (VAT->getSizeExpr())
  150. return VAT;
  151. ty = VT->getElementType().getTypePtr();
  152. }
  153. return nullptr;
  154. }
  155. static const Expr *LookThroughExpr(const Expr *E) {
  156. while (E) {
  157. if (const Expr *Ex = dyn_cast<Expr>(E))
  158. E = Ex->IgnoreParens();
  159. if (const FullExpr *FE = dyn_cast<FullExpr>(E)) {
  160. E = FE->getSubExpr();
  161. continue;
  162. }
  163. if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
  164. E = OVE->getSourceExpr();
  165. continue;
  166. }
  167. break;
  168. }
  169. return E;
  170. }
  171. static void AddLiveExpr(llvm::ImmutableSet<const Expr *> &Set,
  172. llvm::ImmutableSet<const Expr *>::Factory &F,
  173. const Expr *E) {
  174. Set = F.add(Set, LookThroughExpr(E));
  175. }
  176. void TransferFunctions::Visit(Stmt *S) {
  177. if (observer)
  178. observer->observeStmt(S, currentBlock, val);
  179. StmtVisitor<TransferFunctions>::Visit(S);
  180. if (const auto *E = dyn_cast<Expr>(S)) {
  181. val.liveExprs = LV.ESetFact.remove(val.liveExprs, E);
  182. }
  183. // Mark all children expressions live.
  184. switch (S->getStmtClass()) {
  185. default:
  186. break;
  187. case Stmt::StmtExprClass: {
  188. // For statement expressions, look through the compound statement.
  189. S = cast<StmtExpr>(S)->getSubStmt();
  190. break;
  191. }
  192. case Stmt::CXXMemberCallExprClass: {
  193. // Include the implicit "this" pointer as being live.
  194. CXXMemberCallExpr *CE = cast<CXXMemberCallExpr>(S);
  195. if (Expr *ImplicitObj = CE->getImplicitObjectArgument()) {
  196. AddLiveExpr(val.liveExprs, LV.ESetFact, ImplicitObj);
  197. }
  198. break;
  199. }
  200. case Stmt::ObjCMessageExprClass: {
  201. // In calls to super, include the implicit "self" pointer as being live.
  202. ObjCMessageExpr *CE = cast<ObjCMessageExpr>(S);
  203. if (CE->getReceiverKind() == ObjCMessageExpr::SuperInstance)
  204. val.liveDecls = LV.DSetFact.add(val.liveDecls,
  205. LV.analysisContext.getSelfDecl());
  206. break;
  207. }
  208. case Stmt::DeclStmtClass: {
  209. const DeclStmt *DS = cast<DeclStmt>(S);
  210. if (const VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl())) {
  211. for (const VariableArrayType* VA = FindVA(VD->getType());
  212. VA != nullptr; VA = FindVA(VA->getElementType())) {
  213. AddLiveExpr(val.liveExprs, LV.ESetFact, VA->getSizeExpr());
  214. }
  215. }
  216. break;
  217. }
  218. case Stmt::PseudoObjectExprClass: {
  219. // A pseudo-object operation only directly consumes its result
  220. // expression.
  221. Expr *child = cast<PseudoObjectExpr>(S)->getResultExpr();
  222. if (!child) return;
  223. if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(child))
  224. child = OV->getSourceExpr();
  225. child = child->IgnoreParens();
  226. val.liveExprs = LV.ESetFact.add(val.liveExprs, child);
  227. return;
  228. }
  229. // FIXME: These cases eventually shouldn't be needed.
  230. case Stmt::ExprWithCleanupsClass: {
  231. S = cast<ExprWithCleanups>(S)->getSubExpr();
  232. break;
  233. }
  234. case Stmt::CXXBindTemporaryExprClass: {
  235. S = cast<CXXBindTemporaryExpr>(S)->getSubExpr();
  236. break;
  237. }
  238. case Stmt::UnaryExprOrTypeTraitExprClass: {
  239. // No need to unconditionally visit subexpressions.
  240. return;
  241. }
  242. case Stmt::IfStmtClass: {
  243. // If one of the branches is an expression rather than a compound
  244. // statement, it will be bad if we mark it as live at the terminator
  245. // of the if-statement (i.e., immediately after the condition expression).
  246. AddLiveExpr(val.liveExprs, LV.ESetFact, cast<IfStmt>(S)->getCond());
  247. return;
  248. }
  249. case Stmt::WhileStmtClass: {
  250. // If the loop body is an expression rather than a compound statement,
  251. // it will be bad if we mark it as live at the terminator of the loop
  252. // (i.e., immediately after the condition expression).
  253. AddLiveExpr(val.liveExprs, LV.ESetFact, cast<WhileStmt>(S)->getCond());
  254. return;
  255. }
  256. case Stmt::DoStmtClass: {
  257. // If the loop body is an expression rather than a compound statement,
  258. // it will be bad if we mark it as live at the terminator of the loop
  259. // (i.e., immediately after the condition expression).
  260. AddLiveExpr(val.liveExprs, LV.ESetFact, cast<DoStmt>(S)->getCond());
  261. return;
  262. }
  263. case Stmt::ForStmtClass: {
  264. // If the loop body is an expression rather than a compound statement,
  265. // it will be bad if we mark it as live at the terminator of the loop
  266. // (i.e., immediately after the condition expression).
  267. AddLiveExpr(val.liveExprs, LV.ESetFact, cast<ForStmt>(S)->getCond());
  268. return;
  269. }
  270. }
  271. // HACK + FIXME: What is this? One could only guess that this is an attempt to
  272. // fish for live values, for example, arguments from a call expression.
  273. // Maybe we could take inspiration from UninitializedVariable analysis?
  274. for (Stmt *Child : S->children()) {
  275. if (const auto *E = dyn_cast_or_null<Expr>(Child))
  276. AddLiveExpr(val.liveExprs, LV.ESetFact, E);
  277. }
  278. }
  279. static bool writeShouldKill(const VarDecl *VD) {
  280. return VD && !VD->getType()->isReferenceType() &&
  281. !isAlwaysAlive(VD);
  282. }
  283. void TransferFunctions::VisitBinaryOperator(BinaryOperator *B) {
  284. if (LV.killAtAssign && B->getOpcode() == BO_Assign) {
  285. if (const auto *DR = dyn_cast<DeclRefExpr>(B->getLHS()->IgnoreParens())) {
  286. LV.inAssignment[DR] = 1;
  287. }
  288. }
  289. if (B->isAssignmentOp()) {
  290. if (!LV.killAtAssign)
  291. return;
  292. // Assigning to a variable?
  293. Expr *LHS = B->getLHS()->IgnoreParens();
  294. if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(LHS)) {
  295. const Decl* D = DR->getDecl();
  296. bool Killed = false;
  297. if (const BindingDecl* BD = dyn_cast<BindingDecl>(D)) {
  298. Killed = !BD->getType()->isReferenceType();
  299. if (Killed)
  300. val.liveBindings = LV.BSetFact.remove(val.liveBindings, BD);
  301. } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
  302. Killed = writeShouldKill(VD);
  303. if (Killed)
  304. val.liveDecls = LV.DSetFact.remove(val.liveDecls, VD);
  305. }
  306. if (Killed && observer)
  307. observer->observerKill(DR);
  308. }
  309. }
  310. }
  311. void TransferFunctions::VisitBlockExpr(BlockExpr *BE) {
  312. for (const VarDecl *VD :
  313. LV.analysisContext.getReferencedBlockVars(BE->getBlockDecl())) {
  314. if (isAlwaysAlive(VD))
  315. continue;
  316. val.liveDecls = LV.DSetFact.add(val.liveDecls, VD);
  317. }
  318. }
  319. void TransferFunctions::VisitDeclRefExpr(DeclRefExpr *DR) {
  320. const Decl* D = DR->getDecl();
  321. bool InAssignment = LV.inAssignment[DR];
  322. if (const auto *BD = dyn_cast<BindingDecl>(D)) {
  323. if (!InAssignment)
  324. val.liveBindings = LV.BSetFact.add(val.liveBindings, BD);
  325. } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
  326. if (!InAssignment && !isAlwaysAlive(VD))
  327. val.liveDecls = LV.DSetFact.add(val.liveDecls, VD);
  328. }
  329. }
  330. void TransferFunctions::VisitDeclStmt(DeclStmt *DS) {
  331. for (const auto *DI : DS->decls()) {
  332. if (const auto *DD = dyn_cast<DecompositionDecl>(DI)) {
  333. for (const auto *BD : DD->bindings())
  334. val.liveBindings = LV.BSetFact.remove(val.liveBindings, BD);
  335. } else if (const auto *VD = dyn_cast<VarDecl>(DI)) {
  336. if (!isAlwaysAlive(VD))
  337. val.liveDecls = LV.DSetFact.remove(val.liveDecls, VD);
  338. }
  339. }
  340. }
  341. void TransferFunctions::VisitObjCForCollectionStmt(ObjCForCollectionStmt *OS) {
  342. // Kill the iteration variable.
  343. DeclRefExpr *DR = nullptr;
  344. const VarDecl *VD = nullptr;
  345. Stmt *element = OS->getElement();
  346. if (DeclStmt *DS = dyn_cast<DeclStmt>(element)) {
  347. VD = cast<VarDecl>(DS->getSingleDecl());
  348. }
  349. else if ((DR = dyn_cast<DeclRefExpr>(cast<Expr>(element)->IgnoreParens()))) {
  350. VD = cast<VarDecl>(DR->getDecl());
  351. }
  352. if (VD) {
  353. val.liveDecls = LV.DSetFact.remove(val.liveDecls, VD);
  354. if (observer && DR)
  355. observer->observerKill(DR);
  356. }
  357. }
  358. void TransferFunctions::
  359. VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *UE)
  360. {
  361. // While sizeof(var) doesn't technically extend the liveness of 'var', it
  362. // does extent the liveness of metadata if 'var' is a VariableArrayType.
  363. // We handle that special case here.
  364. if (UE->getKind() != UETT_SizeOf || UE->isArgumentType())
  365. return;
  366. const Expr *subEx = UE->getArgumentExpr();
  367. if (subEx->getType()->isVariableArrayType()) {
  368. assert(subEx->isLValue());
  369. val.liveExprs = LV.ESetFact.add(val.liveExprs, subEx->IgnoreParens());
  370. }
  371. }
  372. void TransferFunctions::VisitUnaryOperator(UnaryOperator *UO) {
  373. // Treat ++/-- as a kill.
  374. // Note we don't actually have to do anything if we don't have an observer,
  375. // since a ++/-- acts as both a kill and a "use".
  376. if (!observer)
  377. return;
  378. switch (UO->getOpcode()) {
  379. default:
  380. return;
  381. case UO_PostInc:
  382. case UO_PostDec:
  383. case UO_PreInc:
  384. case UO_PreDec:
  385. break;
  386. }
  387. if (auto *DR = dyn_cast<DeclRefExpr>(UO->getSubExpr()->IgnoreParens())) {
  388. const Decl *D = DR->getDecl();
  389. if (isa<VarDecl>(D) || isa<BindingDecl>(D)) {
  390. // Treat ++/-- as a kill.
  391. observer->observerKill(DR);
  392. }
  393. }
  394. }
  395. LiveVariables::LivenessValues
  396. LiveVariablesImpl::runOnBlock(const CFGBlock *block,
  397. LiveVariables::LivenessValues val,
  398. LiveVariables::Observer *obs) {
  399. TransferFunctions TF(*this, val, obs, block);
  400. // Visit the terminator (if any).
  401. if (const Stmt *term = block->getTerminatorStmt())
  402. TF.Visit(const_cast<Stmt*>(term));
  403. // Apply the transfer function for all Stmts in the block.
  404. for (CFGBlock::const_reverse_iterator it = block->rbegin(),
  405. ei = block->rend(); it != ei; ++it) {
  406. const CFGElement &elem = *it;
  407. if (Optional<CFGAutomaticObjDtor> Dtor =
  408. elem.getAs<CFGAutomaticObjDtor>()) {
  409. val.liveDecls = DSetFact.add(val.liveDecls, Dtor->getVarDecl());
  410. continue;
  411. }
  412. if (!elem.getAs<CFGStmt>())
  413. continue;
  414. const Stmt *S = elem.castAs<CFGStmt>().getStmt();
  415. TF.Visit(const_cast<Stmt*>(S));
  416. stmtsToLiveness[S] = val;
  417. }
  418. return val;
  419. }
  420. void LiveVariables::runOnAllBlocks(LiveVariables::Observer &obs) {
  421. const CFG *cfg = getImpl(impl).analysisContext.getCFG();
  422. for (CFG::const_iterator it = cfg->begin(), ei = cfg->end(); it != ei; ++it)
  423. getImpl(impl).runOnBlock(*it, getImpl(impl).blocksEndToLiveness[*it], &obs);
  424. }
  425. LiveVariables::LiveVariables(void *im) : impl(im) {}
  426. LiveVariables::~LiveVariables() {
  427. delete (LiveVariablesImpl*) impl;
  428. }
  429. std::unique_ptr<LiveVariables>
  430. LiveVariables::computeLiveness(AnalysisDeclContext &AC, bool killAtAssign) {
  431. // No CFG? Bail out.
  432. CFG *cfg = AC.getCFG();
  433. if (!cfg)
  434. return nullptr;
  435. // The analysis currently has scalability issues for very large CFGs.
  436. // Bail out if it looks too large.
  437. if (cfg->getNumBlockIDs() > 300000)
  438. return nullptr;
  439. LiveVariablesImpl *LV = new LiveVariablesImpl(AC, killAtAssign);
  440. // Construct the dataflow worklist. Enqueue the exit block as the
  441. // start of the analysis.
  442. BackwardDataflowWorklist worklist(*cfg, AC);
  443. llvm::BitVector everAnalyzedBlock(cfg->getNumBlockIDs());
  444. // FIXME: we should enqueue using post order.
  445. for (const CFGBlock *B : cfg->nodes()) {
  446. worklist.enqueueBlock(B);
  447. }
  448. while (const CFGBlock *block = worklist.dequeue()) {
  449. // Determine if the block's end value has changed. If not, we
  450. // have nothing left to do for this block.
  451. LivenessValues &prevVal = LV->blocksEndToLiveness[block];
  452. // Merge the values of all successor blocks.
  453. LivenessValues val;
  454. for (CFGBlock::const_succ_iterator it = block->succ_begin(),
  455. ei = block->succ_end(); it != ei; ++it) {
  456. if (const CFGBlock *succ = *it) {
  457. val = LV->merge(val, LV->blocksBeginToLiveness[succ]);
  458. }
  459. }
  460. if (!everAnalyzedBlock[block->getBlockID()])
  461. everAnalyzedBlock[block->getBlockID()] = true;
  462. else if (prevVal.equals(val))
  463. continue;
  464. prevVal = val;
  465. // Update the dataflow value for the start of this block.
  466. LV->blocksBeginToLiveness[block] = LV->runOnBlock(block, val);
  467. // Enqueue the value to the predecessors.
  468. worklist.enqueuePredecessors(block);
  469. }
  470. return std::unique_ptr<LiveVariables>(new LiveVariables(LV));
  471. }
  472. void LiveVariables::dumpBlockLiveness(const SourceManager &M) {
  473. getImpl(impl).dumpBlockLiveness(M);
  474. }
  475. void LiveVariablesImpl::dumpBlockLiveness(const SourceManager &M) {
  476. std::vector<const CFGBlock *> vec;
  477. for (llvm::DenseMap<const CFGBlock *, LiveVariables::LivenessValues>::iterator
  478. it = blocksEndToLiveness.begin(), ei = blocksEndToLiveness.end();
  479. it != ei; ++it) {
  480. vec.push_back(it->first);
  481. }
  482. llvm::sort(vec, [](const CFGBlock *A, const CFGBlock *B) {
  483. return A->getBlockID() < B->getBlockID();
  484. });
  485. std::vector<const VarDecl*> declVec;
  486. for (std::vector<const CFGBlock *>::iterator
  487. it = vec.begin(), ei = vec.end(); it != ei; ++it) {
  488. llvm::errs() << "\n[ B" << (*it)->getBlockID()
  489. << " (live variables at block exit) ]\n";
  490. LiveVariables::LivenessValues vals = blocksEndToLiveness[*it];
  491. declVec.clear();
  492. for (llvm::ImmutableSet<const VarDecl *>::iterator si =
  493. vals.liveDecls.begin(),
  494. se = vals.liveDecls.end(); si != se; ++si) {
  495. declVec.push_back(*si);
  496. }
  497. llvm::sort(declVec, [](const Decl *A, const Decl *B) {
  498. return A->getBeginLoc() < B->getBeginLoc();
  499. });
  500. for (std::vector<const VarDecl*>::iterator di = declVec.begin(),
  501. de = declVec.end(); di != de; ++di) {
  502. llvm::errs() << " " << (*di)->getDeclName().getAsString()
  503. << " <";
  504. (*di)->getLocation().print(llvm::errs(), M);
  505. llvm::errs() << ">\n";
  506. }
  507. }
  508. llvm::errs() << "\n";
  509. }
  510. void LiveVariables::dumpExprLiveness(const SourceManager &M) {
  511. getImpl(impl).dumpExprLiveness(M);
  512. }
  513. void LiveVariablesImpl::dumpExprLiveness(const SourceManager &M) {
  514. // Don't iterate over blockEndsToLiveness directly because it's not sorted.
  515. for (const CFGBlock *B : *analysisContext.getCFG()) {
  516. llvm::errs() << "\n[ B" << B->getBlockID()
  517. << " (live expressions at block exit) ]\n";
  518. for (const Expr *E : blocksEndToLiveness[B].liveExprs) {
  519. llvm::errs() << "\n";
  520. E->dump();
  521. }
  522. llvm::errs() << "\n";
  523. }
  524. }
  525. const void *LiveVariables::getTag() { static int x; return &x; }
  526. const void *RelaxedLiveVariables::getTag() { static int x; return &x; }