Coverage Report

Created: 2022-07-16 07:03

/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
27.1k
        BSetFact(false), killAtAssign(KillAtAssign) {}
55
};
56
} // namespace
57
58
2.13M
static LiveVariablesImpl &getImpl(void *x) {
59
2.13M
  return *((LiveVariablesImpl *) x);
60
2.13M
}
61
62
//===----------------------------------------------------------------------===//
63
// Operations and queries on LivenessValues.
64
//===----------------------------------------------------------------------===//
65
66
1.49M
bool LiveVariables::LivenessValues::isLive(const Expr *E) const {
67
1.49M
  return liveExprs.contains(E);
68
1.49M
}
69
70
636k
bool LiveVariables::LivenessValues::isLive(const VarDecl *D) const {
71
636k
  if (const auto *DD = dyn_cast<DecompositionDecl>(D)) {
72
142
    bool alive = false;
73
142
    for (const BindingDecl *BD : DD->bindings())
74
344
      alive |= liveBindings.contains(BD);
75
142
    return alive;
76
142
  }
77
636k
  return liveDecls.contains(D);
78
636k
}
79
80
namespace {
81
  template <typename SET>
82
248k
  SET mergeSets(SET A, SET B) {
83
248k
    if (A.isEmpty())
84
240k
      return B;
85
86
15.1k
    
for (typename SET::iterator it = B.begin(), ei = B.end(); 7.59k
it != ei;
++it7.51k
) {
87
7.51k
      A = A.add(*it);
88
7.51k
    }
89
7.59k
    return A;
90
248k
  }
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
82.7k
  SET mergeSets(SET A, SET B) {
83
82.7k
    if (A.isEmpty())
84
80.9k
      return B;
85
86
4.58k
    
for (typename SET::iterator it = B.begin(), ei = B.end(); 1.74k
it != ei;
++it2.84k
) {
87
2.84k
      A = A.add(*it);
88
2.84k
    }
89
1.74k
    return A;
90
82.7k
  }
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
82.7k
  SET mergeSets(SET A, SET B) {
83
82.7k
    if (A.isEmpty())
84
76.8k
      return B;
85
86
10.5k
    
for (typename SET::iterator it = B.begin(), ei = B.end(); 5.85k
it != ei;
++it4.66k
) {
87
4.66k
      A = A.add(*it);
88
4.66k
    }
89
5.85k
    return A;
90
82.7k
  }
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
82.7k
  SET mergeSets(SET A, SET B) {
83
82.7k
    if (A.isEmpty())
84
82.7k
      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
82.7k
  }
91
} // namespace
92
93
0
void LiveVariables::Observer::anchor() { }
94
95
LiveVariables::LivenessValues
96
LiveVariablesImpl::merge(LiveVariables::LivenessValues valsA,
97
82.7k
                         LiveVariables::LivenessValues valsB) {
98
99
82.7k
  llvm::ImmutableSetRef<const Expr *> SSetRefA(
100
82.7k
      valsA.liveExprs.getRootWithoutRetain(), ESetFact.getTreeFactory()),
101
82.7k
      SSetRefB(valsB.liveExprs.getRootWithoutRetain(),
102
82.7k
               ESetFact.getTreeFactory());
103
104
82.7k
  llvm::ImmutableSetRef<const VarDecl *>
105
82.7k
    DSetRefA(valsA.liveDecls.getRootWithoutRetain(), DSetFact.getTreeFactory()),
106
82.7k
    DSetRefB(valsB.liveDecls.getRootWithoutRetain(), DSetFact.getTreeFactory());
107
108
82.7k
  llvm::ImmutableSetRef<const BindingDecl *>
109
82.7k
    BSetRefA(valsA.liveBindings.getRootWithoutRetain(), BSetFact.getTreeFactory()),
110
82.7k
    BSetRefB(valsB.liveBindings.getRootWithoutRetain(), BSetFact.getTreeFactory());
111
112
82.7k
  SSetRefA = mergeSets(SSetRefA, SSetRefB);
113
82.7k
  DSetRefA = mergeSets(DSetRefA, DSetRefB);
114
82.7k
  BSetRefA = mergeSets(BSetRefA, BSetRefB);
115
116
  // asImmutableSet() canonicalizes the tree, allowing us to do an easy
117
  // comparison afterwards.
118
82.7k
  return LiveVariables::LivenessValues(SSetRefA.asImmutableSet(),
119
82.7k
                                       DSetRefA.asImmutableSet(),
120
82.7k
                                       BSetRefA.asImmutableSet());
121
82.7k
}
122
123
3.62k
bool LiveVariables::LivenessValues::equals(const LivenessValues &V) const {
124
3.62k
  return liveExprs == V.liveExprs && 
liveDecls == V.liveDecls3.01k
;
125
3.62k
}
126
127
//===----------------------------------------------------------------------===//
128
// Query methods.
129
//===----------------------------------------------------------------------===//
130
131
732k
static bool isAlwaysAlive(const VarDecl *D) {
132
732k
  return D->hasGlobalStorage();
133
732k
}
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
635k
bool LiveVariables::isLive(const Stmt *S, const VarDecl *D) {
140
635k
  return isAlwaysAlive(D) || getImpl(impl).stmtsToLiveness[S].isLive(D);
141
635k
}
142
143
1.49M
bool LiveVariables::isLive(const Stmt *Loc, const Expr *Val) {
144
1.49M
  return getImpl(impl).stmtsToLiveness[Loc].isLive(Val);
145
1.49M
}
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
102k
  : 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
