Coverage Report

Created: 2022-07-16 07:03

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Analysis/ThreadSafety.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- ThreadSafety.cpp ---------------------------------------------------===//
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
// A intra-procedural analysis for thread safety (e.g. deadlocks and race
10
// conditions), based off of an annotation system.
11
//
12
// See http://clang.llvm.org/docs/ThreadSafetyAnalysis.html
13
// for more information.
14
//
15
//===----------------------------------------------------------------------===//
16
17
#include "clang/Analysis/Analyses/ThreadSafety.h"
18
#include "clang/AST/Attr.h"
19
#include "clang/AST/Decl.h"
20
#include "clang/AST/DeclCXX.h"
21
#include "clang/AST/DeclGroup.h"
22
#include "clang/AST/Expr.h"
23
#include "clang/AST/ExprCXX.h"
24
#include "clang/AST/OperationKinds.h"
25
#include "clang/AST/Stmt.h"
26
#include "clang/AST/StmtVisitor.h"
27
#include "clang/AST/Type.h"
28
#include "clang/Analysis/Analyses/PostOrderCFGView.h"
29
#include "clang/Analysis/Analyses/ThreadSafetyCommon.h"
30
#include "clang/Analysis/Analyses/ThreadSafetyTIL.h"
31
#include "clang/Analysis/Analyses/ThreadSafetyTraverse.h"
32
#include "clang/Analysis/Analyses/ThreadSafetyUtil.h"
33
#include "clang/Analysis/AnalysisDeclContext.h"
34
#include "clang/Analysis/CFG.h"
35
#include "clang/Basic/Builtins.h"
36
#include "clang/Basic/LLVM.h"
37
#include "clang/Basic/OperatorKinds.h"
38
#include "clang/Basic/SourceLocation.h"
39
#include "clang/Basic/Specifiers.h"
40
#include "llvm/ADT/ArrayRef.h"
41
#include "llvm/ADT/DenseMap.h"
42
#include "llvm/ADT/ImmutableMap.h"
43
#include "llvm/ADT/Optional.h"
44
#include "llvm/ADT/STLExtras.h"
45
#include "llvm/ADT/SmallVector.h"
46
#include "llvm/ADT/StringRef.h"
47
#include "llvm/Support/Allocator.h"
48
#include "llvm/Support/Casting.h"
49
#include "llvm/Support/ErrorHandling.h"
50
#include "llvm/Support/raw_ostream.h"
51
#include <algorithm>
52
#include <cassert>
53
#include <functional>
54
#include <iterator>
55
#include <memory>
56
#include <string>
57
#include <type_traits>
58
#include <utility>
59
#include <vector>
60
61
using namespace clang;
62
using namespace threadSafety;
63
64
// Key method definition
65
2.25k
ThreadSafetyHandler::~ThreadSafetyHandler() = default;
66
67
/// Issue a warning about an invalid lock expression
68
static void warnInvalidLock(ThreadSafetyHandler &Handler,
69
                            const Expr *MutexExp, const NamedDecl *D,
70
0
                            const Expr *DeclExp, StringRef Kind) {
71
0
  SourceLocation Loc;
72
0
  if (DeclExp)
73
0
    Loc = DeclExp->getExprLoc();
74
75
  // FIXME: add a note about the attribute location in MutexExp or D
76
0
  if (Loc.isValid())
77
0
    Handler.handleInvalidLockExp(Loc);
78
0
}
79
80
namespace {
81
82
/// A set of CapabilityExpr objects, which are compiled from thread safety
83
/// attributes on a function.
84
class CapExprSet : public SmallVector<CapabilityExpr, 4> {
85
public:
86
  /// Push M onto list, but discard duplicates.
87
5.19k
  void push_back_nodup(const CapabilityExpr &CapE) {
88
5.19k
    if (llvm::none_of(*this, [=](const CapabilityExpr &CapE2) {
89
1.09k
          return CapE.equals(CapE2);
90
1.09k
        }))
91
4.76k
      push_back(CapE);
92
5.19k
  }
93
};
94
95
class FactManager;
96
class FactSet;
97
98
/// This is a helper class that stores a fact that is known at a
99
/// particular point in program execution.  Currently, a fact is a capability,
100
/// along with additional information, such as where it was acquired, whether
101
/// it is exclusive or shared, etc.
102
///
103
/// FIXME: this analysis does not currently support re-entrant locking.
104
class FactEntry : public CapabilityExpr {
105
public:
106
  /// Where a fact comes from.
107
  enum SourceKind {
108
    Acquired, ///< The fact has been directly acquired.
109
    Asserted, ///< The fact has been asserted to be held.
110
    Declared, ///< The fact is assumed to be held by callers.
111
    Managed,  ///< The fact has been acquired through a scoped capability.
112
  };
113
114
private:
115
  /// Exclusive or shared.
116
  LockKind LKind : 8;
117
118
  // How it was acquired.
119
  SourceKind Source : 8;
120
121
  /// Where it was acquired.
122
  SourceLocation AcquireLoc;
123
124
public:
125
  FactEntry(const CapabilityExpr &CE, LockKind LK, SourceLocation Loc,
126
            SourceKind Src)
127
4.89k
      : CapabilityExpr(CE), LKind(LK), Source(Src), AcquireLoc(Loc) {}
128
4.89k
  virtual ~FactEntry() = default;
129
130
2.71k
  LockKind kind() const { return LKind;      }
131
3.90k
  SourceLocation loc() const { return AcquireLoc; }
132
133
6.96k
  bool asserted() const { return Source == Asserted; }
134
2.70k
  bool declared() const { return Source == Declared; }
135
1.83k
  bool managed() const { return Source == Managed; }
136
137
  virtual void
138
  handleRemovalFromIntersection(const FactSet &FSet, FactManager &FactMan,
139
                                SourceLocation JoinLoc, LockErrorKind LEK,
140
                                ThreadSafetyHandler &Handler) const = 0;
141
  virtual void handleLock(FactSet &FSet, FactManager &FactMan,
142
                          const FactEntry &entry,
143
                          ThreadSafetyHandler &Handler) const = 0;
144
  virtual void handleUnlock(FactSet &FSet, FactManager &FactMan,
145
                            const CapabilityExpr &Cp, SourceLocation UnlockLoc,
146
                            bool FullyRemove,
147
                            ThreadSafetyHandler &Handler) const = 0;
148
149
  // Return true if LKind >= LK, where exclusive > shared
150
1.87k
  bool isAtLeast(LockKind LK) const {
151
1.87k
    return  (LKind == LK_Exclusive) || 
(LK == LK_Shared)387
;
152
1.87k
  }
153
};
154
155
using FactID = unsigned short;
156
157
/// FactManager manages the memory for all facts that are created during
158
/// the analysis of a single routine.
159
class FactManager {
160
private:
161
  std::vector<std::unique_ptr<const FactEntry>> Facts;
162
163
public:
164
4.68k
  FactID newFact(std::unique_ptr<FactEntry> Entry) {
165
4.68k
    Facts.push_back(std::move(Entry));
166
4.68k
    return static_cast<unsigned short>(Facts.size() - 1);
167
4.68k
  }
168
169
29.5k
  const FactEntry &operator[](FactID F) const { return *Facts[F]; }
170
};
171
172
/// A FactSet is the set of facts that are known to be true at a
173
/// particular program point.  FactSets must be small, because they are
174
/// frequently copied, and are thus implemented as a set of indices into a
175
/// table maintained by a FactManager.  A typical FactSet only holds 1 or 2
176
/// locks, so we can get away with doing a linear search for lookup.  Note
177
/// that a hashtable or map is inappropriate in this case, because lookups
178
/// may involve partial pattern matches, rather than exact matches.
179
class FactSet {
180
private:
181
  using FactVec = SmallVector<FactID, 4>;
182
183
  FactVec FactIDs;
184
185
public:
186
  using iterator = FactVec::iterator;
187
  using const_iterator = FactVec::const_iterator;
188
189
5.48k
  iterator begin() { return FactIDs.begin(); }
190
17.3k
  const_iterator begin() const { return FactIDs.begin(); }
191
192
8.12k
  iterator end() { return FactIDs.end(); }
193
31.8k
  const_iterator end() const { return FactIDs.end(); }
194
195
0
  bool isEmpty() const { return FactIDs.size() == 0; }
196
197
  // Return true if the set contains only negative facts
198
58
  bool isEmpty(FactManager &FactMan) const {
199
58
    for (const auto FID : *this) {
200
34
      if (!FactMan[FID].negative())
201
24
        return false;
202
34
    }
203
34
    return true;
204
58
  }
205
206
0
  void addLockByID(FactID ID) { FactIDs.push_back(ID); }
207
208
4.68k
  FactID addLock(FactManager &FM, std::unique_ptr<FactEntry> Entry) {
209
4.68k
    FactID F = FM.newFact(std::move(Entry));
210
4.68k
    FactIDs.push_back(F);
211
4.68k
    return F;
212
4.68k
  }
213
214
2.73k
  bool removeLock(FactManager& FM, const CapabilityExpr &CapE) {
215
2.73k
    unsigned n = FactIDs.size();
216
2.73k
    if (n == 0)
217
0
      return false;
218
219
3.57k
    
for (unsigned i = 0; 2.73k
i < n-1;
++i842
) {
220
1.80k
      if (FM[FactIDs[i]].matches(CapE)) {
221
966
        FactIDs[i] = FactIDs[n-1];
222
966
        FactIDs.pop_back();
223
966
        return true;
224
966
      }
225
1.80k
    }
226
1.77k
    if (FM[FactIDs[n-1]].matches(CapE)) {
227
1.71k
      FactIDs.pop_back();
228
1.71k
      return true;
229
1.71k
    }
230
60
    return false;
231
1.77k
  }
232
233
2.63k
  iterator findLockIter(FactManager &FM, const CapabilityExpr &CapE) {
234
2.63k
    return std::find_if(begin(), end(), [&](FactID ID) {
235
1.91k
      return FM[ID].matches(CapE);
236
1.91k
    });
237
2.63k
  }
238
239
9.64k
  const FactEntry *findLock(FactManager &FM, const CapabilityExpr &CapE) const {
240
9.64k
    auto I = std::find_if(begin(), end(), [&](FactID ID) {
241
9.01k
      return FM[ID].matches(CapE);
242
9.01k
    });
243
9.64k
    return I != end() ? 
&FM[*I]4.04k
:
nullptr5.59k
;
244
9.64k
  }
245
246
  const FactEntry *findLockUniv(FactManager &FM,
247
3.11k
                                const CapabilityExpr &CapE) const {
248
3.11k
    auto I = std::find_if(begin(), end(), [&](FactID ID) -> bool {
249
3.05k
      return FM[ID].matchesUniv(CapE);
250
3.05k
    });
251
3.11k
    return I != end() ? 
&FM[*I]1.87k
:
nullptr1.24k
;
252
3.11k
  }
253
254
  const FactEntry *findPartialMatch(FactManager &FM,
255
1.24k
                                    const CapabilityExpr &CapE) const {
256
1.24k
    auto I = std::find_if(begin(), end(), [&](FactID ID) -> bool {
257
550
      return FM[ID].partiallyMatches(CapE);
258
550
    });
259
1.24k
    return I != end() ? 
&FM[*I]76
:
nullptr1.16k
;
260
1.24k
  }
261
262
490
  bool containsMutexDecl(FactManager &FM, const ValueDecl* Vd) const {
263
490
    auto I = std::find_if(begin(), end(), [&](FactID ID) -> bool {
264
193
      return FM[ID].valueDecl() == Vd;
265
193
    });
266
490
    return I != end();
267
490
  }
268
};
269
270
class ThreadSafetyAnalyzer;
271
272
} // namespace
273
274
namespace clang {
275
namespace threadSafety {
276
277
class BeforeSet {
278
private:
279
  using BeforeVect = SmallVector<const ValueDecl *, 4>;
280
281
  struct BeforeInfo {
282
    BeforeVect Vect;
283
    int Visited = 0;
284
285
841
    BeforeInfo() = default;
286
    BeforeInfo(BeforeInfo &&) = default;
287
  };
288
289
  using BeforeMap =
290
      llvm::DenseMap<const ValueDecl *, std::unique_ptr<BeforeInfo>>;
291
  using CycleMap = llvm::DenseMap<const ValueDecl *, bool>;
292
293
public:
294
34
  BeforeSet() = default;
295
296
  BeforeInfo* insertAttrExprs(const ValueDecl* Vd,
297
                              ThreadSafetyAnalyzer& Analyzer);
298
299
  BeforeInfo *getBeforeInfoForDecl(const ValueDecl *Vd,
300
                                   ThreadSafetyAnalyzer &Analyzer);
301
302
  void checkBeforeAfter(const ValueDecl* Vd,
303
                        const FactSet& FSet,
304
                        ThreadSafetyAnalyzer& Analyzer,
305
                        SourceLocation Loc, StringRef CapKind);
306
307
private:
308
  BeforeMap BMap;
309
  CycleMap CycMap;
310
};
311
312
} // namespace threadSafety
313
} // namespace clang
314
315
namespace {
316
317
class LocalVariableMap;
318
319
using LocalVarContext = llvm::ImmutableMap<const NamedDecl *, unsigned>;
320
321
/// A side (entry or exit) of a CFG node.
322
enum CFGBlockSide { CBS_Entry, CBS_Exit };
323
324
/// CFGBlockInfo is a struct which contains all the information that is
325
/// maintained for each block in the CFG.  See LocalVariableMap for more
326
/// information about the contexts.
327
struct CFGBlockInfo {
328
  // Lockset held at entry to block
329
  FactSet EntrySet;
330
331
  // Lockset held at exit from block
332
  FactSet ExitSet;
333
334
  // Context held at entry to block
335
  LocalVarContext EntryContext;
336
337
  // Context held at exit from block
338
  LocalVarContext ExitContext;
339
340
  // Location of first statement in block
341
  SourceLocation EntryLoc;
342
343
  // Location of last statement in block.
344
  SourceLocation ExitLoc;
345
346
  // Used to replay contexts later
347
  unsigned EntryIndex;
348
349
  // Is this block reachable?
350
  bool Reachable = false;
351
352
0
  const FactSet &getSet(CFGBlockSide Side) const {
353
0
    return Side == CBS_Entry ? EntrySet : ExitSet;
354
0
  }
355
356
0
  SourceLocation getLocation(CFGBlockSide Side) const {
357
0
    return Side == CBS_Entry ? EntryLoc : ExitLoc;
358
0
  }
359
360
private:
361
  CFGBlockInfo(LocalVarContext EmptyCtx)
362
2.13k
      : EntryContext(EmptyCtx), ExitContext(EmptyCtx) {}
363
364
public:
365
  static CFGBlockInfo getEmptyBlockInfo(LocalVariableMap &M);
366
};
367
368
// A LocalVariableMap maintains a map from local variables to their currently
369
// valid definitions.  It provides SSA-like functionality when traversing the
370
// CFG.  Like SSA, each definition or assignment to a variable is assigned a
371
// unique name (an integer), which acts as the SSA name for that definition.
372
// The total set of names is shared among all CFG basic blocks.
373
// Unlike SSA, we do not rewrite expressions to replace local variables declrefs
374
// with their SSA-names.  Instead, we compute a Context for each point in the
375
// code, which maps local variables to the appropriate SSA-name.  This map
376
// changes with each assignment.
377
//
378
// The map is computed in a single pass over the CFG.  Subsequent analyses can
379
// then query the map to find the appropriate Context for a statement, and use
380
// that Context to look up the definitions of variables.
381
class LocalVariableMap {
382
public:
383
  using Context = LocalVarContext;
384
385
  /// A VarDefinition consists of an expression, representing the value of the
386
  /// variable, along with the context in which that expression should be
387
  /// interpreted.  A reference VarDefinition does not itself contain this
388
  /// information, but instead contains a pointer to a previous VarDefinition.
389
  struct VarDefinition {
390
  public:
391
    friend class LocalVariableMap;
392
393
    // The original declaration for this variable.
394
    const NamedDecl *Dec;
395
396
    // The expression for this variable, OR
397
    const Expr *Exp = nullptr;
398
399
    // Reference to another VarDefinition
400
    unsigned Ref = 0;
401
402
    // The map with which Exp should be interpreted.
403
    Context Ctx;
404
405
64
    bool isReference() { return !Exp; }
406
407
  private:
408
    // Create ordinary variable definition
409
    VarDefinition(const NamedDecl *D, const Expr *E, Context C)
410
734
        : Dec(D), Exp(E), Ctx(C) {}
411
412
    // Create reference to previous definition
413
    VarDefinition(const NamedDecl *D, unsigned R, Context C)
414
2.31k
        : Dec(D), Ref(R), Ctx(C) {}
415
  };
416
417
private:
418
  Context::Factory ContextFactory;
419
  std::vector<VarDefinition> VarDefinitions;
420
  std::vector<std::pair<const Stmt *, Context>> SavedContexts;
421
422
public:
423
2.25k
  LocalVariableMap() {
424
    // index 0 is a placeholder for undefined variables (aka phi-nodes).
425
2.25k
    VarDefinitions.push_back(VarDefinition(nullptr, 0u, getEmptyContext()));
426
2.25k
  }
427
428
  /// Look up a definition, within the given context.
429
0
  const VarDefinition* lookup(const NamedDecl *D, Context Ctx) {
430
0
    const unsigned *i = Ctx.lookup(D);
431
0
    if (!i)
432
0
      return nullptr;
433
0
    assert(*i < VarDefinitions.size());
434
0
    return &VarDefinitions[*i];
435
0
  }
436
437
  /// Look up the definition for D within the given context.  Returns
438
  /// NULL if the expression is not statically known.  If successful, also
439
  /// modifies Ctx to hold the context of the return Expr.
440
292
  const Expr* lookupExpr(const NamedDecl *D, Context &Ctx) {
441
292
    const unsigned *P = Ctx.lookup(D);
442
292
    if (!P)
443
104
      return nullptr;
444
445
188
    unsigned i = *P;
446
268
    while (i > 0) {
447
248
      if (VarDefinitions[i].Exp) {
448
168
        Ctx = VarDefinitions[i].Ctx;
449
168
        return VarDefinitions[i].Exp;
450
168
      }
451
80
      i = VarDefinitions[i].Ref;
452
80
    }
453
20
    return nullptr;
454
188
  }
455
456
4.53k
  Context getEmptyContext() { return ContextFactory.getEmptyMap(); }
457
458
  /// Return the next context after processing S.  This function is used by
459
  /// clients of the class to get the appropriate context when traversing the
460
  /// CFG.  It must be called for every assignment or DeclStmt.
461
2.60k
  Context getNextContext(unsigned &CtxIndex, const Stmt *S, Context C) {
462
2.60k
    if (SavedContexts[CtxIndex+1].first == S) {
463
748
      CtxIndex++;
464
748
      Context Result = SavedContexts[CtxIndex].second;
465
748
      return Result;
466
748
    }
467
1.85k
    return C;
468
2.60k
  }
469
470
0
  void dumpVarDefinitionName(unsigned i) {
471
0
    if (i == 0) {
472
0
      llvm::errs() << "Undefined";
473
0
      return;
474
0
    }
475
0
    const NamedDecl *Dec = VarDefinitions[i].Dec;
476
0
    if (!Dec) {
477
0
      llvm::errs() << "<<NULL>>";
478
0
      return;
479
0
    }
480
0
    Dec->printName(llvm::errs());
481
0
    llvm::errs() << "." << i << " " << ((const void*) Dec);
482
0
  }
483
484
  /// Dumps an ASCII representation of the variable map to llvm::errs()
485
0
  void dump() {
486
0
    for (unsigned i = 1, e = VarDefinitions.size(); i < e; ++i) {
487
0
      const Expr *Exp = VarDefinitions[i].Exp;
488
0
      unsigned Ref = VarDefinitions[i].Ref;
489
0
490
0
      dumpVarDefinitionName(i);
491
0
      llvm::errs() << " = ";
492
0
      if (Exp) Exp->dump();
493
0
      else {
494
0
        dumpVarDefinitionName(Ref);
495
0
        llvm::errs() << "\n";
496
0
      }
497
0
    }
498
0
  }
499
500
  /// Dumps an ASCII representation of a Context to llvm::errs()
501
0
  void dumpContext(Context C) {
502
0
    for (Context::iterator I = C.begin(), E = C.end(); I != E; ++I) {
503
0
      const NamedDecl *D = I.getKey();
504
0
      D->printName(llvm::errs());
505
0
      const unsigned *i = C.lookup(D);
506
0
      llvm::errs() << " -> ";
507
0
      dumpVarDefinitionName(*i);
508
0
      llvm::errs() << "\n";
509
0
    }
510
0
  }
511
512
  /// Builds the variable map.
513
  void traverseCFG(CFG *CFGraph, const PostOrderCFGView *SortedGraph,
514
                   std::vector<CFGBlockInfo> &BlockInfo);
515
516
protected:
517
  friend class VarMapBuilder;
518
519
  // Get the current context index
520
8.04k
  unsigned getContextIndex() { return SavedContexts.size()-1; }
521
522
  // Save the current context for later replay
523
10.9k
  void saveContext(const Stmt *S, Context C) {
524
10.9k
    SavedContexts.push_back(std::make_pair(S, C));
525
10.9k
  }
526
527
  // Adds a new definition to the given context, and returns a new context.
528
  // This method should be called when declaring a new variable.
529
613
  Context addDefinition(const NamedDecl *D, const Expr *Exp, Context Ctx) {
530
613
    assert(!Ctx.contains(D));
531
0
    unsigned newID = VarDefinitions.size();
532
613
    Context NewCtx = ContextFactory.add(Ctx, D, newID);
533
613
    VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
534
613
    return NewCtx;
535
613
  }
536
537
  // Add a new reference to an existing definition.
538
64
  Context addReference(const NamedDecl *D, unsigned i, Context Ctx) {
539
64
    unsigned newID = VarDefinitions.size();
540
64
    Context NewCtx = ContextFactory.add(Ctx, D, newID);
541
64
    VarDefinitions.push_back(VarDefinition(D, i, Ctx));
542
64
    return NewCtx;
543
64
  }
544
545
  // Updates a definition only if that definition is already in the map.
546
  // This method should be called when assigning to an existing variable.
547
121
  Context updateDefinition(const NamedDecl *D, Expr *Exp, Context Ctx) {
548
121
    if (Ctx.contains(D)) {
549
121
      unsigned newID = VarDefinitions.size();
550
121
      Context NewCtx = ContextFactory.remove(Ctx, D);
551
121
      NewCtx = ContextFactory.add(NewCtx, D, newID);
552
121
      VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
553
121
      return NewCtx;
554
121
    }
555
0
    return Ctx;
556
121
  }
557
558
  // Removes a definition from the context, but keeps the variable name
559
  // as a valid variable.  The index 0 is a placeholder for cleared definitions.
560
22
  Context clearDefinition(const NamedDecl *D, Context Ctx) {
561
22
    Context NewCtx = Ctx;
562
22
    if (NewCtx.contains(D)) {
563
22
      NewCtx = ContextFactory.remove(NewCtx, D);
564
22
      NewCtx = ContextFactory.add(NewCtx, D, 0);
565
22
    }
566
22
    return NewCtx;
567
22
  }
568
569
  // Remove a definition entirely frmo the context.
570
12
  Context removeDefinition(const NamedDecl *D, Context Ctx) {
571
12
    Context NewCtx = Ctx;
572
12
    if (NewCtx.contains(D)) {
573
12
      NewCtx = ContextFactory.remove(NewCtx, D);
574
12
    }
575
12
    return NewCtx;
576
12
  }
577
578
  Context intersectContexts(Context C1, Context C2);
579
  Context createReferenceContext(Context C);
580
  void intersectBackEdge(Context C1, Context C2);
581
};
582
583
} // namespace
584
585
// This has to be defined after LocalVariableMap.
586
2.13k
CFGBlockInfo CFGBlockInfo::getEmptyBlockInfo(LocalVariableMap &M) {
587
2.13k
  return CFGBlockInfo(M.getEmptyContext());
588
2.13k
}
589
590
namespace {
591
592
/// Visitor which builds a LocalVariableMap
593
class VarMapBuilder : public ConstStmtVisitor<VarMapBuilder> {
594
public:
595
  LocalVariableMap* VMap;
596
  LocalVariableMap::Context Ctx;
597
598
  VarMapBuilder(LocalVariableMap *VM, LocalVariableMap::Context C)
599
8.04k
      : VMap(VM), Ctx(C) {}
600
601
  void VisitDeclStmt(const DeclStmt *S);
602
  void VisitBinaryOperator(const BinaryOperator *BO);
603
};
604
605
} // namespace
606
607
// Add new local variables to the variable map
608
1.03k
void VarMapBuilder::VisitDeclStmt(const DeclStmt *S) {
609
1.03k
  bool modifiedCtx = false;
610
1.03k
  const DeclGroupRef DGrp = S->getDeclGroup();
611
1.03k
  for (const auto *D : DGrp) {
612
1.03k
    if (const auto *VD = dyn_cast_or_null<VarDecl>(D)) {
613
1.03k
      const Expr *E = VD->getInit();
614
615
      // Add local variables with trivial type to the variable map
616
1.03k
      QualType T = VD->getType();
617
1.03k
      if (T.isTrivialType(VD->getASTContext())) {
618
613
        Ctx = VMap->addDefinition(VD, E, Ctx);
619
613
        modifiedCtx = true;
620
613
      }
621
1.03k
    }
622
1.03k
  }
623
1.03k
  if (modifiedCtx)
624
613
    VMap->saveContext(S, Ctx);
625
1.03k
}
626
627
// Update local variable definitions in variable map
628
2.01k
void VarMapBuilder::VisitBinaryOperator(const BinaryOperator *BO) {
629
2.01k
  if (!BO->isAssignmentOp())
630
439
    return;
631
632
1.57k
  Expr *LHSExp = BO->getLHS()->IgnoreParenCasts();
633
634
  // Update the variable map and current context.
635
1.57k
  if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSExp)) {
636
367
    const ValueDecl *VDec = DRE->getDecl();
637
367
    if (Ctx.lookup(VDec)) {
638
135
      if (BO->getOpcode() == BO_Assign)
639
121
        Ctx = VMap->updateDefinition(VDec, BO->getRHS(), Ctx);
640
14
      else
641
        // FIXME -- handle compound assignment operators
642
14
        Ctx = VMap->clearDefinition(VDec, Ctx);
643
135
      VMap->saveContext(BO, Ctx);
644
135
    }
645
367
  }
