Coverage Report

Created: 2018-09-23 03:40

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
Line
Count
Source (jump to first uncovered line)
1
//===- ExprEngine.h - Path-Sensitive Expression-Level Dataflow --*- 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
//  This file defines a meta-engine for path-sensitive dataflow analysis that
11
//  is built on CoreEngine, but provides the boilerplate to execute transfer
12
//  functions and build the ExplodedGraph at the expression level.
13
//
14
//===----------------------------------------------------------------------===//
15
16
#ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_EXPRENGINE_H
17
#define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_EXPRENGINE_H
18
19
#include "clang/AST/Expr.h"
20
#include "clang/AST/Type.h"
21
#include "clang/Analysis/CFG.h"
22
#include "clang/Analysis/DomainSpecific/ObjCNoReturn.h"
23
#include "clang/Analysis/ProgramPoint.h"
24
#include "clang/Basic/LLVM.h"
25
#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
26
#include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
27
#include "clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h"
28
#include "clang/StaticAnalyzer/Core/PathSensitive/FunctionSummary.h"
29
#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
30
#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
31
#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h"
32
#include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
33
#include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
34
#include "clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h"
35
#include "clang/StaticAnalyzer/Core/PathSensitive/WorkList.h"
36
#include "llvm/ADT/ArrayRef.h"
37
#include <cassert>
38
#include <utility>
39
40
namespace clang {
41
42
class AnalysisDeclContextManager;
43
class AnalyzerOptions;
44
class ASTContext;
45
class ConstructionContext;
46
class CXXBindTemporaryExpr;
47
class CXXCatchStmt;
48
class CXXConstructExpr;
49
class CXXDeleteExpr;
50
class CXXNewExpr;
51
class CXXThisExpr;
52
class Decl;
53
class DeclStmt;
54
class GCCAsmStmt;
55
class LambdaExpr;
56
class LocationContext;
57
class MaterializeTemporaryExpr;
58
class MSAsmStmt;
59
class NamedDecl;
60
class ObjCAtSynchronizedStmt;
61
class ObjCForCollectionStmt;
62
class ObjCIvarRefExpr;
63
class ObjCMessageExpr;
64
class ReturnStmt;
65
class Stmt;
66
67
namespace cross_tu {
68
69
class CrossTranslationUnitContext;
70
71
} // namespace cross_tu
72
73
namespace ento {
74
75
class BasicValueFactory;
76
class CallEvent;
77
class CheckerManager;
78
class ConstraintManager;
79
class CXXTempObjectRegion;
80
class MemRegion;
81
class RegionAndSymbolInvalidationTraits;
82
class SymbolManager;
83
84
class ExprEngine : public SubEngine {
85
public:
86
  /// The modes of inlining, which override the default analysis-wide settings.
87
  enum InliningModes {
88
    /// Follow the default settings for inlining callees.
89
    Inline_Regular = 0,
90
91
    /// Do minimal inlining of callees.
92
    Inline_Minimal = 0x1
93
  };
94
95
  /// Hints for figuring out of a call should be inlined during evalCall().
96
  struct EvalCallOptions {
97
    /// This call is a constructor or a destructor for which we do not currently
98
    /// compute the this-region correctly.
99
    bool IsCtorOrDtorWithImproperlyModeledTargetRegion = false;
100
101
    /// This call is a constructor or a destructor for a single element within
102
    /// an array, a part of array construction or destruction.
103
    bool IsArrayCtorOrDtor = false;
104
105
    /// This call is a constructor or a destructor of a temporary value.
106
    bool IsTemporaryCtorOrDtor = false;
107
108
    /// This call is a constructor for a temporary that is lifetime-extended
109
    /// by binding it to a reference-type field within an aggregate,
110
    /// for example 'A { const C &c; }; A a = { C() };'
111
    bool IsTemporaryLifetimeExtendedViaAggregate = false;
112
113
54.5k
    EvalCallOptions() {}
114
  };
115
116
private:
117
  cross_tu::CrossTranslationUnitContext &CTU;
118
119
  AnalysisManager &AMgr;
120
121
  AnalysisDeclContextManager &AnalysisDeclContexts;
122
123
  CoreEngine Engine;
124
125
  /// G - the simulation graph.
126
  ExplodedGraph &G;
127
128
  /// StateMgr - Object that manages the data for all created states.
129
  ProgramStateManager StateMgr;
130
131
  /// SymMgr - Object that manages the symbol information.
132
  SymbolManager &SymMgr;
133
134
  /// svalBuilder - SValBuilder object that creates SVals from expressions.
135
  SValBuilder &svalBuilder;
136
137
  unsigned int currStmtIdx = 0;
138
  const NodeBuilderContext *currBldrCtx = nullptr;
139
140
  /// Helper object to determine if an Objective-C message expression
141
  /// implicitly never returns.
142
  ObjCNoReturn ObjCNoRet;
143
144
  /// The BugReporter associated with this engine.  It is important that
145
  ///  this object be placed at the very end of member variables so that its
146
  ///  destructor is called before the rest of the ExprEngine is destroyed.
147
  GRBugReporter BR;
148
149
  /// The functions which have been analyzed through inlining. This is owned by
150
  /// AnalysisConsumer. It can be null.
151
  SetOfConstDecls *VisitedCallees;
152
153
  /// The flag, which specifies the mode of inlining for the engine.
154
  InliningModes HowToInline;
155
156
public:
157
  ExprEngine(cross_tu::CrossTranslationUnitContext &CTU, AnalysisManager &mgr,
158
             bool gcEnabled, SetOfConstDecls *VisitedCalleesIn,
159
             FunctionSummariesTy *FS, InliningModes HowToInlineIn);
160
161
  ~ExprEngine() override;
162
163
  /// Returns true if there is still simulation state on the worklist.
164
9.75k
  bool ExecuteWorkList(const LocationContext *L, unsigned Steps = 150000) {
165
9.75k
    return Engine.ExecuteWorkList(L, Steps, nullptr);
166
9.75k
  }
167
168
  /// Execute the work list with an initial state. Nodes that reaches the exit
169
  /// of the function are added into the Dst set, which represent the exit
170
  /// state of the function call. Returns true if there is still simulation
171
  /// state on the worklist.
172
  bool ExecuteWorkListWithInitialState(const LocationContext *L, unsigned Steps,
173
                                       ProgramStateRef InitState,
174
0
                                       ExplodedNodeSet &Dst) {
175
0
    return Engine.ExecuteWorkListWithInitialState(L, Steps, InitState, Dst);
176
0
  }
177
178
  /// getContext - Return the ASTContext associated with this analysis.
179
1.89M
  ASTContext &getContext() const { return AMgr.getASTContext(); }
180
181
144k
  AnalysisManager &getAnalysisManager() override { return AMgr; }
182
183
2.74M
  CheckerManager &getCheckerManager() const {
184
2.74M
    return *AMgr.getCheckerManager();
185
2.74M
  }
186
187
45.5k
  SValBuilder &getSValBuilder() { return svalBuilder; }
188
189
23.4k
  BugReporter &getBugReporter() { return BR; }
190
191
  cross_tu::CrossTranslationUnitContext *
192
17
  getCrossTranslationUnitContext() override {
193
17
    return &CTU;
194
17
  }
195
196
1.75M
  const NodeBuilderContext &getBuilderContext() {
197
1.75M
    assert(currBldrCtx);
198
1.75M
    return *currBldrCtx;
199
1.75M
  }
200
201
  const Stmt *getStmt() const;
202
203
  void GenerateAutoTransition(ExplodedNode *N);
204
  void enqueueEndOfPath(ExplodedNodeSet &S);
205
  void GenerateCallExitNode(ExplodedNode *N);
206
207
  /// Visualize the ExplodedGraph created by executing the simulation.
208
  void ViewGraph(bool trim = false);
209
210
  /// Visualize a trimmed ExplodedGraph that only contains paths to the given
211
  /// nodes.
212
  void ViewGraph(ArrayRef<const ExplodedNode *> Nodes);
213
214
  /// getInitialState - Return the initial state used for the root vertex
215
  ///  in the ExplodedGraph.
216
  ProgramStateRef getInitialState(const LocationContext *InitLoc) override;
217
218
9.13k
  ExplodedGraph &getGraph() { return G; }
219
0
  const ExplodedGraph &getGraph() const { return G; }
220
221
  /// Run the analyzer's garbage collection - remove dead symbols and
222
  /// bindings from the state.
223
  ///
224
  /// Checkers can participate in this process with two callbacks:
225
  /// \c checkLiveSymbols and \c checkDeadSymbols. See the CheckerDocumentation
226
  /// class for more information.
227
  ///
228
  /// \param Node The predecessor node, from which the processing should start.
229
  /// \param Out The returned set of output nodes.
230
  /// \param ReferenceStmt The statement which is about to be processed.
231
  ///        Everything needed for this statement should be considered live.
232
  ///        A null statement means that everything in child LocationContexts
233
  ///        is dead.
234
  /// \param LC The location context of the \p ReferenceStmt. A null location
235
  ///        context means that we have reached the end of analysis and that
236
  ///        all statements and local variables should be considered dead.
237
  /// \param DiagnosticStmt Used as a location for any warnings that should
238
  ///        occur while removing the dead (e.g. leaks). By default, the
239
  ///        \p ReferenceStmt is used.
240
  /// \param K Denotes whether this is a pre- or post-statement purge. This
241
  ///        must only be ProgramPoint::PostStmtPurgeDeadSymbolsKind if an
242
  ///        entire location context is being cleared, in which case the
243
  ///        \p ReferenceStmt must either be a ReturnStmt or \c NULL. Otherwise,
244
  ///        it must be ProgramPoint::PreStmtPurgeDeadSymbolsKind (the default)
245
  ///        and \p ReferenceStmt must be valid (non-null).
246
  void removeDead(ExplodedNode *Node, ExplodedNodeSet &Out,
247
            const Stmt *ReferenceStmt, const LocationContext *LC,
248
            const Stmt *DiagnosticStmt = nullptr,
249
            ProgramPoint::Kind K = ProgramPoint::PreStmtPurgeDeadSymbolsKind);
250
251
  /// processCFGElement - Called by CoreEngine. Used to generate new successor
252
  ///  nodes by processing the 'effects' of a CFG element.
253
  void processCFGElement(const CFGElement E, ExplodedNode *Pred,
254
                         unsigned StmtIdx, NodeBuilderContext *Ctx) override;
255
256
  void ProcessStmt(const Stmt *S, ExplodedNode *Pred);
257
258
  void ProcessLoopExit(const Stmt* S, ExplodedNode *Pred);
259
260
  void ProcessInitializer(const CFGInitializer I, ExplodedNode *Pred);
261
262
  void ProcessImplicitDtor(const CFGImplicitDtor D, ExplodedNode *Pred);
263
264
  void ProcessNewAllocator(const CXXNewExpr *NE, ExplodedNode *Pred);
265
266
  void ProcessAutomaticObjDtor(const CFGAutomaticObjDtor D,
267
                               ExplodedNode *Pred, ExplodedNodeSet &Dst);
268
  void ProcessDeleteDtor(const CFGDeleteDtor D,
269
                         ExplodedNode *Pred, ExplodedNodeSet &Dst);
270
  void ProcessBaseDtor(const CFGBaseDtor D,
271
                       ExplodedNode *Pred, ExplodedNodeSet &Dst);
272
  void ProcessMemberDtor(const CFGMemberDtor D,
273
                         ExplodedNode *Pred, ExplodedNodeSet &Dst);
274
  void ProcessTemporaryDtor(const CFGTemporaryDtor D,
275
                            ExplodedNode *Pred, ExplodedNodeSet &Dst);
276
277
  /// Called by CoreEngine when processing the entrance of a CFGBlock.
278
  void processCFGBlockEntrance(const BlockEdge &L,
279
                               NodeBuilderWithSinks &nodeBuilder,
280
                               ExplodedNode *Pred) override;
281
282
  /// ProcessBranch - Called by CoreEngine.  Used to generate successor
283
  ///  nodes by processing the 'effects' of a branch condition.
284
  void processBranch(const Stmt *Condition, const Stmt *Term,
285
                     NodeBuilderContext& BuilderCtx,
286
                     ExplodedNode *Pred,
287
                     ExplodedNodeSet &Dst,
288
                     const CFGBlock *DstT,
289
                     const CFGBlock *DstF) override;
290
291
  /// Called by CoreEngine.
292
  /// Used to generate successor nodes for temporary destructors depending
293
  /// on whether the corresponding constructor was visited.
294
  void processCleanupTemporaryBranch(const CXXBindTemporaryExpr *BTE,
295
                                     NodeBuilderContext &BldCtx,
296
                                     ExplodedNode *Pred, ExplodedNodeSet &Dst,
297
                                     const CFGBlock *DstT,
298
                                     const CFGBlock *DstF) override;
299
300
  /// Called by CoreEngine.  Used to processing branching behavior
301
  /// at static initializers.
302
  void processStaticInitializer(const DeclStmt *DS,
303
                                NodeBuilderContext& BuilderCtx,
304
                                ExplodedNode *Pred,
305
                                ExplodedNodeSet &Dst,
306
                                const CFGBlock *DstT,
307
                                const CFGBlock *DstF) override;
308
309
  /// processIndirectGoto - Called by CoreEngine.  Used to generate successor
310
  ///  nodes by processing the 'effects' of a computed goto jump.
311
  void processIndirectGoto(IndirectGotoNodeBuilder& builder) override;
312
313
  /// ProcessSwitch - Called by CoreEngine.  Used to generate successor
314
  ///  nodes by processing the 'effects' of a switch statement.
315
  void processSwitch(SwitchNodeBuilder& builder) override;
316
317
  /// Called by CoreEngine.  Used to notify checkers that processing a
318
  /// function has begun. Called for both inlined and and top-level functions.
319
  void processBeginOfFunction(NodeBuilderContext &BC,
320
                              ExplodedNode *Pred, ExplodedNodeSet &Dst,
321
                              const BlockEdge &L) override;
322
323
  /// Called by CoreEngine.  Used to notify checkers that processing a
324
  /// function has ended. Called for both inlined and and top-level functions.
325
  void processEndOfFunction(NodeBuilderContext& BC,
326
                            ExplodedNode *Pred,
327
                            const ReturnStmt *RS = nullptr) override;
328
329
  /// Remove dead bindings/symbols before exiting a function.
330
  void removeDeadOnEndOfFunction(NodeBuilderContext& BC,
331
                                 ExplodedNode *Pred,
332
                                 ExplodedNodeSet &Dst);
333
334
  /// Generate the entry node of the callee.
335
  void processCallEnter(NodeBuilderContext& BC, CallEnter CE,
336
                        ExplodedNode *Pred) override;
337
338
  /// Generate the sequence of nodes that simulate the call exit and the post
339
  /// visit for CallExpr.
340
  void processCallExit(ExplodedNode *Pred) override;
341
342
  /// Called by CoreEngine when the analysis worklist has terminated.
343
  void processEndWorklist(bool hasWorkRemaining) override;
344
345
  /// evalAssume - Callback function invoked by the ConstraintManager when
346
  ///  making assumptions about state values.
347
  ProgramStateRef processAssume(ProgramStateRef state, SVal cond,
348
                                bool assumption) override;
349
350
  /// processRegionChanges - Called by ProgramStateManager whenever a change is made
351
  ///  to the store. Used to update checkers that track region values.
352
  ProgramStateRef
353
  processRegionChanges(ProgramStateRef state,
354
                       const InvalidatedSymbols *invalidated,
355
                       ArrayRef<const MemRegion *> ExplicitRegions,
356
                       ArrayRef<const MemRegion *> Regions,
357
                       const LocationContext *LCtx,
358
                       const CallEvent *Call) override;
359
360
  /// printState - Called by ProgramStateManager to print checker-specific data.
361
  void printState(raw_ostream &Out, ProgramStateRef State, const char *NL,
362
                  const char *Sep,
363
                  const LocationContext *LCtx = nullptr) override;
364
365
132k
  ProgramStateManager &getStateManager() override { return StateMgr; }
366
367
262k
  StoreManager &getStoreManager() { return StateMgr.getStoreManager(); }
368
369
53.9k
  ConstraintManager &getConstraintManager() {
370
53.9k
    return StateMgr.getConstraintManager();
371
53.9k
  }
372
373
  // FIXME: Remove when we migrate over to just using SValBuilder.
374
3.79k
  BasicValueFactory &getBasicVals() {
375
3.79k
    return StateMgr.getBasicVals();
376
3.79k
  }
377
378
  // FIXME: Remove when we migrate over to just using ValueManager.
379
0
  SymbolManager &getSymbolManager() { return SymMgr; }
380
0
  const SymbolManager &getSymbolManager() const { return SymMgr; }
381
382
  // Functions for external checking of whether we have unfinished work
383
4
  bool wasBlocksExhausted() const { return Engine.wasBlocksExhausted(); }
384
4
  bool hasEmptyWorkList() const { return !Engine.getWorkList()->hasWork(); }
385
330
  bool hasWorkRemaining() const { return Engine.hasWorkRemaining(); }
386
387
25.4k
  const CoreEngine &getCoreEngine() const { return Engine; }
388
389
public:
390
  /// Visit - Transfer function logic for all statements.  Dispatches to
391
  ///  other functions that handle specific kinds of statements.
392
  void Visit(const Stmt *S, ExplodedNode *Pred, ExplodedNodeSet &Dst);
393
394
  /// VisitArraySubscriptExpr - Transfer function for array accesses.
395
  void VisitArraySubscriptExpr(const ArraySubscriptExpr *Ex,
396
                               ExplodedNode *Pred,
397
                               ExplodedNodeSet &Dst);
398
399
  /// VisitGCCAsmStmt - Transfer function logic for inline asm.
400
  void VisitGCCAsmStmt(const GCCAsmStmt *A, ExplodedNode *Pred,
401
                       ExplodedNodeSet &Dst);
402
403
  /// VisitMSAsmStmt - Transfer function logic for MS inline asm.
404
  void VisitMSAsmStmt(const MSAsmStmt *A, ExplodedNode *Pred,
405
                      ExplodedNodeSet &Dst);
406
407
  /// VisitBlockExpr - Transfer function logic for BlockExprs.
408
  void VisitBlockExpr(const BlockExpr *BE, ExplodedNode *Pred,
409
                      ExplodedNodeSet &Dst);
410
411
  /// VisitLambdaExpr - Transfer function logic for LambdaExprs.
412
  void VisitLambdaExpr(const LambdaExpr *LE, ExplodedNode *Pred,
413
                       ExplodedNodeSet &Dst);
414
415
  /// VisitBinaryOperator - Transfer function logic for binary operators.
416
  void VisitBinaryOperator(const BinaryOperator* B, ExplodedNode *Pred,
417
                           ExplodedNodeSet &Dst);
418
419
420
  /// VisitCall - Transfer function for function calls.
421
  void VisitCallExpr(const CallExpr *CE, ExplodedNode *Pred,
422
                     ExplodedNodeSet &Dst);
423
424
  /// VisitCast - Transfer function logic for all casts (implicit and explicit).
425
  void VisitCast(const CastExpr *CastE, const Expr *Ex, ExplodedNode *Pred,
426
                 ExplodedNodeSet &Dst);
427
428
  /// VisitCompoundLiteralExpr - Transfer function logic for compound literals.
429
  void VisitCompoundLiteralExpr(const CompoundLiteralExpr *CL,
430
                                ExplodedNode *Pred, ExplodedNodeSet &Dst);
431
432
  /// Transfer function logic for DeclRefExprs and BlockDeclRefExprs.
433
  void VisitCommonDeclRefExpr(const Expr *DR, const NamedDecl *D,
434
                              ExplodedNode *Pred, ExplodedNodeSet &Dst);
435
436
  /// VisitDeclStmt - Transfer function logic for DeclStmts.
437
  void VisitDeclStmt(const DeclStmt *DS, ExplodedNode *Pred,
438
                     ExplodedNodeSet &Dst);
439
440
  /// VisitGuardedExpr - Transfer function logic for ?, __builtin_choose
441
  void VisitGuardedExpr(const Expr *Ex, const Expr *L, const Expr *R,
442
                        ExplodedNode *Pred, ExplodedNodeSet &Dst);
443
444
  void VisitInitListExpr(const InitListExpr *E, ExplodedNode *Pred,
445
                         ExplodedNodeSet &Dst);
446
447
  /// VisitLogicalExpr - Transfer function logic for '&&', '||'
448
  void VisitLogicalExpr(const BinaryOperator* B, ExplodedNode *Pred,
449
                        ExplodedNodeSet &Dst);
450
451
  /// VisitMemberExpr - Transfer function for member expressions.
452
  void VisitMemberExpr(const MemberExpr *M, ExplodedNode *Pred,
453
                       ExplodedNodeSet &Dst);
454
455
  /// VisitAtomicExpr - Transfer function for builtin atomic expressions
456
  void VisitAtomicExpr(const AtomicExpr *E, ExplodedNode *Pred,
457
                       ExplodedNodeSet &Dst);
458
459
  /// Transfer function logic for ObjCAtSynchronizedStmts.
460
  void VisitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt *S,
461
                                   ExplodedNode *Pred, ExplodedNodeSet &Dst);
462
463
  /// Transfer function logic for computing the lvalue of an Objective-C ivar.
464
  void VisitLvalObjCIvarRefExpr(const ObjCIvarRefExpr *DR, ExplodedNode *Pred,
465
                                ExplodedNodeSet &Dst);
466
467
  /// VisitObjCForCollectionStmt - Transfer function logic for
468
  ///  ObjCForCollectionStmt.
469
  void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S,
470
                                  ExplodedNode *Pred, ExplodedNodeSet &Dst);
471
472
  void VisitObjCMessage(const ObjCMessageExpr *ME, ExplodedNode *Pred,
473
                        ExplodedNodeSet &Dst);
474
475
  /// VisitReturnStmt - Transfer function logic for return statements.
476
  void VisitReturnStmt(const ReturnStmt *R, ExplodedNode *Pred,
477
                       ExplodedNodeSet &Dst);
478
479
  /// VisitOffsetOfExpr - Transfer function for offsetof.
480
  void VisitOffsetOfExpr(const OffsetOfExpr *Ex, ExplodedNode *Pred,
481
                         ExplodedNodeSet &Dst);
482
483
  /// VisitUnaryExprOrTypeTraitExpr - Transfer function for sizeof.
484
  void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *Ex,
485
                                     ExplodedNode *Pred, ExplodedNodeSet &Dst);
