Coverage Report

Created: 2020-09-22 08:39

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/StaticAnalyzer/Core/CallEvent.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- CallEvent.cpp - Wrapper for all function and method calls ----------===//
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
/// \file This file defines CallEvent and its subclasses, which represent path-
10
/// sensitive instances of different kinds of function and method calls
11
/// (C, C++, and Objective-C).
12
//
13
//===----------------------------------------------------------------------===//
14
15
#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
16
#include "clang/AST/ASTContext.h"
17
#include "clang/AST/Attr.h"
18
#include "clang/AST/Decl.h"
19
#include "clang/AST/DeclBase.h"
20
#include "clang/AST/DeclCXX.h"
21
#include "clang/AST/DeclObjC.h"
22
#include "clang/AST/Expr.h"
23
#include "clang/AST/ExprCXX.h"
24
#include "clang/AST/ExprObjC.h"
25
#include "clang/AST/ParentMap.h"
26
#include "clang/AST/Stmt.h"
27
#include "clang/AST/Type.h"
28
#include "clang/Analysis/AnalysisDeclContext.h"
29
#include "clang/Analysis/CFG.h"
30
#include "clang/Analysis/CFGStmtMap.h"
31
#include "clang/Analysis/PathDiagnostic.h"
32
#include "clang/Analysis/ProgramPoint.h"
33
#include "clang/Basic/IdentifierTable.h"
34
#include "clang/Basic/LLVM.h"
35
#include "clang/Basic/SourceLocation.h"
36
#include "clang/Basic/SourceManager.h"
37
#include "clang/Basic/Specifiers.h"
38
#include "clang/CrossTU/CrossTranslationUnit.h"
39
#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
40
#include "clang/StaticAnalyzer/Core/PathSensitive/DynamicType.h"
41
#include "clang/StaticAnalyzer/Core/PathSensitive/DynamicTypeInfo.h"
42
#include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
43
#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
44
#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h"
45
#include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
46
#include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
47
#include "clang/StaticAnalyzer/Core/PathSensitive/Store.h"
48
#include "llvm/ADT/ArrayRef.h"
49
#include "llvm/ADT/DenseMap.h"
50
#include "llvm/ADT/None.h"
51
#include "llvm/ADT/Optional.h"
52
#include "llvm/ADT/PointerIntPair.h"
53
#include "llvm/ADT/SmallSet.h"
54
#include "llvm/ADT/SmallVector.h"
55
#include "llvm/ADT/StringExtras.h"
56
#include "llvm/ADT/StringRef.h"
57
#include "llvm/Support/Casting.h"
58
#include "llvm/Support/Compiler.h"
59
#include "llvm/Support/Debug.h"
60
#include "llvm/Support/ErrorHandling.h"
61
#include "llvm/Support/raw_ostream.h"
62
#include <cassert>
63
#include <utility>
64
65
#define DEBUG_TYPE "static-analyzer-call-event"
66
67
using namespace clang;
68
using namespace ento;
69
70
51.7k
QualType CallEvent::getResultType() const {
71
51.7k
  ASTContext &Ctx = getState()->getStateManager().getContext();
72
51.7k
  const Expr *E = getOriginExpr();
73
51.7k
  if (!E)
74
1
    return Ctx.VoidTy;
75
51.7k
  assert(E);
76
77
51.7k
  QualType ResultTy = E->getType();
78
79
  // A function that returns a reference to 'int' will have a result type
80
  // of simply 'int'. Check the origin expr's value kind to recover the
81
  // proper type.
82
51.7k
  switch (E->getValueKind()) {
83
303
  case VK_LValue:
84
303
    ResultTy = Ctx.getLValueReferenceType(ResultTy);
85
303
    break;
86
34
  case VK_XValue:
87
34
    ResultTy = Ctx.getRValueReferenceType(ResultTy);
88
34
    break;
89
51.4k
  case VK_RValue:
90
    // No adjustment is necessary.
91
51.4k
    break;
92
51.7k
  }
93
94
51.7k
  return ResultTy;
95
51.7k
}
96
97
26.8k
static bool isCallback(QualType T) {
98
  // If a parameter is a block or a callback, assume it can modify pointer.
99
26.8k
  if (T->isBlockPointerType() ||
100
26.6k
      T->isFunctionPointerType() ||
101
26.5k
      T->isObjCSelType())
102
261
    return true;
103
104
  // Check if a callback is passed inside a struct (for both, struct passed by
105
  // reference and by value). Dig just one level into the struct for now.
106
107
26.5k
  if (T->isAnyPointerType() || 
T->isReferenceType()17.7k
)
108
11.7k
    T = T->getPointeeType();
109
110
26.5k
  if (const RecordType *RT = T->getAsStructureType()) {
111
14.1k
    const RecordDecl *RD = RT->getDecl();
112
14.8k
    for (const auto *I : RD->fields()) {
113
14.8k
      QualType FieldT = I->getType();
114
14.8k
      if (FieldT->isBlockPointerType() || FieldT->isFunctionPointerType())
115
9
        return true;
116
14.8k
    }
117
14.1k
  }
118
26.5k
  return false;
119
26.5k
}
120
121
22.5k
static bool isVoidPointerToNonConst(QualType T) {
122
22.5k
  if (const auto *PT = T->getAs<PointerType>()) {
123
6.23k
    QualType PointeeTy = PT->getPointeeType();
124
6.23k
    if (PointeeTy.isConstQualified())
125
2.57k
      return false;
126
3.65k
    return PointeeTy->isVoidType();
127
3.65k
  } else
128
16.3k
    return false;
129
22.5k
}
130
131
63.5k
bool CallEvent::hasNonNullArgumentsWithType(bool (*Condition)(QualType)) const {
132
63.5k
  unsigned NumOfArgs = getNumArgs();
133
134
  // If calling using a function pointer, assume the function does not
135
  // satisfy the callback.
136
  // TODO: We could check the types of the arguments here.
137
63.5k
  if (!getDecl())
138
83
    return false;
139
140
63.4k
  unsigned Idx = 0;
141
63.4k
  for (CallEvent::param_type_iterator I = param_type_begin(),
142
63.4k
                                      E = param_type_end();
143
114k
       I != E && 
Idx < NumOfArgs52.3k
;
++I, ++Idx51.3k
) {
144
    // If the parameter is 0, it's harmless.
145
52.3k
    if (getArgSVal(Idx).isZeroConstant())
146
2.92k
      continue;
147
148
49.4k
    if (Condition(*I))
149
1.04k
      return true;
150
49.4k
  }
151
62.4k
  return false;
152
63.4k
}
153
154
35.7k
bool CallEvent::hasNonZeroCallbackArg() const {
155
35.7k
  return hasNonNullArgumentsWithType(isCallback);
156
35.7k
}
157
158
27.7k
bool CallEvent::hasVoidPointerToNonConstArg() const {
159
27.7k
  return hasNonNullArgumentsWithType(isVoidPointerToNonConst);
160
27.7k
}
161
162
112k
bool CallEvent::isGlobalCFunction(StringRef FunctionName) const {
163
112k
  const auto *FD = dyn_cast_or_null<FunctionDecl>(getDecl());
164
112k
  if (!FD)
165
7.04k
    return false;
166
167
105k
  return CheckerContext::isCLibraryFunction(FD, FunctionName);
168
105k
}
169
170
32.3k
AnalysisDeclContext *CallEvent::getCalleeAnalysisDeclContext() const {
171
32.3k
  const Decl *D = getDecl();
172
32.3k
  if (!D)
173
0
    return nullptr;
174
175
32.3k
  AnalysisDeclContext *ADC =
176
32.3k
      LCtx->getAnalysisDeclContext()->getManager()->getContext(D);
177
178
32.3k
  return ADC;
179
32.3k
}
180
181
const StackFrameContext *
182
32.3k
CallEvent::getCalleeStackFrame(unsigned BlockCount) const {
183
32.3k
  AnalysisDeclContext *ADC = getCalleeAnalysisDeclContext();
184
32.3k
  if (!ADC)
185
0
    return nullptr;
186
187
32.3k
  const Expr *E = getOriginExpr();
188
32.3k
  if (!E)
189
0
    return nullptr;
190
191
  // Recover CFG block via reverse lookup.
192
  // TODO: If we were to keep CFG element information as part of the CallEvent
193
  // instead of doing this reverse lookup, we would be able to build the stack
194
  // frame for non-expression-based calls, and also we wouldn't need the reverse
195
  // lookup.
196
32.3k
  CFGStmtMap *Map = LCtx->getAnalysisDeclContext()->getCFGStmtMap();
197
32.3k
  const CFGBlock *B = Map->getBlock(E);
198
32.3k
  assert(B);
199
200
  // Also recover CFG index by scanning the CFG block.
201
32.3k
  unsigned Idx = 0, Sz = B->size();
202
403k
  for (; Idx < Sz; 
++Idx371k
)
203
403k
    if (auto StmtElem = (*B)[Idx].getAs<CFGStmt>())
204
403k
      if (StmtElem->getStmt() == E)
205
32.3k
        break;
206
32.3k
  assert(Idx < Sz);
207
208
32.3k
  return ADC->getManager()->getStackFrame(ADC, LCtx, E, B, BlockCount, Idx);
209
32.3k
}
210
211
const ParamVarRegion
212
21.1k
*CallEvent::getParameterLocation(unsigned Index, unsigned BlockCount) const {
213
21.1k
  const StackFrameContext *SFC = getCalleeStackFrame(BlockCount);
214
  // We cannot construct a VarRegion without a stack frame.
215
21.1k
  if (!SFC)
216
0
    return nullptr;
217
218
21.1k
  const ParamVarRegion *PVR =
219
21.1k
    State->getStateManager().getRegionManager().getParamVarRegion(
220
21.1k
        getOriginExpr(), Index, SFC);
221
21.1k
  return PVR;
222
21.1k
}
223
224
/// Returns true if a type is a pointer-to-const or reference-to-const
225
/// with no further indirection.
226
23.5k
static bool isPointerToConst(QualType Ty) {
227
23.5k
  QualType PointeeTy = Ty->getPointeeType();
228
23.5k
  if (PointeeTy == QualType())
229
14.0k
    return false;
230
9.45k
  if (!PointeeTy.isConstQualified())
231
4.68k
    return false;
232
4.77k
  if (PointeeTy->isAnyPointerType())
233
38
    return false;
234
4.73k
  return true;
235
4.73k
}
236
237
// Try to retrieve the function declaration and find the function parameter
238
// types which are pointers/references to a non-pointer const.
239
// We will not invalidate the corresponding argument regions.
240
static void findPtrToConstParams(llvm::SmallSet<unsigned, 4> &PreserveArgs,
241
30.3k
                                 const CallEvent &Call) {
242
30.3k
  unsigned Idx = 0;
243
30.3k
  for (CallEvent::param_type_iterator I = Call.param_type_begin(),
244
30.3k
                                      E = Call.param_type_end();
245
53.8k
       I != E; 
++I, ++Idx23.5k
) {
246
23.5k
    if (isPointerToConst(*I))
247
4.73k
      PreserveArgs.insert(Idx);
248
23.5k
  }
249
30.3k
}
250
251
ProgramStateRef CallEvent::invalidateRegions(unsigned BlockCount,
252
31.4k
                                             ProgramStateRef Orig) const {
253
31.3k
  ProgramStateRef Result = (Orig ? Orig : 
getState()7
);
254
255
  // Don't invalidate anything if the callee is marked pure/const.
256
31.4k
  if (const Decl *callee = getDecl())
257
31.3k
    if (callee->hasAttr<PureAttr>() || 
callee->hasAttr<ConstAttr>()31.3k
)
258
28
      return Result;
259
260
31.3k
  SmallVector<SVal, 8> ValuesToInvalidate;
261
31.3k
  RegionAndSymbolInvalidationTraits ETraits;
262
263
31.3k
  getExtraInvalidatedValues(ValuesToInvalidate, &ETraits);
264
265
  // Indexes of arguments whose values will be preserved by the call.
266
31.3k
  llvm::SmallSet<unsigned, 4> PreserveArgs;
267
31.3k
  if (!argumentsMayEscape())
268
30.3k
    findPtrToConstParams(PreserveArgs, *this);
269
270
57.5k
  for (unsigned Idx = 0, Count = getNumArgs(); Idx != Count; 
++Idx26.1k
) {
271
    // Mark this region for invalidation.  We batch invalidate regions
272
    // below for efficiency.
273
26.1k
    if (PreserveArgs.count(Idx))
274
4.73k
      if (const MemRegion *MR = getArgSVal(Idx).getAsRegion())
275
4.46k
        ETraits.setTrait(MR->getBaseRegion(),
276
4.46k
                        RegionAndSymbolInvalidationTraits::TK_PreserveContents);
277
        // TODO: Factor this out + handle the lower level const pointers.
278
279
26.1k
    ValuesToInvalidate.push_back(getArgSVal(Idx));
280
281
    // If a function accepts an object by argument (which would of course be a
282
    // temporary that isn't lifetime-extended), invalidate the object itself,
283
    // not only other objects reachable from it. This is necessary because the
284
    // destructor has access to the temporary object after the call.
285
    // TODO: Support placement arguments once we start
286
    // constructing them directly.
287
    // TODO: This is unnecessary when there's no destructor, but that's
288
    // currently hard to figure out.
289
26.1k
    if (getKind() != CE_CXXAllocator)
290
25.4k
      if (isArgumentConstructedDirectly(Idx))
291
9.90k
        if (auto AdjIdx = getAdjustedParameterIndex(Idx))
292
9.90k
          if (const TypedValueRegion *TVR =
293
9.90k
                  getParameterLocation(*AdjIdx, BlockCount))
294
9.90k
            ValuesToInvalidate.push_back(loc::MemRegionVal(TVR));
295
26.1k
  }
296
297
  // Invalidate designated regions using the batch invalidation API.
298
  // NOTE: Even if RegionsToInvalidate is empty, we may still invalidate
299
  //  global variables.
300
31.3k
  return Result->invalidateRegions(ValuesToInvalidate, getOriginExpr(),
301
31.3k
                                   BlockCount, getLocationContext(),
302
31.3k
                                   /*CausedByPointerEscape*/ true,
303
31.3k
                                   /*Symbols=*/nullptr, this, &ETraits);
304
31.3k
}
305
306
ProgramPoint CallEvent::getProgramPoint(bool IsPreVisit,
307
934k
                                        const ProgramPointTag *Tag) const {
308
934k
  if (const Expr *E = getOriginExpr()) {
309
921k
    if (IsPreVisit)
310
513k
      return PreStmt(E, getLocationContext(), Tag);
311
407k
    return PostStmt(E, getLocationContext(), Tag);
312
407k
  }
313
314
12.8k
  const Decl *D = getDecl();
315
12.8k
  assert(D && "Cannot get a program point without a statement or decl");
316
317
12.8k
  SourceLocation Loc = getSourceRange().getBegin();
318
12.8k
  if (IsPreVisit)
319
7.56k
    return PreImplicitCall(D, Loc, getLocationContext(), Tag);
320
5.27k
  return PostImplicitCall(D, Loc, getLocationContext(), Tag);
321
5.27k
}
322
323
1.80M
bool CallEvent::isCalled(const CallDescription &CD) const {
324
  // FIXME: Add ObjC Message support.
325
1.80M
  if (getKind() == CE_ObjCMessage)
326
3.12k
    return false;
327
328
1.79M
  const IdentifierInfo *II = getCalleeIdentifier();
329
1.79M
  if (!II)
330
291k
    return false;
331
1.50M
  const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(getDecl());
332
1.50M
  if (!FD)
333
0
    return false;
334
335
1.50M
  if (CD.Flags & CDF_MaybeBuiltin) {
336
516k
    return CheckerContext::isCLibraryFunction(FD, CD.getFunctionName()) &&
337
2.18k
           (!CD.RequiredArgs || CD.RequiredArgs <= getNumArgs()) &&
338
2.18k
           (!CD.RequiredParams || CD.RequiredParams <= parameters().size());
339
516k
  }
340
341
989k
  if (!CD.IsLookupDone) {
342
7.61k
    CD.IsLookupDone = true;
343
7.61k
    CD.II = &getState()->getStateManager().getContext().Idents.get(
344
7.61k
        CD.getFunctionName());
345
7.61k
  }
346
347
989k
  if (II != CD.II)
348
980k
    return false;
349
350
  // If CallDescription provides prefix names, use them to improve matching
351
  // accuracy.
352
8.83k
  if (CD.QualifiedName.size() > 1 && 
FD744
) {
353
744
    const DeclContext *Ctx = FD->getDeclContext();
354
    // See if we'll be able to match them all.
355
744
    size_t NumUnmatched = CD.QualifiedName.size() - 1;
356
1.57k
    for (; Ctx && isa<NamedDecl>(Ctx); 
Ctx = Ctx->getParent()834
) {
357
840
      if (NumUnmatched == 0)
358
6
        break;
359
360
834
      if (const auto *ND = dyn_cast<NamespaceDecl>(Ctx)) {
361
734
        if (ND->getName() == CD.QualifiedName[NumUnmatched - 1])
362
704
          --NumUnmatched;
363
734
        continue;
364
734
      }
365
366
100
      if (const auto *RD = dyn_cast<RecordDecl>(Ctx)) {
367
100
        if (RD->getName() == CD.QualifiedName[NumUnmatched - 1])
368
65
          --NumUnmatched;
369
100
        continue;
370
100
      }
371
100
    }
372
373
744
    if (NumUnmatched > 0)
374
31
      return false;
375
8.80k
  }
376
377
8.80k
  return (!CD.RequiredArgs || 
CD.RequiredArgs == getNumArgs()8.50k
) &&
378
8.70k
         (!CD.RequiredParams || 
CD.RequiredParams == parameters().size()8.40k
);
379
8.80k
}
380
381
303k
SVal CallEvent::getArgSVal(unsigned Index) const {
382
303k
  const Expr *ArgE = getArgExpr(Index);
383
303k
  if (!ArgE)
384
4.07k
    return UnknownVal();
385
299k
  return getSVal(ArgE);
386
299k
}
387
388
82.4k
SourceRange CallEvent::getArgSourceRange(unsigned Index) const {
389
82.4k
  const Expr *ArgE = getArgExpr(Index);
390
82.4k
  if (!ArgE)
391
996
    return {};
392
81.4k
  return ArgE->getSourceRange();
393
81.4k
}
394
395
27.7k
SVal CallEvent::getReturnValue() const {
396
27.7k
  const Expr *E = getOriginExpr();
397
27.7k
  if (!E)
398
13
    return UndefinedVal();
399
27.7k
  return getSVal(E);
400
27.7k
}
401
402
0
LLVM_DUMP_METHOD void CallEvent::dump() const { dump(llvm::errs()); }
403
404
0
void CallEvent::dump(raw_ostream &Out) const {
405
0
  ASTContext &Ctx = getState()->getStateManager().getContext();
406
0
  if (const Expr *E = getOriginExpr()) {
407
0
    E->printPretty(Out, nullptr, Ctx.getPrintingPolicy());
408
0
    Out << "\n";
409
0
    return;
410
0
  }
411
412
0
  if (const Decl *D = getDecl()) {
413
0
    Out << "Call to ";
414
0
    D->print(Out, Ctx.getPrintingPolicy());
415
0
    return;
416
0
  }
417
418
0
  Out << "Unknown call (type " << getKindAsString() << ")";
419
0
}
420
421
1.14M
bool CallEvent::isCallStmt(const Stmt *S) {
422
1.14M
  return isa<CallExpr>(S) || 
isa<ObjCMessageExpr>(S)1.05M
423
1.04M
                          || isa<CXXConstructExpr>(S)
424
1.01M
                          || isa<CXXNewExpr>(S);
425
1.14M
}
426
427
19.5k
QualType CallEvent::getDeclaredResultType(const Decl *D) {
428
19.5k
  assert(D);
429
19.5k
  if (const auto *FD = dyn_cast<FunctionDecl>(D))
430
18.5k
    return FD->getReturnType();
431
1.01k
  if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
432
983
    return MD->getReturnType();
433
35
  if (const auto *BD = dyn_cast<BlockDecl>(D)) {
434
    // Blocks are difficult because the return type may not be stored in the
435
    // BlockDecl itself. The AST should probably be enhanced, but for now we
436
    // just do what we can.
437
    // If the block is declared without an explicit argument list, the
438
    // signature-as-written just includes the return type, not the entire
439
    // function type.
440
    // FIXME: All blocks should have signatures-as-written, even if the return
441
    // type is inferred. (That's signified with a dependent result type.)
442
35
    if (const TypeSourceInfo *TSI = BD->getSignatureAsWritten()) {
443
31
      QualType Ty = TSI->getType();
444
31
      if (const FunctionType *FT = Ty->getAs<FunctionType>())
445
27
        Ty = FT->getReturnType();
446
31
      if (!Ty->isDependentType())
447
15
        return Ty;
448
20
    }
449
450
20
    return {};
451
20
  }
452
453
0
  llvm_unreachable("unknown callable kind");
454
0
}
455
456
16.6k
bool CallEvent::isVariadic(const Decl *D) {
457
16.6k
  assert(D);
458
459
16.6k
  if (const auto *FD = dyn_cast<FunctionDecl>(D))
460
15.7k
    return FD->isVariadic();
461
874
  if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
462
747
    return MD->isVariadic();
463
127
  if (const auto *BD = dyn_cast<BlockDecl>(D))
464
127
    return BD->isVariadic();
465
466
0
  llvm_unreachable("unknown callable kind");
467
0
}
468
469
static void addParameterValuesToBindings(const StackFrameContext *CalleeCtx,
470
                                         CallEvent::BindingsTy &Bindings,
471
                                         SValBuilder &SVB,
472
                                         const CallEvent &Call,
473
33.7k
                                         ArrayRef<ParmVarDecl*> parameters) {
474
33.7k
  MemRegionManager &MRMgr = SVB.getRegionManager();
475
476
  // If the function has fewer parameters than the call has arguments, we simply
477
  // do not bind any values to them.
478
33.7k
  unsigned NumArgs = Call.getNumArgs();
479
33.7k
  unsigned Idx = 0;
480
33.7k
  ArrayRef<ParmVarDecl*>::iterator I = parameters.begin(), E = parameters.end();
481
59.2k
  for (; I != E && 
Idx < NumArgs25.4k
;
++I, ++Idx25.4k
) {
482
25.4k
    assert(*I && "Formal parameter has no decl?");
483
484
    // TODO: Support allocator calls.
485
25.4k
    if (Call.getKind() != CE_CXXAllocator)
486
24.7k
      if (Call.isArgumentConstructedDirectly(Call.getASTArgumentIndex(Idx)))
487
1.12k
        continue;
488
489
    // TODO: Allocators should receive the correct size and possibly alignment,
490
    // determined in compile-time but not represented as arg-expressions,
491
    // which makes getArgSVal() fail and return UnknownVal.
492
24.2k
    SVal ArgVal = Call.getArgSVal(Idx);
493
24.2k
    if (!ArgVal.isUnknown()) {
494
22.4k
      Loc ParamLoc = SVB.makeLoc(
495
22.4k
          MRMgr.getParamVarRegion(Call.getOriginExpr(), Idx, CalleeCtx));
496
22.4k
      Bindings.push_back(std::make_pair(ParamLoc, ArgVal));
497
22.4k
    }
498
24.2k
  }
499
500
  // FIXME: Variadic arguments are not handled at all right now.
501
33.7k
}
502
503
3
const ConstructionContext *CallEvent::getConstructionContext() const {
504
3
  const StackFrameContext *StackFrame = getCalleeStackFrame(0);
505
3
  if (!StackFrame)
506
0
    return nullptr;
507
508
3
  const CFGElement Element = StackFrame->getCallSiteCFGElement();
509
3
  if (const auto Ctor = Element.getAs<CFGConstructor>()) {
510
2
    return Ctor->getConstructionContext();
511
2
  }
512
513
1
  if (const auto RecCall = Element.getAs<CFGCXXRecordTypedCall>()) {
514
1
    return RecCall->getConstructionContext();
515
1
  }
516
517
0
  return nullptr;
518
0
}
519
520
Optional<SVal>
521
3
CallEvent::getReturnValueUnderConstruction() const {
522
3
  const auto *CC = getConstructionContext();
523
3
  if (!CC)
524
0
    return None;
525
526
3
  EvalCallOptions CallOpts;
527
3
  ExprEngine &Engine = getState()->getStateManager().getOwningEngine();
528
3
  SVal RetVal =
529
3
    Engine.computeObjectUnderConstruction(getOriginExpr(), getState(),
530
3
                                          getLocationContext(), CC, CallOpts);
531
3
  return RetVal;
532
3
}
533
534
499k
ArrayRef<ParmVarDecl*> AnyFunctionCall::parameters() const {
535
499k
  const FunctionDecl *D = getDecl();
536
499k
  if (!D)
537
26
    return None;
538
499k
  return D->parameters();
539
499k
}
540
541
61.4k
RuntimeDefinition AnyFunctionCall::getRuntimeDefinition() const {
542
61.4k
  const FunctionDecl *FD = getDecl();
543
61.4k
  if (!FD)
544
25
    return {};
545
546
  // Note that the AnalysisDeclContext will have the FunctionDecl with
547
  // the definition (if one exists).
548
61.4k
  AnalysisDeclContext *AD =
549
61.4k
    getLocationContext()->getAnalysisDeclContext()->
550
61.4k
    getManager()->getContext(FD);
551
61.4k
  bool IsAutosynthesized;
552
61.4k
  Stmt* Body = AD->getBody(IsAutosynthesized);
553
61.4k
  LLVM_DEBUG({
554
61.4k
    if (IsAutosynthesized)
555
61.4k
      llvm::dbgs() << "Using autosynthesized body for " << FD->getName()
556
61.4k
                   << "\n";
557
61.4k
  });
558
61.4k
  if (Body) {
559
36.4k
    const Decl* Decl = AD->getDecl();
560
36.4k
    return RuntimeDefinition(Decl);
561
36.4k
  }
562
563
25.0k
  ExprEngine &Engine = getState()->getStateManager().getOwningEngine();
564
25.0k
  AnalyzerOptions &Opts = Engine.getAnalysisManager().options;
565
566
  // Try to get CTU definition only if CTUDir is provided.
567
25.0k
  if (!Opts.IsNaiveCTUEnabled)
568
24.9k
    return {};
569
570
52
  cross_tu::CrossTranslationUnitContext &CTUCtx =
571
52
      *Engine.getCrossTranslationUnitContext();
572
52
  llvm::Expected<const FunctionDecl *> CTUDeclOrError =
573
52
      CTUCtx.getCrossTUDefinition(FD, Opts.CTUDir, Opts.CTUIndexName,
574
52
                                  Opts.DisplayCTUProgress);
575
576
52
  if (!CTUDeclOrError) {
577
8
    handleAllErrors(CTUDeclOrError.takeError(),
578
8
                    [&](const cross_tu::IndexError &IE) {
579
8
                      CTUCtx.emitCrossTUDiagnostics(IE);
580
8
                    });
581
8
    return {};
582
8
  }
583
584
44
  return RuntimeDefinition(*CTUDeclOrError);
585
44
}
586
587
void AnyFunctionCall::getInitialStackFrameContents(
588
                                        const StackFrameContext *CalleeCtx,
589
33.0k
                                        BindingsTy &Bindings) const {
590
33.0k
  const auto *D = cast<FunctionDecl>(CalleeCtx->getDecl());
591
33.0k
  SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
592
33.0k
  addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this,
593
33.0k
                               D->parameters());