22.7k
static const VariableArrayType *FindVA(QualType Ty) {
176
22.7k
  const Type *ty = Ty.getTypePtr();
177
24.2k
  while (const ArrayType *VT = dyn_cast<ArrayType>(ty)) {
178
1.60k
    if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(VT))
179
64
      if (VAT->getSizeExpr())
180
64
        return VAT;
181
182
1.54k
    ty = VT->getElementType().getTypePtr();
183
1.54k
  }
184
185
22.6k
  return nullptr;
186
22.7k
}
187
188
422k
static const Expr *LookThroughExpr(const Expr *E) {
189
428k
  while (E) {
190
428k
    if (const Expr *Ex = dyn_cast<Expr>(E))
191
428k
      E = Ex->IgnoreParens();
192
428k
    if (const FullExpr *FE = dyn_cast<FullExpr>(E)) {
193
5.28k
      E = FE->getSubExpr();
194
5.28k
      continue;
195
5.28k
    }
196
423k
    if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
197
780
      E = OVE->getSourceExpr();
198
780
      continue;
199
780
    }
200
422k
    break;
201
423k
  }
202
422k
  return E;
203
422k
}
204
205
static void AddLiveExpr(llvm::ImmutableSet<const Expr *> &Set,
206
                        llvm::ImmutableSet<const Expr *>::Factory &F,
207
422k
                        const Expr *E) {
208
422k
  Set = F.add(Set, LookThroughExpr(E));
209
422k
}
210
211
501k
void TransferFunctions::Visit(Stmt *S) {
212
501k
  if (observer)
213
9.05k
    observer->observeStmt(S, currentBlock, val);
214
215
501k
  StmtVisitor<TransferFunctions>::Visit(S);
216
217
501k
  if (const auto *E = dyn_cast<Expr>(S)) {
218
461k
    val.liveExprs = LV.ESetFact.remove(val.liveExprs, E);
219
461k
  }
220
221
  // Mark all children expressions live.
222
223
501k
  switch (S->getStmtClass()) {
224
459k
    default:
225
459k
      break;
226
459k
    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.13k
    case Stmt::CXXMemberCallExprClass: {
232
      // Include the implicit "this" pointer as being live.
233
6.13k
      CXXMemberCallExpr *CE = cast<CXXMemberCallExpr>(S);
234
6.13k
      if (Expr *ImplicitObj = CE->getImplicitObjectArgument()) {
235
6.13k
        AddLiveExpr(val.liveExprs, LV.ESetFact, ImplicitObj);
236
6.13k
      }
237
6.13k
      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
22.6k
    case Stmt::DeclStmtClass: {
248
22.6k
      const DeclStmt *DS = cast<DeclStmt>(S);
249
22.6k
      if (const VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl())) {
250
22.6k
        for (const VariableArrayType* VA = FindVA(VD->getType());
251
22.7k
             VA != nullptr; 
VA = FindVA(VA->getElementType())64
) {
252
64
          AddLiveExpr(val.liveExprs, LV.ESetFact, VA->getSizeExpr());
253
64
        }
254
22.6k
      }
255
22.6k
      break;
256
0
    }
257
388
    case Stmt::PseudoObjectExprClass: {
258
      // A pseudo-object operation only directly consumes its result
259
      // expression.
260
388
      Expr *child = cast<PseudoObjectExpr>(S)->getResultExpr();
261
388
      if (!child) 
return0
;
262
388
      if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(child))
263
80
        child = OV->getSourceExpr();
264
388
      child = child->IgnoreParens();
265
388
      val.liveExprs = LV.ESetFact.add(val.liveExprs, child);
266
388
      return;
267
388
    }
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
388
    }