646
1.57k
}
647
648
// Computes the intersection of two contexts.  The intersection is the
649
// set of variables which have the same definition in both contexts;
650
// variables with different definitions are discarded.
651
LocalVariableMap::Context
652
664
LocalVariableMap::intersectContexts(Context C1, Context C2) {
653
664
  Context Result = C1;
654
664
  for (const auto &P : C1) {
655
308
    const NamedDecl *Dec = P.first;
656
308
    const unsigned *i2 = C2.lookup(Dec);
657
308
    if (!i2)             // variable doesn't exist on second path
658
12
      Result = removeDefinition(Dec, Result);
659
296
    else if (*i2 != P.second)  // variable exists, but has different definition
660
8
      Result = clearDefinition(Dec, Result);
661
308
  }
662
664
  return Result;
663
664
}
664
665
// For every variable in C, create a new variable that refers to the
666
// definition in C.  Return a new context that contains these new variables.
667
// (We use this for a naive implementation of SSA on loop back-edges.)
668
142
LocalVariableMap::Context LocalVariableMap::createReferenceContext(Context C) {
669
142
  Context Result = getEmptyContext();
670
142
  for (const auto &P : C)
671
64
    Result = addReference(P.first, P.second, Result);
672
142
  return Result;
673
142
}
674
675
// This routine also takes the intersection of C1 and C2, but it does so by
676
// altering the VarDefinitions.  C1 must be the result of an earlier call to
677
// createReferenceContext.
678
134
void LocalVariableMap::intersectBackEdge(Context C1, Context C2) {
679
134
  for (const auto &P : C1) {
680
64
    unsigned i1 = P.second;
681
64
    VarDefinition *VDef = &VarDefinitions[i1];
682
64
    assert(VDef->isReference());
683
684
0
    const unsigned *i2 = C2.lookup(P.first);
685
64
    if (!i2 || (*i2 != i1))
686
12
      VDef->Ref = 0;    // Mark this variable as undefined
687
64
  }
688
134
}
689
690
// Traverse the CFG in topological order, so all predecessors of a block
691
// (excluding back-edges) are visited before the block itself.  At
692
// each point in the code, we calculate a Context, which holds the set of
693
// variable definitions which are visible at that point in execution.
694
// Visible variables are mapped to their definitions using an array that
695
// contains all definitions.
696
//
697
// At join points in the CFG, the set is computed as the intersection of
698
// the incoming sets along each edge, E.g.
699
//
700
//                       { Context                 | VarDefinitions }
701
//   int x = 0;          { x -> x1                 | x1 = 0 }
702
//   int y = 0;          { x -> x1, y -> y1        | y1 = 0, x1 = 0 }
703
//   if (b) x = 1;       { x -> x2, y -> y1        | x2 = 1, y1 = 0, ... }
704
//   else   x = 2;       { x -> x3, y -> y1        | x3 = 2, x2 = 1, ... }
705
//   ...                 { y -> y1  (x is unknown) | x3 = 2, x2 = 1, ... }
706
//
707
// This is essentially a simpler and more naive version of the standard SSA
708
// algorithm.  Those definitions that remain in the intersection are from blocks
709
// that strictly dominate the current block.  We do not bother to insert proper
710
// phi nodes, because they are not used in our analysis; instead, wherever
711
// a phi node would be required, we simply remove that definition from the
712
// context (E.g. x above).
713
//
714
// The initial traversal does not capture back-edges, so those need to be
715
// handled on a separate pass.  Whenever the first pass encounters an
716
// incoming back edge, it duplicates the context, creating new definitions
717
// that refer back to the originals.  (These correspond to places where SSA
718
// might have to insert a phi node.)  On the second pass, these definitions are
719
// set to NULL if the variable has changed on the back-edge (i.e. a phi
720
// node was actually required.)  E.g.
721
//
722
//                       { Context           | VarDefinitions }
723
//   int x = 0, y = 0;   { x -> x1, y -> y1  | y1 = 0, x1 = 0 }
724
//   while (b)           { x -> x2, y -> y1  | [1st:] x2=x1; [2nd:] x2=NULL; }
725
//     x = x+1;          { x -> x3, y -> y1  | x3 = x2 + 1, ... }
726
//   ...                 { y -> y1           | x3 = 2, x2 = 1, ... }
727
void LocalVariableMap::traverseCFG(CFG *CFGraph,
728
                                   const PostOrderCFGView *SortedGraph,
729
2.13k
                                   std::vector<CFGBlockInfo> &BlockInfo) {
730
2.13k
  PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
731
732
8.04k
  for (const auto *CurrBlock : *SortedGraph) {
733
8.04k
    unsigned CurrBlockID = CurrBlock->getBlockID();
734
8.04k
    CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
735
736
8.04k
    VisitedBlocks.insert(CurrBlock);
737
738
    // Calculate the entry context for the current block
739
8.04k
    bool HasBackEdges = false;
740
8.04k
    bool CtxInit = true;
741
8.04k
    for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
742
14.7k
         PE  = CurrBlock->pred_end(); PI != PE; 
++PI6.71k
) {
743
      // if *PI -> CurrBlock is a back edge, so skip it
744
6.71k
      if (*PI == nullptr || !VisitedBlocks.alreadySet(*PI)) {
745
142
        HasBackEdges = true;
746
142
        continue;
747
142
      }
748
749
6.56k
      unsigned PrevBlockID = (*PI)->getBlockID();
750
6.56k
      CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
751
752
6.56k
      if (CtxInit) {
753
5.90k
        CurrBlockInfo->EntryContext = PrevBlockInfo->ExitContext;
754
5.90k
        CtxInit = false;
755
5.90k
      }
756
664
      else {
757
664
        CurrBlockInfo->EntryContext =
758
664
          intersectContexts(CurrBlockInfo->EntryContext,
759
664
                            PrevBlockInfo->ExitContext);
760
664
      }
761
6.56k
    }
762
763
    // Duplicate the context if we have back-edges, so we can call
764
    // intersectBackEdges later.
765
8.04k
    if (HasBackEdges)
766
142
      CurrBlockInfo->EntryContext =
767
142
        createReferenceContext(CurrBlockInfo->EntryContext);
768
769
    // Create a starting context index for the current block
770
8.04k
    saveContext(nullptr, CurrBlockInfo->EntryContext);
771
8.04k
    CurrBlockInfo->EntryIndex = getContextIndex();
772
773
    // Visit all the statements in the basic block.
774
8.04k
    VarMapBuilder VMapBuilder(this, CurrBlockInfo->EntryContext);
775
36.8k
    for (const auto &BI : *CurrBlock) {
776
36.8k
      switch (BI.getKind()) {
777
36.4k
        case CFGElement::Statement: {
778
36.4k
          CFGStmt CS = BI.castAs<CFGStmt>();
779
36.4k
          VMapBuilder.Visit(CS.getStmt());
780
36.4k
          break;
781
0
        }
782
384
        default:
783
384
          break;
784
36.8k
      }
785
36.8k
    }
786
8.04k
    CurrBlockInfo->ExitContext = VMapBuilder.Ctx;
787
788
    // Mark variables on back edges as "unknown" if they've been changed.
789
8.04k
    for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
790
14.7k
         SE  = CurrBlock->succ_end(); SI != SE; 
++SI6.70k
) {
791
      // if CurrBlock -> *SI is *not* a back edge
792
6.70k
      if (*SI == nullptr || 
!VisitedBlocks.alreadySet(*SI)6.70k
)
793
6.57k
        continue;
794
795
134
      CFGBlock *FirstLoopBlock = *SI;
796
134
      Context LoopBegin = BlockInfo[FirstLoopBlock->getBlockID()].EntryContext;
797
134
      Context LoopEnd   = CurrBlockInfo->ExitContext;
798
134
      intersectBackEdge(LoopBegin, LoopEnd);
799
134
    }
800
8.04k
  }
801
802
  // Put an extra entry at the end of the indexed context array
803
2.13k
  unsigned exitID = CFGraph->getExit().getBlockID();
804
2.13k
  saveContext(nullptr, BlockInfo[exitID].ExitContext);
805
2.13k
}
806
807
/// Find the appropriate source locations to use when producing diagnostics for
808
/// each block in the CFG.
809
static void findBlockLocations(CFG *CFGraph,
810
                               const PostOrderCFGView *SortedGraph,
811
2.13k
                               std::vector<CFGBlockInfo> &BlockInfo) {
812
8.04k
  for (const auto *CurrBlock : *SortedGraph) {
813
8.04k
    CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlock->getBlockID()];
814
815
    // Find the source location of the last statement in the block, if the
816
    // block is not empty.
817
8.04k
    if (const Stmt *S = CurrBlock->getTerminatorStmt()) {
818
844
      CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc = S->getBeginLoc();
819
7.19k
    } else {
820
7.19k
      for (CFGBlock::const_reverse_iterator BI = CurrBlock->rbegin(),
821
7.54k
           BE = CurrBlock->rend(); BI != BE; 
++BI350
) {
822
        // FIXME: Handle other CFGElement kinds.
823
3.14k
        if (Optional<CFGStmt> CS = BI->getAs<CFGStmt>()) {
824
2.79k
          CurrBlockInfo->ExitLoc = CS->getStmt()->getBeginLoc();
825
2.79k
          break;
826
2.79k
        }
827
3.14k
      }
828
7.19k
    }
829
830
8.04k
    if (CurrBlockInfo->ExitLoc.isValid()) {
831
      // This block contains at least one statement. Find the source location
832
      // of the first statement in the block.
833
3.63k
      for (const auto &BI : *CurrBlock) {
834
        // FIXME: Handle other CFGElement kinds.
835
3.61k
        if (Optional<CFGStmt> CS = BI.getAs<CFGStmt>()) {
836
3.61k
          CurrBlockInfo->EntryLoc = CS->getStmt()->getBeginLoc();
837
3.61k
          break;
838
3.61k
        }
839
3.61k
      }
840
4.40k
    } else if (CurrBlock->pred_size() == 1 && 
*CurrBlock->pred_begin()2.05k
&&
841
4.40k
               
CurrBlock != &CFGraph->getExit()2.05k
) {
842
      // The block is empty, and has a single predecessor. Use its exit
843
      // location.
844
114
      CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc =
845
114
          BlockInfo[(*CurrBlock->pred_begin())->getBlockID()].ExitLoc;
846
4.29k
    } else if (CurrBlock->succ_size() == 1 && 
*CurrBlock->succ_begin()2.16k
) {
847
      // The block is empty, and has a single successor. Use its entry
848
      // location.
849
2.16k
      CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc =
850
2.16k
          BlockInfo[(*CurrBlock->succ_begin())->getBlockID()].EntryLoc;
851
2.16k
    }
852
8.04k
  }