594
33.0k
}
595
596
27.9k
bool AnyFunctionCall::argumentsMayEscape() const {
597
27.9k
  if (CallEvent::argumentsMayEscape() || 
hasVoidPointerToNonConstArg()27.7k
)
598
937
    return true;
599
600
26.9k
  const FunctionDecl *D = getDecl();
601
26.9k
  if (!D)
602
26
    return true;
603
604
26.9k
  const IdentifierInfo *II = D->getIdentifier();
605
26.9k
  if (!II)
606
4.00k
    return false;
607
608
  // This set of "escaping" APIs is
609
610
  // - 'int pthread_setspecific(ptheread_key k, const void *)' stores a
611
  //   value into thread local storage. The value can later be retrieved with
612
  //   'void *ptheread_getspecific(pthread_key)'. So even thought the
613
  //   parameter is 'const void *', the region escapes through the call.
614
22.9k
  if (II->isStr("pthread_setspecific"))
615
5
    return true;
616
617
  // - xpc_connection_set_context stores a value which can be retrieved later
618
  //   with xpc_connection_get_context.
619
22.9k
  if (II->isStr("xpc_connection_set_context"))
620
0
    return true;
621
622
  // - funopen - sets a buffer for future IO calls.
623
22.9k
  if (II->isStr("funopen"))
624
1
    return true;
625
626
  // - __cxa_demangle - can reallocate memory and can return the pointer to
627
  // the input buffer.
628
22.9k
  if (II->isStr("__cxa_demangle"))
629
8
    return true;
630
631
22.9k
  StringRef FName = II->getName();
632
633
  // - CoreFoundation functions that end with "NoCopy" can free a passed-in
634
  //   buffer even if it is const.
635
22.9k
  if (FName.endswith("NoCopy"))
636
10
    return true;
637
638
  // - NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
639
  //   be deallocated by NSMapRemove.
640
22.9k
  if (FName.startswith("NS") && 
(FName.find("Insert") != StringRef::npos)78
)
641
4
    return true;
642
643
  // - Many CF containers allow objects to escape through custom
644
  //   allocators/deallocators upon container construction. (PR12101)
645
22.9k
  if (FName.startswith("CF") || 
FName.startswith("CG")22.2k
) {
646
677
    return StrInStrNoCase(FName, "InsertValue")  != StringRef::npos ||
647
677
           StrInStrNoCase(FName, "AddValue")     != StringRef::npos ||
648
677
           StrInStrNoCase(FName, "SetValue")     != StringRef::npos ||
649
675
           StrInStrNoCase(FName, "WithData")     != StringRef::npos ||
650
669
           StrInStrNoCase(FName, "AppendValue")  != StringRef::npos ||
651
663
           StrInStrNoCase(FName, "SetAttribute") != StringRef::npos;
652
677
  }
653
654
22.2k
  return false;
655
22.2k
}
656
657
3.71M
const FunctionDecl *SimpleFunctionCall::getDecl() const {
658
3.71M
  const FunctionDecl *D = getOriginExpr()->getDirectCallee();
659
3.71M
  if (D)
660
3.69M
    return D;
661
662
23.5k
  return getSVal(getOriginExpr()->getCallee()).getAsFunctionDecl();
663
23.5k
}
664
665
847k
const FunctionDecl *CXXInstanceCall::getDecl() const {
666
847k
  const auto *CE = cast_or_null<CallExpr>(getOriginExpr());
667
847k
  if (!CE)
668
42.4k
    return AnyFunctionCall::getDecl();
669
670
804k
  const FunctionDecl *D = CE->getDirectCallee();
671
804k
  if (D)
672
804k
    return D;
673
674
408
  return getSVal(CE->getCallee()).getAsFunctionDecl();
675
408
}
676
677
void CXXInstanceCall::getExtraInvalidatedValues(
678
5.75k
    ValueList &Values, RegionAndSymbolInvalidationTraits *ETraits) const {
679
5.75k
  SVal ThisVal = getCXXThisVal();
680
5.75k
  Values.push_back(ThisVal);
681
682
  // Don't invalidate if the method is const and there are no mutable fields.
683
5.75k
  if (const auto *D = cast_or_null<CXXMethodDecl>(getDecl())) {
684
5.74k
    if (!D->isConst())
685
3.11k
      return;
686
    // Get the record decl for the class of 'This'. D->getParent() may return a
687
    // base class decl, rather than the class of the instance which needs to be
688
    // checked for mutable fields.
689
    // TODO: We might as well look at the dynamic type of the object.
690
2.63k
    const Expr *Ex = getCXXThisExpr()->IgnoreParenBaseCasts();
691
2.63k
    QualType T = Ex->getType();
692
2.63k
    if (T->isPointerType()) // Arrow or implicit-this syntax?
693
39
      T = T->getPointeeType();
694
2.63k
    const CXXRecordDecl *ParentRecord = T->getAsCXXRecordDecl();
695
2.63k
    assert(ParentRecord);
696
2.63k
    if (ParentRecord->hasMutableFields())
697
3
      return;
698
    // Preserve CXXThis.
699
2.63k
    const MemRegion *ThisRegion = ThisVal.getAsRegion();
700
2.63k
    if (!ThisRegion)
701
1
      return;
702
703
2.62k
    ETraits->setTrait(ThisRegion->getBaseRegion(),
704
2.62k
                      RegionAndSymbolInvalidationTraits::TK_PreserveContents);
705
2.62k
  }
706
5.75k
}
707
708
54.1k
SVal CXXInstanceCall::getCXXThisVal() const {
709
54.1k
  const Expr *Base = getCXXThisExpr();
710
  // FIXME: This doesn't handle an overloaded ->* operator.
711
54.1k
  if (!Base)
712
0
    return UnknownVal();
713
714
54.1k
  SVal ThisVal = getSVal(Base);
715
54.1k
  assert(ThisVal.isUnknownOrUndef() || ThisVal.getAs<Loc>());
716
54.1k
  return ThisVal;
717
54.1k
}
718
719
12.8k
RuntimeDefinition CXXInstanceCall::getRuntimeDefinition() const {
720
  // Do we have a decl at all?
721
12.8k
  const Decl *D = getDecl();
722
12.8k
  if (!D)
723
1
    return {};
724
725
  // If the method is non-virtual, we know we can inline it.
726
12.8k
  const auto *MD = cast<CXXMethodDecl>(D);
727
12.8k
  if (!MD->isVirtual())
728
12.5k
    return AnyFunctionCall::getRuntimeDefinition();
729
730
  // Do we know the implicit 'this' object being called?
731
289
  const MemRegion *R = getCXXThisVal().getAsRegion();
732
289
  if (!R)
733
0
    return {};
734
735
  // Do we know anything about the type of 'this'?
736
289
  DynamicTypeInfo DynType = getDynamicTypeInfo(getState(), R);
737
289
  if (!DynType.isValid())
738
0
    return {};
739
740
  // Is the type a C++ class? (This is mostly a defensive check.)
741
289
  QualType RegionType = DynType.getType()->getPointeeType();
742
289
  assert(!RegionType.isNull() && "DynamicTypeInfo should always be a pointer.");
743
744
289
  const CXXRecordDecl *RD = RegionType->getAsCXXRecordDecl();
745
289
  if (!RD || !RD->hasDefinition())
746
0
    return {};
747
748
  // Find the decl for this method in that class.
749
289
  const CXXMethodDecl *Result = MD->getCorrespondingMethodInClass(RD, true);
750
289
  if (!Result) {
751
    // We might not even get the original statically-resolved method due to
752
    // some particularly nasty casting (e.g. casts to sister classes).
753
    // However, we should at least be able to search up and down our own class
754
    // hierarchy, and some real bugs have been caught by checking this.
755
3
    assert(!RD->isDerivedFrom(MD->getParent()) && "Couldn't find known method");
756
757
    // FIXME: This is checking that our DynamicTypeInfo is at least as good as
758
    // the static type. However, because we currently don't update
759
    // DynamicTypeInfo when an object is cast, we can't actually be sure the
760
    // DynamicTypeInfo is up to date. This assert should be re-enabled once
761
    // this is fixed. <rdar://problem/12287087>
762
    //assert(!MD->getParent()->isDerivedFrom(RD) && "Bad DynamicTypeInfo");
763
764
3
    return {};
765
3
  }
766
767
  // Does the decl that we found have an implementation?
768
286
  const FunctionDecl *Definition;
769
286
  if (!Result->hasBody(Definition)) {
770
169
    if (!DynType.canBeASubClass())
771
146
      return AnyFunctionCall::getRuntimeDefinition();
772
23
    return {};
773
23
  }
774
775
  // We found a definition. If we're not sure that this devirtualization is
776
  // actually what will happen at runtime, make sure to provide the region so
777
  // that ExprEngine can decide what to do with it.
778
117
  if (DynType.canBeASubClass())
779
8
    return RuntimeDefinition(Definition, R->StripCasts());
780
109
  return RuntimeDefinition(Definition, /*DispatchRegion=*/nullptr);
781
109
}
782
783
void CXXInstanceCall::getInitialStackFrameContents(
784
                                            const StackFrameContext *CalleeCtx,
785
7.30k
                                            BindingsTy &Bindings) const {
786
7.30k
  AnyFunctionCall::getInitialStackFrameContents(CalleeCtx, Bindings);
787
788
  // Handle the binding of 'this' in the new stack frame.
789
7.30k
  SVal ThisVal = getCXXThisVal();
790
7.30k
  if (!ThisVal.isUnknown()) {
791
7.30k
    ProgramStateManager &StateMgr = getState()->getStateManager();
792
7.30k
    SValBuilder &SVB = StateMgr.getSValBuilder();
793
794
7.30k
    const auto *MD = cast<CXXMethodDecl>(CalleeCtx->getDecl());
795
7.30k
    Loc ThisLoc = SVB.getCXXThis(MD, CalleeCtx);
796
797
    // If we devirtualized to a different member function, we need to make sure
798
    // we have the proper layering of CXXBaseObjectRegions.
799
7.30k
    if (MD->getCanonicalDecl() != getDecl()->getCanonicalDecl()) {
800
31
      ASTContext &Ctx = SVB.getContext();
801
31
      const CXXRecordDecl *Class = MD->getParent();
802
31
      QualType Ty = Ctx.getPointerType(Ctx.getRecordType(Class));
803
804
      // FIXME: CallEvent maybe shouldn't be directly accessing StoreManager.
805
31
      bool Failed;
806
31
      ThisVal = StateMgr.getStoreManager().attemptDownCast(ThisVal, Ty, Failed);
807
31
      if (Failed) {
808
        // We might have suffered some sort of placement new earlier, so
809
        // we're constructing in a completely unexpected storage.
810
        // Fall back to a generic pointer cast for this-value.
811
2
        const CXXMethodDecl *StaticMD = cast<CXXMethodDecl>(getDecl());
812
2
        const CXXRecordDecl *StaticClass = StaticMD->getParent();
813
2
        QualType StaticTy = Ctx.getPointerType(Ctx.getRecordType(StaticClass));
814
2
        ThisVal = SVB.evalCast(ThisVal, Ty, StaticTy);
815
2
      }
816
31
    }
817
818
7.30k
    if (!ThisVal.isUnknown())
819
7.29k
      Bindings.push_back(std::make_pair(ThisLoc, ThisVal));
820
7.30k
  }
821
7.30k
}
822
823
44.1k
const Expr *CXXMemberCall::getCXXThisExpr() const {
824
44.1k
  return getOriginExpr()->getImplicitObjectArgument();
825
44.1k
}
826
827
8.47k
RuntimeDefinition CXXMemberCall::getRuntimeDefinition() const {
828
  // C++11 [expr.call]p1: ...If the selected function is non-virtual, or if the
829
  // id-expression in the class member access expression is a qualified-id,
830
  // that function is called. Otherwise, its final overrider in the dynamic type
831
  // of the object expression is called.
832
8.47k
  if (const auto *ME = dyn_cast<MemberExpr>(getOriginExpr()->getCallee()))
833
8.45k
    if (ME->hasQualifier())
834
149
      return AnyFunctionCall::getRuntimeDefinition();
835
836
8.32k
  return CXXInstanceCall::getRuntimeDefinition();
837
8.32k
}
838
839
16.2k
const Expr *CXXMemberOperatorCall::getCXXThisExpr() const {
840
16.2k
  return getOriginExpr()->getArg(0);
841
16.2k
}
842
843
3.16k
const BlockDataRegion *BlockCall::getBlockRegion() const {
844
3.16k
  const Expr *Callee = getOriginExpr()->getCallee();
845
3.16k
  const MemRegion *DataReg = getSVal(Callee).getAsRegion();
846
847
3.16k
  return dyn_cast_or_null<BlockDataRegion>(DataReg);
848
3.16k
}
849
850
664
ArrayRef<ParmVarDecl*> BlockCall::parameters() const {
851
664
  const BlockDecl *D = getDecl();
852
664
  if (!D)
853
11
    return None;
854
653
  return D->parameters();
855
653
}
856
857
void BlockCall::getExtraInvalidatedValues(ValueList &Values,
858
18
                  RegionAndSymbolInvalidationTraits *ETraits) const {
859
  // FIXME: This also needs to invalidate captured globals.
860
18
  if (const MemRegion *R = getBlockRegion())
861
8
    Values.push_back(loc::MemRegionVal(R));
862
18
}
863
864
void BlockCall::getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
865
177
                                             BindingsTy &Bindings) const {
866
177
  SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
867
177
  ArrayRef<ParmVarDecl*> Params;
868
177
  if (isConversionFromLambda()) {
869
7
    auto *LambdaOperatorDecl = cast<CXXMethodDecl>(CalleeCtx->getDecl());
870
7
    Params = LambdaOperatorDecl->parameters();
871
872
    // For blocks converted from a C++ lambda, the callee declaration is the
873
    // operator() method on the lambda so we bind "this" to
874
    // the lambda captured by the block.
875
7
    const VarRegion *CapturedLambdaRegion = getRegionStoringCapturedLambda();
876
7
    SVal ThisVal = loc::MemRegionVal(CapturedLambdaRegion);
877
7
    Loc ThisLoc = SVB.getCXXThis(LambdaOperatorDecl, CalleeCtx);
878
7
    Bindings.push_back(std::make_pair(ThisLoc, ThisVal));
879
170
  } else {
880
170
    Params = cast<BlockDecl>(CalleeCtx->getDecl())->parameters();
881
170
  }
882
883
177
  addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this,
884
177
                               Params);