274
1.74k
    case Stmt::CXXBindTemporaryExprClass: {
275
1.74k
      S = cast<CXXBindTemporaryExpr>(S)->getSubExpr();
276
1.74k
      break;
277
388
    }
278
875
    case Stmt::UnaryExprOrTypeTraitExprClass: {
279
      // No need to unconditionally visit subexpressions.
280
875
      return;
281
388
    }
282
5.29k
    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
5.29k
      AddLiveExpr(val.liveExprs, LV.ESetFact, cast<IfStmt>(S)->getCond());
287
5.29k
      return;
288
388
    }
289
339
    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
339
      AddLiveExpr(val.liveExprs, LV.ESetFact, cast<WhileStmt>(S)->getCond());
294
339
      return;
295
388
    }
296
178
    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
178
      AddLiveExpr(val.liveExprs, LV.ESetFact, cast<DoStmt>(S)->getCond());
301
178
      return;
302
388
    }
303
742
    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
742
      AddLiveExpr(val.liveExprs, LV.ESetFact, cast<ForStmt>(S)->getCond());
308
742
      return;
309
388
    }
310
311
501k
  }
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
493k
  for (Stmt *Child : S->children()) {
317
411k
    if (const auto *E = dyn_cast_or_null<Expr>(Child))
318
410k
      AddLiveExpr(val.liveExprs, LV.ESetFact, E);
319
411k
  }
320
493k
}
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
26.3k
void TransferFunctions::VisitBinaryOperator(BinaryOperator *B) {
328
26.3k
  if (LV.killAtAssign && 
B->getOpcode() == BO_Assign1.77k
) {
329
804
    if (const auto *DR = dyn_cast<DeclRefExpr>(B->getLHS()->IgnoreParens())) {
330
515
      LV.inAssignment[DR] = 1;
331
515
    }
332
804
  }
333
26.3k
  if (B->isAssignmentOp()) {
334
8.73k
    if (!LV.killAtAssign)
335
7.86k
      return;
336
337
    // Assigning to a variable?
338
872
    Expr *LHS = B->getLHS()->IgnoreParens();
339
340
872
    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
872
  }
359
26.3k
}
360
361
430
void TransferFunctions::VisitBlockExpr(BlockExpr *BE) {
362
430
  for (const VarDecl *VD :
363
430
       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
430
}
369
370
116k
void TransferFunctions::VisitDeclRefExpr(DeclRefExpr *DR) {
371
116k
  const Decl* D = DR->getDecl();
372
116k
  bool InAssignment = LV.inAssignment[DR];
373
116k
  if (const auto *BD = dyn_cast<BindingDecl>(D)) {
374
149
    if (!InAssignment)
375
135
      val.liveBindings = LV.BSetFact.add(val.liveBindings, BD);
376
115k
  } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
377
73.7k
    if (!InAssignment && 
!isAlwaysAlive(VD)73.2k
)
378
70.5k
      val.liveDecls = LV.DSetFact.add(val.liveDecls, VD);
379
73.7k
  }
380
116k
}
381
382
22.6k
void TransferFunctions::VisitDeclStmt(DeclStmt *DS) {
383
22.6k
  for (const auto *DI : DS->decls()) {
384
22.6k
    if (const auto *DD = dyn_cast<DecompositionDecl>(DI)) {
385
73
      for (const auto *BD : DD->bindings())
386
163
        val.liveBindings = LV.BSetFact.remove(val.liveBindings, BD);
387
22.5k
    } else if (const auto *VD = dyn_cast<VarDecl>(DI)) {
388
22.5k
      if (!isAlwaysAlive(VD))
389
22.0k
        val.liveDecls = LV.DSetFact.remove(val.liveDecls, VD);
390
22.5k
    }
391
22.6k
  }
392
22.6k
}
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
875
{
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
875
  if (UE->getKind() != UETT_SizeOf || 
UE->isArgumentType()872
)
421
626
    return;
422
423
249
  const Expr *subEx = UE->getArgumentExpr();
424
249
  if (subEx->getType()->isVariableArrayType()) {
425
5
    assert(subEx->isLValue());
426
0
    val.liveExprs = LV.ESetFact.add(val.liveExprs, subEx->IgnoreParens());
427
5
  }
428
249
}
429
430
12.7k
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
12.7k
  if (!observer)