853
2.13k
}
854
855
namespace {
856
857
class LockableFactEntry : public FactEntry {
858
public:
859
  LockableFactEntry(const CapabilityExpr &CE, LockKind LK, SourceLocation Loc,
860
                    SourceKind Src = Acquired)
861
4.58k
      : FactEntry(CE, LK, Loc, Src) {}
862
863
  void
864
  handleRemovalFromIntersection(const FactSet &FSet, FactManager &FactMan,
865
                                SourceLocation JoinLoc, LockErrorKind LEK,
866
1.63k
                                ThreadSafetyHandler &Handler) const override {
867
1.63k
    if (!asserted() && 
!negative()1.60k
&&
!isUniversal()173
) {
868
169
      Handler.handleMutexHeldEndOfScope(getKind(), toString(), loc(), JoinLoc,
869
169
                                        LEK);
870
169
    }
871
1.63k
  }
872
873
  void handleLock(FactSet &FSet, FactManager &FactMan, const FactEntry &entry,
874
67
                  ThreadSafetyHandler &Handler) const override {
875
67
    Handler.handleDoubleLock(entry.getKind(), entry.toString(), loc(),
876
67
                             entry.loc());
877
67
  }
878
879
  void handleUnlock(FactSet &FSet, FactManager &FactMan,
880
                    const CapabilityExpr &Cp, SourceLocation UnlockLoc,
881
                    bool FullyRemove,
882
1.46k
                    ThreadSafetyHandler &Handler) const override {
883
1.46k
    FSet.removeLock(FactMan, Cp);
884
1.46k
    if (!Cp.negative()) {
885
1.46k
      FSet.addLock(FactMan, std::make_unique<LockableFactEntry>(
886
1.46k
                                !Cp, LK_Exclusive, UnlockLoc));
887
1.46k
    }
888
1.46k
  }
889
};
890
891
class ScopedLockableFactEntry : public FactEntry {
892
private:
893
  enum UnderlyingCapabilityKind {
894
    UCK_Acquired,          ///< Any kind of acquired capability.
895
    UCK_ReleasedShared,    ///< Shared capability that was released.
896
    UCK_ReleasedExclusive, ///< Exclusive capability that was released.
897
  };
898
899
  struct UnderlyingCapability {
900
    CapabilityExpr Cap;
901
    UnderlyingCapabilityKind Kind;
902
  };
903
904
  SmallVector<UnderlyingCapability, 2> UnderlyingMutexes;
905
906
public:
907
  ScopedLockableFactEntry(const CapabilityExpr &CE, SourceLocation Loc)
908
316
      : FactEntry(CE, LK_Exclusive, Loc, Acquired) {}
909
910
284
  void addLock(const CapabilityExpr &M) {
911
284
    UnderlyingMutexes.push_back(UnderlyingCapability{M, UCK_Acquired});
912
284
  }
913
914
28
  void addExclusiveUnlock(const CapabilityExpr &M) {
915
28
    UnderlyingMutexes.push_back(UnderlyingCapability{M, UCK_ReleasedExclusive});
916
28
  }
917
918
8
  void addSharedUnlock(const CapabilityExpr &M) {
919
8
    UnderlyingMutexes.push_back(UnderlyingCapability{M, UCK_ReleasedShared});
920
8
  }
921
922
  void
923
  handleRemovalFromIntersection(const FactSet &FSet, FactManager &FactMan,
924
                                SourceLocation JoinLoc, LockErrorKind LEK,
925
28
                                ThreadSafetyHandler &Handler) const override {
926
28
    for (const auto &UnderlyingMutex : UnderlyingMutexes) {
927
28
      const auto *Entry = FSet.findLock(FactMan, UnderlyingMutex.Cap);
928
28
      if ((UnderlyingMutex.Kind == UCK_Acquired && Entry) ||
929
28
          
(16
UnderlyingMutex.Kind != UCK_Acquired16
&&
!Entry0
)) {
930
        // If this scoped lock manages another mutex, and if the underlying
931
        // mutex is still/not held, then warn about the underlying mutex.
932
12
        Handler.handleMutexHeldEndOfScope(UnderlyingMutex.Cap.getKind(),
933
12
                                          UnderlyingMutex.Cap.toString(), loc(),
934
12
                                          JoinLoc, LEK);
935
12
      }
936
28
    }
937
28
  }
938
939
  void handleLock(FactSet &FSet, FactManager &FactMan, const FactEntry &entry,
940
120
                  ThreadSafetyHandler &Handler) const override {
941
120
    for (const auto &UnderlyingMutex : UnderlyingMutexes) {
942
120
      if (UnderlyingMutex.Kind == UCK_Acquired)
943
112
        lock(FSet, FactMan, UnderlyingMutex.Cap, entry.kind(), entry.loc(),
944
112
             &Handler);
945
8
      else
946
8
        unlock(FSet, FactMan, UnderlyingMutex.Cap, entry.loc(), &Handler);
947
120
    }
948
120
  }
949
950
  void handleUnlock(FactSet &FSet, FactManager &FactMan,
951
                    const CapabilityExpr &Cp, SourceLocation UnlockLoc,
952
                    bool FullyRemove,
953
424
                    ThreadSafetyHandler &Handler) const override {
954
424
    assert(!Cp.negative() && "Managing object cannot be negative.");
955
428
    for (const auto &UnderlyingMutex : UnderlyingMutexes) {
956
      // Remove/lock the underlying mutex if it exists/is still unlocked; warn
957
      // on double unlocking/locking if we're not destroying the scoped object.
958
428
      ThreadSafetyHandler *TSHandler = FullyRemove ? 
nullptr292
:
&Handler136
;
959
428
      if (UnderlyingMutex.Kind == UCK_Acquired) {
960
372
        unlock(FSet, FactMan, UnderlyingMutex.Cap, UnlockLoc, TSHandler);
961
372
      } else {
962
56
        LockKind kind = UnderlyingMutex.Kind == UCK_ReleasedShared
963
56
                            ? 
LK_Shared8
964
56
                            : 
LK_Exclusive48
;
965
56
        lock(FSet, FactMan, UnderlyingMutex.Cap, kind, UnlockLoc, TSHandler);
966
56
      }
967
428
    }
968
424
    if (FullyRemove)
969
288
      FSet.removeLock(FactMan, Cp);
970
424
  }
971
972
private:
973
  void lock(FactSet &FSet, FactManager &FactMan, const CapabilityExpr &Cp,
974
            LockKind kind, SourceLocation loc,
975
168
            ThreadSafetyHandler *Handler) const {
976
168
    if (const FactEntry *Fact = FSet.findLock(FactMan, Cp)) {
977
20
      if (Handler)
978
12
        Handler->handleDoubleLock(Cp.getKind(), Cp.toString(), Fact->loc(),
979
12
                                  loc);
980
148
    } else {
981
148
      FSet.removeLock(FactMan, !Cp);
982
148
      FSet.addLock(FactMan,
983
148
                   std::make_unique<LockableFactEntry>(Cp, kind, loc, Managed));
984
148
    }
985
168
  }
986
987
  void unlock(FactSet &FSet, FactManager &FactMan, const CapabilityExpr &Cp,
988
380
              SourceLocation loc, ThreadSafetyHandler *Handler) const {
989
380
    if (FSet.findLock(FactMan, Cp)) {
990
312
      FSet.removeLock(FactMan, Cp);
991
312
      FSet.addLock(FactMan, std::make_unique<LockableFactEntry>(
992
312
                                !Cp, LK_Exclusive, loc));
993
312
    } else 
if (68
Handler68
) {
994
16
      SourceLocation PrevLoc;
995
16
      if (const FactEntry *Neg = FSet.findLock(FactMan, !Cp))
996
12
        PrevLoc = Neg->loc();
997
16
      Handler->handleUnmatchedUnlock(Cp.getKind(), Cp.toString(), loc, PrevLoc);
998
16
    }
999
380
  }
1000
};
1001
1002
/// Class which implements the core thread safety analysis routines.
1003
class ThreadSafetyAnalyzer {
1004
  friend class BuildLockset;
1005
  friend class threadSafety::BeforeSet;
1006
1007
  llvm::BumpPtrAllocator Bpa;
1008
  threadSafety::til::MemRegionRef Arena;
1009
  threadSafety::SExprBuilder SxBuilder;
1010
1011
  ThreadSafetyHandler &Handler;
1012
  const CXXMethodDecl *CurrentMethod;
1013
  LocalVariableMap LocalVarMap;
1014
  FactManager FactMan;
1015
  std::vector<CFGBlockInfo> BlockInfo;
1016
1017
  BeforeSet *GlobalBeforeSet;
1018
1019
public:
1020
  ThreadSafetyAnalyzer(ThreadSafetyHandler &H, BeforeSet* Bset)
1021
2.25k
      : Arena(&Bpa), SxBuilder(Arena), Handler(H), GlobalBeforeSet(Bset) {}
1022
1023
  bool inCurrentScope(const CapabilityExpr &CapE);
1024
1025
  void addLock(FactSet &FSet, std::unique_ptr<FactEntry> Entry,
1026
               bool ReqAttr = false);
1027
  void removeLock(FactSet &FSet, const CapabilityExpr &CapE,
1028
                  SourceLocation UnlockLoc, bool FullyRemove, LockKind Kind);
1029
1030
  template <typename AttrType>
1031
  void getMutexIDs(CapExprSet &Mtxs, AttrType *Attr, const Expr *Exp,
1032
                   const NamedDecl *D, VarDecl *SelfDecl = nullptr);
1033
1034
  template <class AttrType>
1035
  void getMutexIDs(CapExprSet &Mtxs, AttrType *Attr, const Expr *Exp,
1036
                   const NamedDecl *D,
1037
                   const CFGBlock *PredBlock, const CFGBlock *CurrBlock,
1038
                   Expr *BrE, bool Neg);
1039
1040
  const CallExpr* getTrylockCallExpr(const Stmt *Cond, LocalVarContext C,
1041
                                     bool &Negate);
1042
1043
  void getEdgeLockset(FactSet &Result, const FactSet &ExitSet,
1044
                      const CFGBlock* PredBlock,
1045
                      const CFGBlock *CurrBlock);
1046
1047
  bool join(const FactEntry &a, const FactEntry &b, bool CanModify);
1048
1049
  void intersectAndWarn(FactSet &EntrySet, const FactSet &ExitSet,
1050
                        SourceLocation JoinLoc, LockErrorKind EntryLEK,
1051
                        LockErrorKind ExitLEK);
1052
1053
  void intersectAndWarn(FactSet &EntrySet, const FactSet &ExitSet,
1054
778
                        SourceLocation JoinLoc, LockErrorKind LEK) {
1055
778
    intersectAndWarn(EntrySet, ExitSet, JoinLoc, LEK, LEK);
1056
778
  }
1057
1058
  void runAnalysis(AnalysisDeclContext &AC);
1059
};
1060
1061
} // namespace
1062
1063
/// Process acquired_before and acquired_after attributes on Vd.
1064
BeforeSet::BeforeInfo* BeforeSet::insertAttrExprs(const ValueDecl* Vd,
1065
841
    ThreadSafetyAnalyzer& Analyzer) {
1066
  // Create a new entry for Vd.
1067
841
  BeforeInfo *Info = nullptr;
1068
841
  {
1069
    // Keep InfoPtr in its own scope in case BMap is modified later and the
1070
    // reference becomes invalid.
1071
841
    std::unique_ptr<BeforeInfo> &InfoPtr = BMap[Vd];
1072
841
    if (!InfoPtr)
1073
841
      InfoPtr.reset(new BeforeInfo());
1074
841
    Info = InfoPtr.get();
1075
841
  }
1076
1077
841
  for (const auto *At : Vd->attrs()) {
1078
137
    switch (At->getKind()) {
1079
52
      case attr::AcquiredBefore: {
1080
52
        const auto *A = cast<AcquiredBeforeAttr>(At);
1081
1082
        // Read exprs from the attribute, and add them to BeforeVect.
1083
64
        for (const auto *Arg : A->args()) {
1084
64
          CapabilityExpr Cp =
1085
64
            Analyzer.SxBuilder.translateAttrExpr(Arg, nullptr);
1086
64
          if (const ValueDecl *Cpvd = Cp.valueDecl()) {
1087
60
            Info->Vect.push_back(Cpvd);
1088
60
            const auto It = BMap.find(Cpvd);
1089
60
            if (It == BMap.end())
1090
40
              insertAttrExprs(Cpvd, Analyzer);
1091
60
          }
1092
64
        }
1093
52
        break;
1094
0
      }
1095
85
      case attr::AcquiredAfter: {
1096
85
        const auto *A = cast<AcquiredAfterAttr>(At);
1097
1098
        // Read exprs from the attribute, and add them to BeforeVect.
1099
93
        for (const auto *Arg : A->args()) {
1100
93
          CapabilityExpr Cp =
1101
93
            Analyzer.SxBuilder.translateAttrExpr(Arg, nullptr);
1102
93
          if (const ValueDecl *ArgVd = Cp.valueDecl()) {
1103
            // Get entry for mutex listed in attribute
1104
93
            BeforeInfo *ArgInfo = getBeforeInfoForDecl(ArgVd, Analyzer);
1105
93
            ArgInfo->Vect.push_back(Vd);
1106
93
          }
1107
93
        }
1108
85
        break;
1109
0
      }
1110
0
      default:
1111
0
        break;
1112
137
    }
1113
137
  }
1114
1115
841
  return Info;
1116
841
}
1117
1118
BeforeSet::BeforeInfo *
1119
BeforeSet::getBeforeInfoForDecl(const ValueDecl *Vd,
1120
2.73k
                                ThreadSafetyAnalyzer &Analyzer) {
1121
2.73k
  auto It = BMap.find(Vd);
1122
2.73k
  BeforeInfo *Info = nullptr;
1123
2.73k
  if (It == BMap.end())
1124
801
    Info = insertAttrExprs(Vd, Analyzer);
1125
1.93k
  else
1126
1.93k
    Info = It->second.get();
1127
2.73k
  assert(Info && "BMap contained nullptr?");
1128
0
  return Info;
1129
2.73k
}
1130
1131
/// Return true if any mutexes in FSet are in the acquired_before set of Vd.
1132
void BeforeSet::checkBeforeAfter(const ValueDecl* StartVd,
1133
                                 const FactSet& FSet,
1134
                                 ThreadSafetyAnalyzer& Analyzer,
1135
2.19k
                                 SourceLocation Loc, StringRef CapKind) {
1136
2.19k
  SmallVector<BeforeInfo*, 8> InfoVect;
1137
1138
  // Do a depth-first traversal of Vd.
1139
  // Return true if there are cycles.
1140
2.68k
  std::function<bool (const ValueDecl*)> traverse = [&](const ValueDecl* Vd) {
1141
2.68k
    if (!Vd)
1142
44
      return false;
1143
1144
2.64k
    BeforeSet::BeforeInfo *Info = getBeforeInfoForDecl(Vd, Analyzer);
1145
1146
2.64k
    if (Info->Visited == 1)
1147
32
      return true;
1148
1149
2.61k
    if (Info->Visited == 2)
1150
16
      return false;
1151
1152
2.59k
    if (Info->Vect.empty())
1153
2.14k
      return false;
1154
1155
450
    InfoVect.push_back(Info);
1156
450
    Info->Visited = 1;
1157
490
    for (const auto *Vdb : Info->Vect) {
1158
      // Exclude mutexes in our immediate before set.
1159
490
      if (FSet.containsMutexDecl(Analyzer.FactMan, Vdb)) {
1160
49
        StringRef L1 = StartVd->getName();
1161
49
        StringRef L2 = Vdb->getName();
1162
49
        Analyzer.Handler.handleLockAcquiredBefore(CapKind, L1, L2, Loc);
1163
49
      }
1164
      // Transitively search other before sets, and warn on cycles.
1165
490
      if (traverse(Vdb)) {
1166
32
        if (CycMap.find(Vd) == CycMap.end()) {
1167
20
          CycMap.insert(std::make_pair(Vd, true));
1168
20
          StringRef L1 = Vd->getName();
1169
20
          Analyzer.Handler.handleBeforeAfterCycle(L1, Vd->getLocation());
1170
20
        }
1171
32
      }
1172
490
    }
1173
450
    Info->Visited = 2;
1174
450
    return false;
1175
2.59k
  };
1176
1177
2.19k
  traverse(StartVd);
1178
1179
2.19k
  for (auto *Info : InfoVect)
1180
450
    Info->Visited = 0;
1181
2.19k
}
1182
1183
/// Gets the value decl pointer from DeclRefExprs or MemberExprs.
1184
13.8k
static const ValueDecl *getValueDecl(const Expr *Exp) {
1185
13.8k
  if (const auto *CE = dyn_cast<ImplicitCastExpr>(Exp))
1186
0
    return getValueDecl(CE->getSubExpr());
1187
1188
13.8k
  if (const auto *DR = dyn_cast<DeclRefExpr>(Exp))
1189
4.38k
    return DR->getDecl();
1190
1191
9.41k
  if (const auto *ME = dyn_cast<MemberExpr>(Exp))
1192
5.04k
    return ME->getMemberDecl();
1193
1194
4.36k
  return nullptr;
1195
9.41k
}
1196
1197
namespace {
1198
1199
template <typename Ty>
1200
class has_arg_iterator_range {
1201
  using yes = char[1];
1202
  using no = char[2];
1203
1204
  template <typename Inner>
1205
  static yes& test(Inner *I, decltype(I->args()) * = nullptr);
1206
1207
  template <typename>
1208
  static no& test(...);
1209
1210
public:
1211
  static const bool value = sizeof(test<Ty>(nullptr)) == sizeof(yes);
1212
};
1213
1214
} // namespace
1215
1216
2.16k
bool ThreadSafetyAnalyzer::inCurrentScope(const CapabilityExpr &CapE) {
1217
2.16k
  const threadSafety::til::SExpr *SExp = CapE.sexpr();
1218
2.16k
  assert(SExp && "Null expressions should be ignored");
1219
1220
2.16k
  if (const auto *LP = dyn_cast<til::LiteralPtr>(SExp)) {
1221
976
    const ValueDecl *VD = LP->clangDecl();
1222
    // Variables defined in a function are always inaccessible.
1223
976
    if (!VD->isDefinedOutsideFunctionOrMethod())
1224
457
      return false;
1225
    // For now we consider static class members to be inaccessible.
1226
519
    if (isa<CXXRecordDecl>(VD->getDeclContext()))
1227
16
      return false;
1228
    // Global variables are always in scope.
1229
503
    return true;
1230
519
  }
1231
1232
  // Members are in scope from methods of the same class.
1233
1.19k
  if (const auto *P = dyn_cast<til::Project>(SExp)) {
1234
1.16k
    if (!CurrentMethod)
1235
331
      return false;
1236
829
    const ValueDecl *VD = P->clangDecl();
1237
829
    return VD->getDeclContext() == CurrentMethod->getDeclContext();
1238
1.16k
  }
1239
1240
32
  return false;
1241
1.19k
}
1242
1243
/// Add a new lock to the lockset, warning if the lock is already there.
1244
/// \param ReqAttr -- true if this is part of an initial Requires attribute.
1245
void ThreadSafetyAnalyzer::addLock(FactSet &FSet,
1246
                                   std::unique_ptr<FactEntry> Entry,
1247
2.90k
                                   bool ReqAttr) {
1248
2.90k
  if (Entry->shouldIgnore())
1249
0
    return;
1250
1251
2.90k
  if (!ReqAttr && 
!Entry->negative()2.38k
) {
1252
    // look for the negative capability, and remove it from the fact set.
1253
2.38k
    CapabilityExpr NegC = !*Entry;
1254
2.38k
    const FactEntry *Nen = FSet.findLock(FactMan, NegC);
1255
2.38k
    if (Nen) {
1256
274
      FSet.removeLock(FactMan, NegC);
1257
274
    }
1258
2.10k
    else {
1259
2.10k
      if (inCurrentScope(*Entry) && 
!Entry->asserted()1.22k
)
1260
1.11k
        Handler.handleNegativeNotHeld(Entry->getKind(), Entry->toString(),
1261
1.11k
                                      NegC.toString(), Entry->loc());
1262
2.10k
    }
1263
2.38k
  }
1264
1265
  // Check before/after constraints
1266
2.90k
  if (Handler.issueBetaWarnings() &&
1267
2.90k
      
!Entry->asserted()2.82k
&&
!Entry->declared()2.70k
) {
1268
2.19k
    GlobalBeforeSet->checkBeforeAfter(Entry->valueDecl(), FSet, *this,
1269
2.19k
                                      Entry->loc(), Entry->getKind());
1270
2.19k
  }
1271
1272
  // FIXME: Don't always warn when we have support for reentrant locks.
1273
2.90k
  if (const FactEntry *Cp = FSet.findLock(FactMan, *Entry)) {
1274
215
    if (!Entry->asserted())
1275
187
      Cp->handleLock(FSet, FactMan, *Entry, Handler);
1276
2.68k
  } else {
1277
2.68k
    FSet.addLock(FactMan, std::move(Entry));
1278
2.68k
  }
1279
2.90k
}
1280
1281
/// Remove a lock from the lockset, warning if the lock is not there.
1282
/// \param UnlockLoc The source location of the unlock (only used in error msg)
1283
void ThreadSafetyAnalyzer::removeLock(FactSet &FSet, const CapabilityExpr &Cp,
1284
                                      SourceLocation UnlockLoc,
1285
1.97k
                                      bool FullyRemove, LockKind ReceivedKind) {
1286
1.97k
  if (Cp.shouldIgnore())
1287
0
    return;
1288
1289
1.97k
  const FactEntry *LDat = FSet.findLock(FactMan, Cp);
1290
1.97k
  if (!LDat) {
1291
90
    SourceLocation PrevLoc;
1292
90
    if (const FactEntry *Neg = FSet.findLock(FactMan, !Cp))
1293
42
      PrevLoc = Neg->loc();
1294
90
    Handler.handleUnmatchedUnlock(Cp.getKind(), Cp.toString(), UnlockLoc,
1295
90
                                  PrevLoc);
1296
90
    return;
1297
90
  }
1298
1299
  // Generic lock removal doesn't care about lock kind mismatches, but
1300
  // otherwise diagnose when the lock kinds are mismatched.
1301
1.88k
  if (ReceivedKind != LK_Generic && 
LDat->kind() != ReceivedKind186
) {
1302
18
    Handler.handleIncorrectUnlockKind(Cp.getKind(), Cp.toString(), LDat->kind(),
1303
18
                                      ReceivedKind, LDat->loc(), UnlockLoc);
1304
18
  }
1305
1306
1.88k
  LDat->handleUnlock(FSet, FactMan, Cp, UnlockLoc, FullyRemove, Handler);
1307
1.88k
}
1308
1309
/// Extract the list of mutexIDs from the attribute on an expression,
1310
/// and push them onto Mtxs, discarding any duplicates.
1311
template <typename AttrType>
1312
void ThreadSafetyAnalyzer::getMutexIDs(CapExprSet &Mtxs, AttrType *Attr,
1313
                                       const Expr *Exp, const NamedDecl *D,
1314
4.85k
                                       VarDecl *SelfDecl) {
1315
4.85k
  if (Attr->args_size() == 0) {
1316
    // The mutex held is the "this" object.
1317
3.14k
    CapabilityExpr Cp = SxBuilder.translateAttrExpr(nullptr, D, Exp, SelfDecl);
1318
3.14k
    if (Cp.isInvalid()) {
1319
0
      warnInvalidLock(Handler, nullptr, D, Exp, Cp.getKind());
1320
0
      return;
1321
0
    }
1322
    //else
1323
3.14k
    if (!Cp.shouldIgnore())
1324
3.14k
      Mtxs.push_back_nodup(Cp);
1325
3.14k
    return;
1326
3.14k
  }
1327
1328
2.06k
  
for (const auto *Arg : Attr->args())1.71k
{
1329
2.06k
    CapabilityExpr Cp = SxBuilder.translateAttrExpr(Arg, D, Exp, SelfDecl);
1330
2.06k
    if (Cp.isInvalid()) {
1331
0
      warnInvalidLock(Handler, nullptr, D, Exp, Cp.getKind());
1332
0
      continue;
1333
0
    }
1334
    //else
1335
2.06k
    if (!Cp.shouldIgnore())
1336
2.05k
      Mtxs.push_back_nodup(Cp);
1337
2.06k
  }
1338
1.71k
}
ThreadSafety.cpp:void (anonymous namespace)::ThreadSafetyAnalyzer::getMutexIDs<clang::RequiresCapabilityAttr const>((anonymous namespace)::CapExprSet&, clang::RequiresCapabilityAttr const*, clang::Expr const*, clang::NamedDecl const*, clang::VarDecl*)
Line
Count
Source
1314
430
                                       VarDecl *SelfDecl) {
1315
430
  if (Attr->args_size() == 0) {
1316
    // The mutex held is the "this" object.
1317
0
    CapabilityExpr Cp = SxBuilder.translateAttrExpr(nullptr, D, Exp, SelfDecl);
1318
0
    if (Cp.isInvalid()) {
1319
0
      warnInvalidLock(Handler, nullptr, D, Exp, Cp.getKind());
1320
0
      return;
1321
0
    }
1322
    //else
1323
0
    if (!Cp.shouldIgnore())
1324
0
      Mtxs.push_back_nodup(Cp);
1325
0
    return;
1326
0
  }
1327
1328
482
  
for (const auto *Arg : Attr->args())430
{
1329
482
    CapabilityExpr Cp = SxBuilder.translateAttrExpr(Arg, D, Exp, SelfDecl);
1330
482
    if (Cp.isInvalid()) {
1331
0
      warnInvalidLock(Handler, nullptr, D, Exp, Cp.getKind());
1332
0
      continue;
1333
0
    }
1334
    //else
1335
482
    if (!Cp.shouldIgnore())
1336
482
      Mtxs.push_back_nodup(Cp);
1337
482
  }
1338
430
}
ThreadSafety.cpp:void (anonymous namespace)::ThreadSafetyAnalyzer::getMutexIDs<clang::ReleaseCapabilityAttr const>((anonymous namespace)::CapExprSet&, clang::ReleaseCapabilityAttr const*, clang::Expr const*, clang::NamedDecl const*, clang::VarDecl*)
Line
Count
Source
1314
2.18k
                                       VarDecl *SelfDecl) {
1315
2.18k
  if (Attr->args_size() == 0) {
1316
    // The mutex held is the "this" object.
1317
1.64k
    CapabilityExpr Cp = SxBuilder.translateAttrExpr(nullptr, D, Exp, SelfDecl);
1318
1.64k
    if (Cp.isInvalid()) {
1319
0
      warnInvalidLock(Handler, nullptr, D, Exp, Cp.getKind());
1320
0
      return;
1321
0
    }
1322
    //else
1323
1.64k
    if (!Cp.shouldIgnore())
1324
1.64k
      Mtxs.push_back_nodup(Cp);
1325
1.64k
    return;
1326
1.64k
  }
1327
1328
696
  
for (const auto *Arg : Attr->args())536
{
1329
696
    CapabilityExpr Cp = SxBuilder.translateAttrExpr(Arg, D, Exp, SelfDecl);
1330
696
    if (Cp.isInvalid()) {
1331
0
      warnInvalidLock(Handler, nullptr, D, Exp, Cp.getKind());
1332
0
      continue;
1333
0
    }
1334
    //else
1335
696
    if (!Cp.shouldIgnore())
1336
692
      Mtxs.push_back_nodup(Cp);
1337
696
  }
1338
536
}
ThreadSafety.cpp:void (anonymous namespace)::ThreadSafetyAnalyzer::getMutexIDs<clang::AcquireCapabilityAttr const>((anonymous namespace)::CapExprSet&, clang::AcquireCapabilityAttr const*, clang::Expr const*, clang::NamedDecl const*, clang::VarDecl*)
Line
Count
Source
1314
1.92k
                                       VarDecl *SelfDecl) {
1315
1.92k
  if (Attr->args_size() == 0) {
1316
    // The mutex held is the "this" object.
1317
1.30k
    CapabilityExpr Cp = SxBuilder.translateAttrExpr(nullptr, D, Exp, SelfDecl);
1318
1.30k
    if (Cp.isInvalid()) {
1319
0
      warnInvalidLock(Handler, nullptr, D, Exp, Cp.getKind());
1320
0
      return;
1321
0
    }
1322
    //else
1323
1.30k
    if (!Cp.shouldIgnore())
1324
1.30k
      Mtxs.push_back_nodup(Cp);
1325
1.30k
    return;
1326
1.30k
  }
1327
1328
754
  
for (const auto *Arg : Attr->args())622
{
1329
754
    CapabilityExpr Cp = SxBuilder.translateAttrExpr(Arg, D, Exp, SelfDecl);
1330
754
    if (Cp.isInvalid()) {
1331
0
      warnInvalidLock(Handler, nullptr, D, Exp, Cp.getKind());
1332
0
      continue;
1333
0
    }
1334
    //else
1335
754
    if (!Cp.shouldIgnore())
1336
746
      Mtxs.push_back_nodup(Cp);
1337
754
  }
1338
622
}
ThreadSafety.cpp:void (anonymous namespace)::ThreadSafetyAnalyzer::getMutexIDs<clang::TryAcquireCapabilityAttr const>((anonymous namespace)::CapExprSet&, clang::TryAcquireCapabilityAttr const*, clang::Expr const*, clang::NamedDecl const*, clang::VarDecl*)
Line
Count
Source
1314
84
                                       VarDecl *SelfDecl) {
1315
84
  if (Attr->args_size() == 0) {
1316
    // The mutex held is the "this" object.
1317
58
    CapabilityExpr Cp = SxBuilder.translateAttrExpr(nullptr, D, Exp, SelfDecl);
1318
58
    if (Cp.isInvalid()) {
1319
0
      warnInvalidLock(Handler, nullptr, D, Exp, Cp.getKind());
1320
0
      return;
1321
0
    }
1322
    //else
1323
58
    if (!Cp.shouldIgnore())
1324
58
      Mtxs.push_back_nodup(Cp);
1325
58
    return;
1326
58
  }
1327
1328
26
  for (const auto *Arg : Attr->args()) {
1329
26
    CapabilityExpr Cp = SxBuilder.translateAttrExpr(Arg, D, Exp, SelfDecl);
1330
26
    if (Cp.isInvalid()) {
1331
0
      warnInvalidLock(Handler, nullptr, D, Exp, Cp.getKind());
1332
0
      continue;
1333
0
    }
1334
    //else
1335
26
    if (!Cp.shouldIgnore())
1336
26
      Mtxs.push_back_nodup(Cp);
1337
26
  }
1338
26
}
ThreadSafety.cpp:void (anonymous namespace)::ThreadSafetyAnalyzer::getMutexIDs<clang::ExclusiveTrylockFunctionAttr const>((anonymous namespace)::CapExprSet&, clang::ExclusiveTrylockFunctionAttr const*, clang::Expr const*, clang::NamedDecl const*, clang::VarDecl*)
Line
Count
Source
1314
78
                                       VarDecl *SelfDecl) {
1315
78
  if (Attr->args_size() == 0) {
1316
    // The mutex held is the "this" object.
1317
56
    CapabilityExpr Cp = SxBuilder.translateAttrExpr(nullptr, D, Exp, SelfDecl);
1318
56
    if (Cp.isInvalid()) {
1319
0
      warnInvalidLock(Handler, nullptr, D, Exp, Cp.getKind());
1320
0
      return;
1321
0
    }
1322
    //else
1323
56
    if (!Cp.shouldIgnore())
1324
56
      Mtxs.push_back_nodup(Cp);
1325
56
    return;
1326
56
  }
1327
1328
22
  for (const auto *Arg : Attr->args()) {
1329
22
    CapabilityExpr Cp = SxBuilder.translateAttrExpr(Arg, D, Exp, SelfDecl);
1330
22
    if (Cp.isInvalid()) {
1331
0
      warnInvalidLock(Handler, nullptr, D, Exp, Cp.getKind());
1332
0
      continue;
1333
0
    }
1334
    //else
1335
22
    if (!Cp.shouldIgnore())
1336
22
      Mtxs.push_back_nodup(Cp);
1337
22
  }
1338
22
}
ThreadSafety.cpp:void (anonymous namespace)::ThreadSafetyAnalyzer::getMutexIDs<clang::SharedTrylockFunctionAttr const>((anonymous namespace)::CapExprSet&, clang::SharedTrylockFunctionAttr const*, clang::Expr const*, clang::NamedDecl const*, clang::VarDecl*)
Line
Count
Source
1314
6
                                       VarDecl *SelfDecl) {
1315
6
  if (Attr->args_size() == 0) {
1316
    // The mutex held is the "this" object.
1317
2
    CapabilityExpr Cp = SxBuilder.translateAttrExpr(nullptr, D, Exp, SelfDecl);
1318
2
    if (Cp.isInvalid()) {
1319
0
      warnInvalidLock(Handler, nullptr, D, Exp, Cp.getKind());
1320
0
      return;
1321
0
    }
1322
    //else
1323
2
    if (!Cp.shouldIgnore())
1324
2
      Mtxs.push_back_nodup(Cp);
1325
2
    return;
1326
2
  }
1327
1328
4
  for (const auto *Arg : Attr->args()) {
1329
4
    CapabilityExpr Cp = SxBuilder.translateAttrExpr(Arg, D, Exp, SelfDecl);
1330
4
    if (Cp.isInvalid()) {
1331
0
      warnInvalidLock(Handler, nullptr, D, Exp, Cp.getKind());
1332
0
      continue;
1333
0
    }
1334
    //else
1335
4
    if (!Cp.shouldIgnore())
1336
4
      Mtxs.push_back_nodup(Cp);
1337
4
  }
1338
4
}
ThreadSafety.cpp:void (anonymous namespace)::ThreadSafetyAnalyzer::getMutexIDs<clang::AssertExclusiveLockAttr const>((anonymous namespace)::CapExprSet&, clang::AssertExclusiveLockAttr const*, clang::Expr const*, clang::NamedDecl const*, clang::VarDecl*)
Line
Count
Source
1314
38
                                       VarDecl *SelfDecl) {
1315
38
  if (Attr->args_size() == 0) {
1316
    // The mutex held is the "this" object.
1317
30
    CapabilityExpr Cp = SxBuilder.translateAttrExpr(nullptr, D, Exp, SelfDecl);
1318
30
    if (Cp.isInvalid()) {
1319
0
      warnInvalidLock(Handler, nullptr, D, Exp, Cp.getKind());
1320
0
      return;
1321
0
    }
1322
    //else
1323
30
    if (!Cp.shouldIgnore())
1324
30
      Mtxs.push_back_nodup(Cp);
1325
30
    return;
1326
30
  }
1327
1328
10
  
for (const auto *Arg : Attr->args())8
{
1329
10
    CapabilityExpr Cp = SxBuilder.translateAttrExpr(Arg, D, Exp, SelfDecl);
1330
10
    if (Cp.isInvalid()) {
1331
0
      warnInvalidLock(Handler, nullptr, D, Exp, Cp.getKind());
1332
0
      continue;
1333
0
    }
1334
    //else
1335
10
    if (!Cp.shouldIgnore())
1336
10
      Mtxs.push_back_nodup(Cp);
1337
10
  }
1338
8
}
ThreadSafety.cpp:void (anonymous namespace)::ThreadSafetyAnalyzer::getMutexIDs<clang::AssertSharedLockAttr const>((anonymous namespace)::CapExprSet&, clang::AssertSharedLockAttr const*, clang::Expr const*, clang::NamedDecl const*, clang::VarDecl*)
Line
Count
Source
1314
14
                                       VarDecl *SelfDecl) {
1315
14
  if (Attr->args_size() == 0) {
1316
    // The mutex held is the "this" object.
1317
8
    CapabilityExpr Cp = SxBuilder.translateAttrExpr(nullptr, D, Exp, SelfDecl);
1318
8
    if (Cp.isInvalid()) {
1319
0
      warnInvalidLock(Handler, nullptr, D, Exp, Cp.getKind());
1320
0
      return;
1321
0
    }
1322
    //else
1323
8
    if (!Cp.shouldIgnore())
1324
8
      Mtxs.push_back_nodup(Cp);
1325
8
    return;
1326
8
  }
1327
1328
8
  
for (const auto *Arg : Attr->args())6
{
1329
8
    CapabilityExpr Cp = SxBuilder.translateAttrExpr(Arg, D, Exp, SelfDecl);
1330
8
    if (Cp.isInvalid()) {
1331
0
      warnInvalidLock(Handler, nullptr, D, Exp, Cp.getKind());
1332
0
      continue;
1333
0
    }
1334
    //else
1335
8
    if (!Cp.shouldIgnore())
1336
8
      Mtxs.push_back_nodup(Cp);
1337
8
  }
1338
6
}
ThreadSafety.cpp:void (anonymous namespace)::ThreadSafetyAnalyzer::getMutexIDs<clang::AssertCapabilityAttr const>((anonymous namespace)::CapExprSet&, clang::AssertCapabilityAttr const*, clang::Expr const*, clang::NamedDecl const*, clang::VarDecl*)
Line
Count
Source
1314
52
                                       VarDecl *SelfDecl) {
1315
52
  if (Attr->args_size() == 0) {
1316
    // The mutex held is the "this" object.
1317
38
    CapabilityExpr Cp = SxBuilder.translateAttrExpr(nullptr, D, Exp, SelfDecl);
1318
38
    if (Cp.isInvalid()) {
1319
0
      warnInvalidLock(Handler, nullptr, D, Exp, Cp.getKind());
1320
0
      return;
1321
0
    }
1322
    //else
1323
38
    if (!Cp.shouldIgnore())
1324
38
      Mtxs.push_back_nodup(Cp);
1325
38
    return;
1326
38
  }
1327
1328
18
  
for (const auto *Arg : Attr->args())14
{
1329
18
    CapabilityExpr Cp = SxBuilder.translateAttrExpr(Arg, D, Exp, SelfDecl);
1330
18
    if (Cp.isInvalid()) {
1331
0
      warnInvalidLock(Handler, nullptr, D, Exp, Cp.getKind());
1332
0
      continue;
1333
0
    }
1334
    //else
1335
18
    if (!Cp.shouldIgnore())
1336
18
      Mtxs.push_back_nodup(Cp);
1337
18
  }
1338
14
}
ThreadSafety.cpp:void (anonymous namespace)::ThreadSafetyAnalyzer::getMutexIDs<clang::LocksExcludedAttr const>((anonymous namespace)::CapExprSet&, clang::LocksExcludedAttr const*, clang::Expr const*, clang::NamedDecl const*, clang::VarDecl*)
Line
Count
Source
1314
48
                                       VarDecl *SelfDecl) {
1315
48
  if (Attr->args_size() == 0) {
1316
    // The mutex held is the "this" object.
1317
0
    CapabilityExpr Cp = SxBuilder.translateAttrExpr(nullptr, D, Exp, SelfDecl);
1318
0
    if (Cp.isInvalid()) {
1319
0
      warnInvalidLock(Handler, nullptr, D, Exp, Cp.getKind());
1320
0
      return;
1321
0
    }
1322
    //else
1323
0
    if (!Cp.shouldIgnore())
1324
0
      Mtxs.push_back_nodup(Cp);
1325
0
    return;
1326
0
  }
1327
1328
48
  for (const auto *Arg : Attr->args()) {
1329
48
    CapabilityExpr Cp = SxBuilder.translateAttrExpr(Arg, D, Exp, SelfDecl);
1330
48
    if (Cp.isInvalid()) {
1331
0
      warnInvalidLock(Handler, nullptr, D, Exp, Cp.getKind());
1332
0
      continue;
1333
0
    }
1334
    //else
1335
48
    if (!Cp.shouldIgnore())
1336
48
      Mtxs.push_back_nodup(Cp);
1337
48
  }
1338
48
}
1339
1340
/// Extract the list of mutexIDs from a trylock attribute.  If the
1341
/// trylock applies to the given edge, then push them onto Mtxs, discarding
1342
/// any duplicates.
1343
template <class AttrType>
1344
void ThreadSafetyAnalyzer::getMutexIDs(CapExprSet &Mtxs, AttrType *Attr,
1345
                                       const Expr *Exp, const NamedDecl *D,
1346
                                       const CFGBlock *PredBlock,
1347
                                       const CFGBlock *CurrBlock,
1348
336
                                       Expr *BrE, bool Neg) {
1349
  // Find out which branch has the lock
1350
336
  bool branch = false;
1351
336
  if (const auto *BLE = dyn_cast_or_null<CXXBoolLiteralExpr>(BrE))
1352
272
    branch = BLE->getValue();
1353
64
  else if (const auto *ILE = dyn_cast_or_null<IntegerLiteral>(BrE))
1354
64
    branch = ILE->getValue().getBoolValue();
1355
1356
336
  int branchnum = branch ? 0 : 
10
;
1357
336
  if (Neg)
1358
144
    branchnum = !branchnum;
1359
1360
  // If we've taken the trylock branch, then add the lock
1361
336
  int i = 0;
1362
336
  for (CFGBlock::const_succ_iterator SI = PredBlock->succ_begin(),
1363
1.00k
       SE = PredBlock->succ_end(); SI != SE && 
i < 2672
;
++SI, ++i672
) {
1364
672
    if (*SI == CurrBlock && 
i == branchnum336
)
1365
168
      getMutexIDs(Mtxs, Attr, Exp, D);
1366
672
  }
1367
336
}
ThreadSafety.cpp:void (anonymous namespace)::ThreadSafetyAnalyzer::getMutexIDs<clang::TryAcquireCapabilityAttr const>((anonymous namespace)::CapExprSet&, clang::TryAcquireCapabilityAttr const*, clang::Expr const*, clang::NamedDecl const*, clang::CFGBlock const*, clang::CFGBlock const*, clang::Expr*, bool)
Line
Count
Source
1348
168
                                       Expr *BrE, bool Neg) {
1349
  // Find out which branch has the lock
1350
168
  bool branch = false;
1351
168
  if (const auto *BLE = dyn_cast_or_null<CXXBoolLiteralExpr>(BrE))
1352
136
    branch = BLE->getValue();
1353
32
  else if (const auto *ILE = dyn_cast_or_null<IntegerLiteral>(BrE))
1354
32
    branch = ILE->getValue().getBoolValue();
1355
1356
168
  int branchnum = branch ? 0 : 
10
;
1357
168
  if (Neg)
1358
72
    branchnum = !branchnum;
1359
1360
  // If we've taken the trylock branch, then add the lock
1361
168
  int i = 0;
1362
168
  for (CFGBlock::const_succ_iterator SI = PredBlock->succ_begin(),
1363
504
       SE = PredBlock->succ_end(); SI != SE && 
i < 2336
;
++SI, ++i336
) {
1364
336
    if (*SI == CurrBlock && 
i == branchnum168
)
1365
84
      getMutexIDs(Mtxs, Attr, Exp, D);
1366
336
  }
1367
168
}
ThreadSafety.cpp:void (anonymous namespace)::ThreadSafetyAnalyzer::getMutexIDs<clang::ExclusiveTrylockFunctionAttr const>((anonymous namespace)::CapExprSet&, clang::ExclusiveTrylockFunctionAttr const*, clang::Expr const*, clang::NamedDecl const*, clang::CFGBlock const*, clang::CFGBlock const*, clang::Expr*, bool)
Line
Count
Source
1348
156
                                       Expr *BrE, bool Neg) {
1349
  // Find out which branch has the lock
1350
156
  bool branch = false;
1351
156
  if (const auto *BLE = dyn_cast_or_null<CXXBoolLiteralExpr>(BrE))
1352
124
    branch = BLE->getValue();
1353
32
  else if (const auto *ILE = dyn_cast_or_null<IntegerLiteral>(BrE))
1354
32
    branch = ILE->getValue().getBoolValue();
1355
1356
156
  int branchnum = branch ? 0 : 
10
;
1357
156
  if (Neg)
1358
68
    branchnum = !branchnum;
1359
1360
  // If we've taken the trylock branch, then add the lock
1361
156
  int i = 0;
1362
156
  for (CFGBlock::const_succ_iterator SI = PredBlock->succ_begin(),
1363
468
       SE = PredBlock->succ_end(); SI != SE && 
i < 2312
;
++SI, ++i312
) {
1364
312
    if (*SI == CurrBlock && 
i == branchnum156
)
1365
78
      getMutexIDs(Mtxs, Attr, Exp, D);
1366
312
  }
1367
156
}
ThreadSafety.cpp:void (anonymous namespace)::ThreadSafetyAnalyzer::getMutexIDs<clang::SharedTrylockFunctionAttr const>((anonymous namespace)::CapExprSet&, clang::SharedTrylockFunctionAttr const*, clang::Expr const*, clang::NamedDecl const*, clang::CFGBlock const*, clang::CFGBlock const*, clang::Expr*, bool)
Line
Count
Source
1348
12
                                       Expr *BrE, bool Neg) {
1349
  // Find out which branch has the lock
1350
12
  bool branch = false;
1351
12
  if (const auto *BLE = dyn_cast_or_null<CXXBoolLiteralExpr>(BrE))
1352
12
    branch = BLE->getValue();
1353
0
  else if (const auto *ILE = dyn_cast_or_null<IntegerLiteral>(BrE))
1354
0
    branch = ILE->getValue().getBoolValue();
1355
1356
12
  int branchnum = branch ? 0 : 
10
;
1357
12
  if (Neg)
1358
4
    branchnum = !branchnum;
1359
1360
  // If we've taken the trylock branch, then add the lock
1361
12
  int i = 0;
1362
12
  for (CFGBlock::const_succ_iterator SI = PredBlock->succ_begin(),
1363
36
       SE = PredBlock->succ_end(); SI != SE && 
i < 224
;
++SI, ++i24
) {
1364
24
    if (*SI == CurrBlock && 
i == branchnum12
)
1365
6
      getMutexIDs(Mtxs, Attr, Exp, D);
1366
24
  }
1367
12
}
1368
1369
608
static bool getStaticBooleanValue(Expr *E, bool &TCond) {
1370
608
  if (isa<CXXNullPtrLiteralExpr>(E) || 
isa<GNUNullExpr>(E)600
) {
1371
8
    TCond = false;
1372
8
    return true;
1373
600
  } else if (const auto *BLE = dyn_cast<CXXBoolLiteralExpr>(E)) {
1374
16
    TCond = BLE->getValue();
1375
16
    return true;
1376
584
  } else if (const auto *ILE = dyn_cast<IntegerLiteral>(E)) {
1377
416
    TCond = ILE->getValue().getBoolValue();
1378
416
    return true;
1379
416
  } else 
if (auto *168
CE168
= dyn_cast<ImplicitCastExpr>(E))
1380
136
    return getStaticBooleanValue(CE->getSubExpr(), TCond);
1381
32
  return false;
1382
608
}
1383
1384
// If Cond can be traced back to a function call, return the call expression.
1385
// The negate variable should be called with false, and will be set to true
1386
// if the function call is negated, e.g. if (!mu.tryLock(...))
1387
const CallExpr* ThreadSafetyAnalyzer::getTrylockCallExpr(const Stmt *Cond,
1388
                                                         LocalVarContext C,
1389
3.48k
                                                         bool &Negate) {
1390
3.48k
  if (!Cond)
1391
124
    return nullptr;
1392
1393
3.35k
  if (const auto *CallExp = dyn_cast<CallExpr>(Cond)) {
1394
782
    if (CallExp->getBuiltinCallee() == Builtin::BI__builtin_expect)
1395
16
      return getTrylockCallExpr(CallExp->getArg(0), C, Negate);
1396
766
    return CallExp;
1397
782
  }
1398
2.57k
  else if (const auto *PE = dyn_cast<ParenExpr>(Cond))
1399
32
    return getTrylockCallExpr(PE->getSubExpr(), C, Negate);
1400
2.54k
  else if (const auto *CE = dyn_cast<ImplicitCastExpr>(Cond))
1401
996
    return getTrylockCallExpr(CE->getSubExpr(), C, Negate);
1402
1.54k
  else if (const auto *FE = dyn_cast<FullExpr>(Cond))
1403
8
    return getTrylockCallExpr(FE->getSubExpr(), C, Negate);
1404
1.54k
  else if (const auto *DRE = dyn_cast<DeclRefExpr>(Cond)) {
1405
292
    const Expr *E = LocalVarMap.lookupExpr(DRE->getDecl(), C);
1406
292
    return getTrylockCallExpr(E, C, Negate);
1407
292
  }
1408
1.24k
  else if (const auto *UOP = dyn_cast<UnaryOperator>(Cond)) {
1409
160
    if (UOP->getOpcode() == UO_LNot) {
1410
128
      Negate = !Negate;
1411
128
      return getTrylockCallExpr(UOP->getSubExpr(), C, Negate);
1412
128
    }
1413
32
    return nullptr;
1414
160
  }
1415
1.08k
  else if (const auto *BOP = dyn_cast<BinaryOperator>(Cond)) {
1416
592
    if (BOP->getOpcode() == BO_EQ || 
BOP->getOpcode() == BO_NE216
) {
1417
400
      if (BOP->getOpcode() == BO_NE)
1418
24
        Negate = !Negate;
1419
1420
400
      bool TCond = false;
1421
400
      if (getStaticBooleanValue(BOP->getRHS(), TCond)) {
1422
376
        if (!TCond) 
Negate = !Negate208
;
1423
376
        return getTrylockCallExpr(BOP->getLHS(), C, Negate);
1424
376
      }
1425
24
      TCond = false;
1426
24
      if (getStaticBooleanValue(BOP->getLHS(), TCond)) {
1427
16
        if (!TCond) Negate = !Negate;
1428
16
        return getTrylockCallExpr(BOP->getRHS(), C, Negate);
1429
16
      }
1430
8
      return nullptr;
1431
24
    }
1432
192
    if (BOP->getOpcode() == BO_LAnd) {
1433
      // LHS must have been evaluated in a different block.
1434
72
      return getTrylockCallExpr(BOP->getRHS(), C, Negate);
1435
72
    }
1436
120
    if (BOP->getOpcode() == BO_LOr)
1437
24
      return getTrylockCallExpr(BOP->getRHS(), C, Negate);
1438
96
    return nullptr;
1439
496
  } else if (const auto *COP = dyn_cast<ConditionalOperator>(Cond)) {
1440
24
    bool TCond, FCond;
1441
24
    if (getStaticBooleanValue(COP->getTrueExpr(), TCond) &&
1442
24
        getStaticBooleanValue(COP->getFalseExpr(), FCond)) {
1443
24
      if (TCond && 
!FCond8
)
1444
8
        return getTrylockCallExpr(COP->getCond(), C, Negate);
1445
16
      if (!TCond && FCond) {
1446
16
        Negate = !Negate;
1447
16
        return getTrylockCallExpr(COP->getCond(), C, Negate);
1448
16
      }
1449
16
    }
1450
24
  }
1451
472
  return nullptr;
1452
3.35k
}
1453
1454
/// Find the lockset that holds on the edge between PredBlock
1455
/// and CurrBlock.  The edge set is the exit set of PredBlock (passed
1456
/// as the ExitSet parameter) plus any trylocks, which are conditionally held.
1457
void ThreadSafetyAnalyzer::getEdgeLockset(FactSet& Result,
1458
                                          const FactSet &ExitSet,
1459
                                          const CFGBlock *PredBlock,
1460
6.44k
                                          const CFGBlock *CurrBlock) {
1461
6.44k
  Result = ExitSet;
1462
1463
6.44k
  const Stmt *Cond = PredBlock->getTerminatorCondition();
1464
  // We don't acquire try-locks on ?: branches, only when its result is used.
1465
6.44k
  if (!Cond || 
isa<ConditionalOperator>(PredBlock->getTerminatorStmt())1.57k
)
1466
4.94k
    return;
1467
1468
1.49k
  bool Negate = false;
1469
1.49k
  const CFGBlockInfo *PredBlockInfo = &BlockInfo[PredBlock->getBlockID()];
1470
1.49k
  const LocalVarContext &LVarCtx = PredBlockInfo->ExitContext;
1471
1472
1.49k
  const auto *Exp = getTrylockCallExpr(Cond, LVarCtx, Negate);
1473
1.49k
  if (!Exp)
1474
732
    return;
1475
1476
766
  auto *FunDecl = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
1477
766
  if(!FunDecl || !FunDecl->hasAttrs())
1478
446
    return;
1479
1480
320
  CapExprSet ExclusiveLocksToAdd;
1481
320
  CapExprSet SharedLocksToAdd;
1482
1483
  // If the condition is a call to a Trylock function, then grab the attributes
1484
336
  for (const auto *Attr : FunDecl->attrs()) {
1485
336
    switch (Attr->getKind()) {
1486
168
      case attr::TryAcquireCapability: {
1487
168
        auto *A = cast<TryAcquireCapabilityAttr>(Attr);
1488
168
        getMutexIDs(A->isShared() ? 
SharedLocksToAdd12
:
ExclusiveLocksToAdd156
, A,
1489
168
                    Exp, FunDecl, PredBlock, CurrBlock, A->getSuccessValue(),
1490
168
                    Negate);
1491
168
        break;
1492
0
      };
1493
156
      case attr::ExclusiveTrylockFunction: {
1494
156
        const auto *A = cast<ExclusiveTrylockFunctionAttr>(Attr);
1495
156
        getMutexIDs(ExclusiveLocksToAdd, A, Exp, FunDecl, PredBlock, CurrBlock,
1496
156
                    A->getSuccessValue(), Negate);
1497
156
        break;
1498
0
      }
1499
12
      case attr::SharedTrylockFunction: {
1500
12
        const auto *A = cast<SharedTrylockFunctionAttr>(Attr);
1501
12
        getMutexIDs(SharedLocksToAdd, A, Exp, FunDecl, PredBlock, CurrBlock,
1502
12
                    A->getSuccessValue(), Negate);
1503
12
        break;
1504
0
      }
1505
0
      default:
1506
0
        break;
1507
336
    }
1508
336
  }
1509
1510
  // Add and remove locks.
1511
320
  SourceLocation Loc = Exp->getExprLoc();
1512
320
  for (const auto &ExclusiveLockToAdd : ExclusiveLocksToAdd)
1513
156
    addLock(Result, std::make_unique<LockableFactEntry>(ExclusiveLockToAdd,
1514
156
                                                        LK_Exclusive, Loc));
1515
320
  for (const auto &SharedLockToAdd : SharedLocksToAdd)
1516
12
    addLock(Result, std::make_unique<LockableFactEntry>(SharedLockToAdd,
1517
12
                                                        LK_Shared, Loc));
1518
320
}
1519
1520
namespace {
1521
1522
/// We use this class to visit different types of expressions in
1523
/// CFGBlocks, and build up the lockset.
1524
/// An expression may cause us to add or remove locks from the lockset, or else
1525
/// output error messages related to missing locks.
1526
/// FIXME: In future, we may be able to not inherit from a visitor.
1527
class BuildLockset : public ConstStmtVisitor<BuildLockset> {
1528
  friend class ThreadSafetyAnalyzer;
1529
1530
  ThreadSafetyAnalyzer *Analyzer;
1531
  FactSet FSet;
1532
  LocalVariableMap::Context LVarCtx;
1533
  unsigned CtxIndex;
1534
1535
  // helper functions
1536
  void warnIfMutexNotHeld(const NamedDecl *D, const Expr *Exp, AccessKind AK,
1537
                          Expr *MutexExp, ProtectedOperationKind POK,
1538
                          SourceLocation Loc);
1539
  void warnIfMutexHeld(const NamedDecl *D, const Expr *Exp, Expr *MutexExp);
1540
1541
  void checkAccess(const Expr *Exp, AccessKind AK,
1542
                   ProtectedOperationKind POK = POK_VarAccess);
1543
  void checkPtAccess(const Expr *Exp, AccessKind AK,
1544
                     ProtectedOperationKind POK = POK_VarAccess);
1545
1546
  void handleCall(const Expr *Exp, const NamedDecl *D, VarDecl *VD = nullptr);
1547
  void examineArguments(const FunctionDecl *FD,
1548
                        CallExpr::const_arg_iterator ArgBegin,
1549
                        CallExpr::const_arg_iterator ArgEnd,
1550
                        bool SkipFirstParam = false);
1551
1552
public:
1553
  BuildLockset(ThreadSafetyAnalyzer *Anlzr, CFGBlockInfo &Info)
1554
      : ConstStmtVisitor<BuildLockset>(), Analyzer(Anlzr), FSet(Info.EntrySet),
1555
7.88k
        LVarCtx(Info.EntryContext), CtxIndex(Info.EntryIndex) {}
1556
1557
  void VisitUnaryOperator(const UnaryOperator *UO);
1558
  void VisitBinaryOperator(const BinaryOperator *BO);
1559
  void VisitCastExpr(const CastExpr *CE);
1560
  void VisitCallExpr(const CallExpr *Exp);
1561
  void VisitCXXConstructExpr(const CXXConstructExpr *Exp);
1562
  void VisitDeclStmt(const DeclStmt *S);
1563
};
1564
1565
} // namespace
1566
1567
/// Warn if the LSet does not contain a lock sufficient to protect access
1568
/// of at least the passed in AccessKind.
1569
void BuildLockset::warnIfMutexNotHeld(const NamedDecl *D, const Expr *Exp,
1570
                                      AccessKind AK, Expr *MutexExp,
1571
                                      ProtectedOperationKind POK,
1572
3.20k
                                      SourceLocation Loc) {
1573
3.20k
  LockKind LK = getLockKindFromAccessKind(AK);
1574
1575
3.20k
  CapabilityExpr Cp = Analyzer->SxBuilder.translateAttrExpr(MutexExp, D, Exp);
1576
3.20k
  if (Cp.isInvalid()) {
1577
0
    warnInvalidLock(Analyzer->Handler, MutexExp, D, Exp, Cp.getKind());
1578
0
    return;
1579
3.20k
  } else if (Cp.shouldIgnore()) {
1580
20
    return;
1581
20
  }
1582
1583
3.18k
  if (Cp.negative()) {
1584
    // Negative capabilities act like locks excluded
1585
70
    const FactEntry *LDat = FSet.findLock(Analyzer->FactMan, !Cp);
1586
70
    if (LDat) {
1587
10
      Analyzer->Handler.handleFunExcludesLock(
1588
10
          Cp.getKind(), D->getNameAsString(), (!Cp).toString(), Loc);
1589
10
      return;
1590
10
    }
1591
1592
    // If this does not refer to a negative capability in the same class,
1593
    // then stop here.
1594
60
    if (!Analyzer->inCurrentScope(Cp))
1595
18
      return;
1596
1597
    // Otherwise the negative requirement must be propagated to the caller.
1598
42
    LDat = FSet.findLock(Analyzer->FactMan, Cp);
1599
42
    if (!LDat) {
1600
14
      Analyzer->Handler.handleNegativeNotHeld(D, Cp.toString(), Loc);
1601
14
    }
1602
42
    return;
1603
60
  }
1604
1605
3.11k
  const FactEntry *LDat = FSet.findLockUniv(Analyzer->FactMan, Cp);
1606
3.11k
  bool NoError = true;
1607
3.11k
  if (!LDat) {
1608
    // No exact match found.  Look for a partial match.
1609
1.24k
    LDat = FSet.findPartialMatch(Analyzer->FactMan, Cp);
1610
1.24k
    if (LDat) {
1611
      // Warn that there's no precise match.
1612
76
      std::string PartMatchStr = LDat->toString();
1613
76
      StringRef   PartMatchName(PartMatchStr);
1614
76
      Analyzer->Handler.handleMutexNotHeld(Cp.getKind(), D, POK, Cp.toString(),
1615
76
                                           LK, Loc, &PartMatchName);
1616
1.16k
    } else {
1617
      // Warn that there's no match at all.
1618
1.16k
      Analyzer->Handler.handleMutexNotHeld(Cp.getKind(), D, POK, Cp.toString(),
1619
1.16k
                                           LK, Loc);
1620
1.16k
    }
1621
1.24k
    NoError = false;
1622
1.24k
  }
1623
  // Make sure the mutex we found is the right kind.
1624
3.11k
  if (NoError && 
LDat1.87k
&&
!LDat->isAtLeast(LK)1.87k
) {
1625
60
    Analyzer->Handler.handleMutexNotHeld(Cp.getKind(), D, POK, Cp.toString(),
1626
60
                                         LK, Loc);
1627
60
  }
1628
3.11k
}
1629
1630
/// Warn if the LSet contains the given lock.
1631
void BuildLockset::warnIfMutexHeld(const NamedDecl *D, const Expr *Exp,
1632
174
                                   Expr *MutexExp) {
1633
174
  CapabilityExpr Cp = Analyzer->SxBuilder.translateAttrExpr(MutexExp, D, Exp);
1634
174
  if (Cp.isInvalid()) {
1635
0
    warnInvalidLock(Analyzer->Handler, MutexExp, D, Exp, Cp.getKind());
1636
0
    return;
1637
174
  } else if (Cp.shouldIgnore()) {
1638
0
    return;
1639
0
  }
1640
1641
174
  const FactEntry *LDat = FSet.findLock(Analyzer->FactMan, Cp);
1642
174
  if (LDat) {
1643
67
    Analyzer->Handler.handleFunExcludesLock(Cp.getKind(), D->getNameAsString(),
1644
67
                                            Cp.toString(), Exp->getExprLoc());
1645
67
  }
1646
174
}
1647
1648
/// Checks guarded_by and pt_guarded_by attributes.
1649
/// Whenever we identify an access (read or write) to a DeclRefExpr that is
1650
/// marked with guarded_by, we must ensure the appropriate mutexes are held.
1651
/// Similarly, we check if the access is to an expression that dereferences
1652
/// a pointer marked with pt_guarded_by.
1653
void BuildLockset::checkAccess(const Expr *Exp, AccessKind AK,
1654
9.16k
                               ProtectedOperationKind POK) {
1655
9.16k
  Exp = Exp->IgnoreImplicit()->IgnoreParenCasts();
1656
1657
9.16k
  SourceLocation Loc = Exp->getExprLoc();
1658
1659
  // Local variables of reference type cannot be re-assigned;
1660
  // map them to their initializer.
1661
9.21k
  while (const auto *DRE = dyn_cast<DeclRefExpr>(Exp)) {
1662
3.92k
    const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()->getCanonicalDecl());
1663
3.92k
    if (VD && VD->isLocalVarDecl() && 
VD->getType()->isReferenceType()1.86k
) {
1664
44
      if (const auto *E = VD->getInit()) {
1665
        // Guard against self-initialization. e.g., int &i = i;
1666
44
        if (E == Exp)
1667
0
          break;
1668
44
        Exp = E;
1669
44
        continue;
1670
44
      }
1671
44
    }
1672
3.88k
    break;
1673
3.92k
  }