885
177
}
886
887
52.7k
SVal AnyCXXConstructorCall::getCXXThisVal() const {
888
52.7k
  if (Data)
889
52.7k
    return loc::MemRegionVal(static_cast<const MemRegion *>(Data));
890
0
  return UnknownVal();
891
0
}
892
893
void AnyCXXConstructorCall::getExtraInvalidatedValues(ValueList &Values,
894
1.58k
                           RegionAndSymbolInvalidationTraits *ETraits) const {
895
1.58k
  SVal V = getCXXThisVal();
896
1.58k
  if (SymbolRef Sym = V.getAsSymbol(true))
897
119
    ETraits->setTrait(Sym,
898
119
                      RegionAndSymbolInvalidationTraits::TK_SuppressEscape);
899
1.58k
  Values.push_back(V);
900
1.58k
}
901
902
void AnyCXXConstructorCall::getInitialStackFrameContents(
903
                                             const StackFrameContext *CalleeCtx,
904
8.75k
                                             BindingsTy &Bindings) const {
905
8.75k
  AnyFunctionCall::getInitialStackFrameContents(CalleeCtx, Bindings);
906
907
8.75k
  SVal ThisVal = getCXXThisVal();
908
8.75k
  if (!ThisVal.isUnknown()) {
909
8.75k
    SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
910
8.75k
    const auto *MD = cast<CXXMethodDecl>(CalleeCtx->getDecl());
911
8.75k
    Loc ThisLoc = SVB.getCXXThis(MD, CalleeCtx);
912
8.75k
    Bindings.push_back(std::make_pair(ThisLoc, ThisVal));
913
8.75k
  }
914
8.75k
}
915
916
const StackFrameContext *
917
84
CXXInheritedConstructorCall::getInheritingStackFrame() const {
918
84
  const StackFrameContext *SFC = getLocationContext()->getStackFrame();
919
96
  while (isa<CXXInheritedCtorInitExpr>(SFC->getCallSite()))
920
12
    SFC = SFC->getParent()->getStackFrame();
921
84
  return SFC;
922
84
}
923
924
4.52k
SVal CXXDestructorCall::getCXXThisVal() const {
925
4.52k
  if (Data)
926
4.52k
    return loc::MemRegionVal(DtorDataTy::getFromOpaqueValue(Data).getPointer());
927
0
  return UnknownVal();
928
0
}
929
930
1.49k
RuntimeDefinition CXXDestructorCall::getRuntimeDefinition() const {
931
  // Base destructors are always called non-virtually.
932
  // Skip CXXInstanceCall's devirtualization logic in this case.
933
1.49k
  if (isBaseDestructor())
934
125
    return AnyFunctionCall::getRuntimeDefinition();
935
936
1.36k
  return CXXInstanceCall::getRuntimeDefinition();
937
1.36k
}
938
939
29.1k
ArrayRef<ParmVarDecl*> ObjCMethodCall::parameters() const {
940
29.1k
  const ObjCMethodDecl *D = getDecl();
941
29.1k
  if (!D)
942
42
    return None;
943
29.1k
  return D->parameters();
944
29.1k
}
945
946
void ObjCMethodCall::getExtraInvalidatedValues(
947
3.46k
    ValueList &Values, RegionAndSymbolInvalidationTraits *ETraits) const {
948
949
  // If the method call is a setter for property known to be backed by
950
  // an instance variable, don't invalidate the entire receiver, just
951
  // the storage for that instance variable.
952
3.46k
  if (const ObjCPropertyDecl *PropDecl = getAccessedProperty()) {
953
147
    if (const ObjCIvarDecl *PropIvar = PropDecl->getPropertyIvarDecl()) {
954
62
      SVal IvarLVal = getState()->getLValue(PropIvar, getReceiverSVal());
955
62
      if (const MemRegion *IvarRegion = IvarLVal.getAsRegion()) {
956
61
        ETraits->setTrait(
957
61
          IvarRegion,
958
61
          RegionAndSymbolInvalidationTraits::TK_DoNotInvalidateSuperRegion);
959
61
        ETraits->setTrait(
960
61
          IvarRegion,
961
61
          RegionAndSymbolInvalidationTraits::TK_SuppressEscape);
962
61
        Values.push_back(IvarLVal);
963
61
      }
964
62
      return;
965
62
    }
966
3.40k
  }
967
968
3.40k
  Values.push_back(getReceiverSVal());
969
3.40k
}
970
971
27.9k
SVal ObjCMethodCall::getReceiverSVal() const {
972
  // FIXME: Is this the best way to handle class receivers?
973
27.9k
  if (!isInstanceMessage())
974
4.19k
    return UnknownVal();
975
976
23.7k
  if (const Expr *RecE = getOriginExpr()->getInstanceReceiver())
977
22.0k
    return getSVal(RecE);
978
979
  // An instance message with no expression means we are sending to super.
980
  // In this case the object reference is the same as 'self'.
981
1.75k
  assert(getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperInstance);
982
1.75k
  SVal SelfVal = getState()->getSelfSVal(getLocationContext());
983
1.75k
  assert(SelfVal.isValid() && "Calling super but not in ObjC method");
984
1.75k
  return SelfVal;
985
1.75k
}
986
987
723
bool ObjCMethodCall::isReceiverSelfOrSuper() const {
988
723
  if (getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperInstance ||
989
532
      getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperClass)
990
191
      return true;
991
992
532
  if (!isInstanceMessage())
993
18
    return false;
994
995
514
  SVal RecVal = getSVal(getOriginExpr()->getInstanceReceiver());
996
514
  SVal SelfVal = getState()->getSelfSVal(getLocationContext());
997
998
514
  return (RecVal == SelfVal);
999
514
}
1000
1001
13
SourceRange ObjCMethodCall::getSourceRange() const {
1002
13
  switch (getMessageKind()) {
1003
13
  case OCM_Message:
1004
13
    return getOriginExpr()->getSourceRange();
1005
0
  case OCM_PropertyAccess:
1006
0
  case OCM_Subscript:
1007
0
    return getContainingPseudoObjectExpr()->getSourceRange();
1008
0
  }
1009
0
  llvm_unreachable("unknown message kind");
1010
0
}
1011
1012
using ObjCMessageDataTy = llvm::PointerIntPair<const PseudoObjectExpr *, 2>;
1013
1014
117
const PseudoObjectExpr *ObjCMethodCall::getContainingPseudoObjectExpr() const {
1015
117
  assert(Data && "Lazy lookup not yet performed.");
1016
117
  assert(getMessageKind() != OCM_Message && "Explicit message send.");
1017
117
  return ObjCMessageDataTy::getFromOpaqueValue(Data).getPointer();
1018
117
}
1019
1020
static const Expr *
1021
285
getSyntacticFromForPseudoObjectExpr(const PseudoObjectExpr *POE) {
1022
285
  const Expr *Syntactic = POE->getSyntacticForm();
1023
1024
  // This handles the funny case of assigning to the result of a getter.
1025
  // This can happen if the getter returns a non-const reference.
1026
285
  if (const auto *BO = dyn_cast<BinaryOperator>(Syntactic))
1027
140
    Syntactic = BO->getLHS();
1028
1029
285
  return Syntactic;
1030
285
}
1031
1032
7.92k
ObjCMessageKind ObjCMethodCall::getMessageKind() const {
1033
7.92k
  if (!Data) {
1034
    // Find the parent, ignoring implicit casts.
1035
3.79k
    const ParentMap &PM = getLocationContext()->getParentMap();
1036
3.79k
    const Stmt *S = PM.getParentIgnoreParenCasts(getOriginExpr());
1037
1038
    // Check if parent is a PseudoObjectExpr.
1039
3.79k
    if (const auto *POE = dyn_cast_or_null<PseudoObjectExpr>(S)) {
1040
168
      const Expr *Syntactic = getSyntacticFromForPseudoObjectExpr(POE);
1041
1042
168
      ObjCMessageKind K;
1043
168
      switch (Syntactic->getStmtClass()) {
1044
127
      case Stmt::ObjCPropertyRefExprClass:
1045
127
        K = OCM_PropertyAccess;
1046
127
        break;
1047
40
      case Stmt::ObjCSubscriptRefExprClass:
1048
40
        K = OCM_Subscript;
1049
40
        break;
1050
1
      default:
1051
        // FIXME: Can this ever happen?
1052
1
        K = OCM_Message;
1053
1
        break;
1054
168
      }
1055
1056
168
      if (K != OCM_Message) {
1057
167
        const_cast<ObjCMethodCall *>(this)->Data
1058
167
          = ObjCMessageDataTy(POE, K).getOpaqueValue();
1059
167
        assert(getMessageKind() == K);
1060
167
        return K;
1061
167
      }
1062
3.62k
    }
1063
1064
3.62k
    const_cast<ObjCMethodCall *>(this)->Data
1065
3.62k
      = ObjCMessageDataTy(nullptr, 1).getOpaqueValue();
1066
3.62k
    assert(getMessageKind() == OCM_Message);
1067
3.62k
    return OCM_Message;
1068
3.62k
  }
1069
1070
4.12k
  ObjCMessageDataTy Info = ObjCMessageDataTy::getFromOpaqueValue(Data);
1071
4.12k
  if (!Info.getPointer())
1072
3.82k
    return OCM_Message;
1073
307
  return static_cast<ObjCMessageKind>(Info.getInt());
1074
307
}
1075
1076
3.48k
const ObjCPropertyDecl *ObjCMethodCall::getAccessedProperty() const {
1077
  // Look for properties accessed with property syntax (foo.bar = ...)
1078
3.48k
  if (getMessageKind() == OCM_PropertyAccess) {
1079
117
    const PseudoObjectExpr *POE = getContainingPseudoObjectExpr();
1080
117
    assert(POE && "Property access without PseudoObjectExpr?");
1081
1082
117
    const Expr *Syntactic = getSyntacticFromForPseudoObjectExpr(POE);
1083
117
    auto *RefExpr = cast<ObjCPropertyRefExpr>(Syntactic);
1084
1085
117
    if (RefExpr->isExplicitProperty())
1086
99
      return RefExpr->getExplicitProperty();
1087
3.38k
  }
1088
1089
  // Look for properties accessed with method syntax ([foo setBar:...]).
1090
3.38k
  const ObjCMethodDecl *MD = getDecl();
1091
3.38k
  if (!MD || 
!MD->isPropertyAccessor()3.36k
)
1092
3.31k
    return nullptr;
1093
1094
  // Note: This is potentially quite slow.
1095
65
  return MD->findPropertyDecl();
1096
65
}
1097
1098
bool ObjCMethodCall::canBeOverridenInSubclass(ObjCInterfaceDecl *IDecl,
1099
1.38k
                                             Selector Sel) const {
1100
1.38k
  assert(IDecl);
1101
1.38k
  AnalysisManager &AMgr =
1102
1.38k
      getState()->getStateManager().getOwningEngine().getAnalysisManager();
1103
  // If the class interface is declared inside the main file, assume it is not
1104
  // subcassed.
1105
  // TODO: It could actually be subclassed if the subclass is private as well.
1106
  // This is probably very rare.
1107
1.38k
  SourceLocation InterfLoc = IDecl->getEndOfDefinitionLoc();
1108
1.38k
  if (InterfLoc.isValid() && AMgr.isInCodeFile(InterfLoc))
1109
1.24k
    return false;
1110
1111
  // Assume that property accessors are not overridden.
1112
140
  if (getMessageKind() == OCM_PropertyAccess)
1113
7
    return false;
1114
1115
  // We assume that if the method is public (declared outside of main file) or
1116
  // has a parent which publicly declares the method, the method could be
1117
  // overridden in a subclass.
1118
1119
  // Find the first declaration in the class hierarchy that declares
1120
  // the selector.
1121
133
  ObjCMethodDecl *D = nullptr;
1122
137
  while (true) {
1123
137
    D = IDecl->lookupMethod(Sel, true);
1124
1125
    // Cannot find a public definition.
1126
137
    if (!D)
1127
2
      return false;
1128
1129
    // If outside the main file,
1130
135
    if (D->getLocation().isValid() && !AMgr.isInCodeFile(D->getLocation()))
1131
128
      return true;
1132
1133
7
    if (D->isOverriding()) {
1134
      // Search in the superclass on the next iteration.
1135
4
      IDecl = D->getClassInterface();
1136
4
      if (!IDecl)
1137
0
        return false;
1138
1139
4
      IDecl = IDecl->getSuperClass();
1140
4
      if (!IDecl)
1141
0
        return false;
1142
1143
4
      continue;
1144
4
    }
1145
1146
3
    return false;
1147
0
  };
1148
1149
0
  llvm_unreachable("The while loop should always terminate.");
1150
133
}
1151
1152
21
static const ObjCMethodDecl *findDefiningRedecl(const ObjCMethodDecl *MD) {
1153
21
  if (!MD)
1154
0
    return MD;
1155
1156
  // Find the redeclaration that defines the method.
1157
21
  if (!MD->hasBody()) {
1158
21
    for (auto I : MD->redecls())
1159
28
      if (I->hasBody())
1160
7
        MD = cast<ObjCMethodDecl>(I);
1161
21
  }
1162
21
  return MD;
1163
21
}
1164
1165
struct PrivateMethodKey {
1166
  const ObjCInterfaceDecl *Interface;
1167
  Selector LookupSelector;
1168
  bool IsClassMethod;
1169
};
1170
1171
namespace llvm {
1172
template <> struct DenseMapInfo<PrivateMethodKey> {
1173
  using InterfaceInfo = DenseMapInfo<const ObjCInterfaceDecl *>;
1174
  using SelectorInfo = DenseMapInfo<Selector>;
1175
1176
4.14k
  static inline PrivateMethodKey getEmptyKey() {
1177
4.14k
    return {InterfaceInfo::getEmptyKey(), SelectorInfo::getEmptyKey(), false};
1178
4.14k
  }
1179
1180
3.05k
  static inline PrivateMethodKey getTombstoneKey() {
1181
3.05k
    return {InterfaceInfo::getTombstoneKey(), SelectorInfo::getTombstoneKey(),
1182
3.05k
            true};
1183
3.05k
  }
1184
1185
2.92k
  static unsigned getHashValue(const PrivateMethodKey &Key) {
1186
2.92k
    return llvm::hash_combine(
1187
2.92k
        llvm::hash_code(InterfaceInfo::getHashValue(Key.Interface)),
1188
2.92k
        llvm::hash_code(SelectorInfo::getHashValue(Key.LookupSelector)),
1189
2.92k
        Key.IsClassMethod);
1190
2.92k
  }
1191
1192
  static bool isEqual(const PrivateMethodKey &LHS,
1193
22.5k
                      const PrivateMethodKey &RHS) {
1194
22.5k
    return InterfaceInfo::isEqual(LHS.Interface, RHS.Interface) &&
1195
11.5k
           SelectorInfo::isEqual(LHS.LookupSelector, RHS.LookupSelector) &&
1196
11.4k
           LHS.IsClassMethod == RHS.IsClassMethod;
1197
22.5k
  }
1198
};
1199
} // end namespace llvm
1200
1201
static const ObjCMethodDecl *
1202
lookupRuntimeDefinition(const ObjCInterfaceDecl *Interface,
1203
2.73k
                        Selector LookupSelector, bool InstanceMethod) {
1204
  // Repeatedly calling lookupPrivateMethod() is expensive, especially
1205
  // when in many cases it returns null.  We cache the results so
1206
  // that repeated queries on the same ObjCIntefaceDecl and Selector
1207
  // don't incur the same cost.  On some test cases, we can see the
1208
  // same query being issued thousands of times.
1209
  //
1210
  // NOTE: This cache is essentially a "global" variable, but it
1211
  // only gets lazily created when we get here.  The value of the
1212
  // cache probably comes from it being global across ExprEngines,
1213
  // where the same queries may get issued.  If we are worried about
1214
  // concurrency, or possibly loading/unloading ASTs, etc., we may
1215
  // need to revisit this someday.  In terms of memory, this table
1216
  // stays around until clang quits, which also may be bad if we
1217
  // need to release memory.
1218
2.73k
  using PrivateMethodCache =
1219
2.73k
      llvm::DenseMap<PrivateMethodKey, Optional<const ObjCMethodDecl *>>;
1220
1221
2.73k
  static PrivateMethodCache PMC;
1222
2.73k
  Optional<const ObjCMethodDecl *> &Val =
1223
2.73k
      PMC[{Interface, LookupSelector, InstanceMethod}];
1224
1225
  // Query lookupPrivateMethod() if the cache does not hit.
1226
2.73k
  if (!Val.hasValue()) {
1227
956
    Val = Interface->lookupPrivateMethod(LookupSelector, InstanceMethod);
1228
1229
956
    if (!*Val) {
1230
      // Query 'lookupMethod' as a backup.
1231
669
      Val = Interface->lookupMethod(LookupSelector, InstanceMethod);
1232
669
    }
1233
956
  }
1234
1235
2.73k
  return Val.getValue();
1236
2.73k
}
1237
1238
4.11k
RuntimeDefinition ObjCMethodCall::getRuntimeDefinition() const {
1239
4.11k
  const ObjCMessageExpr *E = getOriginExpr();
1240
4.11k
  assert(E);
1241
4.11k
  Selector Sel = E->getSelector();
1242
1243
4.11k
  if (E->isInstanceMessage()) {
1244
    // Find the receiver type.
1245
3.10k
    const ObjCObjectType *ReceiverT = nullptr;
1246
3.10k
    bool CanBeSubClassed = false;
1247
3.10k
    bool LookingForInstanceMethod = true;
1248
3.10k
    QualType SupersType = E->getSuperType();
1249
3.10k
    const MemRegion *Receiver = nullptr;
1250
1251
3.10k
    if (!SupersType.isNull()) {
1252
      // The receiver is guaranteed to be 'super' in this case.
1253
      // Super always means the type of immediate predecessor to the method
1254
      // where the call occurs.
1255
318
      ReceiverT = cast<ObjCObjectPointerType>(SupersType)->getObjectType();
1256
2.79k
    } else {
1257
2.79k
      Receiver = getReceiverSVal().getAsRegion();
1258
2.79k
      if (!Receiver)
1259
4
        return {};
1260
1261
2.78k
      DynamicTypeInfo DTI = getDynamicTypeInfo(getState(), Receiver);
1262
2.78k
      if (!DTI.isValid()) {
1263
1
        assert(isa<AllocaRegion>(Receiver) &&
1264
1
               "Unhandled untyped region class!");
1265
1
        return {};
1266
1
      }
1267
1268
2.78k
      QualType DynType = DTI.getType();
1269
2.78k
      CanBeSubClassed = DTI.canBeASubClass();
1270
1271
2.78k
      const auto *ReceiverDynT =
1272
2.78k
          dyn_cast<ObjCObjectPointerType>(DynType.getCanonicalType());
1273
1274
2.78k
      if (ReceiverDynT) {
1275
2.66k
        ReceiverT = ReceiverDynT->getObjectType();
1276
1277
        // It can be actually class methods called with Class object as a
1278
        // receiver. This type of messages is treated by the compiler as
1279
        // instance (not class).
1280
2.66k
        if (ReceiverT->isObjCClass()) {
1281
1282
51
          SVal SelfVal = getState()->getSelfSVal(getLocationContext());
1283
          // For [self classMethod], return compiler visible declaration.
1284
51
          if (Receiver == SelfVal.getAsRegion()) {
1285
21
            return RuntimeDefinition(findDefiningRedecl(E->getMethodDecl()));
1286
21
          }
1287
1288
          // Otherwise, let's check if we know something about the type
1289
          // inside of this class object.
1290
30
          if (SymbolRef ReceiverSym = getReceiverSVal().getAsSymbol()) {
1291
30
            DynamicTypeInfo DTI =
1292
30
                getClassObjectDynamicTypeInfo(getState(), ReceiverSym);
1293
30
            if (DTI.isValid()) {
1294
              // Let's use this type for lookup.
1295
29
              ReceiverT =
1296
29
                  cast<ObjCObjectType>(DTI.getType().getCanonicalType());
1297
1298
29
              CanBeSubClassed = DTI.canBeASubClass();
1299
              // And it should be a class method instead.
1300
29
              LookingForInstanceMethod = false;
1301
29
            }
1302
30
          }
1303
30
        }
1304
1305
2.64k
        if (CanBeSubClassed)
1306
1.61k
          if (ObjCInterfaceDecl *IDecl = ReceiverT->getInterface())
1307
            // Even if `DynamicTypeInfo` told us that it can be
1308
            // not necessarily this type, but its descendants, we still want
1309
            // to check again if this selector can be actually overridden.
1310
1.38k
            CanBeSubClassed = canBeOverridenInSubclass(IDecl, Sel);
1311
2.64k
      }
1312
2.78k
    }
1313
1314
    // Lookup the instance method implementation.
1315
3.08k
    if (ReceiverT)
1316
2.95k
      if (ObjCInterfaceDecl *IDecl = ReceiverT->getInterface()) {
1317
2.73k
        const ObjCMethodDecl *MD =
1318
2.73k
            lookupRuntimeDefinition(IDecl, Sel, LookingForInstanceMethod);
1319
1320
2.73k
        if (MD && 
!MD->hasBody()2.70k
)
1321
2.36k
          MD = MD->getCanonicalDecl();
1322
1323
2.73k
        if (CanBeSubClassed)
1324
128
          return RuntimeDefinition(MD, Receiver);
1325
2.60k
        else
1326
2.60k
          return RuntimeDefinition(MD, nullptr);
1327
1.00k
      }
1328
1.00k
  } else {
1329
    // This is a class method.
1330
    // If we have type info for the receiver class, we are calling via
1331
    // class name.
1332
1.00k
    if (ObjCInterfaceDecl *IDecl = E->getReceiverInterface()) {
1333
      // Find/Return the method implementation.
1334
1.00k
      return RuntimeDefinition(IDecl->lookupPrivateClassMethod(Sel));
1335
1.00k
    }
1336
352
  }
1337
1338
352
  return {};
1339
352
}
1340
1341
3.52k
bool ObjCMethodCall::argumentsMayEscape() const {
1342
3.52k
  if (isInSystemHeader() && 
!isInstanceMessage()456
) {
1343
119
    Selector Sel = getSelector();
1344
119
    if (Sel.getNumArgs() == 1 &&
1345
5
        Sel.getIdentifierInfoForSlot(0)->isStr("valueWithPointer"))
1346
2
      return true;
1347
3.51k
  }
1348
1349
3.51k
  return CallEvent::argumentsMayEscape();
1350
3.51k
}
1351
1352
void ObjCMethodCall::getInitialStackFrameContents(
1353
                                             const StackFrameContext *CalleeCtx,
1354
541
                                             BindingsTy &Bindings) const {
1355
541
  const auto *D = cast<ObjCMethodDecl>(CalleeCtx->getDecl());
1356
541
  SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
1357
541
  addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this,
1358
541
                               D->parameters());
