blob: 4e063f4ca7421ca50ceee2e5e9cd9a1288634521 [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 Skrobov27720762014-09-23 08:34:41 +000017#include "clang/Analysis/Analyses/PostOrderCFGView.h"
George Karpenkov50657f62017-09-06 21:45:03 +000018#include "clang/Analysis/AnalysisDeclContext.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "clang/Analysis/CFG.h"
Ted Kremenek459597a2011-09-16 23:01:39 +000020#include "llvm/ADT/DenseMap.h"
Artyom Skrobov27720762014-09-23 08:34:41 +000021#include "llvm/ADT/PostOrderIterator.h"
Alexander Shaposhnikovfd905fc2016-10-13 21:31:46 +000022#include "llvm/ADT/PriorityQueue.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000023#include "llvm/Support/raw_ostream.h"
Ted Kremeneke9fda1e2011-07-28 23:07:59 +000024#include <algorithm>
25#include <vector>
Ted Kremenekb56a9902007-09-06 00:17:54 +000026
27using namespace clang;
28
Ted Kremenekb56a9902007-09-06 00:17:54 +000029namespace {
Artyom Skrobov27720762014-09-23 08:34:41 +000030
31class DataflowWorklist {
Artyom Skrobov27720762014-09-23 08:34:41 +000032 llvm::BitVector enqueuedBlocks;
33 PostOrderCFGView *POV;
Alexander Shaposhnikovfd905fc2016-10-13 21:31:46 +000034 llvm::PriorityQueue<const CFGBlock *, SmallVector<const CFGBlock *, 20>,
35 PostOrderCFGView::BlockOrderCompare> worklist;
36
Artyom Skrobov27720762014-09-23 08:34:41 +000037public:
38 DataflowWorklist(const CFG &cfg, AnalysisDeclContext &Ctx)
39 : enqueuedBlocks(cfg.getNumBlockIDs()),
Alexander Shaposhnikovfd905fc2016-10-13 21:31:46 +000040 POV(Ctx.getAnalysis<PostOrderCFGView>()),
41 worklist(POV->getComparator()) {}
Fangrui Song6907ce22018-07-30 19:24:48 +000042
Artyom Skrobov27720762014-09-23 08:34:41 +000043 void enqueueBlock(const CFGBlock *block);
44 void enqueuePredecessors(const CFGBlock *block);
45
46 const CFGBlock *dequeue();
Artyom Skrobov27720762014-09-23 08:34:41 +000047};
48
Alexander Kornienkoab9db512015-06-22 23:07:51 +000049}
Artyom Skrobov27720762014-09-23 08:34:41 +000050
51void DataflowWorklist::enqueueBlock(const clang::CFGBlock *block) {
52 if (block && !enqueuedBlocks[block->getBlockID()]) {
53 enqueuedBlocks[block->getBlockID()] = true;
Alexander Shaposhnikovfd905fc2016-10-13 21:31:46 +000054 worklist.push(block);
Artyom Skrobov27720762014-09-23 08:34:41 +000055 }
56}
57
58void DataflowWorklist::enqueuePredecessors(const clang::CFGBlock *block) {
Artyom Skrobov27720762014-09-23 08:34:41 +000059 for (CFGBlock::const_pred_iterator I = block->pred_begin(),
60 E = block->pred_end(); I != E; ++I) {
61 enqueueBlock(*I);
62 }
Artyom Skrobov27720762014-09-23 08:34:41 +000063}
64
65const CFGBlock *DataflowWorklist::dequeue() {
66 if (worklist.empty())
67 return nullptr;
Alexander Shaposhnikovfd905fc2016-10-13 21:31:46 +000068 const CFGBlock *b = worklist.top();
69 worklist.pop();
Artyom Skrobov27720762014-09-23 08:34:41 +000070 enqueuedBlocks[b->getBlockID()] = false;
71 return b;
72}
73
74namespace {
Ted Kremenek459597a2011-09-16 23:01:39 +000075class LiveVariablesImpl {
Fangrui Song6907ce22018-07-30 19:24:48 +000076public:
Ted Kremenek81ce1c82011-10-24 01:32:45 +000077 AnalysisDeclContext &analysisContext;
Ted Kremenek459597a2011-09-16 23:01:39 +000078 llvm::ImmutableSet<const Stmt *>::Factory SSetFact;
79 llvm::ImmutableSet<const VarDecl *>::Factory DSetFact;
George Karpenkov137ca912018-03-31 01:20:06 +000080 llvm::ImmutableSet<const BindingDecl *>::Factory BSetFact;
Ted Kremenek459597a2011-09-16 23:01:39 +000081 llvm::DenseMap<const CFGBlock *, LiveVariables::LivenessValues> blocksEndToLiveness;
82 llvm::DenseMap<const CFGBlock *, LiveVariables::LivenessValues> blocksBeginToLiveness;
83 llvm::DenseMap<const Stmt *, LiveVariables::LivenessValues> stmtsToLiveness;
84 llvm::DenseMap<const DeclRefExpr *, unsigned> inAssignment;
85 const bool killAtAssign;
Fangrui Song6907ce22018-07-30 19:24:48 +000086
Ted Kremenek459597a2011-09-16 23:01:39 +000087 LiveVariables::LivenessValues
88 merge(LiveVariables::LivenessValues valsA,
89 LiveVariables::LivenessValues valsB);
Craig Topper25542942014-05-20 04:30:07 +000090
91 LiveVariables::LivenessValues
92 runOnBlock(const CFGBlock *block, LiveVariables::LivenessValues val,
93 LiveVariables::Observer *obs = nullptr);
Ted Kremenek459597a2011-09-16 23:01:39 +000094
95 void dumpBlockLiveness(const SourceManager& M);
96
Ted Kremenek81ce1c82011-10-24 01:32:45 +000097 LiveVariablesImpl(AnalysisDeclContext &ac, bool KillAtAssign)
Ted Kremenekc8f008a2011-10-02 01:45:37 +000098 : analysisContext(ac),
99 SSetFact(false), // Do not canonicalize ImmutableSets by default.
100 DSetFact(false), // This is a *major* performance win.
George Karpenkov137ca912018-03-31 01:20:06 +0000101 BSetFact(false),
Ted Kremenekc8f008a2011-10-02 01:45:37 +0000102 killAtAssign(KillAtAssign) {}
Ted Kremenek459597a2011-09-16 23:01:39 +0000103};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000104}
Ted Kremenek82ff6d62008-04-15 18:35:30 +0000105
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000106static LiveVariablesImpl &getImpl(void *x) {
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000107 return *((LiveVariablesImpl *) x);
Ted Kremenekad8bce02007-09-25 04:31:27 +0000108}
Ted Kremenekb56a9902007-09-06 00:17:54 +0000109
110//===----------------------------------------------------------------------===//
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000111// Operations and queries on LivenessValues.
112//===----------------------------------------------------------------------===//
113
114bool LiveVariables::LivenessValues::isLive(const Stmt *S) const {
115 return liveStmts.contains(S);
116}
117
118bool LiveVariables::LivenessValues::isLive(const VarDecl *D) const {
George Karpenkov137ca912018-03-31 01:20:06 +0000119 if (const auto *DD = dyn_cast<DecompositionDecl>(D)) {
120 bool alive = false;
121 for (const BindingDecl *BD : DD->bindings())
122 alive |= liveBindings.contains(BD);
123 return alive;
124 }
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000125 return liveDecls.contains(D);
126}
127
128namespace {
129 template <typename SET>
Ted Kremenek459597a2011-09-16 23:01:39 +0000130 SET mergeSets(SET A, SET B) {
131 if (A.isEmpty())
132 return B;
Fangrui Song6907ce22018-07-30 19:24:48 +0000133
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000134 for (typename SET::iterator it = B.begin(), ei = B.end(); it != ei; ++it) {
Ted Kremenek459597a2011-09-16 23:01:39 +0000135 A = A.add(*it);
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000136 }
137 return A;
138 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000139}
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000140
David Blaikie68e081d2011-12-20 02:48:34 +0000141void LiveVariables::Observer::anchor() { }
142
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000143LiveVariables::LivenessValues
144LiveVariablesImpl::merge(LiveVariables::LivenessValues valsA,
Fangrui Song6907ce22018-07-30 19:24:48 +0000145 LiveVariables::LivenessValues valsB) {
146
Ted Kremenek459597a2011-09-16 23:01:39 +0000147 llvm::ImmutableSetRef<const Stmt *>
148 SSetRefA(valsA.liveStmts.getRootWithoutRetain(), SSetFact.getTreeFactory()),
149 SSetRefB(valsB.liveStmts.getRootWithoutRetain(), SSetFact.getTreeFactory());
Fangrui Song6907ce22018-07-30 19:24:48 +0000150
151
Ted Kremenek459597a2011-09-16 23:01:39 +0000152 llvm::ImmutableSetRef<const VarDecl *>
153 DSetRefA(valsA.liveDecls.getRootWithoutRetain(), DSetFact.getTreeFactory()),
154 DSetRefB(valsB.liveDecls.getRootWithoutRetain(), DSetFact.getTreeFactory());
Fangrui Song6907ce22018-07-30 19:24:48 +0000155
George Karpenkov137ca912018-03-31 01:20:06 +0000156 llvm::ImmutableSetRef<const BindingDecl *>
157 BSetRefA(valsA.liveBindings.getRootWithoutRetain(), BSetFact.getTreeFactory()),
158 BSetRefB(valsB.liveBindings.getRootWithoutRetain(), BSetFact.getTreeFactory());
Ted Kremenek459597a2011-09-16 23:01:39 +0000159
160 SSetRefA = mergeSets(SSetRefA, SSetRefB);
161 DSetRefA = mergeSets(DSetRefA, DSetRefB);
George Karpenkov137ca912018-03-31 01:20:06 +0000162 BSetRefA = mergeSets(BSetRefA, BSetRefB);
Fangrui Song6907ce22018-07-30 19:24:48 +0000163
Ted Kremenekc8f008a2011-10-02 01:45:37 +0000164 // asImmutableSet() canonicalizes the tree, allowing us to do an easy
165 // comparison afterwards.
Ted Kremenek459597a2011-09-16 23:01:39 +0000166 return LiveVariables::LivenessValues(SSetRefA.asImmutableSet(),
George Karpenkov137ca912018-03-31 01:20:06 +0000167 DSetRefA.asImmutableSet(),
Fangrui Song6907ce22018-07-30 19:24:48 +0000168 BSetRefA.asImmutableSet());
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000169}
170
171bool LiveVariables::LivenessValues::equals(const LivenessValues &V) const {
172 return liveStmts == V.liveStmts && liveDecls == V.liveDecls;
173}
174
175//===----------------------------------------------------------------------===//
176// Query methods.
177//===----------------------------------------------------------------------===//
178
179static bool isAlwaysAlive(const VarDecl *D) {
180 return D->hasGlobalStorage();
181}
182
183bool LiveVariables::isLive(const CFGBlock *B, const VarDecl *D) {
184 return isAlwaysAlive(D) || getImpl(impl).blocksEndToLiveness[B].isLive(D);
185}
186
187bool LiveVariables::isLive(const Stmt *S, const VarDecl *D) {
188 return isAlwaysAlive(D) || getImpl(impl).stmtsToLiveness[S].isLive(D);
189}
190
191bool LiveVariables::isLive(const Stmt *Loc, const Stmt *S) {
192 return getImpl(impl).stmtsToLiveness[Loc].isLive(S);
193}
194
195//===----------------------------------------------------------------------===//
196// Dataflow computation.
Mike Stump11289f42009-09-09 15:08:12 +0000197//===----------------------------------------------------------------------===//
Ted Kremenekb56a9902007-09-06 00:17:54 +0000198
199namespace {
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000200class TransferFunctions : public StmtVisitor<TransferFunctions> {
201 LiveVariablesImpl &LV;
202 LiveVariables::LivenessValues &val;
203 LiveVariables::Observer *observer;
Ted Kremenek9865d7f2011-02-11 23:24:26 +0000204 const CFGBlock *currentBlock;
Ted Kremenekb56a9902007-09-06 00:17:54 +0000205public:
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000206 TransferFunctions(LiveVariablesImpl &im,
207 LiveVariables::LivenessValues &Val,
208 LiveVariables::Observer *Observer,
209 const CFGBlock *CurrentBlock)
210 : LV(im), val(Val), observer(Observer), currentBlock(CurrentBlock) {}
Ted Kremenekad8bce02007-09-25 04:31:27 +0000211
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000212 void VisitBinaryOperator(BinaryOperator *BO);
213 void VisitBlockExpr(BlockExpr *BE);
Fangrui Song6907ce22018-07-30 19:24:48 +0000214 void VisitDeclRefExpr(DeclRefExpr *DR);
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000215 void VisitDeclStmt(DeclStmt *DS);
216 void VisitObjCForCollectionStmt(ObjCForCollectionStmt *OS);
217 void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *UE);
218 void VisitUnaryOperator(UnaryOperator *UO);
Mike Stump11289f42009-09-09 15:08:12 +0000219 void Visit(Stmt *S);
Ted Kremenekb56a9902007-09-06 00:17:54 +0000220};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000221}
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000222
Ted Kremenek84a1ca52011-08-06 00:30:00 +0000223static const VariableArrayType *FindVA(QualType Ty) {
224 const Type *ty = Ty.getTypePtr();
225 while (const ArrayType *VT = dyn_cast<ArrayType>(ty)) {
226 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(VT))
227 if (VAT->getSizeExpr())
228 return VAT;
Fangrui Song6907ce22018-07-30 19:24:48 +0000229
Ted Kremenek84a1ca52011-08-06 00:30:00 +0000230 ty = VT->getElementType().getTypePtr();
231 }
Craig Topper25542942014-05-20 04:30:07 +0000232
233 return nullptr;
Ted Kremenek84a1ca52011-08-06 00:30:00 +0000234}
235
Ted Kremenek57170492011-11-05 00:26:53 +0000236static const Stmt *LookThroughStmt(const Stmt *S) {
Ted Kremenek977e30d2011-11-05 07:34:28 +0000237 while (S) {
238 if (const Expr *Ex = dyn_cast<Expr>(S))
Fangrui Song6907ce22018-07-30 19:24:48 +0000239 S = Ex->IgnoreParens();
John McCall29928fc2011-11-09 17:10:36 +0000240 if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(S)) {
241 S = EWC->getSubExpr();
242 continue;
243 }
Ted Kremenek977e30d2011-11-05 07:34:28 +0000244 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(S)) {
245 S = OVE->getSourceExpr();
246 continue;
247 }
248 break;
249 }
Ted Kremenek57170492011-11-05 00:26:53 +0000250 return S;
251}
252
253static void AddLiveStmt(llvm::ImmutableSet<const Stmt *> &Set,
254 llvm::ImmutableSet<const Stmt *>::Factory &F,
255 const Stmt *S) {
256 Set = F.add(Set, LookThroughStmt(S));
257}
258
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000259void TransferFunctions::Visit(Stmt *S) {
260 if (observer)
261 observer->observeStmt(S, currentBlock, val);
Fangrui Song6907ce22018-07-30 19:24:48 +0000262
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000263 StmtVisitor<TransferFunctions>::Visit(S);
Fangrui Song6907ce22018-07-30 19:24:48 +0000264
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000265 if (isa<Expr>(S)) {
266 val.liveStmts = LV.SSetFact.remove(val.liveStmts, S);
267 }
268
269 // Mark all children expressions live.
Fangrui Song6907ce22018-07-30 19:24:48 +0000270
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000271 switch (S->getStmtClass()) {
272 default:
273 break;
274 case Stmt::StmtExprClass: {
275 // For statement expressions, look through the compound statement.
276 S = cast<StmtExpr>(S)->getSubStmt();
277 break;
278 }
279 case Stmt::CXXMemberCallExprClass: {
280 // Include the implicit "this" pointer as being live.
281 CXXMemberCallExpr *CE = cast<CXXMemberCallExpr>(S);
Ted Kremenekb7531d62011-10-06 20:53:28 +0000282 if (Expr *ImplicitObj = CE->getImplicitObjectArgument()) {
Ted Kremenek57170492011-11-05 00:26:53 +0000283 AddLiveStmt(val.liveStmts, LV.SSetFact, ImplicitObj);
Ted Kremenekb7531d62011-10-06 20:53:28 +0000284 }
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000285 break;
286 }
Anna Zaks23665a12012-08-14 00:36:20 +0000287 case Stmt::ObjCMessageExprClass: {
288 // In calls to super, include the implicit "self" pointer as being live.
289 ObjCMessageExpr *CE = cast<ObjCMessageExpr>(S);
290 if (CE->getReceiverKind() == ObjCMessageExpr::SuperInstance)
291 val.liveDecls = LV.DSetFact.add(val.liveDecls,
292 LV.analysisContext.getSelfDecl());
293 break;
294 }
Ted Kremenek84a1ca52011-08-06 00:30:00 +0000295 case Stmt::DeclStmtClass: {
296 const DeclStmt *DS = cast<DeclStmt>(S);
297 if (const VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl())) {
298 for (const VariableArrayType* VA = FindVA(VD->getType());
Craig Topper25542942014-05-20 04:30:07 +0000299 VA != nullptr; VA = FindVA(VA->getElementType())) {
Ted Kremenek57170492011-11-05 00:26:53 +0000300 AddLiveStmt(val.liveStmts, LV.SSetFact, VA->getSizeExpr());
Ted Kremenek84a1ca52011-08-06 00:30:00 +0000301 }
302 }
303 break;
304 }
John McCallfe96e0b2011-11-06 09:01:30 +0000305 case Stmt::PseudoObjectExprClass: {
306 // A pseudo-object operation only directly consumes its result
307 // expression.
308 Expr *child = cast<PseudoObjectExpr>(S)->getResultExpr();
309 if (!child) return;
310 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(child))
311 child = OV->getSourceExpr();
312 child = child->IgnoreParens();
313 val.liveStmts = LV.SSetFact.add(val.liveStmts, child);
314 return;
315 }
316
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000317 // FIXME: These cases eventually shouldn't be needed.
318 case Stmt::ExprWithCleanupsClass: {
319 S = cast<ExprWithCleanups>(S)->getSubExpr();
320 break;
321 }
322 case Stmt::CXXBindTemporaryExprClass: {
323 S = cast<CXXBindTemporaryExpr>(S)->getSubExpr();
324 break;
325 }
Ted Kremenek84a1ca52011-08-06 00:30:00 +0000326 case Stmt::UnaryExprOrTypeTraitExprClass: {
327 // No need to unconditionally visit subexpressions.
328 return;
329 }
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000330 }
Benjamin Kramer973431b2015-07-03 15:12:24 +0000331
332 for (Stmt *Child : S->children()) {
333 if (Child)
334 AddLiveStmt(val.liveStmts, LV.SSetFact, Child);
Ted Kremenek0f5e6f882009-11-26 02:31:33 +0000335 }
Ted Kremenekb56a9902007-09-06 00:17:54 +0000336}
Mike Stump11289f42009-09-09 15:08:12 +0000337
George Karpenkov137ca912018-03-31 01:20:06 +0000338static bool writeShouldKill(const VarDecl *VD) {
339 return VD && !VD->getType()->isReferenceType() &&
340 !isAlwaysAlive(VD);
341}
342
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000343void TransferFunctions::VisitBinaryOperator(BinaryOperator *B) {
344 if (B->isAssignmentOp()) {
345 if (!LV.killAtAssign)
Ted Kremenekfc419a02008-11-14 21:07:14 +0000346 return;
Fangrui Song6907ce22018-07-30 19:24:48 +0000347
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000348 // Assigning to a variable?
349 Expr *LHS = B->getLHS()->IgnoreParens();
Ted Kremenek3b4e1d52008-11-11 19:40:47 +0000350
George Karpenkov137ca912018-03-31 01:20:06 +0000351 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(LHS)) {
352 const Decl* D = DR->getDecl();
353 bool Killed = false;
354
355 if (const BindingDecl* BD = dyn_cast<BindingDecl>(D)) {
356 Killed = !BD->getType()->isReferenceType();
357 if (Killed)
358 val.liveBindings = LV.BSetFact.remove(val.liveBindings, BD);
359 } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
360 Killed = writeShouldKill(VD);
361 if (Killed)
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000362 val.liveDecls = LV.DSetFact.remove(val.liveDecls, VD);
Ted Kremenekfbd2f402008-11-11 17:42:10 +0000363
Ted Kremenek20c91422008-02-22 00:34:10 +0000364 }
George Karpenkov137ca912018-03-31 01:20:06 +0000365
366 if (Killed && observer)
367 observer->observerKill(DR);
368 }
Ted Kremenek3f8ed262007-09-06 21:26:58 +0000369 }
370}
Mike Stump11289f42009-09-09 15:08:12 +0000371
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000372void TransferFunctions::VisitBlockExpr(BlockExpr *BE) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000373 for (const VarDecl *VD :
374 LV.analysisContext.getReferencedBlockVars(BE->getBlockDecl())) {
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000375 if (isAlwaysAlive(VD))
376 continue;
377 val.liveDecls = LV.DSetFact.add(val.liveDecls, VD);
Ted Kremenekb56a9902007-09-06 00:17:54 +0000378 }
Ted Kremenekb56a9902007-09-06 00:17:54 +0000379}
380
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000381void TransferFunctions::VisitDeclRefExpr(DeclRefExpr *DR) {
George Karpenkov137ca912018-03-31 01:20:06 +0000382 const Decl* D = DR->getDecl();
383 bool InAssignment = LV.inAssignment[DR];
George Karpenkovdbddadd2018-04-06 19:14:05 +0000384 if (const auto *BD = dyn_cast<BindingDecl>(D)) {
George Karpenkov137ca912018-03-31 01:20:06 +0000385 if (!InAssignment)
Andrea Di Biagiod3144ea2018-04-02 12:04:37 +0000386 val.liveBindings = LV.BSetFact.add(val.liveBindings, BD);
George Karpenkov137ca912018-03-31 01:20:06 +0000387 } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
388 if (!InAssignment && !isAlwaysAlive(VD))
389 val.liveDecls = LV.DSetFact.add(val.liveDecls, VD);
390 }
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000391}
392
393void TransferFunctions::VisitDeclStmt(DeclStmt *DS) {
George Karpenkov137ca912018-03-31 01:20:06 +0000394 for (const auto *DI : DS->decls()) {
395 if (const auto *DD = dyn_cast<DecompositionDecl>(DI)) {
396 for (const auto *BD : DD->bindings())
397 val.liveBindings = LV.BSetFact.remove(val.liveBindings, BD);
398 } else if (const auto *VD = dyn_cast<VarDecl>(DI)) {
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000399 if (!isAlwaysAlive(VD))
400 val.liveDecls = LV.DSetFact.remove(val.liveDecls, VD);
Ted Kremenek7845b262008-02-25 22:28:54 +0000401 }
George Karpenkov137ca912018-03-31 01:20:06 +0000402 }
Ted Kremenek3f8ed262007-09-06 21:26:58 +0000403}
Mike Stump11289f42009-09-09 15:08:12 +0000404
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000405void TransferFunctions::VisitObjCForCollectionStmt(ObjCForCollectionStmt *OS) {
406 // Kill the iteration variable.
Craig Topper25542942014-05-20 04:30:07 +0000407 DeclRefExpr *DR = nullptr;
408 const VarDecl *VD = nullptr;
Ted Kremenekb56a9902007-09-06 00:17:54 +0000409
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000410 Stmt *element = OS->getElement();
411 if (DeclStmt *DS = dyn_cast<DeclStmt>(element)) {
412 VD = cast<VarDecl>(DS->getSingleDecl());
413 }
414 else if ((DR = dyn_cast<DeclRefExpr>(cast<Expr>(element)->IgnoreParens()))) {
415 VD = cast<VarDecl>(DR->getDecl());
416 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000417
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000418 if (VD) {
419 val.liveDecls = LV.DSetFact.remove(val.liveDecls, VD);
420 if (observer && DR)
421 observer->observerKill(DR);
422 }
Ted Kremenekad8bce02007-09-25 04:31:27 +0000423}
Ted Kremenek3f8ed262007-09-06 21:26:58 +0000424
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000425void TransferFunctions::
426VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *UE)
427{
428 // While sizeof(var) doesn't technically extend the liveness of 'var', it
429 // does extent the liveness of metadata if 'var' is a VariableArrayType.
430 // We handle that special case here.
431 if (UE->getKind() != UETT_SizeOf || UE->isArgumentType())
432 return;
433
Ted Kremenek84a1ca52011-08-06 00:30:00 +0000434 const Expr *subEx = UE->getArgumentExpr();
435 if (subEx->getType()->isVariableArrayType()) {
436 assert(subEx->isLValue());
437 val.liveStmts = LV.SSetFact.add(val.liveStmts, subEx->IgnoreParens());
438 }
Ted Kremenek3f8ed262007-09-06 21:26:58 +0000439}
440
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000441void TransferFunctions::VisitUnaryOperator(UnaryOperator *UO) {
442 // Treat ++/-- as a kill.
443 // Note we don't actually have to do anything if we don't have an observer,
444 // since a ++/-- acts as both a kill and a "use".
445 if (!observer)
446 return;
Fangrui Song6907ce22018-07-30 19:24:48 +0000447
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000448 switch (UO->getOpcode()) {
449 default:
450 return;
451 case UO_PostInc:
Fangrui Song6907ce22018-07-30 19:24:48 +0000452 case UO_PostDec:
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000453 case UO_PreInc:
454 case UO_PreDec:
455 break;
456 }
George Karpenkov137ca912018-03-31 01:20:06 +0000457
458 if (auto *DR = dyn_cast<DeclRefExpr>(UO->getSubExpr()->IgnoreParens())) {
459 const Decl *D = DR->getDecl();
460 if (isa<VarDecl>(D) || isa<BindingDecl>(D)) {
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000461 // Treat ++/-- as a kill.
462 observer->observerKill(DR);
463 }
George Karpenkov137ca912018-03-31 01:20:06 +0000464 }
Ted Kremenek3f8ed262007-09-06 21:26:58 +0000465}
466
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000467LiveVariables::LivenessValues
468LiveVariablesImpl::runOnBlock(const CFGBlock *block,
469 LiveVariables::LivenessValues val,
470 LiveVariables::Observer *obs) {
471
472 TransferFunctions TF(*this, val, obs, block);
Fangrui Song6907ce22018-07-30 19:24:48 +0000473
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000474 // Visit the terminator (if any).
475 if (const Stmt *term = block->getTerminator())
476 TF.Visit(const_cast<Stmt*>(term));
Fangrui Song6907ce22018-07-30 19:24:48 +0000477
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000478 // Apply the transfer function for all Stmts in the block.
479 for (CFGBlock::const_reverse_iterator it = block->rbegin(),
480 ei = block->rend(); it != ei; ++it) {
481 const CFGElement &elem = *it;
Jordan Roseb3244562012-07-26 20:04:08 +0000482
David Blaikie00be69a2013-02-23 00:29:34 +0000483 if (Optional<CFGAutomaticObjDtor> Dtor =
484 elem.getAs<CFGAutomaticObjDtor>()) {
485 val.liveDecls = DSetFact.add(val.liveDecls, Dtor->getVarDecl());
Jordan Roseb3244562012-07-26 20:04:08 +0000486 continue;
487 }
488
David Blaikie2a01f5d2013-02-21 20:58:29 +0000489 if (!elem.getAs<CFGStmt>())
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000490 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +0000491
David Blaikie2a01f5d2013-02-21 20:58:29 +0000492 const Stmt *S = elem.castAs<CFGStmt>().getStmt();
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000493 TF.Visit(const_cast<Stmt*>(S));
494 stmtsToLiveness[S] = val;
495 }
496 return val;
Ted Kremenek6dc7b112007-09-06 23:00:42 +0000497}
498
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000499void LiveVariables::runOnAllBlocks(LiveVariables::Observer &obs) {
500 const CFG *cfg = getImpl(impl).analysisContext.getCFG();
501 for (CFG::const_iterator it = cfg->begin(), ei = cfg->end(); it != ei; ++it)
Fangrui Song6907ce22018-07-30 19:24:48 +0000502 getImpl(impl).runOnBlock(*it, getImpl(impl).blocksEndToLiveness[*it], &obs);
Ted Kremenek85be7cf2008-01-17 20:48:37 +0000503}
504
Fangrui Song6907ce22018-07-30 19:24:48 +0000505LiveVariables::LiveVariables(void *im) : impl(im) {}
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000506
507LiveVariables::~LiveVariables() {
508 delete (LiveVariablesImpl*) impl;
Ted Kremenek05ecfdd2008-01-18 00:40:21 +0000509}
510
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000511LiveVariables *
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000512LiveVariables::computeLiveness(AnalysisDeclContext &AC,
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000513 bool killAtAssign) {
Ted Kremenekb56a9902007-09-06 00:17:54 +0000514
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000515 // No CFG? Bail out.
516 CFG *cfg = AC.getCFG();
517 if (!cfg)
Craig Topper25542942014-05-20 04:30:07 +0000518 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000519
Ted Kremenekde21a1c2012-07-02 20:21:52 +0000520 // The analysis currently has scalability issues for very large CFGs.
521 // Bail out if it looks too large.
522 if (cfg->getNumBlockIDs() > 300000)
Craig Topper25542942014-05-20 04:30:07 +0000523 return nullptr;
Ted Kremenekde21a1c2012-07-02 20:21:52 +0000524
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000525 LiveVariablesImpl *LV = new LiveVariablesImpl(AC, killAtAssign);
526
Artyom Skrobov27720762014-09-23 08:34:41 +0000527 // Construct the dataflow worklist. Enqueue the exit block as the
528 // start of the analysis.
529 DataflowWorklist worklist(*cfg, AC);
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000530 llvm::BitVector everAnalyzedBlock(cfg->getNumBlockIDs());
531
Artyom Skrobov27720762014-09-23 08:34:41 +0000532 // FIXME: we should enqueue using post order.
533 for (CFG::const_iterator it = cfg->begin(), ei = cfg->end(); it != ei; ++it) {
534 const CFGBlock *block = *it;
535 worklist.enqueueBlock(block);
Fangrui Song6907ce22018-07-30 19:24:48 +0000536
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000537 // FIXME: Scan for DeclRefExprs using in the LHS of an assignment.
538 // We need to do this because we lack context in the reverse analysis
539 // to determine if a DeclRefExpr appears in such a context, and thus
540 // doesn't constitute a "use".
Artyom Skrobov27720762014-09-23 08:34:41 +0000541 if (killAtAssign)
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000542 for (CFGBlock::const_iterator bi = block->begin(), be = block->end();
543 bi != be; ++bi) {
David Blaikie00be69a2013-02-23 00:29:34 +0000544 if (Optional<CFGStmt> cs = bi->getAs<CFGStmt>()) {
George Karpenkov137ca912018-03-31 01:20:06 +0000545 const Stmt* stmt = cs->getStmt();
546 if (const auto *BO = dyn_cast<BinaryOperator>(stmt)) {
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000547 if (BO->getOpcode() == BO_Assign) {
George Karpenkov137ca912018-03-31 01:20:06 +0000548 if (const auto *DR =
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000549 dyn_cast<DeclRefExpr>(BO->getLHS()->IgnoreParens())) {
550 LV->inAssignment[DR] = 1;
551 }
552 }
553 }
554 }
555 }
Artyom Skrobov27720762014-09-23 08:34:41 +0000556 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000557
Artyom Skrobov27720762014-09-23 08:34:41 +0000558 while (const CFGBlock *block = worklist.dequeue()) {
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000559 // Determine if the block's end value has changed. If not, we
560 // have nothing left to do for this block.
561 LivenessValues &prevVal = LV->blocksEndToLiveness[block];
Fangrui Song6907ce22018-07-30 19:24:48 +0000562
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000563 // Merge the values of all successor blocks.
564 LivenessValues val;
565 for (CFGBlock::const_succ_iterator it = block->succ_begin(),
566 ei = block->succ_end(); it != ei; ++it) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000567 if (const CFGBlock *succ = *it) {
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000568 val = LV->merge(val, LV->blocksBeginToLiveness[succ]);
Ted Kremenek459597a2011-09-16 23:01:39 +0000569 }
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000570 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000571
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000572 if (!everAnalyzedBlock[block->getBlockID()])
573 everAnalyzedBlock[block->getBlockID()] = true;
574 else if (prevVal.equals(val))
575 continue;
576
577 prevVal = val;
Fangrui Song6907ce22018-07-30 19:24:48 +0000578
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000579 // Update the dataflow value for the start of this block.
580 LV->blocksBeginToLiveness[block] = LV->runOnBlock(block, val);
Fangrui Song6907ce22018-07-30 19:24:48 +0000581
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000582 // Enqueue the value to the predecessors.
Ted Kremenek459597a2011-09-16 23:01:39 +0000583 worklist.enqueuePredecessors(block);
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000584 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000585
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000586 return new LiveVariables(LV);
587}
588
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000589void LiveVariables::dumpBlockLiveness(const SourceManager &M) {
590 getImpl(impl).dumpBlockLiveness(M);
591}
592
593void LiveVariablesImpl::dumpBlockLiveness(const SourceManager &M) {
594 std::vector<const CFGBlock *> vec;
595 for (llvm::DenseMap<const CFGBlock *, LiveVariables::LivenessValues>::iterator
596 it = blocksEndToLiveness.begin(), ei = blocksEndToLiveness.end();
597 it != ei; ++it) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000598 vec.push_back(it->first);
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000599 }
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +0000600 llvm::sort(vec.begin(), vec.end(), [](const CFGBlock *A, const CFGBlock *B) {
Benjamin Kramer15ae7832014-03-07 21:35:40 +0000601 return A->getBlockID() < B->getBlockID();
602 });
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000603
604 std::vector<const VarDecl*> declVec;
605
606 for (std::vector<const CFGBlock *>::iterator
607 it = vec.begin(), ei = vec.end(); it != ei; ++it) {
608 llvm::errs() << "\n[ B" << (*it)->getBlockID()
609 << " (live variables at block exit) ]\n";
Fangrui Song6907ce22018-07-30 19:24:48 +0000610
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000611 LiveVariables::LivenessValues vals = blocksEndToLiveness[*it];
612 declVec.clear();
Fangrui Song6907ce22018-07-30 19:24:48 +0000613
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000614 for (llvm::ImmutableSet<const VarDecl *>::iterator si =
615 vals.liveDecls.begin(),
616 se = vals.liveDecls.end(); si != se; ++si) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000617 declVec.push_back(*si);
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000618 }
Benjamin Kramer15ae7832014-03-07 21:35:40 +0000619
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +0000620 llvm::sort(declVec.begin(), declVec.end(),
621 [](const Decl *A, const Decl *B) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000622 return A->getBeginLoc() < B->getBeginLoc();
623 });
Benjamin Kramer15ae7832014-03-07 21:35:40 +0000624
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000625 for (std::vector<const VarDecl*>::iterator di = declVec.begin(),
626 de = declVec.end(); di != de; ++di) {
627 llvm::errs() << " " << (*di)->getDeclName().getAsString()
628 << " <";
629 (*di)->getLocation().dump(M);
Daniel Dunbare81a5532009-10-17 18:12:37 +0000630 llvm::errs() << ">\n";
Ted Kremenekb56a9902007-09-06 00:17:54 +0000631 }
Ted Kremenek3f8ed262007-09-06 21:26:58 +0000632 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000633 llvm::errs() << "\n";
Ted Kremenekbd9cc5c2007-09-10 17:36:42 +0000634}
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000635
Ted Kremenekdccc2b22011-10-07 22:21:02 +0000636const void *LiveVariables::getTag() { static int x; return &x; }
637const void *RelaxedLiveVariables::getTag() { static int x; return &x; }