LiveVariables.cpp 21 KB

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