486
487
  /// VisitUnaryOperator - Transfer function logic for unary operators.
488
  void VisitUnaryOperator(const UnaryOperator* B, ExplodedNode *Pred,
489
                          ExplodedNodeSet &Dst);
490
491
  /// Handle ++ and -- (both pre- and post-increment).
492
  void VisitIncrementDecrementOperator(const UnaryOperator* U,
493
                                       ExplodedNode *Pred,
494
                                       ExplodedNodeSet &Dst);
495
496
  void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *BTE,
497
                                 ExplodedNodeSet &PreVisit,
498
                                 ExplodedNodeSet &Dst);
499
500
  void VisitCXXCatchStmt(const CXXCatchStmt *CS, ExplodedNode *Pred,
501
                         ExplodedNodeSet &Dst);
502
503
  void VisitCXXThisExpr(const CXXThisExpr *TE, ExplodedNode *Pred,
504
                        ExplodedNodeSet & Dst);
505
506
  void VisitCXXConstructExpr(const CXXConstructExpr *E, ExplodedNode *Pred,
507
                             ExplodedNodeSet &Dst);
508
509
  void VisitCXXDestructor(QualType ObjectType, const MemRegion *Dest,
510
                          const Stmt *S, bool IsBaseDtor,
511
                          ExplodedNode *Pred, ExplodedNodeSet &Dst,
512
                          const EvalCallOptions &Options);
