CallEvent.cpp revision 651f13cea278ec967336033dd032faef0e9fc2ec
1//===- Calls.cpp - Wrapper for all function and method calls ------*- 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/// \file This file defines CallEvent and its subclasses, which represent path-
11/// sensitive instances of different kinds of function and method calls
12/// (C, C++, and Objective-C).
13//
14//===----------------------------------------------------------------------===//
15
16#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
17#include "clang/AST/ParentMap.h"
18#include "clang/Analysis/ProgramPoint.h"
19#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
20#include "llvm/ADT/SmallSet.h"
21#include "llvm/ADT/StringExtras.h"
22#include "llvm/Support/raw_ostream.h"
23
24using namespace clang;
25using namespace ento;
26
27QualType CallEvent::getResultType() const {
28  const Expr *E = getOriginExpr();
29  assert(E && "Calls without origin expressions do not have results");
30  QualType ResultTy = E->getType();
31
32  ASTContext &Ctx = getState()->getStateManager().getContext();
33
34  // A function that returns a reference to 'int' will have a result type
35  // of simply 'int'. Check the origin expr's value kind to recover the
36  // proper type.
37  switch (E->getValueKind()) {
38  case VK_LValue:
39    ResultTy = Ctx.getLValueReferenceType(ResultTy);
40    break;
41  case VK_XValue:
42    ResultTy = Ctx.getRValueReferenceType(ResultTy);
43    break;
44  case VK_RValue:
45    // No adjustment is necessary.
46    break;
47  }
48
49  return ResultTy;
50}
51
52static bool isCallbackArg(SVal V, QualType T) {
53  // If the parameter is 0, it's harmless.
54  if (V.isZeroConstant())
55    return false;
56
57  // If a parameter is a block or a callback, assume it can modify pointer.
58  if (T->isBlockPointerType() ||
59      T->isFunctionPointerType() ||
60      T->isObjCSelType())
61    return true;
62
63  // Check if a callback is passed inside a struct (for both, struct passed by
64  // reference and by value). Dig just one level into the struct for now.
65
66  if (T->isAnyPointerType() || T->isReferenceType())
67    T = T->getPointeeType();
68
69  if (const RecordType *RT = T->getAsStructureType()) {
70    const RecordDecl *RD = RT->getDecl();
71    for (const auto *I : RD->fields()) {
72      QualType FieldT = I->getType();
73      if (FieldT->isBlockPointerType() || FieldT->isFunctionPointerType())
74        return true;
75    }
76  }
77
78  return false;
79}
80
81bool CallEvent::hasNonZeroCallbackArg() const {
82  unsigned NumOfArgs = getNumArgs();
83
84  // If calling using a function pointer, assume the function does not
85  // have a callback. TODO: We could check the types of the arguments here.
86  if (!getDecl())
87    return false;
88
89  unsigned Idx = 0;
90  for (CallEvent::param_type_iterator I = param_type_begin(),
91                                       E = param_type_end();
92       I != E && Idx < NumOfArgs; ++I, ++Idx) {
93    if (NumOfArgs <= Idx)
94      break;
95
96    if (isCallbackArg(getArgSVal(Idx), *I))
97      return true;
98  }
99
100  return false;
101}
102
103bool CallEvent::isGlobalCFunction(StringRef FunctionName) const {
104  const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(getDecl());
105  if (!FD)
106    return false;
107
108  return CheckerContext::isCLibraryFunction(FD, FunctionName);
109}
110
111/// \brief Returns true if a type is a pointer-to-const or reference-to-const
112/// with no further indirection.
113static bool isPointerToConst(QualType Ty) {
114  QualType PointeeTy = Ty->getPointeeType();
115  if (PointeeTy == QualType())
116    return false;
117  if (!PointeeTy.isConstQualified())
118    return false;
119  if (PointeeTy->isAnyPointerType())
120    return false;
121  return true;
122}
123
124// Try to retrieve the function declaration and find the function parameter
125// types which are pointers/references to a non-pointer const.
126// We will not invalidate the corresponding argument regions.
127static void findPtrToConstParams(llvm::SmallSet<unsigned, 4> &PreserveArgs,
128                                 const CallEvent &Call) {
129  unsigned Idx = 0;
130  for (CallEvent::param_type_iterator I = Call.param_type_begin(),
131                                      E = Call.param_type_end();
132       I != E; ++I, ++Idx) {
133    if (isPointerToConst(*I))
134      PreserveArgs.insert(Idx);
135  }
136}
137
138ProgramStateRef CallEvent::invalidateRegions(unsigned BlockCount,
139                                             ProgramStateRef Orig) const {
140  ProgramStateRef Result = (Orig ? Orig : getState());
141
142  SmallVector<SVal, 8> ValuesToInvalidate;
143  RegionAndSymbolInvalidationTraits ETraits;
144
145  getExtraInvalidatedValues(ValuesToInvalidate);
146
147  // Indexes of arguments whose values will be preserved by the call.
148  llvm::SmallSet<unsigned, 4> PreserveArgs;
149  if (!argumentsMayEscape())
150    findPtrToConstParams(PreserveArgs, *this);
151
152  for (unsigned Idx = 0, Count = getNumArgs(); Idx != Count; ++Idx) {
153    // Mark this region for invalidation.  We batch invalidate regions
154    // below for efficiency.
155    if (PreserveArgs.count(Idx))
156      if (const MemRegion *MR = getArgSVal(Idx).getAsRegion())
157        ETraits.setTrait(MR->StripCasts(),
158                        RegionAndSymbolInvalidationTraits::TK_PreserveContents);
159        // TODO: Factor this out + handle the lower level const pointers.
160
161    ValuesToInvalidate.push_back(getArgSVal(Idx));
162  }
163
164  // Invalidate designated regions using the batch invalidation API.
165  // NOTE: Even if RegionsToInvalidate is empty, we may still invalidate
166  //  global variables.
167  return Result->invalidateRegions(ValuesToInvalidate, getOriginExpr(),
168                                   BlockCount, getLocationContext(),
169                                   /*CausedByPointerEscape*/ true,
170                                   /*Symbols=*/0, this, &ETraits);
171}
172
173ProgramPoint CallEvent::getProgramPoint(bool IsPreVisit,
174                                        const ProgramPointTag *Tag) const {
175  if (const Expr *E = getOriginExpr()) {
176    if (IsPreVisit)
177      return PreStmt(E, getLocationContext(), Tag);
178    return PostStmt(E, getLocationContext(), Tag);
179  }
180
181  const Decl *D = getDecl();
182  assert(D && "Cannot get a program point without a statement or decl");
183
184  SourceLocation Loc = getSourceRange().getBegin();
185  if (IsPreVisit)
186    return PreImplicitCall(D, Loc, getLocationContext(), Tag);
187  return PostImplicitCall(D, Loc, getLocationContext(), Tag);
188}
189
190SVal CallEvent::getArgSVal(unsigned Index) const {
191  const Expr *ArgE = getArgExpr(Index);
192  if (!ArgE)
193    return UnknownVal();
194  return getSVal(ArgE);
195}
196
197SourceRange CallEvent::getArgSourceRange(unsigned Index) const {
198  const Expr *ArgE = getArgExpr(Index);
199  if (!ArgE)
200    return SourceRange();
201  return ArgE->getSourceRange();
202}
203
204SVal CallEvent::getReturnValue() const {
205  const Expr *E = getOriginExpr();
206  if (!E)
207    return UndefinedVal();
208  return getSVal(E);
209}
210
211LLVM_DUMP_METHOD void CallEvent::dump() const { dump(llvm::errs()); }
212
213void CallEvent::dump(raw_ostream &Out) const {
214  ASTContext &Ctx = getState()->getStateManager().getContext();
215  if (const Expr *E = getOriginExpr()) {
216    E->printPretty(Out, 0, Ctx.getPrintingPolicy());
217    Out << "\n";
218    return;
219  }
220
221  if (const Decl *D = getDecl()) {
222    Out << "Call to ";
223    D->print(Out, Ctx.getPrintingPolicy());
224    return;
225  }
226
227  // FIXME: a string representation of the kind would be nice.
228  Out << "Unknown call (type " << getKind() << ")";
229}
230
231
232bool CallEvent::isCallStmt(const Stmt *S) {
233  return isa<CallExpr>(S) || isa<ObjCMessageExpr>(S)
234                          || isa<CXXConstructExpr>(S)
235                          || isa<CXXNewExpr>(S);
236}
237
238QualType CallEvent::getDeclaredResultType(const Decl *D) {
239  assert(D);
240  if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(D))
241    return FD->getReturnType();
242  if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(D))
243    return MD->getReturnType();
244  if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
245    // Blocks are difficult because the return type may not be stored in the
246    // BlockDecl itself. The AST should probably be enhanced, but for now we
247    // just do what we can.
248    // If the block is declared without an explicit argument list, the
249    // signature-as-written just includes the return type, not the entire
250    // function type.
251    // FIXME: All blocks should have signatures-as-written, even if the return
252    // type is inferred. (That's signified with a dependent result type.)
253    if (const TypeSourceInfo *TSI = BD->getSignatureAsWritten()) {
254      QualType Ty = TSI->getType();
255      if (const FunctionType *FT = Ty->getAs<FunctionType>())
256        Ty = FT->getReturnType();
257      if (!Ty->isDependentType())
258        return Ty;
259    }
260
261    return QualType();
262  }
263
264  llvm_unreachable("unknown callable kind");
265}
266
267bool CallEvent::isVariadic(const Decl *D) {
268  assert(D);
269
270  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
271    return FD->isVariadic();
272  if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
273    return MD->isVariadic();
274  if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
275    return BD->isVariadic();
276
277  llvm_unreachable("unknown callable kind");
278}
279
280static void addParameterValuesToBindings(const StackFrameContext *CalleeCtx,
281                                         CallEvent::BindingsTy &Bindings,
282                                         SValBuilder &SVB,
283                                         const CallEvent &Call,
284                                         ArrayRef<ParmVarDecl*> parameters) {
285  MemRegionManager &MRMgr = SVB.getRegionManager();
286
287  // If the function has fewer parameters than the call has arguments, we simply
288  // do not bind any values to them.
289  unsigned NumArgs = Call.getNumArgs();
290  unsigned Idx = 0;
291  ArrayRef<ParmVarDecl*>::iterator I = parameters.begin(), E = parameters.end();
292  for (; I != E && Idx < NumArgs; ++I, ++Idx) {
293    const ParmVarDecl *ParamDecl = *I;
294    assert(ParamDecl && "Formal parameter has no decl?");
295
296    SVal ArgVal = Call.getArgSVal(Idx);
297    if (!ArgVal.isUnknown()) {
298      Loc ParamLoc = SVB.makeLoc(MRMgr.getVarRegion(ParamDecl, CalleeCtx));
299      Bindings.push_back(std::make_pair(ParamLoc, ArgVal));
300    }
301  }
302
303  // FIXME: Variadic arguments are not handled at all right now.
304}
305
306ArrayRef<ParmVarDecl*> AnyFunctionCall::parameters() const {
307  const FunctionDecl *D = getDecl();
308  if (!D)
309    return llvm::ArrayRef<ParmVarDecl*>();
310  return D->parameters();
311}
312
313void AnyFunctionCall::getInitialStackFrameContents(
314                                        const StackFrameContext *CalleeCtx,
315                                        BindingsTy &Bindings) const {
316  const FunctionDecl *D = cast<FunctionDecl>(CalleeCtx->getDecl());
317  SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
318  addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this,
319                               D->parameters());
320}
321
322bool AnyFunctionCall::argumentsMayEscape() const {
323  if (hasNonZeroCallbackArg())
324    return true;
325
326  const FunctionDecl *D = getDecl();
327  if (!D)
328    return true;
329
330  const IdentifierInfo *II = D->getIdentifier();
331  if (!II)
332    return false;
333
334  // This set of "escaping" APIs is
335
336  // - 'int pthread_setspecific(ptheread_key k, const void *)' stores a
337  //   value into thread local storage. The value can later be retrieved with
338  //   'void *ptheread_getspecific(pthread_key)'. So even thought the
339  //   parameter is 'const void *', the region escapes through the call.
340  if (II->isStr("pthread_setspecific"))
341    return true;
342
343  // - xpc_connection_set_context stores a value which can be retrieved later
344  //   with xpc_connection_get_context.
345  if (II->isStr("xpc_connection_set_context"))
346    return true;
347
348  // - funopen - sets a buffer for future IO calls.
349  if (II->isStr("funopen"))
350    return true;
351
352  StringRef FName = II->getName();
353
354  // - CoreFoundation functions that end with "NoCopy" can free a passed-in
355  //   buffer even if it is const.
356  if (FName.endswith("NoCopy"))
357    return true;
358
359  // - NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
360  //   be deallocated by NSMapRemove.
361  if (FName.startswith("NS") && (FName.find("Insert") != StringRef::npos))
362    return true;
363
364  // - Many CF containers allow objects to escape through custom
365  //   allocators/deallocators upon container construction. (PR12101)
366  if (FName.startswith("CF") || FName.startswith("CG")) {
367    return StrInStrNoCase(FName, "InsertValue")  != StringRef::npos ||
368           StrInStrNoCase(FName, "AddValue")     != StringRef::npos ||
369           StrInStrNoCase(FName, "SetValue")     != StringRef::npos ||
370           StrInStrNoCase(FName, "WithData")     != StringRef::npos ||
371           StrInStrNoCase(FName, "AppendValue")  != StringRef::npos ||
372           StrInStrNoCase(FName, "SetAttribute") != StringRef::npos;
373  }
374
375  return false;
376}
377
378
379const FunctionDecl *SimpleFunctionCall::getDecl() const {
380  const FunctionDecl *D = getOriginExpr()->getDirectCallee();
381  if (D)
382    return D;
383
384  return getSVal(getOriginExpr()->getCallee()).getAsFunctionDecl();
385}
386
387
388const FunctionDecl *CXXInstanceCall::getDecl() const {
389  const CallExpr *CE = cast_or_null<CallExpr>(getOriginExpr());
390  if (!CE)
391    return AnyFunctionCall::getDecl();
392
393  const FunctionDecl *D = CE->getDirectCallee();
394  if (D)
395    return D;
396
397  return getSVal(CE->getCallee()).getAsFunctionDecl();
398}
399
400void CXXInstanceCall::getExtraInvalidatedValues(ValueList &Values) const {
401  Values.push_back(getCXXThisVal());
402}
403
404SVal CXXInstanceCall::getCXXThisVal() const {
405  const Expr *Base = getCXXThisExpr();
406  // FIXME: This doesn't handle an overloaded ->* operator.
407  if (!Base)
408    return UnknownVal();
409
410  SVal ThisVal = getSVal(Base);
411  assert(ThisVal.isUnknownOrUndef() || ThisVal.getAs<Loc>());
412  return ThisVal;
413}
414
415
416RuntimeDefinition CXXInstanceCall::getRuntimeDefinition() const {
417  // Do we have a decl at all?
418  const Decl *D = getDecl();
419  if (!D)
420    return RuntimeDefinition();
421
422  // If the method is non-virtual, we know we can inline it.
423  const CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
424  if (!MD->isVirtual())
425    return AnyFunctionCall::getRuntimeDefinition();
426
427  // Do we know the implicit 'this' object being called?
428  const MemRegion *R = getCXXThisVal().getAsRegion();
429  if (!R)
430    return RuntimeDefinition();
431
432  // Do we know anything about the type of 'this'?
433  DynamicTypeInfo DynType = getState()->getDynamicTypeInfo(R);
434  if (!DynType.isValid())
435    return RuntimeDefinition();
436
437  // Is the type a C++ class? (This is mostly a defensive check.)
438  QualType RegionType = DynType.getType()->getPointeeType();
439  assert(!RegionType.isNull() && "DynamicTypeInfo should always be a pointer.");
440
441  const CXXRecordDecl *RD = RegionType->getAsCXXRecordDecl();
442  if (!RD || !RD->hasDefinition())
443    return RuntimeDefinition();
444
445  // Find the decl for this method in that class.
446  const CXXMethodDecl *Result = MD->getCorrespondingMethodInClass(RD, true);
447  if (!Result) {
448    // We might not even get the original statically-resolved method due to
449    // some particularly nasty casting (e.g. casts to sister classes).
450    // However, we should at least be able to search up and down our own class
451    // hierarchy, and some real bugs have been caught by checking this.
452    assert(!RD->isDerivedFrom(MD->getParent()) && "Couldn't find known method");
453
454    // FIXME: This is checking that our DynamicTypeInfo is at least as good as
455    // the static type. However, because we currently don't update
456    // DynamicTypeInfo when an object is cast, we can't actually be sure the
457    // DynamicTypeInfo is up to date. This assert should be re-enabled once
458    // this is fixed. <rdar://problem/12287087>
459    //assert(!MD->getParent()->isDerivedFrom(RD) && "Bad DynamicTypeInfo");
460
461    return RuntimeDefinition();
462  }
463
464  // Does the decl that we found have an implementation?
465  const FunctionDecl *Definition;
466  if (!Result->hasBody(Definition))
467    return RuntimeDefinition();
468
469  // We found a definition. If we're not sure that this devirtualization is
470  // actually what will happen at runtime, make sure to provide the region so
471  // that ExprEngine can decide what to do with it.
472  if (DynType.canBeASubClass())
473    return RuntimeDefinition(Definition, R->StripCasts());
474  return RuntimeDefinition(Definition, /*DispatchRegion=*/0);
475}
476
477void CXXInstanceCall::getInitialStackFrameContents(
478                                            const StackFrameContext *CalleeCtx,
479                                            BindingsTy &Bindings) const {
480  AnyFunctionCall::getInitialStackFrameContents(CalleeCtx, Bindings);
481
482  // Handle the binding of 'this' in the new stack frame.
483  SVal ThisVal = getCXXThisVal();
484  if (!ThisVal.isUnknown()) {
485    ProgramStateManager &StateMgr = getState()->getStateManager();
486    SValBuilder &SVB = StateMgr.getSValBuilder();
487
488    const CXXMethodDecl *MD = cast<CXXMethodDecl>(CalleeCtx->getDecl());
489    Loc ThisLoc = SVB.getCXXThis(MD, CalleeCtx);
490
491    // If we devirtualized to a different member function, we need to make sure
492    // we have the proper layering of CXXBaseObjectRegions.
493    if (MD->getCanonicalDecl() != getDecl()->getCanonicalDecl()) {
494      ASTContext &Ctx = SVB.getContext();
495      const CXXRecordDecl *Class = MD->getParent();
496      QualType Ty = Ctx.getPointerType(Ctx.getRecordType(Class));
497
498      // FIXME: CallEvent maybe shouldn't be directly accessing StoreManager.
499      bool Failed;
500      ThisVal = StateMgr.getStoreManager().evalDynamicCast(ThisVal, Ty, Failed);
501      assert(!Failed && "Calling an incorrectly devirtualized method");
502    }
503
504    if (!ThisVal.isUnknown())
505      Bindings.push_back(std::make_pair(ThisLoc, ThisVal));
506  }
507}
508
509
510
511const Expr *CXXMemberCall::getCXXThisExpr() const {
512  return getOriginExpr()->getImplicitObjectArgument();
513}
514
515RuntimeDefinition CXXMemberCall::getRuntimeDefinition() const {
516  // C++11 [expr.call]p1: ...If the selected function is non-virtual, or if the
517  // id-expression in the class member access expression is a qualified-id,
518  // that function is called. Otherwise, its final overrider in the dynamic type
519  // of the object expression is called.
520  if (const MemberExpr *ME = dyn_cast<MemberExpr>(getOriginExpr()->getCallee()))
521    if (ME->hasQualifier())
522      return AnyFunctionCall::getRuntimeDefinition();
523
524  return CXXInstanceCall::getRuntimeDefinition();
525}
526
527
528const Expr *CXXMemberOperatorCall::getCXXThisExpr() const {
529  return getOriginExpr()->getArg(0);
530}
531
532
533const BlockDataRegion *BlockCall::getBlockRegion() const {
534  const Expr *Callee = getOriginExpr()->getCallee();
535  const MemRegion *DataReg = getSVal(Callee).getAsRegion();
536
537  return dyn_cast_or_null<BlockDataRegion>(DataReg);
538}
539
540ArrayRef<ParmVarDecl*> BlockCall::parameters() const {
541  const BlockDecl *D = getDecl();
542  if (!D)
543    return 0;
544  return D->parameters();
545}
546
547void BlockCall::getExtraInvalidatedValues(ValueList &Values) const {
548  // FIXME: This also needs to invalidate captured globals.
549  if (const MemRegion *R = getBlockRegion())
550    Values.push_back(loc::MemRegionVal(R));
551}
552
553void BlockCall::getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
554                                             BindingsTy &Bindings) const {
555  const BlockDecl *D = cast<BlockDecl>(CalleeCtx->getDecl());
556  SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
557  addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this,
558                               D->parameters());
559}
560
561
562SVal CXXConstructorCall::getCXXThisVal() const {
563  if (Data)
564    return loc::MemRegionVal(static_cast<const MemRegion *>(Data));
565  return UnknownVal();
566}
567
568void CXXConstructorCall::getExtraInvalidatedValues(ValueList &Values) const {
569  if (Data)
570    Values.push_back(loc::MemRegionVal(static_cast<const MemRegion *>(Data)));
571}
572
573void CXXConstructorCall::getInitialStackFrameContents(
574                                             const StackFrameContext *CalleeCtx,
575                                             BindingsTy &Bindings) const {
576  AnyFunctionCall::getInitialStackFrameContents(CalleeCtx, Bindings);
577
578  SVal ThisVal = getCXXThisVal();
579  if (!ThisVal.isUnknown()) {
580    SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
581    const CXXMethodDecl *MD = cast<CXXMethodDecl>(CalleeCtx->getDecl());
582    Loc ThisLoc = SVB.getCXXThis(MD, CalleeCtx);
583    Bindings.push_back(std::make_pair(ThisLoc, ThisVal));
584  }
585}
586
587SVal CXXDestructorCall::getCXXThisVal() const {
588  if (Data)
589    return loc::MemRegionVal(DtorDataTy::getFromOpaqueValue(Data).getPointer());
590  return UnknownVal();
591}
592
593RuntimeDefinition CXXDestructorCall::getRuntimeDefinition() const {
594  // Base destructors are always called non-virtually.
595  // Skip CXXInstanceCall's devirtualization logic in this case.
596  if (isBaseDestructor())
597    return AnyFunctionCall::getRuntimeDefinition();
598
599  return CXXInstanceCall::getRuntimeDefinition();
600}
601
602ArrayRef<ParmVarDecl*> ObjCMethodCall::parameters() const {
603  const ObjCMethodDecl *D = getDecl();
604  if (!D)
605    return ArrayRef<ParmVarDecl*>();
606  return D->parameters();
607}
608
609void
610ObjCMethodCall::getExtraInvalidatedValues(ValueList &Values) const {
611  Values.push_back(getReceiverSVal());
612}
613
614SVal ObjCMethodCall::getSelfSVal() const {
615  const LocationContext *LCtx = getLocationContext();
616  const ImplicitParamDecl *SelfDecl = LCtx->getSelfDecl();
617  if (!SelfDecl)
618    return SVal();
619  return getState()->getSVal(getState()->getRegion(SelfDecl, LCtx));
620}
621
622SVal ObjCMethodCall::getReceiverSVal() const {
623  // FIXME: Is this the best way to handle class receivers?
624  if (!isInstanceMessage())
625    return UnknownVal();
626
627  if (const Expr *RecE = getOriginExpr()->getInstanceReceiver())
628    return getSVal(RecE);
629
630  // An instance message with no expression means we are sending to super.
631  // In this case the object reference is the same as 'self'.
632  assert(getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperInstance);
633  SVal SelfVal = getSelfSVal();
634  assert(SelfVal.isValid() && "Calling super but not in ObjC method");
635  return SelfVal;
636}
637
638bool ObjCMethodCall::isReceiverSelfOrSuper() const {
639  if (getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperInstance ||
640      getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperClass)
641      return true;
642
643  if (!isInstanceMessage())
644    return false;
645
646  SVal RecVal = getSVal(getOriginExpr()->getInstanceReceiver());
647
648  return (RecVal == getSelfSVal());
649}
650
651SourceRange ObjCMethodCall::getSourceRange() const {
652  switch (getMessageKind()) {
653  case OCM_Message:
654    return getOriginExpr()->getSourceRange();
655  case OCM_PropertyAccess:
656  case OCM_Subscript:
657    return getContainingPseudoObjectExpr()->getSourceRange();
658  }
659  llvm_unreachable("unknown message kind");
660}
661
662typedef llvm::PointerIntPair<const PseudoObjectExpr *, 2> ObjCMessageDataTy;
663
664const PseudoObjectExpr *ObjCMethodCall::getContainingPseudoObjectExpr() const {
665  assert(Data != 0 && "Lazy lookup not yet performed.");
666  assert(getMessageKind() != OCM_Message && "Explicit message send.");
667  return ObjCMessageDataTy::getFromOpaqueValue(Data).getPointer();
668}
669
670ObjCMessageKind ObjCMethodCall::getMessageKind() const {
671  if (Data == 0) {
672
673    // Find the parent, ignoring implicit casts.
674    ParentMap &PM = getLocationContext()->getParentMap();
675    const Stmt *S = PM.getParentIgnoreParenCasts(getOriginExpr());
676
677    // Check if parent is a PseudoObjectExpr.
678    if (const PseudoObjectExpr *POE = dyn_cast_or_null<PseudoObjectExpr>(S)) {
679      const Expr *Syntactic = POE->getSyntacticForm();
680
681      // This handles the funny case of assigning to the result of a getter.
682      // This can happen if the getter returns a non-const reference.
683      if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(Syntactic))
684        Syntactic = BO->getLHS();
685
686      ObjCMessageKind K;
687      switch (Syntactic->getStmtClass()) {
688      case Stmt::ObjCPropertyRefExprClass:
689        K = OCM_PropertyAccess;
690        break;
691      case Stmt::ObjCSubscriptRefExprClass:
692        K = OCM_Subscript;
693        break;
694      default:
695        // FIXME: Can this ever happen?
696        K = OCM_Message;
697        break;
698      }
699
700      if (K != OCM_Message) {
701        const_cast<ObjCMethodCall *>(this)->Data
702          = ObjCMessageDataTy(POE, K).getOpaqueValue();
703        assert(getMessageKind() == K);
704        return K;
705      }
706    }
707
708    const_cast<ObjCMethodCall *>(this)->Data
709      = ObjCMessageDataTy(0, 1).getOpaqueValue();
710    assert(getMessageKind() == OCM_Message);
711    return OCM_Message;
712  }
713
714  ObjCMessageDataTy Info = ObjCMessageDataTy::getFromOpaqueValue(Data);
715  if (!Info.getPointer())
716    return OCM_Message;
717  return static_cast<ObjCMessageKind>(Info.getInt());
718}
719
720
721bool ObjCMethodCall::canBeOverridenInSubclass(ObjCInterfaceDecl *IDecl,
722                                             Selector Sel) const {
723  assert(IDecl);
724  const SourceManager &SM =
725    getState()->getStateManager().getContext().getSourceManager();
726
727  // If the class interface is declared inside the main file, assume it is not
728  // subcassed.
729  // TODO: It could actually be subclassed if the subclass is private as well.
730  // This is probably very rare.
731  SourceLocation InterfLoc = IDecl->getEndOfDefinitionLoc();
732  if (InterfLoc.isValid() && SM.isInMainFile(InterfLoc))
733    return false;
734
735  // Assume that property accessors are not overridden.
736  if (getMessageKind() == OCM_PropertyAccess)
737    return false;
738
739  // We assume that if the method is public (declared outside of main file) or
740  // has a parent which publicly declares the method, the method could be
741  // overridden in a subclass.
742
743  // Find the first declaration in the class hierarchy that declares
744  // the selector.
745  ObjCMethodDecl *D = 0;
746  while (true) {
747    D = IDecl->lookupMethod(Sel, true);
748
749    // Cannot find a public definition.
750    if (!D)
751      return false;
752
753    // If outside the main file,
754    if (D->getLocation().isValid() && !SM.isInMainFile(D->getLocation()))
755      return true;
756
757    if (D->isOverriding()) {
758      // Search in the superclass on the next iteration.
759      IDecl = D->getClassInterface();
760      if (!IDecl)
761        return false;
762
763      IDecl = IDecl->getSuperClass();
764      if (!IDecl)
765        return false;
766
767      continue;
768    }
769
770    return false;
771  };
772
773  llvm_unreachable("The while loop should always terminate.");
774}
775
776RuntimeDefinition ObjCMethodCall::getRuntimeDefinition() const {
777  const ObjCMessageExpr *E = getOriginExpr();
778  assert(E);
779  Selector Sel = E->getSelector();
780
781  if (E->isInstanceMessage()) {
782
783    // Find the the receiver type.
784    const ObjCObjectPointerType *ReceiverT = 0;
785    bool CanBeSubClassed = false;
786    QualType SupersType = E->getSuperType();
787    const MemRegion *Receiver = 0;
788
789    if (!SupersType.isNull()) {
790      // Super always means the type of immediate predecessor to the method
791      // where the call occurs.
792      ReceiverT = cast<ObjCObjectPointerType>(SupersType);
793    } else {
794      Receiver = getReceiverSVal().getAsRegion();
795      if (!Receiver)
796        return RuntimeDefinition();
797
798      DynamicTypeInfo DTI = getState()->getDynamicTypeInfo(Receiver);
799      QualType DynType = DTI.getType();
800      CanBeSubClassed = DTI.canBeASubClass();
801      ReceiverT = dyn_cast<ObjCObjectPointerType>(DynType);
802
803      if (ReceiverT && CanBeSubClassed)
804        if (ObjCInterfaceDecl *IDecl = ReceiverT->getInterfaceDecl())
805          if (!canBeOverridenInSubclass(IDecl, Sel))
806            CanBeSubClassed = false;
807    }
808
809    // Lookup the method implementation.
810    if (ReceiverT)
811      if (ObjCInterfaceDecl *IDecl = ReceiverT->getInterfaceDecl()) {
812        // Repeatedly calling lookupPrivateMethod() is expensive, especially
813        // when in many cases it returns null.  We cache the results so
814        // that repeated queries on the same ObjCIntefaceDecl and Selector
815        // don't incur the same cost.  On some test cases, we can see the
816        // same query being issued thousands of times.
817        //
818        // NOTE: This cache is essentially a "global" variable, but it
819        // only gets lazily created when we get here.  The value of the
820        // cache probably comes from it being global across ExprEngines,
821        // where the same queries may get issued.  If we are worried about
822        // concurrency, or possibly loading/unloading ASTs, etc., we may
823        // need to revisit this someday.  In terms of memory, this table
824        // stays around until clang quits, which also may be bad if we
825        // need to release memory.
826        typedef std::pair<const ObjCInterfaceDecl*, Selector>
827                PrivateMethodKey;
828        typedef llvm::DenseMap<PrivateMethodKey,
829                               Optional<const ObjCMethodDecl *> >
830                PrivateMethodCache;
831
832        static PrivateMethodCache PMC;
833        Optional<const ObjCMethodDecl *> &Val = PMC[std::make_pair(IDecl, Sel)];
834
835        // Query lookupPrivateMethod() if the cache does not hit.
836        if (!Val.hasValue()) {
837          Val = IDecl->lookupPrivateMethod(Sel);
838
839          // If the method is a property accessor, we should try to "inline" it
840          // even if we don't actually have an implementation.
841          if (!*Val)
842            if (const ObjCMethodDecl *CompileTimeMD = E->getMethodDecl())
843              if (CompileTimeMD->isPropertyAccessor())
844                Val = IDecl->lookupInstanceMethod(Sel);
845        }
846
847        const ObjCMethodDecl *MD = Val.getValue();
848        if (CanBeSubClassed)
849          return RuntimeDefinition(MD, Receiver);
850        else
851          return RuntimeDefinition(MD, 0);
852      }
853
854  } else {
855    // This is a class method.
856    // If we have type info for the receiver class, we are calling via
857    // class name.
858    if (ObjCInterfaceDecl *IDecl = E->getReceiverInterface()) {
859      // Find/Return the method implementation.
860      return RuntimeDefinition(IDecl->lookupPrivateClassMethod(Sel));
861    }
862  }
863
864  return RuntimeDefinition();
865}
866
867bool ObjCMethodCall::argumentsMayEscape() const {
868  if (isInSystemHeader() && !isInstanceMessage()) {
869    Selector Sel = getSelector();
870    if (Sel.getNumArgs() == 1 &&
871        Sel.getIdentifierInfoForSlot(0)->isStr("valueWithPointer"))
872      return true;
873  }
874
875  return CallEvent::argumentsMayEscape();
876}
877
878void ObjCMethodCall::getInitialStackFrameContents(
879                                             const StackFrameContext *CalleeCtx,
880                                             BindingsTy &Bindings) const {
881  const ObjCMethodDecl *D = cast<ObjCMethodDecl>(CalleeCtx->getDecl());
882  SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
883  addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this,
884                               D->parameters());
885
886  SVal SelfVal = getReceiverSVal();
887  if (!SelfVal.isUnknown()) {
888    const VarDecl *SelfD = CalleeCtx->getAnalysisDeclContext()->getSelfDecl();
889    MemRegionManager &MRMgr = SVB.getRegionManager();
890    Loc SelfLoc = SVB.makeLoc(MRMgr.getVarRegion(SelfD, CalleeCtx));
891    Bindings.push_back(std::make_pair(SelfLoc, SelfVal));
892  }
893}
894
895CallEventRef<>
896CallEventManager::getSimpleCall(const CallExpr *CE, ProgramStateRef State,
897                                const LocationContext *LCtx) {
898  if (const CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(CE))
899    return create<CXXMemberCall>(MCE, State, LCtx);
900
901  if (const CXXOperatorCallExpr *OpCE = dyn_cast<CXXOperatorCallExpr>(CE)) {
902    const FunctionDecl *DirectCallee = OpCE->getDirectCallee();
903    if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DirectCallee))
904      if (MD->isInstance())
905        return create<CXXMemberOperatorCall>(OpCE, State, LCtx);
906
907  } else if (CE->getCallee()->getType()->isBlockPointerType()) {
908    return create<BlockCall>(CE, State, LCtx);
909  }
910
911  // Otherwise, it's a normal function call, static member function call, or
912  // something we can't reason about.
913  return create<SimpleFunctionCall>(CE, State, LCtx);
914}
915
916
917CallEventRef<>
918CallEventManager::getCaller(const StackFrameContext *CalleeCtx,
919                            ProgramStateRef State) {
920  const LocationContext *ParentCtx = CalleeCtx->getParent();
921  const LocationContext *CallerCtx = ParentCtx->getCurrentStackFrame();
922  assert(CallerCtx && "This should not be used for top-level stack frames");
923
924  const Stmt *CallSite = CalleeCtx->getCallSite();
925
926  if (CallSite) {
927    if (const CallExpr *CE = dyn_cast<CallExpr>(CallSite))
928      return getSimpleCall(CE, State, CallerCtx);
929
930    switch (CallSite->getStmtClass()) {
931    case Stmt::CXXConstructExprClass:
932    case Stmt::CXXTemporaryObjectExprClass: {
933      SValBuilder &SVB = State->getStateManager().getSValBuilder();
934      const CXXMethodDecl *Ctor = cast<CXXMethodDecl>(CalleeCtx->getDecl());
935      Loc ThisPtr = SVB.getCXXThis(Ctor, CalleeCtx);
936      SVal ThisVal = State->getSVal(ThisPtr);
937
938      return getCXXConstructorCall(cast<CXXConstructExpr>(CallSite),
939                                   ThisVal.getAsRegion(), State, CallerCtx);
940    }
941    case Stmt::CXXNewExprClass:
942      return getCXXAllocatorCall(cast<CXXNewExpr>(CallSite), State, CallerCtx);
943    case Stmt::ObjCMessageExprClass:
944      return getObjCMethodCall(cast<ObjCMessageExpr>(CallSite),
945                               State, CallerCtx);
946    default:
947      llvm_unreachable("This is not an inlineable statement.");
948    }
949  }
950
951  // Fall back to the CFG. The only thing we haven't handled yet is
952  // destructors, though this could change in the future.
953  const CFGBlock *B = CalleeCtx->getCallSiteBlock();
954  CFGElement E = (*B)[CalleeCtx->getIndex()];
955  assert(E.getAs<CFGImplicitDtor>() &&
956         "All other CFG elements should have exprs");
957  assert(!E.getAs<CFGTemporaryDtor>() && "We don't handle temporaries yet");
958
959  SValBuilder &SVB = State->getStateManager().getSValBuilder();
960  const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CalleeCtx->getDecl());
961  Loc ThisPtr = SVB.getCXXThis(Dtor, CalleeCtx);
962  SVal ThisVal = State->getSVal(ThisPtr);
963
964  const Stmt *Trigger;
965  if (Optional<CFGAutomaticObjDtor> AutoDtor = E.getAs<CFGAutomaticObjDtor>())
966    Trigger = AutoDtor->getTriggerStmt();
967  else if (Optional<CFGDeleteDtor> DeleteDtor = E.getAs<CFGDeleteDtor>())
968    Trigger = cast<Stmt>(DeleteDtor->getDeleteExpr());
969  else
970    Trigger = Dtor->getBody();
971
972  return getCXXDestructorCall(Dtor, Trigger, ThisVal.getAsRegion(),
973                              E.getAs<CFGBaseDtor>().hasValue(), State,
974                              CallerCtx);
975}
976