Coverage Report

Created: 2021-09-21 08:58

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