435
12.3k
    return;
436
437
373
  switch (UO->getOpcode()) {
438
259
  default:
439
259
    return;
440
259
  case UO_PostInc:
441
19
  case UO_PostDec:
442
112
  case UO_PreInc:
443
114
  case UO_PreDec:
444
114
    break;
445
373
  }
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
102k
                              LiveVariables::Observer *obs) {
460
461
102k
  TransferFunctions TF(*this, val, obs, block);
462
463
  // Visit the terminator (if any).
464
102k
  if (const Stmt *term = block->getTerminatorStmt())
465
9.87k
    TF.Visit(const_cast<Stmt*>(term));
466
467
  // Apply the transfer function for all Stmts in the block.
468
102k
  for (CFGBlock::const_reverse_iterator it = block->rbegin(),
469
601k
       ei = block->rend(); it != ei; 
++it499k
) {
470
499k
    const CFGElement &elem = *it;
471
472
499k
    if (Optional<CFGAutomaticObjDtor> Dtor =
473
499k
            elem.getAs<CFGAutomaticObjDtor>()) {
474
642
      val.liveDecls = DSetFact.add(val.liveDecls, Dtor->getVarDecl());
475
642
      continue;
476
642
    }
477
478
498k
    if (!elem.getAs<CFGStmt>())
479
7.02k
      continue;
480
481
491k
    const Stmt *S = elem.castAs<CFGStmt>().getStmt();
482
491k
    TF.Visit(const_cast<Stmt*>(S));
483
491k
    stmtsToLiveness[S] = val;
484
491k
  }
485
102k
  return val;
486
102k
}
487
488
519
void LiveVariables::runOnAllBlocks(LiveVariables::Observer &obs) {
489
519
  const CFG *cfg = getImpl(impl).analysisContext.getCFG();
490
3.01k
  for (CFG::const_iterator it = cfg->begin(), ei = cfg->end(); it != ei; 
++it2.49k
)
491
2.49k
    getImpl(impl).runOnBlock(*it, getImpl(impl).blocksEndToLiveness[*it], &obs);
492
519
}
493
494
27.1k
LiveVariables::LiveVariables(void *im) : impl(im) {}
495
496
27.1k
LiveVariables::~LiveVariables() {
497
27.1k
  delete (LiveVariablesImpl*) impl;
498
27.1k
}
499
500
std::unique_ptr<LiveVariables>
501
27.1k
LiveVariables::computeLiveness(AnalysisDeclContext &AC, bool killAtAssign) {
502
503
  // No CFG?  Bail out.
504
27.1k
  CFG *cfg = AC.getCFG();
505
27.1k
  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
27.1k
  if (cfg->getNumBlockIDs() > 300000)
511
0
    return nullptr;
512
513
27.1k
  LiveVariablesImpl *LV = new LiveVariablesImpl(AC, killAtAssign);
514
515
  // Construct the dataflow worklist.  Enqueue the exit block as the
516
  // start of the analysis.
517
27.1k
  BackwardDataflowWorklist worklist(*cfg, AC);
518
27.1k
  llvm::BitVector everAnalyzedBlock(cfg->getNumBlockIDs());
519
520
  // FIXME: we should enqueue using post order.
521
97.3k
  for (const CFGBlock *B : cfg->nodes()) {
522
97.3k
    worklist.enqueueBlock(B);
523
97.3k
  }
524
525
128k
  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
101k
    LivenessValues &prevVal = LV->blocksEndToLiveness[block];
529
530
    // Merge the values of all successor blocks.
531
101k
    LivenessValues val;
532
101k
    for (CFGBlock::const_succ_iterator it = block->succ_begin(),
533
184k
                                       ei = block->succ_end(); it != ei; 
++it83.8k
) {
534
83.8k
      if (const CFGBlock *succ = *it) {
535
82.7k
        val = LV->merge(val, LV->blocksBeginToLiveness[succ]);
536
82.7k
      }
537
83.8k
    }
538
539
101k
    if (!everAnalyzedBlock[block->getBlockID()])
540
97.3k
      everAnalyzedBlock[block->getBlockID()] = true;
541
3.62k
    else if (prevVal.equals(val))
542
1.25k
      continue;
543
544
99.7k
    prevVal = val;
545
546
    // Update the dataflow value for the start of this block.
547
99.7k
    LV->blocksBeginToLiveness[block] = LV->runOnBlock(block, val);
548
549
    // Enqueue the value to the predecessors.
550
99.7k
    worklist.enqueuePredecessors(block);
551
99.7k
  }
