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