513
514
  void VisitCXXNewAllocatorCall(const CXXNewExpr *CNE,
515
                                ExplodedNode *Pred,
516
                                ExplodedNodeSet &Dst);
517
518
  void VisitCXXNewExpr(const CXXNewExpr *CNE, ExplodedNode *Pred,
519
                       ExplodedNodeSet &Dst);
520
521
  void VisitCXXDeleteExpr(const CXXDeleteExpr *CDE, ExplodedNode *Pred,
522
                          ExplodedNodeSet &Dst);
523
524
  /// Create a C++ temporary object for an rvalue.
525
  void CreateCXXTemporaryObject(const MaterializeTemporaryExpr *ME,
526
                                ExplodedNode *Pred,
527
                                ExplodedNodeSet &Dst);
528
529
  /// evalEagerlyAssumeBinOpBifurcation - Given the nodes in 'Src', eagerly assume symbolic
530
  ///  expressions of the form 'x != 0' and generate new nodes (stored in Dst)
531
  ///  with those assumptions.
532
  void evalEagerlyAssumeBinOpBifurcation(ExplodedNodeSet &Dst, ExplodedNodeSet &Src,
533
                         const Expr *Ex);
534
535
  static std::pair<const ProgramPointTag *, const ProgramPointTag *>
536
    geteagerlyAssumeBinOpBifurcationTags();
