Coverage Report

Created: 2018-07-19 20:53

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/clang/include/clang/Analysis/Analyses/ThreadSafetyCommon.h
Line
Count
Source (jump to first uncovered line)
1
//===- ThreadSafetyCommon.h -------------------------------------*- C++ -*-===//
2
//
3
//                     The LLVM Compiler Infrastructure
4
//
5
// This file is distributed under the University of Illinois Open Source
6
// License. See LICENSE.TXT for details.
7
//
8
//===----------------------------------------------------------------------===//
9
//
10
// Parts of thread safety analysis that are not specific to thread safety
11
// itself have been factored into classes here, where they can be potentially
12
// used by other analyses.  Currently these include:
13
//
14
// * Generalize clang CFG visitors.
15
// * Conversion of the clang CFG to SSA form.
16
// * Translation of clang Exprs to TIL SExprs
17
//
18
// UNDER CONSTRUCTION.  USE AT YOUR OWN RISK.
19
//
20
//===----------------------------------------------------------------------===//
21
22
#ifndef LLVM_CLANG_ANALYSIS_ANALYSES_THREADSAFETYCOMMON_H
23
#define LLVM_CLANG_ANALYSIS_ANALYSES_THREADSAFETYCOMMON_H
24
25
#include "clang/AST/Decl.h"
26
#include "clang/Analysis/Analyses/PostOrderCFGView.h"
27
#include "clang/Analysis/Analyses/ThreadSafetyTIL.h"
28
#include "clang/Analysis/Analyses/ThreadSafetyTraverse.h"
29
#include "clang/Analysis/Analyses/ThreadSafetyUtil.h"
30
#include "clang/Analysis/AnalysisDeclContext.h"
31
#include "clang/Analysis/CFG.h"
32
#include "clang/Basic/LLVM.h"
33
#include "llvm/ADT/DenseMap.h"
34
#include "llvm/ADT/SmallVector.h"
35
#include "llvm/Support/Casting.h"
36
#include <sstream>
37
#include <string>
38
#include <utility>
39
#include <vector>
40
41
namespace clang {
42
43
class AbstractConditionalOperator;
44
class ArraySubscriptExpr;
45
class BinaryOperator;
46
class CallExpr;
47
class CastExpr;
48
class CXXDestructorDecl;
49
class CXXMemberCallExpr;
50
class CXXOperatorCallExpr;
51
class CXXThisExpr;
52
class DeclRefExpr;
53
class DeclStmt;
54
class Expr;
55
class MemberExpr;
56
class Stmt;
57
class UnaryOperator;
58
59
namespace threadSafety {
60
61
// Various helper functions on til::SExpr
62
namespace sx {
63
64
1.08k
inline bool equals(const til::SExpr *E1, const til::SExpr *E2) {
65
1.08k
  return til::EqualsComparator::compareExprs(E1, E2);
66
1.08k
}
67
68
10.5k
inline bool matches(const til::SExpr *E1, const til::SExpr *E2) {
69
10.5k
  // We treat a top-level wildcard as the "univsersal" lock.
70
10.5k
  // It matches everything for the purpose of checking locks, but not
71
10.5k
  // for unlocking them.
72
10.5k
  if (isa<til::Wildcard>(E1))
73
120
    return isa<til::Wildcard>(E2);
74
10.4k
  if (isa<til::Wildcard>(E2))
75
24
    return isa<til::Wildcard>(E1);
76
10.3k
77
10.3k
  return til::MatchComparator::compareExprs(E1, E2);
78
10.3k
}
79
80
289
inline bool partiallyMatches(const til::SExpr *E1, const til::SExpr *E2) {
81
289
  const auto *PE1 = dyn_cast_or_null<til::Project>(E1);
82
289
  if (!PE1)
83
12
    return false;
84
277
  const auto *PE2 = dyn_cast_or_null<til::Project>(E2);
85
277
  if (!PE2)
86
24
    return false;
87
253
  return PE1->clangDecl() == PE2->clangDecl();
88
253
}
89
90
2.71k
inline std::string toString(const til::SExpr *E) {
91
2.71k
  std::stringstream ss;
92
2.71k
  til::StdPrinter::print(E, ss);
93
2.71k
  return ss.str();
94
2.71k
}
95
96
}  // namespace sx
97
98
// This class defines the interface of a clang CFG Visitor.
99
// CFGWalker will invoke the following methods.
100
// Note that methods are not virtual; the visitor is templatized.
101
class CFGVisitor {
102
  // Enter the CFG for Decl D, and perform any initial setup operations.
103
  void enterCFG(CFG *Cfg, const NamedDecl *D, const CFGBlock *First) {}
104
105
  // Enter a CFGBlock.
106
  void enterCFGBlock(const CFGBlock *B) {}
107
108
  // Returns true if this visitor implements handlePredecessor
109
  bool visitPredecessors() { return true; }
110
111
  // Process a predecessor edge.
112
  void handlePredecessor(const CFGBlock *Pred) {}
113
114
  // Process a successor back edge to a previously visited block.
115
  void handlePredecessorBackEdge(const CFGBlock *Pred) {}
116
117
  // Called just before processing statements.
118
  void enterCFGBlockBody(const CFGBlock *B) {}
119
120
  // Process an ordinary statement.
121
  void handleStatement(const Stmt *S) {}
122
123
  // Process a destructor call
124
  void handleDestructorCall(const VarDecl *VD, const CXXDestructorDecl *DD) {}
125
126
  // Called after all statements have been handled.
127
  void exitCFGBlockBody(const CFGBlock *B) {}
128
129
  // Return true
130
  bool visitSuccessors() { return true; }
131
132
  // Process a successor edge.
133
  void handleSuccessor(const CFGBlock *Succ) {}
134
135
  // Process a successor back edge to a previously visited block.
136
  void handleSuccessorBackEdge(const CFGBlock *Succ) {}
137
138
  // Leave a CFGBlock.
139
  void exitCFGBlock(const CFGBlock *B) {}
140
141
  // Leave the CFG, and perform any final cleanup operations.
142
  void exitCFG(const CFGBlock *Last) {}
143
};
144
145
// Walks the clang CFG, and invokes methods on a given CFGVisitor.
146
class CFGWalker {
147
public:
148
1.92k
  CFGWalker() = default;
149
150
  // Initialize the CFGWalker.  This setup only needs to be done once, even
151
  // if there are multiple passes over the CFG.
152
1.92k
  bool init(AnalysisDeclContext &AC) {
153
1.92k
    ACtx = &AC;
154
1.92k
    CFGraph = AC.getCFG();
155
1.92k
    if (!CFGraph)
156
0
      return false;
157
1.92k
158
1.92k
    // Ignore anonymous functions.
159
1.92k
    if (!dyn_cast_or_null<NamedDecl>(AC.getDecl()))
160
3
      return false;
161
1.91k
162
1.91k
    SortedGraph = AC.getAnalysis<PostOrderCFGView>();
163
1.91k
    if (!SortedGraph)
164
0
      return false;
165
1.91k
166
1.91k
    return true;
167
1.91k
  }
168
169
  // Traverse the CFG, calling methods on V as appropriate.
170
  template <class Visitor>
171
0
  void walk(Visitor &V) {
172
0
    PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
173
0
174
0
    V.enterCFG(CFGraph, getDecl(), &CFGraph->getEntry());
175
0
176
0
    for (const auto *CurrBlock : *SortedGraph) {
177
0
      VisitedBlocks.insert(CurrBlock);
178
0
179
0
      V.enterCFGBlock(CurrBlock);
180
0
181
0
      // Process predecessors, handling back edges last
182
0
      if (V.visitPredecessors()) {
183
0
        SmallVector<CFGBlock*, 4> BackEdges;
184
0
        // Process successors
185
0
        for (CFGBlock::const_pred_iterator SI = CurrBlock->pred_begin(),
186
0
                                           SE = CurrBlock->pred_end();
187
0
             SI != SE; ++SI) {
188
0
          if (*SI == nullptr)
189
0
            continue;
190
0
191
0
          if (!VisitedBlocks.alreadySet(*SI)) {
192
0
            BackEdges.push_back(*SI);
193
0
            continue;
194
0
          }
195
0
          V.handlePredecessor(*SI);
196
0
        }
197
0
198
0
        for (auto *Blk : BackEdges)
199
0
          V.handlePredecessorBackEdge(Blk);
200
0
      }
201
0
202
0
      V.enterCFGBlockBody(CurrBlock);
203
0
204
0
      // Process statements
205
0
      for (const auto &BI : *CurrBlock) {
206
0
        switch (BI.getKind()) {
207
0
        case CFGElement::Statement:
208
0
          V.handleStatement(BI.castAs<CFGStmt>().getStmt());
209
0
          break;
210
0
211
0
        case CFGElement::AutomaticObjectDtor: {
212
0
          CFGAutomaticObjDtor AD = BI.castAs<CFGAutomaticObjDtor>();
213
0
          auto *DD = const_cast<CXXDestructorDecl *>(
214
0
              AD.getDestructorDecl(ACtx->getASTContext()));
215
0
          auto *VD = const_cast<VarDecl *>(AD.getVarDecl());
216
0
          V.handleDestructorCall(VD, DD);
217
0
          break;
218
0
        }
219
0
        default:
220
0
          break;
221
0
        }
222
0
      }
223
0
224
0
      V.exitCFGBlockBody(CurrBlock);
225
0
226
0
      // Process successors, handling back edges first.
227
0
      if (V.visitSuccessors()) {
228
0
        SmallVector<CFGBlock*, 8> ForwardEdges;
229
0
230
0
        // Process successors
231
0
        for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
232
0
                                           SE = CurrBlock->succ_end();
233
0
             SI != SE; ++SI) {
234
0
          if (*SI == nullptr)
235
0
            continue;
236
0
237
0
          if (!VisitedBlocks.alreadySet(*SI)) {
238
0
            ForwardEdges.push_back(*SI);
239
0
            continue;
240
0
          }
241
0
          V.handleSuccessorBackEdge(*SI);
242
0
        }
243
0
244
0
        for (auto *Blk : ForwardEdges)
245
0
          V.handleSuccessor(Blk);
246
0
      }
247
0
248
0
      V.exitCFGBlock(CurrBlock);
249
0
    }
250
0
    V.exitCFG(&CFGraph->getExit());
251
0
  }
252
253
0
  const CFG *getGraph() const { return CFGraph; }
254
1.91k
  CFG *getGraph() { return CFGraph; }
255
256
1.91k
  const NamedDecl *getDecl() const {
257
1.91k
    return dyn_cast<NamedDecl>(ACtx->getDecl());
258
1.91k
  }
259
260
1.80k
  const PostOrderCFGView *getSortedGraph() const { return SortedGraph; }
261
262
private:
263
  CFG *CFGraph = nullptr;
264
  AnalysisDeclContext *ACtx = nullptr;
265
  PostOrderCFGView *SortedGraph = nullptr;
266
};
267
268
// TODO: move this back into ThreadSafety.cpp
269
// This is specific to thread safety.  It is here because
270
// translateAttrExpr needs it, but that should be moved too.
271
class CapabilityExpr {
272
private:
273
  /// The capability expression.
274
  const til::SExpr* CapExpr;
275
276
  /// True if this is a negative capability.
277
  bool Negated;
278
279
public:
280
10.9k
  CapabilityExpr(const til::SExpr *E, bool Neg) : CapExpr(E), Negated(Neg) {}
281
282
20.3k
  const til::SExpr* sexpr() const { return CapExpr; }
283
7.09k
  bool negative() const { return Negated; }
284
285
3.27k
  CapabilityExpr operator!() const {
286
3.27k
    return CapabilityExpr(CapExpr, !Negated);
287
3.27k
  }
288
289
1.08k
  bool equals(const CapabilityExpr &other) const {
290
1.08k
    return (Negated == other.Negated) && sx::equals(CapExpr, other.CapExpr);
291
1.08k
  }
292
293
12.6k
  bool matches(const CapabilityExpr &other) const {
294
12.6k
    return (Negated == other.Negated) && 
sx::matches(CapExpr, other.CapExpr)10.5k
;
295
12.6k
  }
296
297
2.42k
  bool matchesUniv(const CapabilityExpr &CapE) const {
298
2.42k
    return isUniversal() || 
matches(CapE)2.40k
;
299
2.42k
  }
300
301
398
  bool partiallyMatches(const CapabilityExpr &other) const {
302
398
    return (Negated == other.Negated) &&
303
398
            
sx::partiallyMatches(CapExpr, other.CapExpr)289
;
304
398
  }
305
306
1.99k
  const ValueDecl* valueDecl() const {
307
1.99k
    if (Negated || 
CapExpr == nullptr1.98k
)
308
15
      return nullptr;
309
1.97k
    if (const auto *P = dyn_cast<til::Project>(CapExpr))
310
1.40k
      return P->clangDecl();
311
576
    if (const auto *P = dyn_cast<til::LiteralPtr>(CapExpr))
312
532
      return P->clangDecl();
313
44
    return nullptr;
314
44
  }
315
316
2.70k
  std::string toString() const {
317
2.70k
    if (Negated)
318
603
      return "!" + sx::toString(CapExpr);
319
2.10k
    return sx::toString(CapExpr);
320
2.10k
  }
321
322
10.7k
  bool shouldIgnore() const { return CapExpr == nullptr; }
323
324
7.01k
  bool isInvalid() const { return sexpr() && 
isa<til::Undefined>(sexpr())6.98k
; }
325
326
2.57k
  bool isUniversal() const { return sexpr() && isa<til::Wildcard>(sexpr()); }
327
};
328
329
// Translate clang::Expr to til::SExpr.
330
class SExprBuilder {
331
public:
332
  /// Encapsulates the lexical context of a function call.  The lexical
333
  /// context includes the arguments to the call, including the implicit object
334
  /// argument.  When an attribute containing a mutex expression is attached to
335
  /// a method, the expression may refer to formal parameters of the method.
336
  /// Actual arguments must be substituted for formal parameters to derive
337
  /// the appropriate mutex expression in the lexical context where the function
338
  /// is called.  PrevCtx holds the context in which the arguments themselves
339
  /// should be evaluated; multiple calling contexts can be chained together
340
  /// by the lock_returned attribute.
341
  struct CallingContext {
342
    // The previous context; or 0 if none.
343
    CallingContext  *Prev;
344
345
    // The decl to which the attr is attached.
346
    const NamedDecl *AttrDecl;
347
348
    // Implicit object argument -- e.g. 'this'
349
    const Expr *SelfArg = nullptr;
350
351
    // Number of funArgs
352
    unsigned NumArgs = 0;
353
354
    // Function arguments
355
    const Expr *const *FunArgs = nullptr;
356
357
    // is Self referred to with -> or .?
358
    bool SelfArrow = false;
359
360
    CallingContext(CallingContext *P, const NamedDecl *D = nullptr)
361
6.44k
        : Prev(P), AttrDecl(D) {}
362
  };
363
364
1.92k
  SExprBuilder(til::MemRegionRef A) : Arena(A) {
365
1.92k
    // FIXME: we don't always have a self-variable.
366
1.92k
    SelfVar = new (Arena) til::Variable(nullptr);
367
1.92k
    SelfVar->setKind(til::Variable::VK_SFun);
368
1.92k
  }
369
370
  // Translate a clang expression in an attribute to a til::SExpr.
371
  // Constructs the context from D, DeclExp, and SelfDecl.
372
  CapabilityExpr translateAttrExpr(const Expr *AttrExp, const NamedDecl *D,
373
                                   const Expr *DeclExp, VarDecl *SelfD=nullptr);
374
375
  CapabilityExpr translateAttrExpr(const Expr *AttrExp, CallingContext *Ctx);
376
377
  // Translate a clang statement or expression to a TIL expression.
378
  // Also performs substitution of variables; Ctx provides the context.
379
  // Dispatches on the type of S.
380
  til::SExpr *translate(const Stmt *S, CallingContext *Ctx);
381
  til::SCFG  *buildCFG(CFGWalker &Walker);
382
383
  til::SExpr *lookupStmt(const Stmt *S);
384
385
0
  til::BasicBlock *lookupBlock(const CFGBlock *B) {
386
0
    return BlockMap[B->getBlockID()];
387
0
  }
388
389
  const til::SCFG *getCFG() const { return Scfg; }
390
  til::SCFG *getCFG() { return Scfg; }
391
392
private:
393
  // We implement the CFGVisitor API
394
  friend class CFGWalker;
395
396
  til::SExpr *translateDeclRefExpr(const DeclRefExpr *DRE,
397
                                   CallingContext *Ctx) ;
398
  til::SExpr *translateCXXThisExpr(const CXXThisExpr *TE, CallingContext *Ctx);
399
  til::SExpr *translateMemberExpr(const MemberExpr *ME, CallingContext *Ctx);
400
  til::SExpr *translateCallExpr(const CallExpr *CE, CallingContext *Ctx,
401
                                const Expr *SelfE = nullptr);
402
  til::SExpr *translateCXXMemberCallExpr(const CXXMemberCallExpr *ME,
403
                                         CallingContext *Ctx);
404
  til::SExpr *translateCXXOperatorCallExpr(const CXXOperatorCallExpr *OCE,
405
                                           CallingContext *Ctx);
406
  til::SExpr *translateUnaryOperator(const UnaryOperator *UO,
407
                                     CallingContext *Ctx);
408
  til::SExpr *translateBinOp(til::TIL_BinaryOpcode Op,
409
                             const BinaryOperator *BO,
410
                             CallingContext *Ctx, bool Reverse = false);
411
  til::SExpr *translateBinAssign(til::TIL_BinaryOpcode Op,
412
                                 const BinaryOperator *BO,
413
                                 CallingContext *Ctx, bool Assign = false);
414
  til::SExpr *translateBinaryOperator(const BinaryOperator *BO,
415
                                      CallingContext *Ctx);
416
  til::SExpr *translateCastExpr(const CastExpr *CE, CallingContext *Ctx);
417
  til::SExpr *translateArraySubscriptExpr(const ArraySubscriptExpr *E,
418
                                          CallingContext *Ctx);
419
  til::SExpr *translateAbstractConditionalOperator(
420
      const AbstractConditionalOperator *C, CallingContext *Ctx);
421
422
  til::SExpr *translateDeclStmt(const DeclStmt *S, CallingContext *Ctx);
423
424
  // Map from statements in the clang CFG to SExprs in the til::SCFG.
425
  using StatementMap = llvm::DenseMap<const Stmt *, til::SExpr *>;
426
427
  // Map from clang local variables to indices in a LVarDefinitionMap.
428
  using LVarIndexMap = llvm::DenseMap<const ValueDecl *, unsigned>;
429
430
  // Map from local variable indices to SSA variables (or constants).
431
  using NameVarPair = std::pair<const ValueDecl *, til::SExpr *>;
432
  using LVarDefinitionMap = CopyOnWriteVector<NameVarPair>;
433
434
  struct BlockInfo {
435
    LVarDefinitionMap ExitMap;
436
    bool HasBackEdges = false;
437
438
    // Successors yet to be processed
439
    unsigned UnprocessedSuccessors = 0;
440
441
    // Predecessors already processed
442
    unsigned ProcessedPredecessors = 0;
443
444
0
    BlockInfo() = default;
445
0
    BlockInfo(BlockInfo &&) = default;
446
    BlockInfo &operator=(BlockInfo &&) = default;
447
  };
448
449
  void enterCFG(CFG *Cfg, const NamedDecl *D, const CFGBlock *First);
450
  void enterCFGBlock(const CFGBlock *B);
451
0
  bool visitPredecessors() { return true; }
452
  void handlePredecessor(const CFGBlock *Pred);
453
  void handlePredecessorBackEdge(const CFGBlock *Pred);
454
  void enterCFGBlockBody(const CFGBlock *B);
455
  void handleStatement(const Stmt *S);
456
  void handleDestructorCall(const VarDecl *VD, const CXXDestructorDecl *DD);
457
  void exitCFGBlockBody(const CFGBlock *B);
458
0
  bool visitSuccessors() { return true; }
459
  void handleSuccessor(const CFGBlock *Succ);
460
  void handleSuccessorBackEdge(const CFGBlock *Succ);
461
  void exitCFGBlock(const CFGBlock *B);
462
  void exitCFG(const CFGBlock *Last);
463
464
0
  void insertStmt(const Stmt *S, til::SExpr *E) {
465
0
    SMap.insert(std::make_pair(S, E));
466
0
  }
467
468
  til::SExpr *getCurrentLVarDefinition(const ValueDecl *VD);
469
470
  til::SExpr *addStatement(til::SExpr *E, const Stmt *S,
471
                           const ValueDecl *VD = nullptr);
472
  til::SExpr *lookupVarDecl(const ValueDecl *VD);
473
  til::SExpr *addVarDecl(const ValueDecl *VD, til::SExpr *E);
474
  til::SExpr *updateVarDecl(const ValueDecl *VD, til::SExpr *E);
475
476
  void makePhiNodeVar(unsigned i, unsigned NPreds, til::SExpr *E);
477
  void mergeEntryMap(LVarDefinitionMap Map);
478
  void mergeEntryMapBackEdge();
479
  void mergePhiNodesBackEdge(const CFGBlock *Blk);
480
481
private:
482
  // Set to true when parsing capability expressions, which get translated
483
  // inaccurately in order to hack around smart pointers etc.
484
  static const bool CapabilityExprMode = true;
485
486
  til::MemRegionRef Arena;
487
488
  // Variable to use for 'this'.  May be null.
489
  til::Variable *SelfVar = nullptr;
490
491
  til::SCFG *Scfg = nullptr;
492
493
  // Map from Stmt to TIL Variables
494
  StatementMap SMap;
495
496
  // Indices of clang local vars.
497
  LVarIndexMap LVarIdxMap;
498
499
  // Map from clang to til BBs.
500
  std::vector<til::BasicBlock *> BlockMap;
501
502
  // Extra information per BB. Indexed by clang BlockID.
503
  std::vector<BlockInfo> BBInfo;           
504
505
  LVarDefinitionMap CurrentLVarMap;
506
  std::vector<til::Phi *> CurrentArguments;
507
  std::vector<til::SExpr *> CurrentInstructions;
508
  std::vector<til::Phi *> IncompleteArgs;
509
  til::BasicBlock *CurrentBB = nullptr;
510
  BlockInfo *CurrentBlockInfo = nullptr;
511
};
512
513
// Dump an SCFG to llvm::errs().
514
void printSCFG(CFGWalker &Walker);
515
516
} // namespace threadSafety
517
} // namespace clang
518
519
#endif // LLVM_CLANG_THREAD_SAFETY_COMMON_H