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