537
538
1.05k
  SVal evalMinus(SVal X) {
539
1.05k
    return X.isValid() ? svalBuilder.evalMinus(X.castAs<NonLoc>()) : 
X0
;
540
1.05k
  }
541
542
914
  SVal evalComplement(SVal X) {
543
914
    return X.isValid() ? svalBuilder.evalComplement(X.castAs<NonLoc>()) : 
X0
;
544
914
  }
545
546
  ProgramStateRef handleLValueBitCast(ProgramStateRef state, const Expr *Ex,
547
                                      const LocationContext *LCtx, QualType T,
548
                                      QualType ExTy, const CastExpr *CastE,
549
                                      StmtNodeBuilder &Bldr,
550
                                      ExplodedNode *Pred);
551
552
  ProgramStateRef handleLVectorSplat(ProgramStateRef state,
553
                                     const LocationContext *LCtx,
554
                                     const CastExpr *CastE,
555
                                     StmtNodeBuilder &Bldr,
556
                                     ExplodedNode *Pred);
557
558
  void handleUOExtension(ExplodedNodeSet::iterator I,
559
                         const UnaryOperator* U,
560
                         StmtNodeBuilder &Bldr);
561
562
public:
563
  SVal evalBinOp(ProgramStateRef state, BinaryOperator::Opcode op,
564
669
                 NonLoc L, NonLoc R, QualType T) {
565
669
    return svalBuilder.evalBinOpNN(state, op, L, R, T);
566
669
  }