1674
1675
9.16k
  if (const auto *UO = dyn_cast<UnaryOperator>(Exp)) {
1676
    // For dereferences
1677
254
    if (UO->getOpcode() == UO_Deref)
1678
254
      checkPtAccess(UO->getSubExpr(), AK, POK);
1679
254
    return;
1680
254
  }
1681
1682
8.91k
  if (const auto *BO = dyn_cast<BinaryOperator>(Exp)) {
1683
16
    switch (BO->getOpcode()) {
1684
8
    case BO_PtrMemD: // .*
1685
8
      return checkAccess(BO->getLHS(), AK, POK);
1686
4
    case BO_PtrMemI: // ->*
1687
4
      return checkPtAccess(BO->getLHS(), AK, POK);
1688
4
    default:
1689
4
      return;
1690
16
    }
1691
16
  }
1692
1693
8.89k
  if (const auto *AE = dyn_cast<ArraySubscriptExpr>(Exp)) {
1694
72
    checkPtAccess(AE->getLHS(), AK, POK);
1695
72
    return;
1696
72
  }
1697
1698
8.82k
  if (const auto *ME = dyn_cast<MemberExpr>(Exp)) {
1699
4.36k
    if (ME->isArrow())
1700
3.56k
      checkPtAccess(ME->getBase(), AK, POK);
1701
799
    else
1702
799
      checkAccess(ME->getBase(), AK, POK);
1703
4.36k
  }
