blob: 1f616f7a5d9cda1583109ee0dd5d4a8bbf92fd18 [file] [log] [blame]
Benjamin Kramera93d0f22012-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 Kremenekcf6e41b2007-12-21 21:42:19 +000014#include "clang/Analysis/Analyses/LiveVariables.h"
Benjamin Kramera93d0f22012-12-01 17:12:56 +000015#include "clang/AST/Stmt.h"
Ted Kremenek88299892011-07-28 23:07:59 +000016#include "clang/AST/StmtVisitor.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000017#include "clang/Analysis/Analyses/PostOrderCFGView.h"
18#include "clang/Analysis/AnalysisContext.h"
19#include "clang/Analysis/CFG.h"
Ted Kremenek87aa1252011-09-16 23:01:39 +000020#include "llvm/ADT/DenseMap.h"
Benjamin Kramera93d0f22012-12-01 17:12:56 +000021#include "llvm/ADT/PostOrderIterator.h"
22#include "llvm/Support/raw_ostream.h"
Ted Kremenek88299892011-07-28 23:07:59 +000023#include <algorithm>
24#include <vector>
Ted Kremeneke4e63342007-09-06 00:17:54 +000025
26using namespace clang;
27
Ted Kremeneke4e63342007-09-06 00:17:54 +000028namespace {
Mike Stump1eb44332009-09-09 15:08:12 +000029
Ted Kremenek87aa1252011-09-16 23:01:39 +000030class DataflowWorklist {
31 SmallVector<const CFGBlock *, 20> worklist;
32 llvm::BitVector enqueuedBlocks;
Ted Kremenekedb18632011-10-22 02:14:23 +000033 PostOrderCFGView *POV;
Ted Kremenek87aa1252011-09-16 23:01:39 +000034public:
Ted Kremenek1d26f482011-10-24 01:32:45 +000035 DataflowWorklist(const CFG &cfg, AnalysisDeclContext &Ctx)
Ted Kremenek87aa1252011-09-16 23:01:39 +000036 : enqueuedBlocks(cfg.getNumBlockIDs()),
Ted Kremenekedb18632011-10-22 02:14:23 +000037 POV(Ctx.getAnalysis<PostOrderCFGView>()) {}
Ted Kremenek87aa1252011-09-16 23:01:39 +000038
39 void enqueueBlock(const CFGBlock *block);
40 void enqueueSuccessors(const CFGBlock *block);
41 void enqueuePredecessors(const CFGBlock *block);
42
43 const CFGBlock *dequeue();
44
45 void sortWorklist();
46};
47
48}
49
50void DataflowWorklist::enqueueBlock(const clang::CFGBlock *block) {
51 if (block && !enqueuedBlocks[block->getBlockID()]) {
52 enqueuedBlocks[block->getBlockID()] = true;
53 worklist.push_back(block);
54 }
55}
56
57void DataflowWorklist::enqueueSuccessors(const clang::CFGBlock *block) {
58 const unsigned OldWorklistSize = worklist.size();
59 for (CFGBlock::const_succ_iterator I = block->succ_begin(),
60 E = block->succ_end(); I != E; ++I) {
61 enqueueBlock(*I);
62 }
63
64 if (OldWorklistSize == 0 || OldWorklistSize == worklist.size())
65 return;
66
67 sortWorklist();
68}
69
70void DataflowWorklist::enqueuePredecessors(const clang::CFGBlock *block) {
71 const unsigned OldWorklistSize = worklist.size();
72 for (CFGBlock::const_pred_iterator I = block->pred_begin(),
73 E = block->pred_end(); I != E; ++I) {
74 enqueueBlock(*I);
75 }
76
77 if (OldWorklistSize == 0 || OldWorklistSize == worklist.size())
78 return;
79
80 sortWorklist();
81}
82
83void DataflowWorklist::sortWorklist() {
Ted Kremenekedb18632011-10-22 02:14:23 +000084 std::sort(worklist.begin(), worklist.end(), POV->getComparator());
Ted Kremenek87aa1252011-09-16 23:01:39 +000085}
86
Ted Kremenek87aa1252011-09-16 23:01:39 +000087const CFGBlock *DataflowWorklist::dequeue() {
88 if (worklist.empty())
89 return 0;
90 const CFGBlock *b = worklist.back();
91 worklist.pop_back();
92 enqueuedBlocks[b->getBlockID()] = false;
93 return b;
94}
95
96namespace {
97class LiveVariablesImpl {
98public:
Ted Kremenek1d26f482011-10-24 01:32:45 +000099 AnalysisDeclContext &analysisContext;
Ted Kremenek87aa1252011-09-16 23:01:39 +0000100 std::vector<LiveVariables::LivenessValues> cfgBlockValues;
101 llvm::ImmutableSet<const Stmt *>::Factory SSetFact;
102 llvm::ImmutableSet<const VarDecl *>::Factory DSetFact;
103 llvm::DenseMap<const CFGBlock *, LiveVariables::LivenessValues> blocksEndToLiveness;
104 llvm::DenseMap<const CFGBlock *, LiveVariables::LivenessValues> blocksBeginToLiveness;
105 llvm::DenseMap<const Stmt *, LiveVariables::LivenessValues> stmtsToLiveness;
106 llvm::DenseMap<const DeclRefExpr *, unsigned> inAssignment;
107 const bool killAtAssign;
108
109 LiveVariables::LivenessValues
110 merge(LiveVariables::LivenessValues valsA,
111 LiveVariables::LivenessValues valsB);
112
113 LiveVariables::LivenessValues runOnBlock(const CFGBlock *block,
114 LiveVariables::LivenessValues val,
115 LiveVariables::Observer *obs = 0);
116
117 void dumpBlockLiveness(const SourceManager& M);
118
Ted Kremenek1d26f482011-10-24 01:32:45 +0000119 LiveVariablesImpl(AnalysisDeclContext &ac, bool KillAtAssign)
Ted Kremenek3c2b5f72011-10-02 01:45:37 +0000120 : analysisContext(ac),
121 SSetFact(false), // Do not canonicalize ImmutableSets by default.
122 DSetFact(false), // This is a *major* performance win.
123 killAtAssign(KillAtAssign) {}
Ted Kremenek87aa1252011-09-16 23:01:39 +0000124};
Ted Kremenek88299892011-07-28 23:07:59 +0000125}
Ted Kremenek7deed0c2008-04-15 18:35:30 +0000126
Ted Kremenek9c378f72011-08-12 23:37:29 +0000127static LiveVariablesImpl &getImpl(void *x) {
Ted Kremenek88299892011-07-28 23:07:59 +0000128 return *((LiveVariablesImpl *) x);
Ted Kremenekfdd225e2007-09-25 04:31:27 +0000129}
Ted Kremeneke4e63342007-09-06 00:17:54 +0000130
131//===----------------------------------------------------------------------===//
Ted Kremenek88299892011-07-28 23:07:59 +0000132// Operations and queries on LivenessValues.
133//===----------------------------------------------------------------------===//
134
135bool LiveVariables::LivenessValues::isLive(const Stmt *S) const {
136 return liveStmts.contains(S);
137}
138
139bool LiveVariables::LivenessValues::isLive(const VarDecl *D) const {
140 return liveDecls.contains(D);
141}
142
143namespace {
144 template <typename SET>
Ted Kremenek87aa1252011-09-16 23:01:39 +0000145 SET mergeSets(SET A, SET B) {
146 if (A.isEmpty())
147 return B;
148
Ted Kremenek88299892011-07-28 23:07:59 +0000149 for (typename SET::iterator it = B.begin(), ei = B.end(); it != ei; ++it) {
Ted Kremenek87aa1252011-09-16 23:01:39 +0000150 A = A.add(*it);
Ted Kremenek88299892011-07-28 23:07:59 +0000151 }
152 return A;
153 }
154}
155
David Blaikie99ba9e32011-12-20 02:48:34 +0000156void LiveVariables::Observer::anchor() { }
157
Ted Kremenek88299892011-07-28 23:07:59 +0000158LiveVariables::LivenessValues
159LiveVariablesImpl::merge(LiveVariables::LivenessValues valsA,
160 LiveVariables::LivenessValues valsB) {
Ted Kremenek87aa1252011-09-16 23:01:39 +0000161
162 llvm::ImmutableSetRef<const Stmt *>
163 SSetRefA(valsA.liveStmts.getRootWithoutRetain(), SSetFact.getTreeFactory()),
164 SSetRefB(valsB.liveStmts.getRootWithoutRetain(), SSetFact.getTreeFactory());
165
166
167 llvm::ImmutableSetRef<const VarDecl *>
168 DSetRefA(valsA.liveDecls.getRootWithoutRetain(), DSetFact.getTreeFactory()),
169 DSetRefB(valsB.liveDecls.getRootWithoutRetain(), DSetFact.getTreeFactory());
170
171
172 SSetRefA = mergeSets(SSetRefA, SSetRefB);
173 DSetRefA = mergeSets(DSetRefA, DSetRefB);
174
Ted Kremenek3c2b5f72011-10-02 01:45:37 +0000175 // asImmutableSet() canonicalizes the tree, allowing us to do an easy
176 // comparison afterwards.
Ted Kremenek87aa1252011-09-16 23:01:39 +0000177 return LiveVariables::LivenessValues(SSetRefA.asImmutableSet(),
178 DSetRefA.asImmutableSet());
Ted Kremenek88299892011-07-28 23:07:59 +0000179}
180
181bool LiveVariables::LivenessValues::equals(const LivenessValues &V) const {
182 return liveStmts == V.liveStmts && liveDecls == V.liveDecls;
183}
184
185//===----------------------------------------------------------------------===//
186// Query methods.
187//===----------------------------------------------------------------------===//
188
189static bool isAlwaysAlive(const VarDecl *D) {
190 return D->hasGlobalStorage();
191}
192
193bool LiveVariables::isLive(const CFGBlock *B, const VarDecl *D) {
194 return isAlwaysAlive(D) || getImpl(impl).blocksEndToLiveness[B].isLive(D);
195}
196
197bool LiveVariables::isLive(const Stmt *S, const VarDecl *D) {
198 return isAlwaysAlive(D) || getImpl(impl).stmtsToLiveness[S].isLive(D);
199}
200
201bool LiveVariables::isLive(const Stmt *Loc, const Stmt *S) {
202 return getImpl(impl).stmtsToLiveness[Loc].isLive(S);
203}
204
205//===----------------------------------------------------------------------===//
206// Dataflow computation.
Mike Stump1eb44332009-09-09 15:08:12 +0000207//===----------------------------------------------------------------------===//
Ted Kremeneke4e63342007-09-06 00:17:54 +0000208
209namespace {
Ted Kremenek88299892011-07-28 23:07:59 +0000210class TransferFunctions : public StmtVisitor<TransferFunctions> {
211 LiveVariablesImpl &LV;
212 LiveVariables::LivenessValues &val;
213 LiveVariables::Observer *observer;
Ted Kremenek848ec832011-02-11 23:24:26 +0000214 const CFGBlock *currentBlock;
Ted Kremeneke4e63342007-09-06 00:17:54 +0000215public:
Ted Kremenek88299892011-07-28 23:07:59 +0000216 TransferFunctions(LiveVariablesImpl &im,
217 LiveVariables::LivenessValues &Val,
218 LiveVariables::Observer *Observer,
219 const CFGBlock *CurrentBlock)
220 : LV(im), val(Val), observer(Observer), currentBlock(CurrentBlock) {}
Ted Kremenekfdd225e2007-09-25 04:31:27 +0000221
Ted Kremenek88299892011-07-28 23:07:59 +0000222 void VisitBinaryOperator(BinaryOperator *BO);
223 void VisitBlockExpr(BlockExpr *BE);
224 void VisitDeclRefExpr(DeclRefExpr *DR);
225 void VisitDeclStmt(DeclStmt *DS);
226 void VisitObjCForCollectionStmt(ObjCForCollectionStmt *OS);
227 void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *UE);
228 void VisitUnaryOperator(UnaryOperator *UO);
Mike Stump1eb44332009-09-09 15:08:12 +0000229 void Visit(Stmt *S);
Ted Kremeneke4e63342007-09-06 00:17:54 +0000230};
Ted Kremenek11e72182007-10-01 20:33:52 +0000231}
Ted Kremenek88299892011-07-28 23:07:59 +0000232
Ted Kremenekf91a5b02011-08-06 00:30:00 +0000233static const VariableArrayType *FindVA(QualType Ty) {
234 const Type *ty = Ty.getTypePtr();
235 while (const ArrayType *VT = dyn_cast<ArrayType>(ty)) {
236 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(VT))
237 if (VAT->getSizeExpr())
238 return VAT;
239
240 ty = VT->getElementType().getTypePtr();
241 }
242
243 return 0;
244}
245
Ted Kremenekddaec0d2011-11-05 00:26:53 +0000246static const Stmt *LookThroughStmt(const Stmt *S) {
Ted Kremenek6bbecd52011-11-05 07:34:28 +0000247 while (S) {
248 if (const Expr *Ex = dyn_cast<Expr>(S))
249 S = Ex->IgnoreParens();
John McCallf3fb5c52011-11-09 17:10:36 +0000250 if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(S)) {
251 S = EWC->getSubExpr();
252 continue;
253 }
Ted Kremenek6bbecd52011-11-05 07:34:28 +0000254 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(S)) {
255 S = OVE->getSourceExpr();
256 continue;
257 }
258 break;
259 }
Ted Kremenekddaec0d2011-11-05 00:26:53 +0000260 return S;
261}
262
263static void AddLiveStmt(llvm::ImmutableSet<const Stmt *> &Set,
264 llvm::ImmutableSet<const Stmt *>::Factory &F,
265 const Stmt *S) {
266 Set = F.add(Set, LookThroughStmt(S));
267}
268
Ted Kremenek88299892011-07-28 23:07:59 +0000269void TransferFunctions::Visit(Stmt *S) {
270 if (observer)
271 observer->observeStmt(S, currentBlock, val);
Ted Kremenekbfbcefb2009-12-24 02:40:30 +0000272
Ted Kremenek88299892011-07-28 23:07:59 +0000273 StmtVisitor<TransferFunctions>::Visit(S);
Ted Kremenekb1a7b652009-11-26 02:31:33 +0000274
Ted Kremenek88299892011-07-28 23:07:59 +0000275 if (isa<Expr>(S)) {
276 val.liveStmts = LV.SSetFact.remove(val.liveStmts, S);
277 }
278
279 // Mark all children expressions live.
280
281 switch (S->getStmtClass()) {
282 default:
283 break;
284 case Stmt::StmtExprClass: {
285 // For statement expressions, look through the compound statement.
286 S = cast<StmtExpr>(S)->getSubStmt();
287 break;
288 }
289 case Stmt::CXXMemberCallExprClass: {
290 // Include the implicit "this" pointer as being live.
291 CXXMemberCallExpr *CE = cast<CXXMemberCallExpr>(S);
Ted Kremenekc8085032011-10-06 20:53:28 +0000292 if (Expr *ImplicitObj = CE->getImplicitObjectArgument()) {
Ted Kremenekddaec0d2011-11-05 00:26:53 +0000293 AddLiveStmt(val.liveStmts, LV.SSetFact, ImplicitObj);
Ted Kremenekc8085032011-10-06 20:53:28 +0000294 }
Ted Kremenek88299892011-07-28 23:07:59 +0000295 break;
296 }
Anna Zaksc7394062012-08-14 00:36:20 +0000297 case Stmt::ObjCMessageExprClass: {
298 // In calls to super, include the implicit "self" pointer as being live.
299 ObjCMessageExpr *CE = cast<ObjCMessageExpr>(S);
300 if (CE->getReceiverKind() == ObjCMessageExpr::SuperInstance)
301 val.liveDecls = LV.DSetFact.add(val.liveDecls,
302 LV.analysisContext.getSelfDecl());
303 break;
304 }
Ted Kremenekf91a5b02011-08-06 00:30:00 +0000305 case Stmt::DeclStmtClass: {
306 const DeclStmt *DS = cast<DeclStmt>(S);
307 if (const VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl())) {
308 for (const VariableArrayType* VA = FindVA(VD->getType());
309 VA != 0; VA = FindVA(VA->getElementType())) {
Ted Kremenekddaec0d2011-11-05 00:26:53 +0000310 AddLiveStmt(val.liveStmts, LV.SSetFact, VA->getSizeExpr());
Ted Kremenekf91a5b02011-08-06 00:30:00 +0000311 }
312 }
313 break;
314 }
John McCall4b9c2d22011-11-06 09:01:30 +0000315 case Stmt::PseudoObjectExprClass: {
316 // A pseudo-object operation only directly consumes its result
317 // expression.
318 Expr *child = cast<PseudoObjectExpr>(S)->getResultExpr();
319 if (!child) return;
320 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(child))
321 child = OV->getSourceExpr();
322 child = child->IgnoreParens();
323 val.liveStmts = LV.SSetFact.add(val.liveStmts, child);
324 return;
325 }
326
Ted Kremenek88299892011-07-28 23:07:59 +0000327 // FIXME: These cases eventually shouldn't be needed.
328 case Stmt::ExprWithCleanupsClass: {
329 S = cast<ExprWithCleanups>(S)->getSubExpr();
330 break;
331 }
332 case Stmt::CXXBindTemporaryExprClass: {
333 S = cast<CXXBindTemporaryExpr>(S)->getSubExpr();
334 break;
335 }
Ted Kremenekf91a5b02011-08-06 00:30:00 +0000336 case Stmt::UnaryExprOrTypeTraitExprClass: {
337 // No need to unconditionally visit subexpressions.
338 return;
339 }
Ted Kremenek88299892011-07-28 23:07:59 +0000340 }
341
342 for (Stmt::child_iterator it = S->child_begin(), ei = S->child_end();
343 it != ei; ++it) {
Ted Kremenekddaec0d2011-11-05 00:26:53 +0000344 if (Stmt *child = *it)
345 AddLiveStmt(val.liveStmts, LV.SSetFact, child);
Ted Kremenekb1a7b652009-11-26 02:31:33 +0000346 }
Ted Kremeneke4e63342007-09-06 00:17:54 +0000347}
Mike Stump1eb44332009-09-09 15:08:12 +0000348
Ted Kremenek88299892011-07-28 23:07:59 +0000349void TransferFunctions::VisitBinaryOperator(BinaryOperator *B) {
350 if (B->isAssignmentOp()) {
351 if (!LV.killAtAssign)
Ted Kremenek06529ae2008-11-14 21:07:14 +0000352 return;
Ted Kremenek88299892011-07-28 23:07:59 +0000353
354 // Assigning to a variable?
355 Expr *LHS = B->getLHS()->IgnoreParens();
356
Ted Kremenek9c378f72011-08-12 23:37:29 +0000357 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(LHS))
Ted Kremenek88299892011-07-28 23:07:59 +0000358 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
359 // Assignments to references don't kill the ref's address
360 if (VD->getType()->isReferenceType())
361 return;
Ted Kremeneke97d9db2008-11-11 19:40:47 +0000362
Ted Kremenek88299892011-07-28 23:07:59 +0000363 if (!isAlwaysAlive(VD)) {
364 // The variable is now dead.
365 val.liveDecls = LV.DSetFact.remove(val.liveDecls, VD);
366 }
Ted Kremenek8f5aab62008-11-11 17:42:10 +0000367
Ted Kremenek88299892011-07-28 23:07:59 +0000368 if (observer)
369 observer->observerKill(DR);
Ted Kremenek56206312008-02-22 00:34:10 +0000370 }
Ted Kremenek27b07c52007-09-06 21:26:58 +0000371 }
372}
Mike Stump1eb44332009-09-09 15:08:12 +0000373
Ted Kremenek88299892011-07-28 23:07:59 +0000374void TransferFunctions::VisitBlockExpr(BlockExpr *BE) {
Ted Kremenek15ce1642011-12-22 01:30:46 +0000375 AnalysisDeclContext::referenced_decls_iterator I, E;
376 llvm::tie(I, E) =
377 LV.analysisContext.getReferencedBlockVars(BE->getBlockDecl());
378 for ( ; I != E ; ++I) {
379 const VarDecl *VD = *I;
Ted Kremenek88299892011-07-28 23:07:59 +0000380 if (isAlwaysAlive(VD))
381 continue;
382 val.liveDecls = LV.DSetFact.add(val.liveDecls, VD);
Ted Kremeneke4e63342007-09-06 00:17:54 +0000383 }
Ted Kremeneke4e63342007-09-06 00:17:54 +0000384}
385
Ted Kremenek88299892011-07-28 23:07:59 +0000386void TransferFunctions::VisitDeclRefExpr(DeclRefExpr *DR) {
387 if (const VarDecl *D = dyn_cast<VarDecl>(DR->getDecl()))
388 if (!isAlwaysAlive(D) && LV.inAssignment.find(DR) == LV.inAssignment.end())
389 val.liveDecls = LV.DSetFact.add(val.liveDecls, D);
390}
391
392void TransferFunctions::VisitDeclStmt(DeclStmt *DS) {
Ted Kremenek14f8b4f2008-08-05 20:46:55 +0000393 for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE = DS->decl_end();
394 DI != DE; ++DI)
Ted Kremenek9c378f72011-08-12 23:37:29 +0000395 if (VarDecl *VD = dyn_cast<VarDecl>(*DI)) {
Ted Kremenek88299892011-07-28 23:07:59 +0000396 if (!isAlwaysAlive(VD))
397 val.liveDecls = LV.DSetFact.remove(val.liveDecls, VD);
Ted Kremenekdcc48102008-02-25 22:28:54 +0000398 }
Ted Kremenek27b07c52007-09-06 21:26:58 +0000399}
Mike Stump1eb44332009-09-09 15:08:12 +0000400
Ted Kremenek88299892011-07-28 23:07:59 +0000401void TransferFunctions::VisitObjCForCollectionStmt(ObjCForCollectionStmt *OS) {
402 // Kill the iteration variable.
403 DeclRefExpr *DR = 0;
404 const VarDecl *VD = 0;
Ted Kremeneke4e63342007-09-06 00:17:54 +0000405
Ted Kremenek88299892011-07-28 23:07:59 +0000406 Stmt *element = OS->getElement();
407 if (DeclStmt *DS = dyn_cast<DeclStmt>(element)) {
408 VD = cast<VarDecl>(DS->getSingleDecl());
409 }
410 else if ((DR = dyn_cast<DeclRefExpr>(cast<Expr>(element)->IgnoreParens()))) {
411 VD = cast<VarDecl>(DR->getDecl());
412 }
413
414 if (VD) {
415 val.liveDecls = LV.DSetFact.remove(val.liveDecls, VD);
416 if (observer && DR)
417 observer->observerKill(DR);
418 }
Ted Kremenekfdd225e2007-09-25 04:31:27 +0000419}
Ted Kremenek27b07c52007-09-06 21:26:58 +0000420
Ted Kremenek88299892011-07-28 23:07:59 +0000421void TransferFunctions::
422VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *UE)
423{
424 // While sizeof(var) doesn't technically extend the liveness of 'var', it
425 // does extent the liveness of metadata if 'var' is a VariableArrayType.
426 // We handle that special case here.
427 if (UE->getKind() != UETT_SizeOf || UE->isArgumentType())
428 return;
429
Ted Kremenekf91a5b02011-08-06 00:30:00 +0000430 const Expr *subEx = UE->getArgumentExpr();
431 if (subEx->getType()->isVariableArrayType()) {
432 assert(subEx->isLValue());
433 val.liveStmts = LV.SSetFact.add(val.liveStmts, subEx->IgnoreParens());
434 }
Ted Kremenek27b07c52007-09-06 21:26:58 +0000435}
436
Ted Kremenek88299892011-07-28 23:07:59 +0000437void TransferFunctions::VisitUnaryOperator(UnaryOperator *UO) {
438 // Treat ++/-- as a kill.
439 // Note we don't actually have to do anything if we don't have an observer,
440 // since a ++/-- acts as both a kill and a "use".
441 if (!observer)
442 return;
443
444 switch (UO->getOpcode()) {
445 default:
446 return;
447 case UO_PostInc:
448 case UO_PostDec:
449 case UO_PreInc:
450 case UO_PreDec:
451 break;
452 }
453
454 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(UO->getSubExpr()->IgnoreParens()))
455 if (isa<VarDecl>(DR->getDecl())) {
456 // Treat ++/-- as a kill.
457 observer->observerKill(DR);
458 }
Ted Kremenek27b07c52007-09-06 21:26:58 +0000459}
460
Ted Kremenek88299892011-07-28 23:07:59 +0000461LiveVariables::LivenessValues
462LiveVariablesImpl::runOnBlock(const CFGBlock *block,
463 LiveVariables::LivenessValues val,
464 LiveVariables::Observer *obs) {
465
466 TransferFunctions TF(*this, val, obs, block);
467
468 // Visit the terminator (if any).
469 if (const Stmt *term = block->getTerminator())
470 TF.Visit(const_cast<Stmt*>(term));
471
472 // Apply the transfer function for all Stmts in the block.
473 for (CFGBlock::const_reverse_iterator it = block->rbegin(),
474 ei = block->rend(); it != ei; ++it) {
475 const CFGElement &elem = *it;
Jordan Rosed7f1d132012-07-26 20:04:08 +0000476
477 if (const CFGAutomaticObjDtor *Dtor = dyn_cast<CFGAutomaticObjDtor>(&elem)){
478 val.liveDecls = DSetFact.add(val.liveDecls, Dtor->getVarDecl());
479 continue;
480 }
481
Ted Kremenek88299892011-07-28 23:07:59 +0000482 if (!isa<CFGStmt>(elem))
483 continue;
484
485 const Stmt *S = cast<CFGStmt>(elem).getStmt();
486 TF.Visit(const_cast<Stmt*>(S));
487 stmtsToLiveness[S] = val;
488 }
489 return val;
Ted Kremenek055c2752007-09-06 23:00:42 +0000490}
491
Ted Kremenek88299892011-07-28 23:07:59 +0000492void LiveVariables::runOnAllBlocks(LiveVariables::Observer &obs) {
493 const CFG *cfg = getImpl(impl).analysisContext.getCFG();
494 for (CFG::const_iterator it = cfg->begin(), ei = cfg->end(); it != ei; ++it)
495 getImpl(impl).runOnBlock(*it, getImpl(impl).blocksEndToLiveness[*it], &obs);
Ted Kremenek86946742008-01-17 20:48:37 +0000496}
497
Ted Kremenek88299892011-07-28 23:07:59 +0000498LiveVariables::LiveVariables(void *im) : impl(im) {}
499
500LiveVariables::~LiveVariables() {
501 delete (LiveVariablesImpl*) impl;
Ted Kremenek2a9da9c2008-01-18 00:40:21 +0000502}
503
Ted Kremenek88299892011-07-28 23:07:59 +0000504LiveVariables *
Ted Kremenek1d26f482011-10-24 01:32:45 +0000505LiveVariables::computeLiveness(AnalysisDeclContext &AC,
Ted Kremenek88299892011-07-28 23:07:59 +0000506 bool killAtAssign) {
Ted Kremeneke4e63342007-09-06 00:17:54 +0000507
Ted Kremenek88299892011-07-28 23:07:59 +0000508 // No CFG? Bail out.
509 CFG *cfg = AC.getCFG();
510 if (!cfg)
511 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000512
Ted Kremenekd4aeb802012-07-02 20:21:52 +0000513 // The analysis currently has scalability issues for very large CFGs.
514 // Bail out if it looks too large.
515 if (cfg->getNumBlockIDs() > 300000)
516 return 0;
517
Ted Kremenek88299892011-07-28 23:07:59 +0000518 LiveVariablesImpl *LV = new LiveVariablesImpl(AC, killAtAssign);
519
520 // Construct the dataflow worklist. Enqueue the exit block as the
521 // start of the analysis.
Ted Kremenekedb18632011-10-22 02:14:23 +0000522 DataflowWorklist worklist(*cfg, AC);
Ted Kremenek88299892011-07-28 23:07:59 +0000523 llvm::BitVector everAnalyzedBlock(cfg->getNumBlockIDs());
524
525 // FIXME: we should enqueue using post order.
526 for (CFG::const_iterator it = cfg->begin(), ei = cfg->end(); it != ei; ++it) {
527 const CFGBlock *block = *it;
528 worklist.enqueueBlock(block);
529
530 // FIXME: Scan for DeclRefExprs using in the LHS of an assignment.
531 // We need to do this because we lack context in the reverse analysis
532 // to determine if a DeclRefExpr appears in such a context, and thus
533 // doesn't constitute a "use".
534 if (killAtAssign)
535 for (CFGBlock::const_iterator bi = block->begin(), be = block->end();
536 bi != be; ++bi) {
537 if (const CFGStmt *cs = bi->getAs<CFGStmt>()) {
Ted Kremenekf1d10d92011-08-23 23:05:04 +0000538 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(cs->getStmt())) {
Ted Kremenek88299892011-07-28 23:07:59 +0000539 if (BO->getOpcode() == BO_Assign) {
540 if (const DeclRefExpr *DR =
541 dyn_cast<DeclRefExpr>(BO->getLHS()->IgnoreParens())) {
542 LV->inAssignment[DR] = 1;
543 }
544 }
545 }
546 }
547 }
548 }
549
Ted Kremenek87aa1252011-09-16 23:01:39 +0000550 worklist.sortWorklist();
551
552 while (const CFGBlock *block = worklist.dequeue()) {
Ted Kremenek88299892011-07-28 23:07:59 +0000553 // Determine if the block's end value has changed. If not, we
554 // have nothing left to do for this block.
555 LivenessValues &prevVal = LV->blocksEndToLiveness[block];
556
557 // Merge the values of all successor blocks.
558 LivenessValues val;
559 for (CFGBlock::const_succ_iterator it = block->succ_begin(),
560 ei = block->succ_end(); it != ei; ++it) {
Ted Kremenek87aa1252011-09-16 23:01:39 +0000561 if (const CFGBlock *succ = *it) {
Ted Kremenek88299892011-07-28 23:07:59 +0000562 val = LV->merge(val, LV->blocksBeginToLiveness[succ]);
Ted Kremenek87aa1252011-09-16 23:01:39 +0000563 }
Ted Kremenek88299892011-07-28 23:07:59 +0000564 }
565
566 if (!everAnalyzedBlock[block->getBlockID()])
567 everAnalyzedBlock[block->getBlockID()] = true;
568 else if (prevVal.equals(val))
569 continue;
570
571 prevVal = val;
572
573 // Update the dataflow value for the start of this block.
574 LV->blocksBeginToLiveness[block] = LV->runOnBlock(block, val);
575
576 // Enqueue the value to the predecessors.
Ted Kremenek87aa1252011-09-16 23:01:39 +0000577 worklist.enqueuePredecessors(block);
Ted Kremenek88299892011-07-28 23:07:59 +0000578 }
579
580 return new LiveVariables(LV);
581}
582
Benjamin Kramer39997fc2011-08-02 04:50:49 +0000583static bool compare_entries(const CFGBlock *A, const CFGBlock *B) {
Ted Kremenek88299892011-07-28 23:07:59 +0000584 return A->getBlockID() < B->getBlockID();
585}
Benjamin Kramer39997fc2011-08-02 04:50:49 +0000586
587static bool compare_vd_entries(const Decl *A, const Decl *B) {
Ted Kremenek88299892011-07-28 23:07:59 +0000588 SourceLocation ALoc = A->getLocStart();
589 SourceLocation BLoc = B->getLocStart();
590 return ALoc.getRawEncoding() < BLoc.getRawEncoding();
591}
592
593void LiveVariables::dumpBlockLiveness(const SourceManager &M) {
594 getImpl(impl).dumpBlockLiveness(M);
595}
596
597void LiveVariablesImpl::dumpBlockLiveness(const SourceManager &M) {
598 std::vector<const CFGBlock *> vec;
599 for (llvm::DenseMap<const CFGBlock *, LiveVariables::LivenessValues>::iterator
600 it = blocksEndToLiveness.begin(), ei = blocksEndToLiveness.end();
601 it != ei; ++it) {
602 vec.push_back(it->first);
603 }
604 std::sort(vec.begin(), vec.end(), compare_entries);
605
606 std::vector<const VarDecl*> declVec;
607
608 for (std::vector<const CFGBlock *>::iterator
609 it = vec.begin(), ei = vec.end(); it != ei; ++it) {
610 llvm::errs() << "\n[ B" << (*it)->getBlockID()
611 << " (live variables at block exit) ]\n";
612
613 LiveVariables::LivenessValues vals = blocksEndToLiveness[*it];
614 declVec.clear();
615
616 for (llvm::ImmutableSet<const VarDecl *>::iterator si =
617 vals.liveDecls.begin(),
618 se = vals.liveDecls.end(); si != se; ++si) {
619 declVec.push_back(*si);
620 }
621
622 std::sort(declVec.begin(), declVec.end(), compare_vd_entries);
623
624 for (std::vector<const VarDecl*>::iterator di = declVec.begin(),
625 de = declVec.end(); di != de; ++di) {
626 llvm::errs() << " " << (*di)->getDeclName().getAsString()
627 << " <";
628 (*di)->getLocation().dump(M);
Daniel Dunbarc0d56722009-10-17 18:12:37 +0000629 llvm::errs() << ">\n";
Ted Kremeneke4e63342007-09-06 00:17:54 +0000630 }
Ted Kremenek27b07c52007-09-06 21:26:58 +0000631 }
Ted Kremenek88299892011-07-28 23:07:59 +0000632 llvm::errs() << "\n";
Ted Kremenekc0576ca2007-09-10 17:36:42 +0000633}
Ted Kremenek88299892011-07-28 23:07:59 +0000634
Ted Kremeneka5937bb2011-10-07 22:21:02 +0000635const void *LiveVariables::getTag() { static int x; return &x; }
636const void *RelaxedLiveVariables::getTag() { static int x; return &x; }