567
568
  SVal evalBinOp(ProgramStateRef state, BinaryOperator::Opcode op,
569
0
                 NonLoc L, SVal R, QualType T) {
570
0
    return R.isValid() ? svalBuilder.evalBinOpNN(state, op, L,
571
0
                                                 R.castAs<NonLoc>(), T) : R;
572
0
  }
573
574
  SVal evalBinOp(ProgramStateRef ST, BinaryOperator::Opcode Op,
575
58.0k
                 SVal LHS, SVal RHS, QualType T) {
576
58.0k
    return svalBuilder.evalBinOp(ST, Op, LHS, RHS, T);
577
58.0k
  }
578
579
  /// By looking at a certain item that may be potentially part of an object's
580
  /// ConstructionContext, retrieve such object's location. A particular
581
  /// statement can be transparently passed as \p Item in most cases.
582
  static Optional<SVal>
583
  getObjectUnderConstruction(ProgramStateRef State,
584
                             const ConstructionContextItem &Item,
585
                             const LocationContext *LC);
586
587
protected:
588
  /// evalBind - Handle the semantics of binding a value to a specific location.
589
  ///  This method is used by evalStore, VisitDeclStmt, and others.
590
  void evalBind(ExplodedNodeSet &Dst, const Stmt *StoreE, ExplodedNode *Pred,
591
                SVal location, SVal Val, bool atDeclInit = false,
592
                const ProgramPoint *PP = nullptr);