1704
1705
8.82k
  const ValueDecl *D = getValueDecl(Exp);
1706
8.82k
  if (!D || 
!D->hasAttrs()8.24k
)
1707
6.16k
    return;
1708
1709
2.66k
  if (D->hasAttr<GuardedVarAttr>() && 
FSet.isEmpty(Analyzer->FactMan)48
) {
1710
25
    Analyzer->Handler.handleNoMutexHeld(D, POK, AK, Loc);
1711
25
  }
1712
1713
2.66k
  for (const auto *I : D->specific_attrs<GuardedByAttr>())
1714
2.11k
    warnIfMutexNotHeld(D, Exp, AK, I->getArg(), POK, Loc);
1715
2.66k
}
1716
1717
/// Checks pt_guarded_by and pt_guarded_var attributes.
1718
/// POK is the same  operationKind that was passed to checkAccess.
1719
void BuildLockset::checkPtAccess(const Expr *Exp, AccessKind AK,
1720
5.03k
                                 ProtectedOperationKind POK) {
1721
6.25k
  while (true) {
1722
6.25k
    if (const auto *PE = dyn_cast<ParenExpr>(Exp)) {
1723
4
      Exp = PE->getSubExpr();
1724
4
      continue;
1725
4
    }
1726
6.25k
    if (const auto *CE = dyn_cast<CastExpr>(Exp)) {
1727
1.27k
      if (CE->getCastKind() == CK_ArrayToPointerDecay) {
1728
        // If it's an actual array, and not a pointer, then it's elements
1729
        // are protected by GUARDED_BY, not PT_GUARDED_BY;
1730
64
        checkAccess(CE->getSubExpr(), AK, POK);
1731
64
        return;
1732
64
      }
1733
1.21k
      Exp = CE->getSubExpr();
1734
1.21k
      continue;
1735
1.27k
    }
1736
4.97k
    break;
1737
6.25k
  }
1738
1739
  // Pass by reference warnings are under a different flag.
1740
4.97k
  ProtectedOperationKind PtPOK = POK_VarDereference;
1741
4.97k
  if (POK == POK_PassByRef) 
PtPOK = POK_PtPassByRef130
;
1742
1743
4.97k
  const ValueDecl *D = getValueDecl(Exp);
1744
4.97k
  if (!D || 
!D->hasAttrs()1.18k
)
1745
4.51k
    return;
1746
1747
462
  if (D->hasAttr<PtGuardedVarAttr>() && 
FSet.isEmpty(Analyzer->FactMan)10
)
1748
9
    Analyzer->Handler.handleNoMutexHeld(D, PtPOK, AK, Exp->getExprLoc());
1749
1750
462
  for (auto const *I : D->specific_attrs<PtGuardedByAttr>())
1751
408
    warnIfMutexNotHeld(D, Exp, AK, I->getArg(), PtPOK, Exp->getExprLoc());
1752
462
}
1753
1754
/// Process a function call, method call, constructor call,
1755
/// or destructor call.  This involves looking at the attributes on the
1756
/// corresponding function/method/constructor/destructor, issuing warnings,
1757
/// and updating the locksets accordingly.
1758
///
1759
/// FIXME: For classes annotated with one of the guarded annotations, we need
1760
/// to treat const method calls as reads and non-const method calls as writes,
1761
/// and check that the appropriate locks are held. Non-const method calls with
1762
/// the same signature as const method calls can be also treated as reads.
1763
///
1764
void BuildLockset::handleCall(const Expr *Exp, const NamedDecl *D,
1765
4.67k
                              VarDecl *VD) {
1766
4.67k
  SourceLocation Loc = Exp->getExprLoc();
1767
4.67k
  CapExprSet ExclusiveLocksToAdd, SharedLocksToAdd;
1768
4.67k
  CapExprSet ExclusiveLocksToRemove, SharedLocksToRemove, GenericLocksToRemove;
1769
4.67k
  CapExprSet ScopedReqsAndExcludes;
1770
1771
  // Figure out if we're constructing an object of scoped lockable class
1772
4.67k
  bool isScopedVar = false;
1773
4.67k
  if (VD) {
1774
336
    if (const auto *CD = dyn_cast<const CXXConstructorDecl>(D)) {
1775
336
      const CXXRecordDecl* PD = CD->getParent();
1776
336
      if (PD && PD->hasAttr<ScopedLockableAttr>())
1777
316
        isScopedVar = true;
1778
336
    }
1779
336
  }
1780
1781
5.04k
  for(const Attr *At : D->attrs()) {
1782
5.04k
    switch (At->getKind()) {
1783
      // When we encounter a lock function, we need to add the lock to our
1784
      // lockset.
1785
1.83k
      case attr::AcquireCapability: {
1786
1.83k
        const auto *A = cast<AcquireCapabilityAttr>(At);
1787
1.83k
        Analyzer->getMutexIDs(A->isShared() ? 
SharedLocksToAdd249
1788
1.83k
                                            : 
ExclusiveLocksToAdd1.58k
,
1789
1.83k
                              A, Exp, D, VD);
1790
1.83k
        break;
1791
0
      }
1792
1793
      // An assert will add a lock to the lockset, but will not generate
1794
      // a warning if it is already there, and will not generate a warning
1795
      // if it is not removed.
1796
38
      case attr::AssertExclusiveLock: {
1797
38
        const auto *A = cast<AssertExclusiveLockAttr>(At);
1798
1799
38
        CapExprSet AssertLocks;
1800
38
        Analyzer->getMutexIDs(AssertLocks, A, Exp, D, VD);
1801
38
        for (const auto &AssertLock : AssertLocks)
1802
40
          Analyzer->addLock(
1803
40
              FSet, std::make_unique<LockableFactEntry>(
1804
40
                        AssertLock, LK_Exclusive, Loc, FactEntry::Asserted));
1805
38
        break;
1806
0
      }
1807
14
      case attr::AssertSharedLock: {
1808
14
        const auto *A = cast<AssertSharedLockAttr>(At);
1809
1810
14
        CapExprSet AssertLocks;
1811
14
        Analyzer->getMutexIDs(AssertLocks, A, Exp, D, VD);
1812
14
        for (const auto &AssertLock : AssertLocks)
1813
16
          Analyzer->addLock(
1814
16
              FSet, std::make_unique<LockableFactEntry>(
1815
16
                        AssertLock, LK_Shared, Loc, FactEntry::Asserted));
1816
14
        break;
1817
0
      }
1818
1819
52
      case attr::AssertCapability: {
1820
52
        const auto *A = cast<AssertCapabilityAttr>(At);
1821
52
        CapExprSet AssertLocks;
1822
52
        Analyzer->getMutexIDs(AssertLocks, A, Exp, D, VD);
1823
52
        for (const auto &AssertLock : AssertLocks)
1824
56
          Analyzer->addLock(FSet, std::make_unique<LockableFactEntry>(
1825
56
                                      AssertLock,
1826
56
                                      A->isShared() ? 
LK_Shared16
:
LK_Exclusive40
,
1827
56
                                      Loc, FactEntry::Asserted));
1828
52
        break;
1829
0
      }
1830
1831
      // When we encounter an unlock function, we need to remove unlocked
1832
      // mutexes from the lockset, and flag a warning if they are not there.
1833
2.02k
      case attr::ReleaseCapability: {
1834
2.02k
        const auto *A = cast<ReleaseCapabilityAttr>(At);
1835
2.02k
        if (A->isGeneric())
1836
1.83k
          Analyzer->getMutexIDs(GenericLocksToRemove, A, Exp, D, VD);
1837
192
        else if (A->isShared())
1838
38
          Analyzer->getMutexIDs(SharedLocksToRemove, A, Exp, D, VD);
1839
154
        else
1840
154
          Analyzer->getMutexIDs(ExclusiveLocksToRemove, A, Exp, D, VD);
1841
2.02k
        break;
1842
0
      }
1843
1844
624
      case attr::RequiresCapability: {
1845
624
        const auto *A = cast<RequiresCapabilityAttr>(At);
1846
688
        for (auto *Arg : A->args()) {
1847
688
          warnIfMutexNotHeld(D, Exp, A->isShared() ? 
AK_Read127
:
AK_Written561
, Arg,
1848
688
                             POK_FunctionCall, Exp->getExprLoc());
1849
          // use for adopting a lock
1850
688
          if (isScopedVar)
1851
16
            Analyzer->getMutexIDs(ScopedReqsAndExcludes, A, Exp, D, VD);
1852
688
        }
1853
624
        break;
1854
0
      }
1855
1856
164
      case attr::LocksExcluded: {
1857
164
        const auto *A = cast<LocksExcludedAttr>(At);
1858
174
        for (auto *Arg : A->args()) {
1859
174
          warnIfMutexHeld(D, Exp, Arg);
1860
          // use for deferring a lock
1861
174
          if (isScopedVar)
1862
48
            Analyzer->getMutexIDs(ScopedReqsAndExcludes, A, Exp, D, VD);
1863
174
        }
1864
164
        break;
1865
0
      }
1866
1867
      // Ignore attributes unrelated to thread-safety
1868
285
      default:
1869
285
        break;
1870
5.04k
    }
1871
5.04k
  }
1872
1873
  // Remove locks first to allow lock upgrading/downgrading.
1874
  // FIXME -- should only fully remove if the attribute refers to 'this'.
1875
4.67k
  bool Dtor = isa<CXXDestructorDecl>(D);
1876
4.67k
  for (const auto &M : ExclusiveLocksToRemove)
1877
154
    Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Exclusive);
