blob: dcde5e7619fe0044cf52259b8a101637f0af44bf [file] [log] [blame]
Benjamin Kramer444a1302012-12-01 17:12:56 +00001//=- LiveVariables.cpp - Live Variable Analysis for Source CFGs ----------*-==//
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//
10// This file implements Live Variables analysis for source-level CFGs.
11//
12//===----------------------------------------------------------------------===//
13
Ted Kremenekbf593f82007-12-21 21:42:19 +000014#include "clang/Analysis/Analyses/LiveVariables.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000015#include "clang/AST/Stmt.h"
Ted Kremeneke9fda1e2011-07-28 23:07:59 +000016#include "clang/AST/StmtVisitor.h"
Artyom Skrobov12ce6d92014-07-28 08:47:38 +000017#include "clang/Analysis/Analyses/DataflowWorklist.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "clang/Analysis/AnalysisContext.h"
19#include "clang/Analysis/CFG.h"
Ted Kremenek459597a2011-09-16 23:01:39 +000020#include "llvm/ADT/DenseMap.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000021#include "llvm/Support/raw_ostream.h"
Ted Kremeneke9fda1e2011-07-28 23:07:59 +000022#include <algorithm>
23#include <vector>
Ted Kremenekb56a9902007-09-06 00:17:54 +000024
25using namespace clang;
26
Ted Kremenekb56a9902007-09-06 00:17:54 +000027namespace {
Ted Kremenek459597a2011-09-16 23:01:39 +000028class LiveVariablesImpl {
29public:
Ted Kremenek81ce1c82011-10-24 01:32:45 +000030 AnalysisDeclContext &analysisContext;
Ted Kremenek459597a2011-09-16 23:01:39 +000031 std::vector<LiveVariables::LivenessValues> cfgBlockValues;
32 llvm::ImmutableSet<const Stmt *>::Factory SSetFact;
33 llvm::ImmutableSet<const VarDecl *>::Factory DSetFact;
34 llvm::DenseMap<const CFGBlock *, LiveVariables::LivenessValues> blocksEndToLiveness;
35 llvm::DenseMap<const CFGBlock *, LiveVariables::LivenessValues> blocksBeginToLiveness;
36 llvm::DenseMap<const Stmt *, LiveVariables::LivenessValues> stmtsToLiveness;
37 llvm::DenseMap<const DeclRefExpr *, unsigned> inAssignment;
38 const bool killAtAssign;
39
40 LiveVariables::LivenessValues
41 merge(LiveVariables::LivenessValues valsA,
42 LiveVariables::LivenessValues valsB);
Craig Topper25542942014-05-20 04:30:07 +000043
44 LiveVariables::LivenessValues
45 runOnBlock(const CFGBlock *block, LiveVariables::LivenessValues val,
46 LiveVariables::Observer *obs = nullptr);
Ted Kremenek459597a2011-09-16 23:01:39 +000047
48 void dumpBlockLiveness(const SourceManager& M);
49
Ted Kremenek81ce1c82011-10-24 01:32:45 +000050 LiveVariablesImpl(AnalysisDeclContext &ac, bool KillAtAssign)
Ted Kremenekc8f008a2011-10-02 01:45:37 +000051 : analysisContext(ac),
52 SSetFact(false), // Do not canonicalize ImmutableSets by default.
53 DSetFact(false), // This is a *major* performance win.
54 killAtAssign(KillAtAssign) {}
Ted Kremenek459597a2011-09-16 23:01:39 +000055};
Ted Kremeneke9fda1e2011-07-28 23:07:59 +000056}
Ted Kremenek82ff6d62008-04-15 18:35:30 +000057
Ted Kremenek5ef32db2011-08-12 23:37:29 +000058static LiveVariablesImpl &getImpl(void *x) {
Ted Kremeneke9fda1e2011-07-28 23:07:59 +000059 return *((LiveVariablesImpl *) x);
Ted Kremenekad8bce02007-09-25 04:31:27 +000060}
Ted Kremenekb56a9902007-09-06 00:17:54 +000061
62//===----------------------------------------------------------------------===//
Ted Kremeneke9fda1e2011-07-28 23:07:59 +000063// Operations and queries on LivenessValues.
64//===----------------------------------------------------------------------===//
65
66bool LiveVariables::LivenessValues::isLive(const Stmt *S) const {
67 return liveStmts.contains(S);
68}
69
70bool LiveVariables::LivenessValues::isLive(const VarDecl *D) const {
71 return liveDecls.contains(D);
72}
73
74namespace {
75 template <typename SET>
Ted Kremenek459597a2011-09-16 23:01:39 +000076 SET mergeSets(SET A, SET B) {
77 if (A.isEmpty())
78 return B;
79
Ted Kremeneke9fda1e2011-07-28 23:07:59 +000080 for (typename SET::iterator it = B.begin(), ei = B.end(); it != ei; ++it) {
Ted Kremenek459597a2011-09-16 23:01:39 +000081 A = A.add(*it);
Ted Kremeneke9fda1e2011-07-28 23:07:59 +000082 }
83 return A;
84 }
85}
86
David Blaikie68e081d2011-12-20 02:48:34 +000087void LiveVariables::Observer::anchor() { }
88
Ted Kremeneke9fda1e2011-07-28 23:07:59 +000089LiveVariables::LivenessValues
90LiveVariablesImpl::merge(LiveVariables::LivenessValues valsA,
91 LiveVariables::LivenessValues valsB) {
Ted Kremenek459597a2011-09-16 23:01:39 +000092
93 llvm::ImmutableSetRef<const Stmt *>
94 SSetRefA(valsA.liveStmts.getRootWithoutRetain(), SSetFact.getTreeFactory()),
95 SSetRefB(valsB.liveStmts.getRootWithoutRetain(), SSetFact.getTreeFactory());
96
97
98 llvm::ImmutableSetRef<const VarDecl *>
99 DSetRefA(valsA.liveDecls.getRootWithoutRetain(), DSetFact.getTreeFactory()),
100 DSetRefB(valsB.liveDecls.getRootWithoutRetain(), DSetFact.getTreeFactory());
101
102
103 SSetRefA = mergeSets(SSetRefA, SSetRefB);
104 DSetRefA = mergeSets(DSetRefA, DSetRefB);
105
Ted Kremenekc8f008a2011-10-02 01:45:37 +0000106 // asImmutableSet() canonicalizes the tree, allowing us to do an easy
107 // comparison afterwards.
Ted Kremenek459597a2011-09-16 23:01:39 +0000108 return LiveVariables::LivenessValues(SSetRefA.asImmutableSet(),
109 DSetRefA.asImmutableSet());
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000110}
111
112bool LiveVariables::LivenessValues::equals(const LivenessValues &V) const {
113 return liveStmts == V.liveStmts && liveDecls == V.liveDecls;
114}
115
116//===----------------------------------------------------------------------===//
117// Query methods.
118//===----------------------------------------------------------------------===//
119
120static bool isAlwaysAlive(const VarDecl *D) {
121 return D->hasGlobalStorage();
122}
123
124bool LiveVariables::isLive(const CFGBlock *B, const VarDecl *D) {
125 return isAlwaysAlive(D) || getImpl(impl).blocksEndToLiveness[B].isLive(D);
126}
127
128bool LiveVariables::isLive(const Stmt *S, const VarDecl *D) {
129 return isAlwaysAlive(D) || getImpl(impl).stmtsToLiveness[S].isLive(D);
130}
131
132bool LiveVariables::isLive(const Stmt *Loc, const Stmt *S) {
133 return getImpl(impl).stmtsToLiveness[Loc].isLive(S);
134}
135
136//===----------------------------------------------------------------------===//
137// Dataflow computation.
Mike Stump11289f42009-09-09 15:08:12 +0000138//===----------------------------------------------------------------------===//
Ted Kremenekb56a9902007-09-06 00:17:54 +0000139
140namespace {
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000141class TransferFunctions : public StmtVisitor<TransferFunctions> {
142 LiveVariablesImpl &LV;
143 LiveVariables::LivenessValues &val;
144 LiveVariables::Observer *observer;
Ted Kremenek9865d7f2011-02-11 23:24:26 +0000145 const CFGBlock *currentBlock;
Ted Kremenekb56a9902007-09-06 00:17:54 +0000146public:
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000147 TransferFunctions(LiveVariablesImpl &im,
148 LiveVariables::LivenessValues &Val,
149 LiveVariables::Observer *Observer,
150 const CFGBlock *CurrentBlock)
151 : LV(im), val(Val), observer(Observer), currentBlock(CurrentBlock) {}
Ted Kremenekad8bce02007-09-25 04:31:27 +0000152
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000153 void VisitBinaryOperator(BinaryOperator *BO);
154 void VisitBlockExpr(BlockExpr *BE);
155 void VisitDeclRefExpr(DeclRefExpr *DR);
156 void VisitDeclStmt(DeclStmt *DS);
157 void VisitObjCForCollectionStmt(ObjCForCollectionStmt *OS);
158 void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *UE);
159 void VisitUnaryOperator(UnaryOperator *UO);
Mike Stump11289f42009-09-09 15:08:12 +0000160 void Visit(Stmt *S);
Ted Kremenekb56a9902007-09-06 00:17:54 +0000161};
Ted Kremenekfb4750b2007-10-01 20:33:52 +0000162}
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000163
Ted Kremenek84a1ca52011-08-06 00:30:00 +0000164static const VariableArrayType *FindVA(QualType Ty) {
165 const Type *ty = Ty.getTypePtr();
166 while (const ArrayType *VT = dyn_cast<ArrayType>(ty)) {
167 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(VT))
168 if (VAT->getSizeExpr())
169 return VAT;
170
171 ty = VT->getElementType().getTypePtr();
172 }
Craig Topper25542942014-05-20 04:30:07 +0000173
174 return nullptr;
Ted Kremenek84a1ca52011-08-06 00:30:00 +0000175}
176
Ted Kremenek57170492011-11-05 00:26:53 +0000177static const Stmt *LookThroughStmt(const Stmt *S) {
Ted Kremenek977e30d2011-11-05 07:34:28 +0000178 while (S) {
179 if (const Expr *Ex = dyn_cast<Expr>(S))
180 S = Ex->IgnoreParens();
John McCall29928fc2011-11-09 17:10:36 +0000181 if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(S)) {
182 S = EWC->getSubExpr();
183 continue;
184 }
Ted Kremenek977e30d2011-11-05 07:34:28 +0000185 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(S)) {
186 S = OVE->getSourceExpr();
187 continue;
188 }
189 break;
190 }
Ted Kremenek57170492011-11-05 00:26:53 +0000191 return S;
192}
193
194static void AddLiveStmt(llvm::ImmutableSet<const Stmt *> &Set,
195 llvm::ImmutableSet<const Stmt *>::Factory &F,
196 const Stmt *S) {
197 Set = F.add(Set, LookThroughStmt(S));
198}
199
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000200void TransferFunctions::Visit(Stmt *S) {
201 if (observer)
202 observer->observeStmt(S, currentBlock, val);
Ted Kremenek9c951ab2009-12-24 02:40:30 +0000203
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000204 StmtVisitor<TransferFunctions>::Visit(S);
Ted Kremenek0f5e6f882009-11-26 02:31:33 +0000205
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000206 if (isa<Expr>(S)) {
207 val.liveStmts = LV.SSetFact.remove(val.liveStmts, S);
208 }
209
210 // Mark all children expressions live.
211
212 switch (S->getStmtClass()) {
213 default:
214 break;
215 case Stmt::StmtExprClass: {
216 // For statement expressions, look through the compound statement.
217 S = cast<StmtExpr>(S)->getSubStmt();
218 break;
219 }
220 case Stmt::CXXMemberCallExprClass: {
221 // Include the implicit "this" pointer as being live.
222 CXXMemberCallExpr *CE = cast<CXXMemberCallExpr>(S);
Ted Kremenekb7531d62011-10-06 20:53:28 +0000223 if (Expr *ImplicitObj = CE->getImplicitObjectArgument()) {
Ted Kremenek57170492011-11-05 00:26:53 +0000224 AddLiveStmt(val.liveStmts, LV.SSetFact, ImplicitObj);
Ted Kremenekb7531d62011-10-06 20:53:28 +0000225 }
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000226 break;
227 }
Anna Zaks23665a12012-08-14 00:36:20 +0000228 case Stmt::ObjCMessageExprClass: {
229 // In calls to super, include the implicit "self" pointer as being live.
230 ObjCMessageExpr *CE = cast<ObjCMessageExpr>(S);
231 if (CE->getReceiverKind() == ObjCMessageExpr::SuperInstance)
232 val.liveDecls = LV.DSetFact.add(val.liveDecls,
233 LV.analysisContext.getSelfDecl());
234 break;
235 }
Ted Kremenek84a1ca52011-08-06 00:30:00 +0000236 case Stmt::DeclStmtClass: {
237 const DeclStmt *DS = cast<DeclStmt>(S);
238 if (const VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl())) {
239 for (const VariableArrayType* VA = FindVA(VD->getType());
Craig Topper25542942014-05-20 04:30:07 +0000240 VA != nullptr; VA = FindVA(VA->getElementType())) {
Ted Kremenek57170492011-11-05 00:26:53 +0000241 AddLiveStmt(val.liveStmts, LV.SSetFact, VA->getSizeExpr());
Ted Kremenek84a1ca52011-08-06 00:30:00 +0000242 }
243 }
244 break;
245 }
John McCallfe96e0b2011-11-06 09:01:30 +0000246 case Stmt::PseudoObjectExprClass: {
247 // A pseudo-object operation only directly consumes its result
248 // expression.
249 Expr *child = cast<PseudoObjectExpr>(S)->getResultExpr();
250 if (!child) return;
251 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(child))
252 child = OV->getSourceExpr();
253 child = child->IgnoreParens();
254 val.liveStmts = LV.SSetFact.add(val.liveStmts, child);
255 return;
256 }
257
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000258 // FIXME: These cases eventually shouldn't be needed.
259 case Stmt::ExprWithCleanupsClass: {
260 S = cast<ExprWithCleanups>(S)->getSubExpr();
261 break;
262 }
263 case Stmt::CXXBindTemporaryExprClass: {
264 S = cast<CXXBindTemporaryExpr>(S)->getSubExpr();
265 break;
266 }
Ted Kremenek84a1ca52011-08-06 00:30:00 +0000267 case Stmt::UnaryExprOrTypeTraitExprClass: {
268 // No need to unconditionally visit subexpressions.
269 return;
270 }
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000271 }
272
273 for (Stmt::child_iterator it = S->child_begin(), ei = S->child_end();
274 it != ei; ++it) {
Ted Kremenek57170492011-11-05 00:26:53 +0000275 if (Stmt *child = *it)
276 AddLiveStmt(val.liveStmts, LV.SSetFact, child);
Ted Kremenek0f5e6f882009-11-26 02:31:33 +0000277 }
Ted Kremenekb56a9902007-09-06 00:17:54 +0000278}
Mike Stump11289f42009-09-09 15:08:12 +0000279
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000280void TransferFunctions::VisitBinaryOperator(BinaryOperator *B) {
281 if (B->isAssignmentOp()) {
282 if (!LV.killAtAssign)
Ted Kremenekfc419a02008-11-14 21:07:14 +0000283 return;
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000284
285 // Assigning to a variable?
286 Expr *LHS = B->getLHS()->IgnoreParens();
287
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000288 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(LHS))
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000289 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
290 // Assignments to references don't kill the ref's address
291 if (VD->getType()->isReferenceType())
292 return;
Ted Kremenek3b4e1d52008-11-11 19:40:47 +0000293
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000294 if (!isAlwaysAlive(VD)) {
295 // The variable is now dead.
296 val.liveDecls = LV.DSetFact.remove(val.liveDecls, VD);
297 }
Ted Kremenekfbd2f402008-11-11 17:42:10 +0000298
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000299 if (observer)
300 observer->observerKill(DR);
Ted Kremenek20c91422008-02-22 00:34:10 +0000301 }
Ted Kremenek3f8ed262007-09-06 21:26:58 +0000302 }
303}
Mike Stump11289f42009-09-09 15:08:12 +0000304
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000305void TransferFunctions::VisitBlockExpr(BlockExpr *BE) {
Ted Kremenek299cfb72011-12-22 01:30:46 +0000306 AnalysisDeclContext::referenced_decls_iterator I, E;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000307 std::tie(I, E) =
Ted Kremenek299cfb72011-12-22 01:30:46 +0000308 LV.analysisContext.getReferencedBlockVars(BE->getBlockDecl());
309 for ( ; I != E ; ++I) {
310 const VarDecl *VD = *I;
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000311 if (isAlwaysAlive(VD))
312 continue;
313 val.liveDecls = LV.DSetFact.add(val.liveDecls, VD);
Ted Kremenekb56a9902007-09-06 00:17:54 +0000314 }
Ted Kremenekb56a9902007-09-06 00:17:54 +0000315}
316
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000317void TransferFunctions::VisitDeclRefExpr(DeclRefExpr *DR) {
318 if (const VarDecl *D = dyn_cast<VarDecl>(DR->getDecl()))
319 if (!isAlwaysAlive(D) && LV.inAssignment.find(DR) == LV.inAssignment.end())
320 val.liveDecls = LV.DSetFact.add(val.liveDecls, D);
321}
322
323void TransferFunctions::VisitDeclStmt(DeclStmt *DS) {
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000324 for (const auto *DI : DS->decls())
325 if (const auto *VD = dyn_cast<VarDecl>(DI)) {
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000326 if (!isAlwaysAlive(VD))
327 val.liveDecls = LV.DSetFact.remove(val.liveDecls, VD);
Ted Kremenek7845b262008-02-25 22:28:54 +0000328 }
Ted Kremenek3f8ed262007-09-06 21:26:58 +0000329}
Mike Stump11289f42009-09-09 15:08:12 +0000330
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000331void TransferFunctions::VisitObjCForCollectionStmt(ObjCForCollectionStmt *OS) {
332 // Kill the iteration variable.
Craig Topper25542942014-05-20 04:30:07 +0000333 DeclRefExpr *DR = nullptr;
334 const VarDecl *VD = nullptr;
Ted Kremenekb56a9902007-09-06 00:17:54 +0000335
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000336 Stmt *element = OS->getElement();
337 if (DeclStmt *DS = dyn_cast<DeclStmt>(element)) {
338 VD = cast<VarDecl>(DS->getSingleDecl());
339 }
340 else if ((DR = dyn_cast<DeclRefExpr>(cast<Expr>(element)->IgnoreParens()))) {
341 VD = cast<VarDecl>(DR->getDecl());
342 }
343
344 if (VD) {
345 val.liveDecls = LV.DSetFact.remove(val.liveDecls, VD);
346 if (observer && DR)
347 observer->observerKill(DR);
348 }
Ted Kremenekad8bce02007-09-25 04:31:27 +0000349}
Ted Kremenek3f8ed262007-09-06 21:26:58 +0000350
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000351void TransferFunctions::
352VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *UE)
353{
354 // While sizeof(var) doesn't technically extend the liveness of 'var', it
355 // does extent the liveness of metadata if 'var' is a VariableArrayType.
356 // We handle that special case here.
357 if (UE->getKind() != UETT_SizeOf || UE->isArgumentType())
358 return;
359
Ted Kremenek84a1ca52011-08-06 00:30:00 +0000360 const Expr *subEx = UE->getArgumentExpr();
361 if (subEx->getType()->isVariableArrayType()) {
362 assert(subEx->isLValue());
363 val.liveStmts = LV.SSetFact.add(val.liveStmts, subEx->IgnoreParens());
364 }
Ted Kremenek3f8ed262007-09-06 21:26:58 +0000365}
366
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000367void TransferFunctions::VisitUnaryOperator(UnaryOperator *UO) {
368 // Treat ++/-- as a kill.
369 // Note we don't actually have to do anything if we don't have an observer,
370 // since a ++/-- acts as both a kill and a "use".
371 if (!observer)
372 return;
373
374 switch (UO->getOpcode()) {
375 default:
376 return;
377 case UO_PostInc:
378 case UO_PostDec:
379 case UO_PreInc:
380 case UO_PreDec:
381 break;
382 }
383
384 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(UO->getSubExpr()->IgnoreParens()))
385 if (isa<VarDecl>(DR->getDecl())) {
386 // Treat ++/-- as a kill.
387 observer->observerKill(DR);
388 }
Ted Kremenek3f8ed262007-09-06 21:26:58 +0000389}
390
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000391LiveVariables::LivenessValues
392LiveVariablesImpl::runOnBlock(const CFGBlock *block,
393 LiveVariables::LivenessValues val,
394 LiveVariables::Observer *obs) {
395
396 TransferFunctions TF(*this, val, obs, block);
397
398 // Visit the terminator (if any).
399 if (const Stmt *term = block->getTerminator())
400 TF.Visit(const_cast<Stmt*>(term));
401
402 // Apply the transfer function for all Stmts in the block.
403 for (CFGBlock::const_reverse_iterator it = block->rbegin(),
404 ei = block->rend(); it != ei; ++it) {
405 const CFGElement &elem = *it;
Jordan Roseb3244562012-07-26 20:04:08 +0000406
David Blaikie00be69a2013-02-23 00:29:34 +0000407 if (Optional<CFGAutomaticObjDtor> Dtor =
408 elem.getAs<CFGAutomaticObjDtor>()) {
409 val.liveDecls = DSetFact.add(val.liveDecls, Dtor->getVarDecl());
Jordan Roseb3244562012-07-26 20:04:08 +0000410 continue;
411 }
412
David Blaikie2a01f5d2013-02-21 20:58:29 +0000413 if (!elem.getAs<CFGStmt>())
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000414 continue;
415
David Blaikie2a01f5d2013-02-21 20:58:29 +0000416 const Stmt *S = elem.castAs<CFGStmt>().getStmt();
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000417 TF.Visit(const_cast<Stmt*>(S));
418 stmtsToLiveness[S] = val;
419 }
420 return val;
Ted Kremenek6dc7b112007-09-06 23:00:42 +0000421}
422
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000423void LiveVariables::runOnAllBlocks(LiveVariables::Observer &obs) {
424 const CFG *cfg = getImpl(impl).analysisContext.getCFG();
425 for (CFG::const_iterator it = cfg->begin(), ei = cfg->end(); it != ei; ++it)
426 getImpl(impl).runOnBlock(*it, getImpl(impl).blocksEndToLiveness[*it], &obs);
Ted Kremenek85be7cf2008-01-17 20:48:37 +0000427}
428
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000429LiveVariables::LiveVariables(void *im) : impl(im) {}
430
431LiveVariables::~LiveVariables() {
432 delete (LiveVariablesImpl*) impl;
Ted Kremenek05ecfdd2008-01-18 00:40:21 +0000433}
434
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000435LiveVariables *
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000436LiveVariables::computeLiveness(AnalysisDeclContext &AC,
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000437 bool killAtAssign) {
Ted Kremenekb56a9902007-09-06 00:17:54 +0000438
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000439 // No CFG? Bail out.
440 CFG *cfg = AC.getCFG();
441 if (!cfg)
Craig Topper25542942014-05-20 04:30:07 +0000442 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000443
Ted Kremenekde21a1c2012-07-02 20:21:52 +0000444 // The analysis currently has scalability issues for very large CFGs.
445 // Bail out if it looks too large.
446 if (cfg->getNumBlockIDs() > 300000)
Craig Topper25542942014-05-20 04:30:07 +0000447 return nullptr;
Ted Kremenekde21a1c2012-07-02 20:21:52 +0000448
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000449 LiveVariablesImpl *LV = new LiveVariablesImpl(AC, killAtAssign);
450
451 // Construct the dataflow worklist. Enqueue the exit block as the
452 // start of the analysis.
Ted Kremenek5abde7c2011-10-22 02:14:23 +0000453 DataflowWorklist worklist(*cfg, AC);
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000454 llvm::BitVector everAnalyzedBlock(cfg->getNumBlockIDs());
455
456 // FIXME: we should enqueue using post order.
457 for (CFG::const_iterator it = cfg->begin(), ei = cfg->end(); it != ei; ++it) {
458 const CFGBlock *block = *it;
459 worklist.enqueueBlock(block);
460
461 // FIXME: Scan for DeclRefExprs using in the LHS of an assignment.
462 // We need to do this because we lack context in the reverse analysis
463 // to determine if a DeclRefExpr appears in such a context, and thus
464 // doesn't constitute a "use".
465 if (killAtAssign)
466 for (CFGBlock::const_iterator bi = block->begin(), be = block->end();
467 bi != be; ++bi) {
David Blaikie00be69a2013-02-23 00:29:34 +0000468 if (Optional<CFGStmt> cs = bi->getAs<CFGStmt>()) {
469 if (const BinaryOperator *BO =
470 dyn_cast<BinaryOperator>(cs->getStmt())) {
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000471 if (BO->getOpcode() == BO_Assign) {
472 if (const DeclRefExpr *DR =
473 dyn_cast<DeclRefExpr>(BO->getLHS()->IgnoreParens())) {
474 LV->inAssignment[DR] = 1;
475 }
476 }
477 }
478 }
479 }
480 }
481
Ted Kremenek459597a2011-09-16 23:01:39 +0000482 worklist.sortWorklist();
483
484 while (const CFGBlock *block = worklist.dequeue()) {
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000485 // Determine if the block's end value has changed. If not, we
486 // have nothing left to do for this block.
487 LivenessValues &prevVal = LV->blocksEndToLiveness[block];
488
489 // Merge the values of all successor blocks.
490 LivenessValues val;
491 for (CFGBlock::const_succ_iterator it = block->succ_begin(),
492 ei = block->succ_end(); it != ei; ++it) {
Ted Kremenek459597a2011-09-16 23:01:39 +0000493 if (const CFGBlock *succ = *it) {
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000494 val = LV->merge(val, LV->blocksBeginToLiveness[succ]);
Ted Kremenek459597a2011-09-16 23:01:39 +0000495 }
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000496 }
497
498 if (!everAnalyzedBlock[block->getBlockID()])
499 everAnalyzedBlock[block->getBlockID()] = true;
500 else if (prevVal.equals(val))
501 continue;
502
503 prevVal = val;
504
505 // Update the dataflow value for the start of this block.
506 LV->blocksBeginToLiveness[block] = LV->runOnBlock(block, val);
507
508 // Enqueue the value to the predecessors.
Ted Kremenek459597a2011-09-16 23:01:39 +0000509 worklist.enqueuePredecessors(block);
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000510 }
511
512 return new LiveVariables(LV);
513}
514
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000515void LiveVariables::dumpBlockLiveness(const SourceManager &M) {
516 getImpl(impl).dumpBlockLiveness(M);
517}
518
519void LiveVariablesImpl::dumpBlockLiveness(const SourceManager &M) {
520 std::vector<const CFGBlock *> vec;
521 for (llvm::DenseMap<const CFGBlock *, LiveVariables::LivenessValues>::iterator
522 it = blocksEndToLiveness.begin(), ei = blocksEndToLiveness.end();
523 it != ei; ++it) {
524 vec.push_back(it->first);
525 }
Benjamin Kramer15ae7832014-03-07 21:35:40 +0000526 std::sort(vec.begin(), vec.end(), [](const CFGBlock *A, const CFGBlock *B) {
527 return A->getBlockID() < B->getBlockID();
528 });
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000529
530 std::vector<const VarDecl*> declVec;
531
532 for (std::vector<const CFGBlock *>::iterator
533 it = vec.begin(), ei = vec.end(); it != ei; ++it) {
534 llvm::errs() << "\n[ B" << (*it)->getBlockID()
535 << " (live variables at block exit) ]\n";
536
537 LiveVariables::LivenessValues vals = blocksEndToLiveness[*it];
538 declVec.clear();
539
540 for (llvm::ImmutableSet<const VarDecl *>::iterator si =
541 vals.liveDecls.begin(),
542 se = vals.liveDecls.end(); si != se; ++si) {
543 declVec.push_back(*si);
544 }
Benjamin Kramer15ae7832014-03-07 21:35:40 +0000545
546 std::sort(declVec.begin(), declVec.end(), [](const Decl *A, const Decl *B) {
547 return A->getLocStart() < B->getLocStart();
548 });
549
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000550 for (std::vector<const VarDecl*>::iterator di = declVec.begin(),
551 de = declVec.end(); di != de; ++di) {
552 llvm::errs() << " " << (*di)->getDeclName().getAsString()
553 << " <";
554 (*di)->getLocation().dump(M);
Daniel Dunbare81a5532009-10-17 18:12:37 +0000555 llvm::errs() << ">\n";
Ted Kremenekb56a9902007-09-06 00:17:54 +0000556 }
Ted Kremenek3f8ed262007-09-06 21:26:58 +0000557 }
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000558 llvm::errs() << "\n";
Ted Kremenekbd9cc5c2007-09-10 17:36:42 +0000559}
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000560
Ted Kremenekdccc2b22011-10-07 22:21:02 +0000561const void *LiveVariables::getTag() { static int x; return &x; }
562const void *RelaxedLiveVariables::getTag() { static int x; return &x; }