593
594
  /// Call PointerEscape callback when a value escapes as a result of bind.
595
  ProgramStateRef processPointerEscapedOnBind(ProgramStateRef State,
596
                                              SVal Loc,
597
                                              SVal Val,
598
                                              const LocationContext *LCtx) override;
599
  /// Call PointerEscape callback when a value escapes as a result of
600
  /// region invalidation.
601
  /// \param[in] ITraits Specifies invalidation traits for regions/symbols.
602
  ProgramStateRef notifyCheckersOfPointerEscape(
603
                           ProgramStateRef State,
604
                           const InvalidatedSymbols *Invalidated,
605
                           ArrayRef<const MemRegion *> ExplicitRegions,
606
                           ArrayRef<const MemRegion *> Regions,
607
                           const CallEvent *Call,
608
                           RegionAndSymbolInvalidationTraits &ITraits) override;
609
610
  /// A simple wrapper when you only need to notify checkers of pointer-escape
611
  /// of a single value.
612
  ProgramStateRef escapeValue(ProgramStateRef State, SVal V,
613
                              PointerEscapeKind K) const;
614
615
public:
616
  // FIXME: 'tag' should be removed, and a LocationContext should be used
617
  // instead.
618
  // FIXME: Comment on the meaning of the arguments, when 'St' may not
619
  // be the same as Pred->state, and when 'location' may not be the
620
  // same as state->getLValue(Ex).
621
  /// Simulate a read of the result of Ex.