1878
4.67k
  for (const auto &M : SharedLocksToRemove)
1879
38
    Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Shared);
1880
4.67k
  for (const auto &M : GenericLocksToRemove)
1881
1.78k
    Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Generic);
1882
1883
  // Add locks.
1884
4.67k
  FactEntry::SourceKind Source =
1885
4.67k
      isScopedVar ? 
FactEntry::Managed316
:
FactEntry::Acquired4.35k
;
1886
4.67k
  for (const auto &M : ExclusiveLocksToAdd)
1887
1.54k
    Analyzer->addLock(FSet, std::make_unique<LockableFactEntry>(M, LK_Exclusive,
1888
1.54k
                                                                Loc, Source));
1889
4.67k
  for (const auto &M : SharedLocksToAdd)
1890
237
    Analyzer->addLock(
1891
237
        FSet, std::make_unique<LockableFactEntry>(M, LK_Shared, Loc, Source));
1892
1893
4.67k
  if (isScopedVar) {
1894
    // Add the managing object as a dummy mutex, mapped to the underlying mutex.
1895
316
    SourceLocation MLoc = VD->getLocation();
1896
316
    DeclRefExpr DRE(VD->getASTContext(), VD, false, VD->getType(), VK_LValue,
1897
316
                    VD->getLocation());
1898
    // FIXME: does this store a pointer to DRE?
1899
316
    CapabilityExpr Scp = Analyzer->SxBuilder.translateAttrExpr(&DRE, nullptr);
1900
1901
316
    auto ScopedEntry = std::make_unique<ScopedLockableFactEntry>(Scp, MLoc);
1902
316
    for (const auto &M : ExclusiveLocksToAdd)
1903
176
      ScopedEntry->addLock(M);
1904
316
    for (const auto &M : SharedLocksToAdd)
1905
44
      ScopedEntry->addLock(M);
1906
316
    for (const auto &M : ScopedReqsAndExcludes)
1907
64
      ScopedEntry->addLock(M);
1908
316
    for (const auto &M : ExclusiveLocksToRemove)
1909
28
      ScopedEntry->addExclusiveUnlock(M);
1910
316
    for (const auto &M : SharedLocksToRemove)
1911
8
      ScopedEntry->addSharedUnlock(M);
1912
316
    Analyzer->addLock(FSet, std::move(ScopedEntry));
1913
316
  }
