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 
22 using namespace clang;
23 using namespace ento;
24 
25 QualType 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 
50 static 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 
80 bool 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.
104 static 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.
118 static 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 
129 ProgramStateRef 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 
195 ProgramPoint 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 
212 SVal CallEvent::getArgSVal(unsigned Index) const {
213   const Expr *ArgE = getArgExpr(Index);
214   if (!ArgE)
215     return UnknownVal();
216   return getSVal(ArgE);
217 }
218 
219 SourceRange CallEvent::getArgSourceRange(unsigned Index) const {
220   const Expr *ArgE = getArgExpr(Index);
221   if (!ArgE)
222     return SourceRange();
223   return ArgE->getSourceRange();
224 }
225 
226 void CallEvent::dump() const {
227   dump(llvm::errs());
228 }
229 
230 void 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 
249 bool CallEvent::isCallStmt(const Stmt *S) {
250   return isa<CallExpr>(S) || isa<ObjCMessageExpr>(S)
251                           || isa<CXXConstructExpr>(S)
252                           || isa<CXXNewExpr>(S);
253 }
254 
255 /// \brief Returns the result type, adjusted for references.
256 QualType CallEvent::getDeclaredResultType(const Decl *D) {
257   assert(D);
258   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(D))
259     return FD->getResultType();
260   else if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(D))
261     return MD->getResultType();
262   return QualType();
263 }
264 
265 static void addParameterValuesToBindings(const StackFrameContext *CalleeCtx,
266                                          CallEvent::BindingsTy &Bindings,
267                                          SValBuilder &SVB,
268                                          const CallEvent &Call,
269                                          CallEvent::param_iterator I,
270                                          CallEvent::param_iterator E) {
271   MemRegionManager &MRMgr = SVB.getRegionManager();
272 
273   unsigned Idx = 0;
274   for (; I != E; ++I, ++Idx) {
275     const ParmVarDecl *ParamDecl = *I;
276     assert(ParamDecl && "Formal parameter has no decl?");
277 
278     SVal ArgVal = Call.getArgSVal(Idx);
279     if (!ArgVal.isUnknown()) {
280       Loc ParamLoc = SVB.makeLoc(MRMgr.getVarRegion(ParamDecl, CalleeCtx));
281       Bindings.push_back(std::make_pair(ParamLoc, ArgVal));
282     }
283   }
284 
285   // FIXME: Variadic arguments are not handled at all right now.
286 }
287 
288 
289 CallEvent::param_iterator AnyFunctionCall::param_begin() const {
290   const FunctionDecl *D = getDecl();
291   if (!D)
292     return 0;
293 
294   return D->param_begin();
295 }
296 
297 CallEvent::param_iterator AnyFunctionCall::param_end() const {
298   const FunctionDecl *D = getDecl();
299   if (!D)
300     return 0;
301 
302   return D->param_end();
303 }
304 
305 void AnyFunctionCall::getInitialStackFrameContents(
306                                         const StackFrameContext *CalleeCtx,
307                                         BindingsTy &Bindings) const {
308   const FunctionDecl *D = cast<FunctionDecl>(CalleeCtx->getDecl());
309   SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
310   addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this,
311                                D->param_begin(), D->param_end());
312 }
313 
314 bool AnyFunctionCall::argumentsMayEscape() const {
315   if (hasNonZeroCallbackArg())
316     return true;
317 
318   const FunctionDecl *D = getDecl();
319   if (!D)
320     return true;
321 
322   const IdentifierInfo *II = D->getIdentifier();
323   if (!II)
324     return true;
325 
326   // This set of "escaping" APIs is
327 
328   // - 'int pthread_setspecific(ptheread_key k, const void *)' stores a
329   //   value into thread local storage. The value can later be retrieved with
330   //   'void *ptheread_getspecific(pthread_key)'. So even thought the
331   //   parameter is 'const void *', the region escapes through the call.
332   if (II->isStr("pthread_setspecific"))
333     return true;
334 
335   // - xpc_connection_set_context stores a value which can be retrieved later
336   //   with xpc_connection_get_context.
337   if (II->isStr("xpc_connection_set_context"))
338     return true;
339 
340   // - funopen - sets a buffer for future IO calls.
341   if (II->isStr("funopen"))
342     return true;
343 
344   StringRef FName = II->getName();
345 
346   // - CoreFoundation functions that end with "NoCopy" can free a passed-in
347   //   buffer even if it is const.
348   if (FName.endswith("NoCopy"))
349     return true;
350 
351   // - NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
352   //   be deallocated by NSMapRemove.
353   if (FName.startswith("NS") && (FName.find("Insert") != StringRef::npos))
354     return true;
355 
356   // - Many CF containers allow objects to escape through custom
357   //   allocators/deallocators upon container construction. (PR12101)
358   if (FName.startswith("CF") || FName.startswith("CG")) {
359     return StrInStrNoCase(FName, "InsertValue")  != StringRef::npos ||
360            StrInStrNoCase(FName, "AddValue")     != StringRef::npos ||
361            StrInStrNoCase(FName, "SetValue")     != StringRef::npos ||
362            StrInStrNoCase(FName, "WithData")     != StringRef::npos ||
363            StrInStrNoCase(FName, "AppendValue")  != StringRef::npos ||
364            StrInStrNoCase(FName, "SetAttribute") != StringRef::npos;
365   }
366 
367   return false;
368 }
369 
370 
371 const FunctionDecl *SimpleCall::getDecl() const {
372   const FunctionDecl *D = getOriginExpr()->getDirectCallee();
373   if (D)
374     return D;
375 
376   return getSVal(getOriginExpr()->getCallee()).getAsFunctionDecl();
377 }
378 
379 
380 const FunctionDecl *CXXInstanceCall::getDecl() const {
381   const CallExpr *CE = cast_or_null<CallExpr>(getOriginExpr());
382   if (!CE)
383     return AnyFunctionCall::getDecl();
384 
385   const FunctionDecl *D = CE->getDirectCallee();
386   if (D)
387     return D;
388 
389   return getSVal(CE->getCallee()).getAsFunctionDecl();
390 }
391 
392 void CXXInstanceCall::getExtraInvalidatedRegions(RegionList &Regions) const {
393   if (const MemRegion *R = getCXXThisVal().getAsRegion())
394     Regions.push_back(R);
395 }
396 
397 SVal CXXInstanceCall::getCXXThisVal() const {
398   const Expr *Base = getCXXThisExpr();
399   // FIXME: This doesn't handle an overloaded ->* operator.
400   if (!Base)
401     return UnknownVal();
402 
403   SVal ThisVal = getSVal(Base);
404   assert(ThisVal.isUnknownOrUndef() || isa<Loc>(ThisVal));
405   return ThisVal;
406 }
407 
408 
409 RuntimeDefinition CXXInstanceCall::getRuntimeDefinition() const {
410   // Do we have a decl at all?
411   const Decl *D = getDecl();
412   if (!D)
413     return RuntimeDefinition();
414 
415   // If the method is non-virtual, we know we can inline it.
416   const CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
417   if (!MD->isVirtual())
418     return AnyFunctionCall::getRuntimeDefinition();
419 
420   // Do we know the implicit 'this' object being called?
421   const MemRegion *R = getCXXThisVal().getAsRegion();
422   if (!R)
423     return RuntimeDefinition();
424 
425   // Do we know anything about the type of 'this'?
426   DynamicTypeInfo DynType = getState()->getDynamicTypeInfo(R);
427   if (!DynType.isValid())
428     return RuntimeDefinition();
429 
430   // Is the type a C++ class? (This is mostly a defensive check.)
431   QualType RegionType = DynType.getType()->getPointeeType();
432   assert(!RegionType.isNull() && "DynamicTypeInfo should always be a pointer.");
433 
434   const CXXRecordDecl *RD = RegionType->getAsCXXRecordDecl();
435   if (!RD || !RD->hasDefinition())
436     return RuntimeDefinition();
437 
438   // Find the decl for this method in that class.
439   const CXXMethodDecl *Result = MD->getCorrespondingMethodInClass(RD, true);
440   if (!Result) {
441     // We might not even get the original statically-resolved method due to
442     // some particularly nasty casting (e.g. casts to sister classes).
443     // However, we should at least be able to search up and down our own class
444     // hierarchy, and some real bugs have been caught by checking this.
445     assert(!RD->isDerivedFrom(MD->getParent()) && "Couldn't find known method");
446 
447     // FIXME: This is checking that our DynamicTypeInfo is at least as good as
448     // the static type. However, because we currently don't update
449     // DynamicTypeInfo when an object is cast, we can't actually be sure the
450     // DynamicTypeInfo is up to date. This assert should be re-enabled once
451     // this is fixed. <rdar://problem/12287087>
452     //assert(!MD->getParent()->isDerivedFrom(RD) && "Bad DynamicTypeInfo");
453 
454     return RuntimeDefinition();
455   }
456 
457   // Does the decl that we found have an implementation?
458   const FunctionDecl *Definition;
459   if (!Result->hasBody(Definition))
460     return RuntimeDefinition();
461 
462   // We found a definition. If we're not sure that this devirtualization is
463   // actually what will happen at runtime, make sure to provide the region so
464   // that ExprEngine can decide what to do with it.
465   if (DynType.canBeASubClass())
466     return RuntimeDefinition(Definition, R->StripCasts());
467   return RuntimeDefinition(Definition, /*DispatchRegion=*/0);
468 }
469 
470 void CXXInstanceCall::getInitialStackFrameContents(
471                                             const StackFrameContext *CalleeCtx,
472                                             BindingsTy &Bindings) const {
473   AnyFunctionCall::getInitialStackFrameContents(CalleeCtx, Bindings);
474 
475   // Handle the binding of 'this' in the new stack frame.
476   SVal ThisVal = getCXXThisVal();
477   if (!ThisVal.isUnknown()) {
478     ProgramStateManager &StateMgr = getState()->getStateManager();
479     SValBuilder &SVB = StateMgr.getSValBuilder();
480 
481     const CXXMethodDecl *MD = cast<CXXMethodDecl>(CalleeCtx->getDecl());
482     Loc ThisLoc = SVB.getCXXThis(MD, CalleeCtx);
483 
484     // If we devirtualized to a different member function, we need to make sure
485     // we have the proper layering of CXXBaseObjectRegions.
486     if (MD->getCanonicalDecl() != getDecl()->getCanonicalDecl()) {
487       ASTContext &Ctx = SVB.getContext();
488       const CXXRecordDecl *Class = MD->getParent();
489       QualType Ty = Ctx.getPointerType(Ctx.getRecordType(Class));
490 
491       // FIXME: CallEvent maybe shouldn't be directly accessing StoreManager.
492       bool Failed;
493       ThisVal = StateMgr.getStoreManager().evalDynamicCast(ThisVal, Ty, Failed);
494       assert(!Failed && "Calling an incorrectly devirtualized method");
495     }
496 
497     if (!ThisVal.isUnknown())
498       Bindings.push_back(std::make_pair(ThisLoc, ThisVal));
499   }
500 }
501 
502 
503 
504 const Expr *CXXMemberCall::getCXXThisExpr() const {
505   return getOriginExpr()->getImplicitObjectArgument();
506 }
507 
508 RuntimeDefinition CXXMemberCall::getRuntimeDefinition() const {
509   // C++11 [expr.call]p1: ...If the selected function is non-virtual, or if the
510   // id-expression in the class member access expression is a qualified-id,
511   // that function is called. Otherwise, its final overrider in the dynamic type
512   // of the object expression is called.
513   if (const MemberExpr *ME = dyn_cast<MemberExpr>(getOriginExpr()->getCallee()))
514     if (ME->hasQualifier())
515       return AnyFunctionCall::getRuntimeDefinition();
516 
517   return CXXInstanceCall::getRuntimeDefinition();
518 }
519 
520 
521 const Expr *CXXMemberOperatorCall::getCXXThisExpr() const {
522   return getOriginExpr()->getArg(0);
523 }
524 
525 
526 const BlockDataRegion *BlockCall::getBlockRegion() const {
527   const Expr *Callee = getOriginExpr()->getCallee();
528   const MemRegion *DataReg = getSVal(Callee).getAsRegion();
529 
530   return dyn_cast_or_null<BlockDataRegion>(DataReg);
531 }
532 
533 CallEvent::param_iterator BlockCall::param_begin() const {
534   const BlockDecl *D = getBlockDecl();
535   if (!D)
536     return 0;
537   return D->param_begin();
538 }
539 
540 CallEvent::param_iterator BlockCall::param_end() const {
541   const BlockDecl *D = getBlockDecl();
542   if (!D)
543     return 0;
544   return D->param_end();
545 }
546 
547 void BlockCall::getExtraInvalidatedRegions(RegionList &Regions) const {
548   // FIXME: This also needs to invalidate captured globals.
549   if (const MemRegion *R = getBlockRegion())
550     Regions.push_back(R);
551 }
552 
553 void 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->param_begin(), D->param_end());
559 }
560 
561 
562 SVal CXXConstructorCall::getCXXThisVal() const {
563   if (Data)
564     return loc::MemRegionVal(static_cast<const MemRegion *>(Data));
565   return UnknownVal();
566 }
567 
568 void CXXConstructorCall::getExtraInvalidatedRegions(RegionList &Regions) const {
569   if (Data)
570     Regions.push_back(static_cast<const MemRegion *>(Data));
571 }
572 
573 void 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 
587 
588 
589 SVal CXXDestructorCall::getCXXThisVal() const {
590   if (Data)
591     return loc::MemRegionVal(DtorDataTy::getFromOpaqueValue(Data).getPointer());
592   return UnknownVal();
593 }
594 
595 RuntimeDefinition CXXDestructorCall::getRuntimeDefinition() const {
596   // Base destructors are always called non-virtually.
597   // Skip CXXInstanceCall's devirtualization logic in this case.
598   if (isBaseDestructor())
599     return AnyFunctionCall::getRuntimeDefinition();
600 
601   return CXXInstanceCall::getRuntimeDefinition();
602 }
603 
604 
605 CallEvent::param_iterator ObjCMethodCall::param_begin() const {
606   const ObjCMethodDecl *D = getDecl();
607   if (!D)
608     return 0;
609 
610   return D->param_begin();
611 }
612 
613 CallEvent::param_iterator ObjCMethodCall::param_end() const {
614   const ObjCMethodDecl *D = getDecl();
615   if (!D)
616     return 0;
617 
618   return D->param_end();
619 }
620 
621 void
622 ObjCMethodCall::getExtraInvalidatedRegions(RegionList &Regions) const {
623   if (const MemRegion *R = getReceiverSVal().getAsRegion())
624     Regions.push_back(R);
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         const ObjCMethodDecl *MD = IDecl->lookupPrivateMethod(Sel);
822         if (CanBeSubClassed)
823           return RuntimeDefinition(MD, Receiver);
824         else
825           return RuntimeDefinition(MD, 0);
826       }
827 
828   } else {
829     // This is a class method.
830     // If we have type info for the receiver class, we are calling via
831     // class name.
832     if (ObjCInterfaceDecl *IDecl = E->getReceiverInterface()) {
833       // Find/Return the method implementation.
834       return RuntimeDefinition(IDecl->lookupPrivateClassMethod(Sel));
835     }
836   }
837 
838   return RuntimeDefinition();
839 }
840 
841 void ObjCMethodCall::getInitialStackFrameContents(
842                                              const StackFrameContext *CalleeCtx,
843                                              BindingsTy &Bindings) const {
844   const ObjCMethodDecl *D = cast<ObjCMethodDecl>(CalleeCtx->getDecl());
845   SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
846   addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this,
847                                D->param_begin(), D->param_end());
848 
849   SVal SelfVal = getReceiverSVal();
850   if (!SelfVal.isUnknown()) {
851     const VarDecl *SelfD = CalleeCtx->getAnalysisDeclContext()->getSelfDecl();
852     MemRegionManager &MRMgr = SVB.getRegionManager();
853     Loc SelfLoc = SVB.makeLoc(MRMgr.getVarRegion(SelfD, CalleeCtx));
854     Bindings.push_back(std::make_pair(SelfLoc, SelfVal));
855   }
856 }
857 
858 CallEventRef<>
859 CallEventManager::getSimpleCall(const CallExpr *CE, ProgramStateRef State,
860                                 const LocationContext *LCtx) {
861   if (const CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(CE))
862     return create<CXXMemberCall>(MCE, State, LCtx);
863 
864   if (const CXXOperatorCallExpr *OpCE = dyn_cast<CXXOperatorCallExpr>(CE)) {
865     const FunctionDecl *DirectCallee = OpCE->getDirectCallee();
866     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DirectCallee))
867       if (MD->isInstance())
868         return create<CXXMemberOperatorCall>(OpCE, State, LCtx);
869 
870   } else if (CE->getCallee()->getType()->isBlockPointerType()) {
871     return create<BlockCall>(CE, State, LCtx);
872   }
873 
874   // Otherwise, it's a normal function call, static member function call, or
875   // something we can't reason about.
876   return create<FunctionCall>(CE, State, LCtx);
877 }
878 
879 
880 CallEventRef<>
881 CallEventManager::getCaller(const StackFrameContext *CalleeCtx,
882                             ProgramStateRef State) {
883   const LocationContext *ParentCtx = CalleeCtx->getParent();
884   const LocationContext *CallerCtx = ParentCtx->getCurrentStackFrame();
885   assert(CallerCtx && "This should not be used for top-level stack frames");
886 
887   const Stmt *CallSite = CalleeCtx->getCallSite();
888 
889   if (CallSite) {
890     if (const CallExpr *CE = dyn_cast<CallExpr>(CallSite))
891       return getSimpleCall(CE, State, CallerCtx);
892 
893     switch (CallSite->getStmtClass()) {
894     case Stmt::CXXConstructExprClass:
895     case Stmt::CXXTemporaryObjectExprClass: {
896       SValBuilder &SVB = State->getStateManager().getSValBuilder();
897       const CXXMethodDecl *Ctor = cast<CXXMethodDecl>(CalleeCtx->getDecl());
898       Loc ThisPtr = SVB.getCXXThis(Ctor, CalleeCtx);
899       SVal ThisVal = State->getSVal(ThisPtr);
900 
901       return getCXXConstructorCall(cast<CXXConstructExpr>(CallSite),
902                                    ThisVal.getAsRegion(), State, CallerCtx);
903     }
904     case Stmt::CXXNewExprClass:
905       return getCXXAllocatorCall(cast<CXXNewExpr>(CallSite), State, CallerCtx);
906     case Stmt::ObjCMessageExprClass:
907       return getObjCMethodCall(cast<ObjCMessageExpr>(CallSite),
908                                State, CallerCtx);
909     default:
910       llvm_unreachable("This is not an inlineable statement.");
911     }
912   }
913 
914   // Fall back to the CFG. The only thing we haven't handled yet is
915   // destructors, though this could change in the future.
916   const CFGBlock *B = CalleeCtx->getCallSiteBlock();
917   CFGElement E = (*B)[CalleeCtx->getIndex()];
918   assert(isa<CFGImplicitDtor>(E) && "All other CFG elements should have exprs");
919   assert(!isa<CFGTemporaryDtor>(E) && "We don't handle temporaries yet");
920 
921   SValBuilder &SVB = State->getStateManager().getSValBuilder();
922   const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CalleeCtx->getDecl());
923   Loc ThisPtr = SVB.getCXXThis(Dtor, CalleeCtx);
924   SVal ThisVal = State->getSVal(ThisPtr);
925 
926   const Stmt *Trigger;
927   if (const CFGAutomaticObjDtor *AutoDtor = dyn_cast<CFGAutomaticObjDtor>(&E))
928     Trigger = AutoDtor->getTriggerStmt();
929   else
930     Trigger = Dtor->getBody();
931 
932   return getCXXDestructorCall(Dtor, Trigger, ThisVal.getAsRegion(),
933                               isa<CFGBaseDtor>(E), State, CallerCtx);
934 }
935