622
  void evalLoad(ExplodedNodeSet &Dst,
623
                const Expr *NodeEx,  /* Eventually will be a CFGStmt */
624
                const Expr *BoundExpr,
625
                ExplodedNode *Pred,
626
                ProgramStateRef St,
627
                SVal location,
628
                const ProgramPointTag *tag = nullptr,
629
                QualType LoadTy = QualType());
630
631
  // FIXME: 'tag' should be removed, and a LocationContext should be used
632
  // instead.
633
  void evalStore(ExplodedNodeSet &Dst, const Expr *AssignE, const Expr *StoreE,
634
                 ExplodedNode *Pred, ProgramStateRef St, SVal TargetLV, SVal Val,
635
                 const ProgramPointTag *tag = nullptr);
636
637
  /// Return the CFG element corresponding to the worklist element
638
  /// that is currently being processed by ExprEngine.
639
42.2k
  CFGElement getCurrentCFGElement() {
640
42.2k
    return (*currBldrCtx->getBlock())[currStmtIdx];
641
42.2k
  }
642
643
  /// Create a new state in which the call return value is binded to the
644
  /// call origin expression.
645
  ProgramStateRef bindReturnValue(const CallEvent &Call,
646
                                  const LocationContext *LCtx,
647
                                  ProgramStateRef State);
648
649
  /// Evaluate a call, running pre- and post-call checks and allowing checkers
650
  /// to be responsible for handling the evaluation of the call itself.
651
  void evalCall(ExplodedNodeSet &Dst, ExplodedNode *Pred,
652
                const CallEvent &Call);
653
654
  /// Default implementation of call evaluation.
655
  void defaultEvalCall(NodeBuilder &B, ExplodedNode *Pred,
656
                       const CallEvent &Call,
657
                       const EvalCallOptions &CallOpts = {});
658
659
private:
660
  ProgramStateRef finishArgumentConstruction(ProgramStateRef State,
661
                                             const CallEvent &Call);
662
  void finishArgumentConstruction(ExplodedNodeSet &Dst, ExplodedNode *Pred,
663
                                  const CallEvent &Call);
664
665
  void evalLoadCommon(ExplodedNodeSet &Dst,
666
                      const Expr *NodeEx,  /* Eventually will be a CFGStmt */
667
                      const Expr *BoundEx,
668
                      ExplodedNode *Pred,
669
                      ProgramStateRef St,
670
                      SVal location,
671
                      const ProgramPointTag *tag,
672
                      QualType LoadTy);
673
674
  // FIXME: 'tag' should be removed, and a LocationContext should be used
675
  // instead.
676
  void evalLocation(ExplodedNodeSet &Dst,
677
                    const Stmt *NodeEx, /* This will eventually be a CFGStmt */
678
                    const Stmt *BoundEx,
679
                    ExplodedNode *Pred,
680
                    ProgramStateRef St, SVal location,
681
                    const ProgramPointTag *tag, bool isLoad);
682
683
  /// Count the stack depth and determine if the call is recursive.
684
  void examineStackFrames(const Decl *D, const LocationContext *LCtx,
685
                          bool &IsRecursive, unsigned &StackDepth);
686
687
  enum CallInlinePolicy {
688
    CIP_Allowed,
689
    CIP_DisallowedOnce,
690
    CIP_DisallowedAlways
691
  };
692
693
  /// See if a particular call should be inlined, by only looking
694
  /// at the call event and the current state of analysis.
695
  CallInlinePolicy mayInlineCallKind(const CallEvent &Call,
696
                                     const ExplodedNode *Pred,
697
                                     AnalyzerOptions &Opts,
698
                                     const EvalCallOptions &CallOpts);
699
700
  /// Checks our policies and decides weither the given call should be inlined.
701
  bool shouldInlineCall(const CallEvent &Call, const Decl *D,
702
                        const ExplodedNode *Pred,
703
                        const EvalCallOptions &CallOpts = {});
704
705
  bool inlineCall(const CallEvent &Call, const Decl *D, NodeBuilder &Bldr,
706
                  ExplodedNode *Pred, ProgramStateRef State);
707
708
  /// Conservatively evaluate call by invalidating regions and binding
709
  /// a conjured return value.
710
  void conservativeEvalCall(const CallEvent &Call, NodeBuilder &Bldr,
711
                            ExplodedNode *Pred, ProgramStateRef State);
712
713
  /// Either inline or process the call conservatively (or both), based
714
  /// on DynamicDispatchBifurcation data.
715
  void BifurcateCall(const MemRegion *BifurReg,
716
                     const CallEvent &Call, const Decl *D, NodeBuilder &Bldr,
717
                     ExplodedNode *Pred);
718
719
  bool replayWithoutInlining(ExplodedNode *P, const LocationContext *CalleeLC);
720
721
  /// Models a trivial copy or move constructor or trivial assignment operator
722
  /// call with a simple bind.
723
  void performTrivialCopy(NodeBuilder &Bldr, ExplodedNode *Pred,
724
                          const CallEvent &Call);
725
726
  /// If the value of the given expression \p InitWithAdjustments is a NonLoc,
727
  /// copy it into a new temporary object region, and replace the value of the
728
  /// expression with that.
729
  ///