1914
4.67k
}
1915
1916
/// For unary operations which read and write a variable, we need to
1917
/// check whether we hold any required mutexes. Reads are checked in
1918
/// VisitCastExpr.
1919
844
void BuildLockset::VisitUnaryOperator(const UnaryOperator *UO) {
1920
844
  switch (UO->getOpcode()) {
1921
4
    case UO_PostDec:
1922
12
    case UO_PostInc:
1923
16
    case UO_PreDec:
1924
60
    case UO_PreInc:
1925
60
      checkAccess(UO->getSubExpr(), AK_Written);
1926
60
      break;
1927
784
    default:
1928
784
      break;
1929
844
  }
1930
844
}
1931
1932
/// For binary operations which assign to a variable (writes), we need to check
1933
/// whether we hold any required mutexes.
1934
/// FIXME: Deal with non-primitive types.
1935
2.01k
void BuildLockset::VisitBinaryOperator(const BinaryOperator *BO) {
1936
2.01k
  if (!BO->isAssignmentOp())
1937
439
    return;
1938
1939
  // adjust the context
1940
1.57k
  LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, BO, LVarCtx);
1941
1942
1.57k
  checkAccess(BO->getLHS(), AK_Written);
1943
1.57k
}
1944
1945
/// Whenever we do an LValue to Rvalue cast, we are reading a variable and
1946
/// need to ensure we hold any required mutexes.
1947
/// FIXME: Deal with non-primitive types.
1948
5.20k
void BuildLockset::VisitCastExpr(const CastExpr *CE) {
1949
5.20k
  if (CE->getCastKind() != CK_LValueToRValue)
1950
2.76k
    return;
1951
2.43k
  checkAccess(CE->getSubExpr(), AK_Read);
1952
2.43k
}
1953
1954
void BuildLockset::examineArguments(const FunctionDecl *FD,
1955
                                    CallExpr::const_arg_iterator ArgBegin,
1956
                                    CallExpr::const_arg_iterator ArgEnd,
1957
6.15k
                                    bool SkipFirstParam) {
1958
  // Currently we can't do anything if we don't know the function declaration.
1959
6.15k
  if (!FD)
1960
12
    return;
1961
1962
  // NO_THREAD_SAFETY_ANALYSIS does double duty here.  Normally it
1963
  // only turns off checking within the body of a function, but we also
1964
  // use it to turn off checking in arguments to the function.  This
1965
  // could result in some false negatives, but the alternative is to
1966
  // create yet another attribute.
1967
6.14k
  if (FD->hasAttr<NoThreadSafetyAnalysisAttr>())
1968
40
    return;
1969
1970
6.10k
  const ArrayRef<ParmVarDecl *> Params = FD->parameters();
1971
6.10k
  auto Param = Params.begin();
1972
6.10k
  if (SkipFirstParam)
1973
28
    ++Param;
1974
1975
  // There can be default arguments, so we stop when one iterator is at end().
1976
7.61k
  for (auto Arg = ArgBegin; Param != Params.end() && 
Arg != ArgEnd1.50k
;
1977
6.10k
       
++Param, ++Arg1.50k
) {
1978
1.50k
    QualType Qt = (*Param)->getType();
1979
1.50k
    if (Qt->isReferenceType())
1980
295
      checkAccess(*Arg, AK_Read, POK_PassByRef);
1981
1.50k
  }
1982
6.10k
}
1983
1984
5.55k
void BuildLockset::VisitCallExpr(const CallExpr *Exp) {
1985
5.55k
  if (const auto *CE = dyn_cast<CXXMemberCallExpr>(Exp)) {
1986
4.09k
    const auto *ME = dyn_cast<MemberExpr>(CE->getCallee());
1987
    // ME can be null when calling a method pointer
1988
4.09k
    const CXXMethodDecl *MD = CE->getMethodDecl();
1989
1990
4.09k
    if (ME && 
MD4.08k
) {
1991
4.08k
      if (ME->isArrow()) {
1992
        // Should perhaps be AK_Written if !MD->isConst().
1993
774
        checkPtAccess(CE->getImplicitObjectArgument(), AK_Read);
1994
3.31k
      } else {
1995
        // Should perhaps be AK_Written if !MD->isConst().
1996
3.31k
        checkAccess(CE->getImplicitObjectArgument(), AK_Read);
1997
3.31k
      }
1998
4.08k
    }
1999
2000
4.09k
    examineArguments(CE->getDirectCallee(), CE->arg_begin(), CE->arg_end());
2001
4.09k
  } else 
if (const auto *1.46k
OE1.46k
= dyn_cast<CXXOperatorCallExpr>(Exp)) {
2002
520
    OverloadedOperatorKind OEop = OE->getOperator();
2003
520
    switch (OEop) {
2004
32
      case OO_Equal:
2005
36
      case OO_PlusEqual:
2006
40
      case OO_MinusEqual:
2007
44
      case OO_StarEqual:
2008
48
      case OO_SlashEqual:
2009
52
      case OO_PercentEqual:
2010
56
      case OO_CaretEqual:
2011
60
      case OO_AmpEqual:
2012
64
      case OO_PipeEqual:
2013
68
      case OO_LessLessEqual:
2014
72
      case OO_GreaterGreaterEqual:
2015
72
        checkAccess(OE->getArg(1), AK_Read);
2016
72
        LLVM_FALLTHROUGH;
2017
80
      case OO_PlusPlus:
2018
88
      case OO_MinusMinus:
2019
88
        checkAccess(OE->getArg(0), AK_Written);
2020
88
        break;
2021
116
      case OO_Star:
2022
132
      case OO_ArrowStar:
2023
292
      case OO_Arrow:
2024
376
      case OO_Subscript:
2025
376
        if (!(OEop == OO_Star && 
OE->getNumArgs() > 1116
)) {
2026
          // Grrr.  operator* can be multiplication...
2027
372
          checkPtAccess(OE->getArg(0), AK_Read);
2028
372
        }
2029
376
        LLVM_FALLTHROUGH;
2030
432
      default: {
2031
        // TODO: get rid of this, and rely on pass-by-ref instead.
2032
432
        const Expr *Obj = OE->getArg(0);
2033
432
        checkAccess(Obj, AK_Read);
2034
        // Check the remaining arguments. For method operators, the first
2035
        // argument is the implicit self argument, and doesn't appear in the
2036
        // FunctionDecl, but for non-methods it does.
2037
432
        const FunctionDecl *FD = OE->getDirectCallee();
2038
432
        examineArguments(FD, std::next(OE->arg_begin()), OE->arg_end(),
2039
432
                         /*SkipFirstParam*/ !isa<CXXMethodDecl>(FD));
2040
432
        break;
2041
376
      }
2042
520
    }
2043
944
  } else {
2044
944
    examineArguments(Exp->getDirectCallee(), Exp->arg_begin(), Exp->arg_end());
2045
944
  }
2046
2047
5.55k
  auto *D = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
2048
5.55k
  if(!D || !D->hasAttrs())
2049
1.53k
    return;
2050
4.02k
  handleCall(Exp, D);
2051
4.02k
}
2052
2053
718
void BuildLockset::VisitCXXConstructExpr(const CXXConstructExpr *Exp) {
2054
718
  const CXXConstructorDecl *D = Exp->getConstructor();
2055
718
  if (D && D->isCopyConstructor()) {
2056
31
    const Expr* Source = Exp->getArg(0);
2057
31
    checkAccess(Source, AK_Read);
2058
687
  } else {
2059
687
    examineArguments(D, Exp->arg_begin(), Exp->arg_end());
2060
687
  }
2061
718
}
2062
2063
static CXXConstructorDecl *
2064
4
findConstructorForByValueReturn(const CXXRecordDecl *RD) {
2065
  // Prefer a move constructor over a copy constructor. If there's more than
2066
  // one copy constructor or more than one move constructor, we arbitrarily
2067
  // pick the first declared such constructor rather than trying to guess which
2068
  // one is more appropriate.
2069
4
  CXXConstructorDecl *CopyCtor = nullptr;
2070
8
  for (auto *Ctor : RD->ctors()) {
2071
8
    if (Ctor->isDeleted())
2072
0
      continue;
2073
8
    if (Ctor->isMoveConstructor())
2074
4
      return Ctor;
2075
4
    if (!CopyCtor && Ctor->isCopyConstructor())
2076
0
      CopyCtor = Ctor;
2077
4
  }
2078
0
  return CopyCtor;
2079
4
}
2080
2081
static Expr *buildFakeCtorCall(CXXConstructorDecl *CD, ArrayRef<Expr *> Args,
2082
4
                               SourceLocation Loc) {
2083
4
  ASTContext &Ctx = CD->getASTContext();
2084
4
  return CXXConstructExpr::Create(Ctx, Ctx.getRecordType(CD->getParent()), Loc,
2085
4
                                  CD, true, Args, false, false, false, false,
2086
4
                                  CXXConstructExpr::CK_Complete,
2087
4
                                  SourceRange(Loc, Loc));
2088
4
}
2089
2090
1.03k
void BuildLockset::VisitDeclStmt(const DeclStmt *S) {
2091
  // adjust the context
2092
1.03k
  LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, S, LVarCtx);
2093
2094
1.03k
  for (auto *D : S->getDeclGroup()) {
2095
1.03k
    if (auto *VD = dyn_cast_or_null<VarDecl>(D)) {
2096
1.03k
      Expr *E = VD->getInit();
2097
1.03k
      if (!E)
2098
95
        continue;
2099
936
      E = E->IgnoreParens();
2100
2101
      // handle constructors that involve temporaries
2102
936
      if (auto *EWC = dyn_cast<ExprWithCleanups>(E))
2103
83
        E = EWC->getSubExpr()->IgnoreParens();
2104
936
      if (auto *CE = dyn_cast<CastExpr>(E))
2105
192
        if (CE->getCastKind() == CK_NoOp ||
2106
192
            
CE->getCastKind() == CK_ConstructorConversion186
||
2107
192
            
CE->getCastKind() == CK_UserDefinedConversion184
)
2108
10
          E = CE->getSubExpr()->IgnoreParens();
2109
936
      if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(E))
2110
12
        E = BTE->getSubExpr()->IgnoreParens();
2111
2112
936
      if (const auto *CE = dyn_cast<CXXConstructExpr>(E)) {
2113
555
        const auto *CtorD = dyn_cast_or_null<NamedDecl>(CE->getConstructor());
2114
555
        if (!CtorD || !CtorD->hasAttrs())
2115
223
          continue;
2116
332
        handleCall(E, CtorD, VD);
2117
381
      } else if (isa<CallExpr>(E) && 
E->isPRValue()72
) {
2118
        // If the object is initialized by a function call that returns a
2119
        // scoped lockable by value, use the attributes on the copy or move
2120
        // constructor to figure out what effect that should have on the
2121
        // lockset.
2122
        // FIXME: Is this really the best way to handle this situation?
2123
72
        auto *RD = E->getType()->getAsCXXRecordDecl();
2124
72
        if (!RD || 
!RD->hasAttr<ScopedLockableAttr>()4
)
2125
68
          continue;
2126
4
        CXXConstructorDecl *CtorD = findConstructorForByValueReturn(RD);
2127
4
        if (!CtorD || !CtorD->hasAttrs())
2128
0
          continue;
2129
4
        handleCall(buildFakeCtorCall(CtorD, {E}, E->getBeginLoc()), CtorD, VD);
2130
4
      }
2131
936
    }
2132
1.03k
  }