552
553
27.1k
  return std::unique_ptr<LiveVariables>(new LiveVariables(LV));
554
27.1k
}
555
556
2
void LiveVariables::dumpBlockLiveness(const SourceManager &M) {
557
2
  getImpl(impl).dumpBlockLiveness(M);
558
2
}
559
560
2
void LiveVariablesImpl::dumpBlockLiveness(const SourceManager &M) {
561
2
  std::vector<const CFGBlock *> vec;
562
2
  for (llvm::DenseMap<const CFGBlock *, LiveVariables::LivenessValues>::iterator
563
2
       it = blocksEndToLiveness.begin(), ei = blocksEndToLiveness.end();
564
8
       it != ei; 
++it6
) {
565
6
    vec.push_back(it->first);
566
6
  }
567
4
  llvm::sort(vec, [](const CFGBlock *A, const CFGBlock *B) {
568
4
    return A->getBlockID() < B->getBlockID();
569
4
  });
570
571
2
  std::vector<const VarDecl*> declVec;
572
573
2
  for (std::vector<const CFGBlock *>::iterator
574
8
        it = vec.begin(), ei = vec.end(); it != ei; 
++it6
) {
575
6
    llvm::errs() << "\n[ B" << (*it)->getBlockID()
576
6
                 << " (live variables at block exit) ]\n";
577
578
6
    LiveVariables::LivenessValues vals = blocksEndToLiveness[*it];
579
6
    declVec.clear();
580
581
6
    for (llvm::ImmutableSet<const VarDecl *>::iterator si =
582
6
          vals.liveDecls.begin(),
583
7
          se = vals.liveDecls.end(); si != se; 
++si1
) {
584
1
      declVec.push_back(*si);
585
1
    }
586
587
6
    llvm::sort(declVec, [](const Decl *A, const Decl *B) {
588
0
      return A->getBeginLoc() < B->getBeginLoc();
589
0
    });
590
591
6
    for (std::vector<const VarDecl*>::iterator di = declVec.begin(),
592
7
         de = declVec.end(); di != de; 
++di1
) {
593
1
      llvm::errs() << " " << (*di)->getDeclName().getAsString()
594
1
                   << " <";
595
1
      (*di)->getLocation().print(llvm::errs(), M);
596
1
      llvm::errs() << ">\n";
597
1
    }
598
6
  }
599
2
  llvm::errs() << "\n";
600
2
}
601
602
12
void LiveVariables::dumpExprLiveness(const SourceManager &M) {
603
12
  getImpl(impl).dumpExprLiveness(M);
604
12
}
605
606
12
void LiveVariablesImpl::dumpExprLiveness(const SourceManager &M) {
607
  // Don't iterate over blockEndsToLiveness directly because it's not sorted.
608
59
  for (const CFGBlock *B : *analysisContext.getCFG()) {
609
610
59
    llvm::errs() << "\n[ B" << B->getBlockID()
611
59
                 << " (live expressions at block exit) ]\n";
612
59
    for (const Expr *E : blocksEndToLiveness[B].liveExprs) {
613
14
      llvm::errs() << "\n";
614
14
      E->dump();
615
14
    }
616
59
    llvm::errs() << "\n";
617
59
  }
618
12
}
619
620
521
const void *LiveVariables::getTag() { static int x; return &x; }
621
2.15M
const void *RelaxedLiveVariables::getTag() { static int x; return &x; }