730
  /// If \p Result is provided, the new region will be bound to this expression
731
  /// instead of \p InitWithAdjustments.
732
  ///
733
  /// Returns the temporary region with adjustments into the optional
734
  /// OutRegionWithAdjustments out-parameter if a new region was indeed needed,
735
  /// otherwise sets it to nullptr.
736
  ProgramStateRef createTemporaryRegionIfNeeded(
737
      ProgramStateRef State, const LocationContext *LC,
738
      const Expr *InitWithAdjustments, const Expr *Result = nullptr,
739
      const SubRegion **OutRegionWithAdjustments = nullptr);
740
741
  /// Returns a region representing the first element of a (possibly
742
  /// multi-dimensional) array, for the purposes of element construction or
743
  /// destruction.
744
  ///
745
  /// On return, \p Ty will be set to the base type of the array.
746
  ///
747
  /// If the type is not an array type at all, the original value is returned.
748
  /// Otherwise the "IsArray" flag is set.
749
  static SVal makeZeroElementRegion(ProgramStateRef State, SVal LValue,
750
                                    QualType &Ty, bool &IsArray);
751
752
  /// For a DeclStmt or CXXInitCtorInitializer, walk backward in the current CFG
753
  /// block to find the constructor expression that directly constructed into
754
  /// the storage for this statement. Returns null if the constructor for this
755
  /// statement created a temporary object region rather than directly
756
  /// constructing into an existing region.
757
  const CXXConstructExpr *findDirectConstructorForCurrentCFGElement();
758
759
  /// Update the program state with all the path-sensitive information
760
  /// that's necessary to perform construction of an object with a given
761
  /// syntactic construction context. If the construction context is unavailable
762
  /// or unusable for any reason, a dummy temporary region is returned, and the
763
  /// IsConstructorWithImproperlyModeledTargetRegion flag is set in \p CallOpts.
764
  /// Returns the updated program state and the new object's this-region.
765
  std::pair<ProgramStateRef, SVal> prepareForObjectConstruction(
766
      const Expr *E, ProgramStateRef State, const LocationContext *LCtx,
767
      const ConstructionContext *CC, EvalCallOptions &CallOpts);
768
769
  /// Store the location of a C++ object corresponding to a statement
770
  /// until the statement is actually encountered. For example, if a DeclStmt
771
  /// has CXXConstructExpr as its initializer, the object would be considered
772
  /// to be "under construction" between CXXConstructExpr and DeclStmt.
773
  /// This allows, among other things, to keep bindings to variable's fields
774
  /// made within the constructor alive until its declaration actually
775
  /// goes into scope.
776
  static ProgramStateRef
777
  addObjectUnderConstruction(ProgramStateRef State,
778
                             const ConstructionContextItem &Item,
779
                             const LocationContext *LC, SVal V);
780
781
  /// Mark the object sa fully constructed, cleaning up the state trait
782
  /// that tracks objects under construction.
783
  static ProgramStateRef
784
  finishObjectConstruction(ProgramStateRef State,
785
                           const ConstructionContextItem &Item,
786
                           const LocationContext *LC);
787
788
  /// If the given expression corresponds to a temporary that was used for
789
  /// passing into an elidable copy/move constructor and that constructor
790
  /// was actually elided, track that we also need to elide the destructor.
791
  static ProgramStateRef elideDestructor(ProgramStateRef State,
792
                                         const CXXBindTemporaryExpr *BTE,
793
                                         const LocationContext *LC);
794
795
  /// Stop tracking the destructor that corresponds to an elided constructor.
796
  static ProgramStateRef
797
  cleanupElidedDestructor(ProgramStateRef State,
798
                          const CXXBindTemporaryExpr *BTE,
799
                          const LocationContext *LC);
800
801
  /// Returns true if the given expression corresponds to a temporary that
802
  /// was constructed for passing into an elidable copy/move constructor
803
  /// and that constructor was actually elided.
804
  static bool isDestructorElided(ProgramStateRef State,
805
                                 const CXXBindTemporaryExpr *BTE,
806
                                 const LocationContext *LC);
807
808
  /// Check if all objects under construction have been fully constructed
809
  /// for the given context range (including FromLC, not including ToLC).
810
  /// This is useful for assertions. Also checks if elided destructors
811
  /// were cleaned up.
812
  static bool areAllObjectsFullyConstructed(ProgramStateRef State,
813
                                            const LocationContext *FromLC,
814
                                            const LocationContext *ToLC);
815
};
816
817
/// Traits for storing the call processing policy inside GDM.
818
/// The GDM stores the corresponding CallExpr pointer.
819
// FIXME: This does not use the nice trait macros because it must be accessible
820
// from multiple translation units.
821
struct ReplayWithoutInlining{};
822
template <>
823
struct ProgramStateTrait<ReplayWithoutInlining> :
824
  public ProgramStatePartialTrait<const void*> {
825
43.4k
  static void *GDMIndex() { static int index = 0; return &index; }
826
};
827
828
} // namespace ento
829
830
} // namespace clang
831
832
#endif // LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_EXPRENGINE_H