1359
1360
541
  SVal SelfVal = getReceiverSVal();
1361
541
  if (!SelfVal.isUnknown()) {
1362
489
    const VarDecl *SelfD = CalleeCtx->getAnalysisDeclContext()->getSelfDecl();
1363
489
    MemRegionManager &MRMgr = SVB.getRegionManager();
1364
489
    Loc SelfLoc = SVB.makeLoc(MRMgr.getVarRegion(SelfD, CalleeCtx));
1365
489
    Bindings.push_back(std::make_pair(SelfLoc, SelfVal));
1366
489
  }
1367
541
}
1368
1369
CallEventRef<>
1370
CallEventManager::getSimpleCall(const CallExpr *CE, ProgramStateRef State,
1371
143k
                                const LocationContext *LCtx) {
1372
143k
  if (const auto *MCE = dyn_cast<CXXMemberCallExpr>(CE))
1373
19.2k
    return create<CXXMemberCall>(MCE, State, LCtx);
1374
1375
124k
  if (const auto *OpCE = dyn_cast<CXXOperatorCallExpr>(CE)) {
1376
8.36k
    const FunctionDecl *DirectCallee = OpCE->getDirectCallee();
1377
8.36k
    if (const auto *MD = dyn_cast<CXXMethodDecl>(DirectCallee))
1378
8.22k
      if (MD->isInstance())
1379
8.22k
        return create<CXXMemberOperatorCall>(OpCE, State, LCtx);
1380
1381
116k
  } else if (CE->getCallee()->getType()->isBlockPointerType()) {
1382
585
    return create<BlockCall>(CE, State, LCtx);
1383
585
  }
1384
1385
  // Otherwise, it's a normal function call, static member function call, or
1386
  // something we can't reason about.
1387
115k
  return create<SimpleFunctionCall>(CE, State, LCtx);
1388
115k
}
1389
1390
CallEventRef<>
1391
CallEventManager::getCaller(const StackFrameContext *CalleeCtx,
1392
85.2k
                            ProgramStateRef State) {
1393
85.2k
  const LocationContext *ParentCtx = CalleeCtx->getParent();
1394
85.2k
  const LocationContext *CallerCtx = ParentCtx->getStackFrame();
1395
85.2k
  assert(CallerCtx && "This should not be used for top-level stack frames");
1396
1397
85.2k
  const Stmt *CallSite = CalleeCtx->getCallSite();
1398
1399
85.2k
  if (CallSite) {
1400
83.7k
    if (CallEventRef<> Out = getCall(CallSite, State, CallerCtx))
1401
65.7k
      return Out;
1402
1403
18.0k
    SValBuilder &SVB = State->getStateManager().getSValBuilder();
1404
18.0k
    const auto *Ctor = cast<CXXMethodDecl>(CalleeCtx->getDecl());
1405
18.0k
    Loc ThisPtr = SVB.getCXXThis(Ctor, CalleeCtx);
1406
18.0k
    SVal ThisVal = State->getSVal(ThisPtr);
1407
1408
18.0k
    if (const auto *CE = dyn_cast<CXXConstructExpr>(CallSite))
1409
18.0k
      return getCXXConstructorCall(CE, ThisVal.getAsRegion(), State, CallerCtx);
1410
8
    else if (const auto *CIE = dyn_cast<CXXInheritedCtorInitExpr>(CallSite))
1411
8
      return getCXXInheritedConstructorCall(CIE, ThisVal.getAsRegion(), State,
1412
8
                                            CallerCtx);
1413
0
    else {
1414
      // All other cases are handled by getCall.
1415
0
      llvm_unreachable("This is not an inlineable statement");
1416
0
    }
1417
1.45k
  }
1418
1419
  // Fall back to the CFG. The only thing we haven't handled yet is
1420
  // destructors, though this could change in the future.
1421
1.45k
  const CFGBlock *B = CalleeCtx->getCallSiteBlock();
1422
1.45k
  CFGElement E = (*B)[CalleeCtx->getIndex()];
1423
1.45k
  assert((E.getAs<CFGImplicitDtor>() || E.getAs<CFGTemporaryDtor>()) &&
1424
1.45k
         "All other CFG elements should have exprs");
1425
1426
1.45k
  SValBuilder &SVB = State->getStateManager().getSValBuilder();
1427
1.45k
  const auto *Dtor = cast<CXXDestructorDecl>(CalleeCtx->getDecl());
1428
1.45k
  Loc ThisPtr = SVB.getCXXThis(Dtor, CalleeCtx);
1429
1.45k
  SVal ThisVal = State->getSVal(ThisPtr);
1430
1431
1.45k
  const Stmt *Trigger;
1432
1.45k
  if (Optional<CFGAutomaticObjDtor> AutoDtor = E.getAs<CFGAutomaticObjDtor>())
1433
865
    Trigger = AutoDtor->getTriggerStmt();
1434
594
  else if (Optional<CFGDeleteDtor> DeleteDtor = E.getAs<CFGDeleteDtor>())
1435
82
    Trigger = DeleteDtor->getDeleteExpr();
1436
512
  else
1437
512
    Trigger = Dtor->getBody();
1438
1439
1.45k
  return getCXXDestructorCall(Dtor, Trigger, ThisVal.getAsRegion(),
1440
1.45k
                              E.getAs<CFGBaseDtor>().hasValue(), State,
1441
1.45k
                              CallerCtx);
1442
1.45k
}
1443
1444
CallEventRef<> CallEventManager::getCall(const Stmt *S, ProgramStateRef State,
1445
84.2k
                                         const LocationContext *LC) {
1446
84.2k
  if (const auto *CE = dyn_cast<CallExpr>(S)) {
1447
63.6k
    return getSimpleCall(CE, State, LC);
1448
20.6k
  } else if (const auto *NE = dyn_cast<CXXNewExpr>(S)) {
1449
817
    return getCXXAllocatorCall(NE, State, LC);
1450
19.7k
  } else if (const auto *ME = dyn_cast<ObjCMessageExpr>(S)) {
1451
1.76k
    return getObjCMethodCall(ME, State, LC);
1452
18.0k
  } else {
1453
18.0k
    return nullptr;
1454
18.0k
  }
1455
84.2k
}