2133
1.03k
}
2134
2135
/// Given two facts merging on a join point, possibly warn and decide whether to
2136
/// keep or replace.
2137
///
2138
/// \param CanModify Whether we can replace \p A by \p B.
2139
/// \return  false if we should keep \p A, true if we should take \p B.
2140
bool ThreadSafetyAnalyzer::join(const FactEntry &A, const FactEntry &B,
2141
1.16k
                                bool CanModify) {
2142
1.16k
  if (A.kind() != B.kind()) {
2143
    // For managed capabilities, the destructor should unlock in the right mode
2144
    // anyway. For asserted capabilities no unlocking is needed.
2145
68
    if ((A.managed() || 
A.asserted()36
) &&
(48
B.managed()48
||
B.asserted()8
)) {
2146
      // The shared capability subsumes the exclusive capability, if possible.
2147
40
      bool ShouldTakeB = B.kind() == LK_Shared;
2148
40
      if (CanModify || 
!ShouldTakeB8
)
2149
32
        return ShouldTakeB;
2150
40
    }
2151
36
    Handler.handleExclusiveAndShared(B.getKind(), B.toString(), B.loc(),
2152
36
                                     A.loc());
2153
    // Take the exclusive capability to reduce further warnings.
2154
36
    return CanModify && 
B.kind() == LK_Exclusive20
;
2155
1.09k
  } else {
2156
    // The non-asserted capability is the one we want to track.
2157
1.09k
    return CanModify && 
A.asserted()1.00k
&&
!B.asserted()20
;
2158
1.09k
  }
2159
1.16k
}
2160
2161
/// Compute the intersection of two locksets and issue warnings for any
2162
/// locks in the symmetric difference.
2163
///
2164
/// This function is used at a merge point in the CFG when comparing the lockset
2165
/// of each branch being merged. For example, given the following sequence:
2166
/// A; if () then B; else C; D; we need to check that the lockset after B and C
2167
/// are the same. In the event of a difference, we use the intersection of these
2168
/// two locksets at the start of D.
2169
///
2170
/// \param EntrySet A lockset for entry into a (possibly new) block.
2171
/// \param ExitSet The lockset on exiting a preceding block.
2172
/// \param JoinLoc The location of the join point for error reporting
2173
/// \param EntryLEK The warning if a mutex is missing from \p EntrySet.
2174
/// \param ExitLEK The warning if a mutex is missing from \p ExitSet.
2175
void ThreadSafetyAnalyzer::intersectAndWarn(FactSet &EntrySet,
2176
                                            const FactSet &ExitSet,
2177
                                            SourceLocation JoinLoc,
2178
                                            LockErrorKind EntryLEK,
2179
2.85k
                                            LockErrorKind ExitLEK) {
2180
2.85k
  FactSet EntrySetOrig = EntrySet;
2181
2182
  // Find locks in ExitSet that conflict or are not in EntrySet, and warn.
2183
2.85k
  for (const auto &Fact : ExitSet) {
2184
2.63k
    const FactEntry &ExitFact = FactMan[Fact];
2185
2186
2.63k
    FactSet::iterator EntryIt = EntrySet.findLockIter(FactMan, ExitFact);
2187
2.63k
    if (EntryIt != EntrySet.end()) {
2188
1.16k
      if (join(FactMan[*EntryIt], ExitFact,
2189
1.16k
               EntryLEK != LEK_LockedSomeLoopIterations))
2190
44
        *EntryIt = Fact;
2191
1.46k
    } else if (!ExitFact.managed()) {
2192
1.43k
      ExitFact.handleRemovalFromIntersection(ExitSet, FactMan, JoinLoc,
2193
1.43k
                                             EntryLEK, Handler);
2194
1.43k
    }
2195
2.63k
  }
2196
2197
  // Find locks in EntrySet that are not in ExitSet, and remove them.
2198
2.85k
  for (const auto &Fact : EntrySetOrig) {
2199
1.41k
    const FactEntry *EntryFact = &FactMan[Fact];
2200
1.41k
    const FactEntry *ExitFact = ExitSet.findLock(FactMan, *EntryFact);
2201
2202
1.41k
    if (!ExitFact) {
2203
248
      if (!EntryFact->managed() || 
ExitLEK == LEK_LockedSomeLoopIterations28
)
2204
228
        EntryFact->handleRemovalFromIntersection(EntrySetOrig, FactMan, JoinLoc,
2205
228
                                                 ExitLEK, Handler);
2206
248
      if (ExitLEK == LEK_LockedSomePredecessors)
2207
186
        EntrySet.removeLock(FactMan, *EntryFact);
2208
248
    }
2209
1.41k
  }
2210
2.85k
}
2211
2212
// Return true if block B never continues to its successors.
2213
6.46k
static bool neverReturns(const CFGBlock *B) {
2214
6.46k
  if (B->hasNoReturnElement())
2215
24
    return true;
2216
6.44k
  if (B->empty())
2217
2.11k
    return false;
2218
2219
4.32k
  CFGElement Last = B->back();
2220
4.32k
  if (Optional<CFGStmt> S = Last.getAs<CFGStmt>()) {
2221
4.00k
    if (isa<CXXThrowExpr>(S->getStmt()))
2222
4
      return true;
2223
4.00k
  }
2224
4.32k
  return false;
2225
4.32k
}
2226
2227
/// Check a function's CFG for thread-safety violations.
2228
///
2229
/// We traverse the blocks in the CFG, compute the set of mutexes that are held
2230
/// at the end of each block, and issue warnings for thread safety violations.
2231
/// Each block in the CFG is traversed exactly once.
2232
2.25k
void ThreadSafetyAnalyzer::runAnalysis(AnalysisDeclContext &AC) {
2233
  // TODO: this whole function needs be rewritten as a visitor for CFGWalker.
2234
  // For now, we just use the walker to set things up.
2235
2.25k
  threadSafety::CFGWalker walker;
2236
2.25k
  if (!walker.init(AC))
2237
3
    return;
2238
2239
  // AC.dumpCFG(true);
2240
  // threadSafety::printSCFG(walker);
2241
2242
2.24k
  CFG *CFGraph = walker.getGraph();
2243
2.24k
  const NamedDecl *D = walker.getDecl();
2244
2.24k
  const auto *CurrentFunction = dyn_cast<FunctionDecl>(D);
2245
2.24k
  CurrentMethod = dyn_cast<CXXMethodDecl>(D);
2246
2247
2.24k
  if (D->hasAttr<NoThreadSafetyAnalysisAttr>())
2248
36
    return;
2249
2250
  // FIXME: Do something a bit more intelligent inside constructor and
2251
  // destructor code.  Constructors and destructors must assume unique access
2252
  // to 'this', so checks on member variable access is disabled, but we should
2253
  // still enable checks on other objects.
2254
2.21k
  if (isa<CXXConstructorDecl>(D))
2255
51
    return;  // Don't check inside constructors.
2256
2.16k
  if (isa<CXXDestructorDecl>(D))
2257
26
    return;  // Don't check inside destructors.
2258
2259
2.13k
  Handler.enterFunction(CurrentFunction);
2260
2261
2.13k
  BlockInfo.resize(CFGraph->getNumBlockIDs(),
2262
2.13k
    CFGBlockInfo::getEmptyBlockInfo(LocalVarMap));
2263
2264
  // We need to explore the CFG via a "topological" ordering.
2265
  // That way, we will be guaranteed to have information about required
2266
  // predecessor locksets when exploring a new block.
2267
2.13k
  const PostOrderCFGView *SortedGraph = walker.getSortedGraph();
2268
2.13k
  PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
2269
2270
  // Mark entry block as reachable
2271
2.13k
  BlockInfo[CFGraph->getEntry().getBlockID()].Reachable = true;
2272
2273
  // Compute SSA names for local variables
2274
2.13k
  LocalVarMap.traverseCFG(CFGraph, SortedGraph, BlockInfo);
2275
2276
  // Fill in source locations for all CFGBlocks.
2277
2.13k
  findBlockLocations(CFGraph, SortedGraph, BlockInfo);
2278
2279
2.13k
  CapExprSet ExclusiveLocksAcquired;
2280
2.13k
  CapExprSet SharedLocksAcquired;
2281
2.13k
  CapExprSet LocksReleased;
2282
2283
  // Add locks from exclusive_locks_required and shared_locks_required
2284
  // to initial lockset. Also turn off checking for lock and unlock functions.
2285
  // FIXME: is there a more intelligent way to check lock/unlock functions?
2286
2.13k
  if (!SortedGraph->empty() && D->hasAttrs()) {
2287
557
    const CFGBlock *FirstBlock = *SortedGraph->begin();
2288
557
    FactSet &InitialLockset = BlockInfo[FirstBlock->getBlockID()].EntrySet;
2289
2290
557
    CapExprSet ExclusiveLocksToAdd;
2291
557
    CapExprSet SharedLocksToAdd;
2292
2293
557
    SourceLocation Loc = D->getLocation();
2294
691
    for (const auto *Attr : D->attrs()) {
2295
691
      Loc = Attr->getLocation();
2296
691
      if (const auto *A = dyn_cast<RequiresCapabilityAttr>(Attr)) {
2297
414
        getMutexIDs(A->isShared() ? 
SharedLocksToAdd59
:
ExclusiveLocksToAdd355
, A,
2298
414
                    nullptr, D);
2299
414
      } else 
if (const auto *277
A277
= dyn_cast<ReleaseCapabilityAttr>(Attr)) {
2300
        // UNLOCK_FUNCTION() is used to hide the underlying lock implementation.
2301
        // We must ignore such methods.
2302
91
        if (A->args_size() == 0)
2303
14
          return;
2304
77
        getMutexIDs(A->isShared() ? 
SharedLocksToAdd8
:
ExclusiveLocksToAdd69
, A,
2305
77
                    nullptr, D);
2306
77
        getMutexIDs(LocksReleased, A, nullptr, D);
2307
186
      } else if (const auto *A = dyn_cast<AcquireCapabilityAttr>(Attr)) {
2308
106
        if (A->args_size() == 0)
2309
18
          return;
2310
88
        getMutexIDs(A->isShared() ? 
SharedLocksAcquired28
2311
88
                                  : 
ExclusiveLocksAcquired60
,
2312
88
                    A, nullptr, D);
2313
88
      } else 
if (80
isa<ExclusiveTrylockFunctionAttr>(Attr)80
) {
2314
        // Don't try to check trylock functions for now.
2315
4
        return;
2316
76
      } else if (isa<SharedTrylockFunctionAttr>(Attr)) {
2317
        // Don't try to check trylock functions for now.
2318
2
        return;
2319
74
      } else if (isa<TryAcquireCapabilityAttr>(Attr)) {
2320
        // Don't try to check trylock functions for now.
2321
6
        return;
2322
6
      }
2323
691
    }
2324
2325
    // FIXME -- Loc can be wrong here.
2326
513
    for (const auto &Mu : ExclusiveLocksToAdd) {
2327
436
      auto Entry = std::make_unique<LockableFactEntry>(Mu, LK_Exclusive, Loc,
2328
436
                                                       FactEntry::Declared);
2329
436
      addLock(InitialLockset, std::move(Entry), true);
2330
436
    }
2331
513
    for (const auto &Mu : SharedLocksToAdd) {
2332
83
      auto Entry = std::make_unique<LockableFactEntry>(Mu, LK_Shared, Loc,
2333
83
                                                       FactEntry::Declared);
2334
83
      addLock(InitialLockset, std::move(Entry), true);
2335
83
    }
2336
513
  }
2337
2338
7.90k
  
for (const auto *CurrBlock : *SortedGraph)2.09k
{
2339
7.90k
    unsigned CurrBlockID = CurrBlock->getBlockID();
2340
7.90k
    CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
2341
2342
    // Use the default initial lockset in case there are no predecessors.
2343
7.90k
    VisitedBlocks.insert(CurrBlock);
2344
2345
    // Iterate through the predecessor blocks and warn if the lockset for all
2346
    // predecessors is not the same. We take the entry lockset of the current
2347
    // block to be the intersection of all previous locksets.
2348
    // FIXME: By keeping the intersection, we may output more errors in future
2349
    // for a lock which is not in the intersection, but was in the union. We
2350
    // may want to also keep the union in future. As an example, let's say
2351
    // the intersection contains Mutex L, and the union contains L and M.
2352
    // Later we unlock M. At this point, we would output an error because we
2353
    // never locked M; although the real error is probably that we forgot to
2354
    // lock M on all code paths. Conversely, let's say that later we lock M.
2355
    // In this case, we should compare against the intersection instead of the
2356
    // union because the real error is probably that we forgot to unlock M on
2357
    // all code paths.
2358
7.90k
    bool LocksetInitialized = false;
2359
7.90k
    for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
2360
14.5k
         PE  = CurrBlock->pred_end(); PI != PE; 
++PI6.61k
) {
2361
      // if *PI -> CurrBlock is a back edge
2362
6.61k
      if (*PI == nullptr || !VisitedBlocks.alreadySet(*PI))
2363
142
        continue;
2364
2365
6.46k
      unsigned PrevBlockID = (*PI)->getBlockID();
2366
6.46k
      CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
2367
2368
      // Ignore edges from blocks that can't return.
2369
6.46k
      if (neverReturns(*PI) || 
!PrevBlockInfo->Reachable6.44k
)
2370
28
        continue;
2371
2372
      // Okay, we can reach this block from the entry.
2373
6.44k
      CurrBlockInfo->Reachable = true;
2374
2375
6.44k
      FactSet PrevLockset;
2376
6.44k
      getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet, *PI, CurrBlock);
2377
2378
6.44k
      if (!LocksetInitialized) {
2379
5.79k
        CurrBlockInfo->EntrySet = PrevLockset;
2380
5.79k
        LocksetInitialized = true;
2381
5.79k
      } else {
2382
        // Surprisingly 'continue' doesn't always produce back edges, because
2383
        // the CFG has empty "transition" blocks where they meet with the end
2384
        // of the regular loop body. We still want to diagnose them as loop.
2385
644
        intersectAndWarn(
2386
644
            CurrBlockInfo->EntrySet, PrevLockset, CurrBlockInfo->EntryLoc,
2387
644
            isa_and_nonnull<ContinueStmt>((*PI)->getTerminatorStmt())
2388
644
                ? 
LEK_LockedSomeLoopIterations16
2389
644
                : 
LEK_LockedSomePredecessors628
);
2390
644
      }
2391
6.44k
    }
2392
2393
    // Skip rest of block if it's not reachable.
2394
7.90k
    if (!CurrBlockInfo->Reachable)
2395
16
      continue;
2396
2397
7.88k
    BuildLockset LocksetBuilder(this, *CurrBlockInfo);
2398
2399
    // Visit all the statements in the basic block.
2400
36.6k
    for (const auto &BI : *CurrBlock) {
2401
36.6k
      switch (BI.getKind()) {
2402
36.2k
        case CFGElement::Statement: {
2403
36.2k
          CFGStmt CS = BI.castAs<CFGStmt>();
2404
36.2k
          LocksetBuilder.Visit(CS.getStmt());
2405
36.2k
          break;
2406
0
        }
2407
        // Ignore BaseDtor, MemberDtor, and TemporaryDtor for now.
2408
350
        case CFGElement::AutomaticObjectDtor: {
2409
350
          CFGAutomaticObjDtor AD = BI.castAs<CFGAutomaticObjDtor>();
2410
350
          const auto *DD = AD.getDestructorDecl(AC.getASTContext());
2411
350
          if (!DD->hasAttrs())
2412
37
            break;
2413
2414
          // Create a dummy expression,
2415
313
          auto *VD = const_cast<VarDecl *>(AD.getVarDecl());
2416
313
          DeclRefExpr DRE(VD->getASTContext(), VD, false,
2417
313
                          VD->getType().getNonReferenceType(), VK_LValue,
2418
313
                          AD.getTriggerStmt()->getEndLoc());
2419
313
          LocksetBuilder.handleCall(&DRE, DD);
2420
313
          break;
2421
350
        }
2422
34
        default:
2423
34
          break;
2424
36.6k
      }
2425
36.6k
    }
2426
7.88k
    CurrBlockInfo->ExitSet = LocksetBuilder.FSet;
2427
2428
    // For every back edge from CurrBlock (the end of the loop) to another block
2429
    // (FirstLoopBlock) we need to check that the Lockset of Block is equal to
2430
    // the one held at the beginning of FirstLoopBlock. We can look up the
2431
    // Lockset held at the beginning of FirstLoopBlock in the EntryLockSets map.
2432
7.88k
    for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
2433
14.4k
         SE  = CurrBlock->succ_end(); SI != SE; 
++SI6.60k
) {
2434
      // if CurrBlock -> *SI is *not* a back edge
2435
6.60k
      if (*SI == nullptr || 
!VisitedBlocks.alreadySet(*SI)6.60k
)
2436
6.47k
        continue;
2437
2438
134
      CFGBlock *FirstLoopBlock = *SI;
2439
134
      CFGBlockInfo *PreLoop = &BlockInfo[FirstLoopBlock->getBlockID()];
2440
134
      CFGBlockInfo *LoopEnd = &BlockInfo[CurrBlockID];
2441
134
      intersectAndWarn(PreLoop->EntrySet, LoopEnd->ExitSet, PreLoop->EntryLoc,
2442
134
                       LEK_LockedSomeLoopIterations);
2443
134
    }
2444
7.88k
  }
2445
2446
2.09k
  CFGBlockInfo *Initial = &BlockInfo[CFGraph->getEntry().getBlockID()];
2447
2.09k
  CFGBlockInfo *Final   = &BlockInfo[CFGraph->getExit().getBlockID()];
2448
2449
  // Skip the final check if the exit block is unreachable.
2450
2.09k
  if (!Final->Reachable)
2451
20
    return;
2452
2453
  // By default, we expect all locks held on entry to be held on exit.
2454
2.07k
  FactSet ExpectedExitSet = Initial->EntrySet;
2455
2456
  // Adjust the expected exit set by adding or removing locks, as declared
2457
  // by *-LOCK_FUNCTION and UNLOCK_FUNCTION.  The intersect below will then
2458
  // issue the appropriate warning.
2459
  // FIXME: the location here is not quite right.
2460
2.07k
  for (const auto &Lock : ExclusiveLocksAcquired)
2461
52
    ExpectedExitSet.addLock(FactMan, std::make_unique<LockableFactEntry>(
2462
52
                                         Lock, LK_Exclusive, D->getLocation()));
2463
2.07k
  for (const auto &Lock : SharedLocksAcquired)
2464
24
    ExpectedExitSet.addLock(FactMan, std::make_unique<LockableFactEntry>(
2465
24
                                         Lock, LK_Shared, D->getLocation()));
2466
2.07k
  for (const auto &Lock : LocksReleased)
2467
69
    ExpectedExitSet.removeLock(FactMan, Lock);
2468
2469
  // FIXME: Should we call this function for all blocks which exit the function?
2470
2.07k
  intersectAndWarn(ExpectedExitSet, Final->ExitSet, Final->ExitLoc,
2471
2.07k
                   LEK_LockedAtEndOfFunction, LEK_NotLockedAtEndOfFunction);
2472
2473
2.07k
  Handler.leaveFunction(CurrentFunction);
2474
2.07k
}
2475
2476
/// Check a function's CFG for thread-safety violations.
2477
///
2478
/// We traverse the blocks in the CFG, compute the set of mutexes that are held
2479
/// at the end of each block, and issue warnings for thread safety violations.
2480
/// Each block in the CFG is traversed exactly once.
2481
void threadSafety::runThreadSafetyAnalysis(AnalysisDeclContext &AC,
2482
                                           ThreadSafetyHandler &Handler,
2483
2.25k
                                           BeforeSet **BSet) {
2484
2.25k
  if (!*BSet)
2485
34
    *BSet = new BeforeSet;
2486
2.25k
  ThreadSafetyAnalyzer Analyzer(Handler, *BSet);
2487
2.25k
  Analyzer.runAnalysis(AC);
2488
2.25k
}
2489
2490
83.4k
void threadSafety::threadSafetyCleanup(BeforeSet *Cache) { delete Cache; }
2491
2492
/// Helper function that returns a LockKind required for the given level
2493
/// of access.
2494
3.24k
LockKind threadSafety::getLockKindFromAccessKind(AccessKind AK) {
2495
3.24k
  switch (AK) {
2496
1.29k
    case AK_Read :
2497
1.29k
      return LK_Shared;
2498
1.95k
    case AK_Written :
2499
1.95k
      return LK_Exclusive;
2500
3.24k
  }
2501
0
  llvm_unreachable("Unknown AccessKind");
2502
0
}