1 //===- Calls.cpp - Wrapper for all function and method calls ------*- C++ -*--//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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).
14 //===----------------------------------------------------------------------===//
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 "clang/StaticAnalyzer/Core/PathSensitive/DynamicTypeMap.h"
21 #include "llvm/ADT/SmallSet.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/Support/raw_ostream.h"
25 using namespace clang;
28 QualType CallEvent::getResultType() const {
29 const Expr *E = getOriginExpr();
30 assert(E && "Calls without origin expressions do not have results");
31 QualType ResultTy = E->getType();
33 ASTContext &Ctx = getState()->getStateManager().getContext();
35 // A function that returns a reference to 'int' will have a result type
36 // of simply 'int'. Check the origin expr's value kind to recover the
38 switch (E->getValueKind()) {
40 ResultTy = Ctx.getLValueReferenceType(ResultTy);
43 ResultTy = Ctx.getRValueReferenceType(ResultTy);
46 // No adjustment is necessary.
53 static bool isCallback(QualType T) {
54 // If a parameter is a block or a callback, assume it can modify pointer.
55 if (T->isBlockPointerType() ||
56 T->isFunctionPointerType() ||
60 // Check if a callback is passed inside a struct (for both, struct passed by
61 // reference and by value). Dig just one level into the struct for now.
63 if (T->isAnyPointerType() || T->isReferenceType())
64 T = T->getPointeeType();
66 if (const RecordType *RT = T->getAsStructureType()) {
67 const RecordDecl *RD = RT->getDecl();
68 for (const auto *I : RD->fields()) {
69 QualType FieldT = I->getType();
70 if (FieldT->isBlockPointerType() || FieldT->isFunctionPointerType())
77 static bool isVoidPointerToNonConst(QualType T) {
78 if (const PointerType *PT = T->getAs<PointerType>()) {
79 QualType PointeeTy = PT->getPointeeType();
80 if (PointeeTy.isConstQualified())
82 return PointeeTy->isVoidType();
87 bool CallEvent::hasNonNullArgumentsWithType(bool (*Condition)(QualType)) const {
88 unsigned NumOfArgs = getNumArgs();
90 // If calling using a function pointer, assume the function does not
91 // satisfy the callback.
92 // TODO: We could check the types of the arguments here.
97 for (CallEvent::param_type_iterator I = param_type_begin(),
99 I != E && Idx < NumOfArgs; ++I, ++Idx) {
100 if (NumOfArgs <= Idx)
103 // If the parameter is 0, it's harmless.
104 if (getArgSVal(Idx).isZeroConstant())
113 bool CallEvent::hasNonZeroCallbackArg() const {
114 return hasNonNullArgumentsWithType(isCallback);
117 bool CallEvent::hasVoidPointerToNonConstArg() const {
118 return hasNonNullArgumentsWithType(isVoidPointerToNonConst);
121 bool CallEvent::isGlobalCFunction(StringRef FunctionName) const {
122 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(getDecl());
126 return CheckerContext::isCLibraryFunction(FD, FunctionName);
129 /// \brief Returns true if a type is a pointer-to-const or reference-to-const
130 /// with no further indirection.
131 static bool isPointerToConst(QualType Ty) {
132 QualType PointeeTy = Ty->getPointeeType();
133 if (PointeeTy == QualType())
135 if (!PointeeTy.isConstQualified())
137 if (PointeeTy->isAnyPointerType())
142 // Try to retrieve the function declaration and find the function parameter
143 // types which are pointers/references to a non-pointer const.
144 // We will not invalidate the corresponding argument regions.
145 static void findPtrToConstParams(llvm::SmallSet<unsigned, 4> &PreserveArgs,
146 const CallEvent &Call) {
148 for (CallEvent::param_type_iterator I = Call.param_type_begin(),
149 E = Call.param_type_end();
150 I != E; ++I, ++Idx) {
151 if (isPointerToConst(*I))
152 PreserveArgs.insert(Idx);
156 ProgramStateRef CallEvent::invalidateRegions(unsigned BlockCount,
157 ProgramStateRef Orig) const {
158 ProgramStateRef Result = (Orig ? Orig : getState());
160 // Don't invalidate anything if the callee is marked pure/const.
161 if (const Decl *callee = getDecl())
162 if (callee->hasAttr<PureAttr>() || callee->hasAttr<ConstAttr>())
165 SmallVector<SVal, 8> ValuesToInvalidate;
166 RegionAndSymbolInvalidationTraits ETraits;
168 getExtraInvalidatedValues(ValuesToInvalidate, &ETraits);
170 // Indexes of arguments whose values will be preserved by the call.
171 llvm::SmallSet<unsigned, 4> PreserveArgs;
172 if (!argumentsMayEscape())
173 findPtrToConstParams(PreserveArgs, *this);
175 for (unsigned Idx = 0, Count = getNumArgs(); Idx != Count; ++Idx) {
176 // Mark this region for invalidation. We batch invalidate regions
177 // below for efficiency.
178 if (PreserveArgs.count(Idx))
179 if (const MemRegion *MR = getArgSVal(Idx).getAsRegion())
180 ETraits.setTrait(MR->getBaseRegion(),
181 RegionAndSymbolInvalidationTraits::TK_PreserveContents);
182 // TODO: Factor this out + handle the lower level const pointers.
184 ValuesToInvalidate.push_back(getArgSVal(Idx));
187 // Invalidate designated regions using the batch invalidation API.
188 // NOTE: Even if RegionsToInvalidate is empty, we may still invalidate
190 return Result->invalidateRegions(ValuesToInvalidate, getOriginExpr(),
191 BlockCount, getLocationContext(),
192 /*CausedByPointerEscape*/ true,
193 /*Symbols=*/nullptr, this, &ETraits);
196 ProgramPoint CallEvent::getProgramPoint(bool IsPreVisit,
197 const ProgramPointTag *Tag) const {
198 if (const Expr *E = getOriginExpr()) {
200 return PreStmt(E, getLocationContext(), Tag);
201 return PostStmt(E, getLocationContext(), Tag);
204 const Decl *D = getDecl();
205 assert(D && "Cannot get a program point without a statement or decl");
207 SourceLocation Loc = getSourceRange().getBegin();
209 return PreImplicitCall(D, Loc, getLocationContext(), Tag);
210 return PostImplicitCall(D, Loc, getLocationContext(), Tag);
213 bool CallEvent::isCalled(const CallDescription &CD) const {
214 assert(getKind() != CE_ObjCMessage && "Obj-C methods are not supported");
216 CD.II = &getState()->getStateManager().getContext().Idents.get(CD.FuncName);
217 if (getCalleeIdentifier() != CD.II)
219 return (CD.RequiredArgs == CallDescription::NoArgRequirement ||
220 CD.RequiredArgs == getNumArgs());
223 SVal CallEvent::getArgSVal(unsigned Index) const {
224 const Expr *ArgE = getArgExpr(Index);
227 return getSVal(ArgE);
230 SourceRange CallEvent::getArgSourceRange(unsigned Index) const {
231 const Expr *ArgE = getArgExpr(Index);
233 return SourceRange();
234 return ArgE->getSourceRange();
237 SVal CallEvent::getReturnValue() const {
238 const Expr *E = getOriginExpr();
240 return UndefinedVal();
244 LLVM_DUMP_METHOD void CallEvent::dump() const { dump(llvm::errs()); }
246 void CallEvent::dump(raw_ostream &Out) const {
247 ASTContext &Ctx = getState()->getStateManager().getContext();
248 if (const Expr *E = getOriginExpr()) {
249 E->printPretty(Out, nullptr, Ctx.getPrintingPolicy());
254 if (const Decl *D = getDecl()) {
256 D->print(Out, Ctx.getPrintingPolicy());
260 // FIXME: a string representation of the kind would be nice.
261 Out << "Unknown call (type " << getKind() << ")";
265 bool CallEvent::isCallStmt(const Stmt *S) {
266 return isa<CallExpr>(S) || isa<ObjCMessageExpr>(S)
267 || isa<CXXConstructExpr>(S)
268 || isa<CXXNewExpr>(S);
271 QualType CallEvent::getDeclaredResultType(const Decl *D) {
273 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(D))
274 return FD->getReturnType();
275 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(D))
276 return MD->getReturnType();
277 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
278 // Blocks are difficult because the return type may not be stored in the
279 // BlockDecl itself. The AST should probably be enhanced, but for now we
280 // just do what we can.
281 // If the block is declared without an explicit argument list, the
282 // signature-as-written just includes the return type, not the entire
284 // FIXME: All blocks should have signatures-as-written, even if the return
285 // type is inferred. (That's signified with a dependent result type.)
286 if (const TypeSourceInfo *TSI = BD->getSignatureAsWritten()) {
287 QualType Ty = TSI->getType();
288 if (const FunctionType *FT = Ty->getAs<FunctionType>())
289 Ty = FT->getReturnType();
290 if (!Ty->isDependentType())
297 llvm_unreachable("unknown callable kind");
300 bool CallEvent::isVariadic(const Decl *D) {
303 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
304 return FD->isVariadic();
305 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
306 return MD->isVariadic();
307 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
308 return BD->isVariadic();
310 llvm_unreachable("unknown callable kind");
313 static void addParameterValuesToBindings(const StackFrameContext *CalleeCtx,
314 CallEvent::BindingsTy &Bindings,
316 const CallEvent &Call,
317 ArrayRef<ParmVarDecl*> parameters) {
318 MemRegionManager &MRMgr = SVB.getRegionManager();
320 // If the function has fewer parameters than the call has arguments, we simply
321 // do not bind any values to them.
322 unsigned NumArgs = Call.getNumArgs();
324 ArrayRef<ParmVarDecl*>::iterator I = parameters.begin(), E = parameters.end();
325 for (; I != E && Idx < NumArgs; ++I, ++Idx) {
326 const ParmVarDecl *ParamDecl = *I;
327 assert(ParamDecl && "Formal parameter has no decl?");
329 SVal ArgVal = Call.getArgSVal(Idx);
330 if (!ArgVal.isUnknown()) {
331 Loc ParamLoc = SVB.makeLoc(MRMgr.getVarRegion(ParamDecl, CalleeCtx));
332 Bindings.push_back(std::make_pair(ParamLoc, ArgVal));
336 // FIXME: Variadic arguments are not handled at all right now.
339 ArrayRef<ParmVarDecl*> AnyFunctionCall::parameters() const {
340 const FunctionDecl *D = getDecl();
343 return D->parameters();
346 void AnyFunctionCall::getInitialStackFrameContents(
347 const StackFrameContext *CalleeCtx,
348 BindingsTy &Bindings) const {
349 const FunctionDecl *D = cast<FunctionDecl>(CalleeCtx->getDecl());
350 SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
351 addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this,
355 bool AnyFunctionCall::argumentsMayEscape() const {
356 if (CallEvent::argumentsMayEscape() || hasVoidPointerToNonConstArg())
359 const FunctionDecl *D = getDecl();
363 const IdentifierInfo *II = D->getIdentifier();
367 // This set of "escaping" APIs is
369 // - 'int pthread_setspecific(ptheread_key k, const void *)' stores a
370 // value into thread local storage. The value can later be retrieved with
371 // 'void *ptheread_getspecific(pthread_key)'. So even thought the
372 // parameter is 'const void *', the region escapes through the call.
373 if (II->isStr("pthread_setspecific"))
376 // - xpc_connection_set_context stores a value which can be retrieved later
377 // with xpc_connection_get_context.
378 if (II->isStr("xpc_connection_set_context"))
381 // - funopen - sets a buffer for future IO calls.
382 if (II->isStr("funopen"))
385 // - __cxa_demangle - can reallocate memory and can return the pointer to
387 if (II->isStr("__cxa_demangle"))
390 StringRef FName = II->getName();
392 // - CoreFoundation functions that end with "NoCopy" can free a passed-in
393 // buffer even if it is const.
394 if (FName.endswith("NoCopy"))
397 // - NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
398 // be deallocated by NSMapRemove.
399 if (FName.startswith("NS") && (FName.find("Insert") != StringRef::npos))
402 // - Many CF containers allow objects to escape through custom
403 // allocators/deallocators upon container construction. (PR12101)
404 if (FName.startswith("CF") || FName.startswith("CG")) {
405 return StrInStrNoCase(FName, "InsertValue") != StringRef::npos ||
406 StrInStrNoCase(FName, "AddValue") != StringRef::npos ||
407 StrInStrNoCase(FName, "SetValue") != StringRef::npos ||
408 StrInStrNoCase(FName, "WithData") != StringRef::npos ||
409 StrInStrNoCase(FName, "AppendValue") != StringRef::npos ||
410 StrInStrNoCase(FName, "SetAttribute") != StringRef::npos;
417 const FunctionDecl *SimpleFunctionCall::getDecl() const {
418 const FunctionDecl *D = getOriginExpr()->getDirectCallee();
422 return getSVal(getOriginExpr()->getCallee()).getAsFunctionDecl();
426 const FunctionDecl *CXXInstanceCall::getDecl() const {
427 const CallExpr *CE = cast_or_null<CallExpr>(getOriginExpr());
429 return AnyFunctionCall::getDecl();
431 const FunctionDecl *D = CE->getDirectCallee();
435 return getSVal(CE->getCallee()).getAsFunctionDecl();
438 void CXXInstanceCall::getExtraInvalidatedValues(
439 ValueList &Values, RegionAndSymbolInvalidationTraits *ETraits) const {
440 SVal ThisVal = getCXXThisVal();
441 Values.push_back(ThisVal);
443 // Don't invalidate if the method is const and there are no mutable fields.
444 if (const CXXMethodDecl *D = cast_or_null<CXXMethodDecl>(getDecl())) {
447 // Get the record decl for the class of 'This'. D->getParent() may return a
448 // base class decl, rather than the class of the instance which needs to be
449 // checked for mutable fields.
450 const Expr *Ex = getCXXThisExpr()->ignoreParenBaseCasts();
451 const CXXRecordDecl *ParentRecord = Ex->getType()->getAsCXXRecordDecl();
452 if (!ParentRecord || ParentRecord->hasMutableFields())
455 const MemRegion *ThisRegion = ThisVal.getAsRegion();
459 ETraits->setTrait(ThisRegion->getBaseRegion(),
460 RegionAndSymbolInvalidationTraits::TK_PreserveContents);
464 SVal CXXInstanceCall::getCXXThisVal() const {
465 const Expr *Base = getCXXThisExpr();
466 // FIXME: This doesn't handle an overloaded ->* operator.
470 SVal ThisVal = getSVal(Base);
471 assert(ThisVal.isUnknownOrUndef() || ThisVal.getAs<Loc>());
476 RuntimeDefinition CXXInstanceCall::getRuntimeDefinition() const {
477 // Do we have a decl at all?
478 const Decl *D = getDecl();
480 return RuntimeDefinition();
482 // If the method is non-virtual, we know we can inline it.
483 const CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
484 if (!MD->isVirtual())
485 return AnyFunctionCall::getRuntimeDefinition();
487 // Do we know the implicit 'this' object being called?
488 const MemRegion *R = getCXXThisVal().getAsRegion();
490 return RuntimeDefinition();
492 // Do we know anything about the type of 'this'?
493 DynamicTypeInfo DynType = getDynamicTypeInfo(getState(), R);
494 if (!DynType.isValid())
495 return RuntimeDefinition();
497 // Is the type a C++ class? (This is mostly a defensive check.)
498 QualType RegionType = DynType.getType()->getPointeeType();
499 assert(!RegionType.isNull() && "DynamicTypeInfo should always be a pointer.");
501 const CXXRecordDecl *RD = RegionType->getAsCXXRecordDecl();
502 if (!RD || !RD->hasDefinition())
503 return RuntimeDefinition();
505 // Find the decl for this method in that class.
506 const CXXMethodDecl *Result = MD->getCorrespondingMethodInClass(RD, true);
508 // We might not even get the original statically-resolved method due to
509 // some particularly nasty casting (e.g. casts to sister classes).
510 // However, we should at least be able to search up and down our own class
511 // hierarchy, and some real bugs have been caught by checking this.
512 assert(!RD->isDerivedFrom(MD->getParent()) && "Couldn't find known method");
514 // FIXME: This is checking that our DynamicTypeInfo is at least as good as
515 // the static type. However, because we currently don't update
516 // DynamicTypeInfo when an object is cast, we can't actually be sure the
517 // DynamicTypeInfo is up to date. This assert should be re-enabled once
518 // this is fixed. <rdar://problem/12287087>
519 //assert(!MD->getParent()->isDerivedFrom(RD) && "Bad DynamicTypeInfo");
521 return RuntimeDefinition();
524 // Does the decl that we found have an implementation?
525 const FunctionDecl *Definition;
526 if (!Result->hasBody(Definition))
527 return RuntimeDefinition();
529 // We found a definition. If we're not sure that this devirtualization is
530 // actually what will happen at runtime, make sure to provide the region so
531 // that ExprEngine can decide what to do with it.
532 if (DynType.canBeASubClass())
533 return RuntimeDefinition(Definition, R->StripCasts());
534 return RuntimeDefinition(Definition, /*DispatchRegion=*/nullptr);
537 void CXXInstanceCall::getInitialStackFrameContents(
538 const StackFrameContext *CalleeCtx,
539 BindingsTy &Bindings) const {
540 AnyFunctionCall::getInitialStackFrameContents(CalleeCtx, Bindings);
542 // Handle the binding of 'this' in the new stack frame.
543 SVal ThisVal = getCXXThisVal();
544 if (!ThisVal.isUnknown()) {
545 ProgramStateManager &StateMgr = getState()->getStateManager();
546 SValBuilder &SVB = StateMgr.getSValBuilder();
548 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CalleeCtx->getDecl());
549 Loc ThisLoc = SVB.getCXXThis(MD, CalleeCtx);
551 // If we devirtualized to a different member function, we need to make sure
552 // we have the proper layering of CXXBaseObjectRegions.
553 if (MD->getCanonicalDecl() != getDecl()->getCanonicalDecl()) {
554 ASTContext &Ctx = SVB.getContext();
555 const CXXRecordDecl *Class = MD->getParent();
556 QualType Ty = Ctx.getPointerType(Ctx.getRecordType(Class));
558 // FIXME: CallEvent maybe shouldn't be directly accessing StoreManager.
560 ThisVal = StateMgr.getStoreManager().attemptDownCast(ThisVal, Ty, Failed);
561 assert(!Failed && "Calling an incorrectly devirtualized method");
564 if (!ThisVal.isUnknown())
565 Bindings.push_back(std::make_pair(ThisLoc, ThisVal));
571 const Expr *CXXMemberCall::getCXXThisExpr() const {
572 return getOriginExpr()->getImplicitObjectArgument();
575 RuntimeDefinition CXXMemberCall::getRuntimeDefinition() const {
576 // C++11 [expr.call]p1: ...If the selected function is non-virtual, or if the
577 // id-expression in the class member access expression is a qualified-id,
578 // that function is called. Otherwise, its final overrider in the dynamic type
579 // of the object expression is called.
580 if (const MemberExpr *ME = dyn_cast<MemberExpr>(getOriginExpr()->getCallee()))
581 if (ME->hasQualifier())
582 return AnyFunctionCall::getRuntimeDefinition();
584 return CXXInstanceCall::getRuntimeDefinition();
588 const Expr *CXXMemberOperatorCall::getCXXThisExpr() const {
589 return getOriginExpr()->getArg(0);
593 const BlockDataRegion *BlockCall::getBlockRegion() const {
594 const Expr *Callee = getOriginExpr()->getCallee();
595 const MemRegion *DataReg = getSVal(Callee).getAsRegion();
597 return dyn_cast_or_null<BlockDataRegion>(DataReg);
600 ArrayRef<ParmVarDecl*> BlockCall::parameters() const {
601 const BlockDecl *D = getDecl();
604 return D->parameters();
607 void BlockCall::getExtraInvalidatedValues(ValueList &Values,
608 RegionAndSymbolInvalidationTraits *ETraits) const {
609 // FIXME: This also needs to invalidate captured globals.
610 if (const MemRegion *R = getBlockRegion())
611 Values.push_back(loc::MemRegionVal(R));
614 void BlockCall::getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
615 BindingsTy &Bindings) const {
616 SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
617 ArrayRef<ParmVarDecl*> Params;
618 if (isConversionFromLambda()) {
619 auto *LambdaOperatorDecl = cast<CXXMethodDecl>(CalleeCtx->getDecl());
620 Params = LambdaOperatorDecl->parameters();
622 // For blocks converted from a C++ lambda, the callee declaration is the
623 // operator() method on the lambda so we bind "this" to
624 // the lambda captured by the block.
625 const VarRegion *CapturedLambdaRegion = getRegionStoringCapturedLambda();
626 SVal ThisVal = loc::MemRegionVal(CapturedLambdaRegion);
627 Loc ThisLoc = SVB.getCXXThis(LambdaOperatorDecl, CalleeCtx);
628 Bindings.push_back(std::make_pair(ThisLoc, ThisVal));
630 Params = cast<BlockDecl>(CalleeCtx->getDecl())->parameters();
633 addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this,
638 SVal CXXConstructorCall::getCXXThisVal() const {
640 return loc::MemRegionVal(static_cast<const MemRegion *>(Data));
644 void CXXConstructorCall::getExtraInvalidatedValues(ValueList &Values,
645 RegionAndSymbolInvalidationTraits *ETraits) const {
647 Values.push_back(loc::MemRegionVal(static_cast<const MemRegion *>(Data)));
650 void CXXConstructorCall::getInitialStackFrameContents(
651 const StackFrameContext *CalleeCtx,
652 BindingsTy &Bindings) const {
653 AnyFunctionCall::getInitialStackFrameContents(CalleeCtx, Bindings);
655 SVal ThisVal = getCXXThisVal();
656 if (!ThisVal.isUnknown()) {
657 SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
658 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CalleeCtx->getDecl());
659 Loc ThisLoc = SVB.getCXXThis(MD, CalleeCtx);
660 Bindings.push_back(std::make_pair(ThisLoc, ThisVal));
664 SVal CXXDestructorCall::getCXXThisVal() const {
666 return loc::MemRegionVal(DtorDataTy::getFromOpaqueValue(Data).getPointer());
670 RuntimeDefinition CXXDestructorCall::getRuntimeDefinition() const {
671 // Base destructors are always called non-virtually.
672 // Skip CXXInstanceCall's devirtualization logic in this case.
673 if (isBaseDestructor())
674 return AnyFunctionCall::getRuntimeDefinition();
676 return CXXInstanceCall::getRuntimeDefinition();
679 ArrayRef<ParmVarDecl*> ObjCMethodCall::parameters() const {
680 const ObjCMethodDecl *D = getDecl();
683 return D->parameters();
686 void ObjCMethodCall::getExtraInvalidatedValues(
687 ValueList &Values, RegionAndSymbolInvalidationTraits *ETraits) const {
689 // If the method call is a setter for property known to be backed by
690 // an instance variable, don't invalidate the entire receiver, just
691 // the storage for that instance variable.
692 if (const ObjCPropertyDecl *PropDecl = getAccessedProperty()) {
693 if (const ObjCIvarDecl *PropIvar = PropDecl->getPropertyIvarDecl()) {
694 SVal IvarLVal = getState()->getLValue(PropIvar, getReceiverSVal());
695 const MemRegion *IvarRegion = IvarLVal.getAsRegion();
698 RegionAndSymbolInvalidationTraits::TK_DoNotInvalidateSuperRegion);
699 ETraits->setTrait(IvarRegion,
700 RegionAndSymbolInvalidationTraits::TK_SuppressEscape);
701 Values.push_back(IvarLVal);
706 Values.push_back(getReceiverSVal());
709 SVal ObjCMethodCall::getSelfSVal() const {
710 const LocationContext *LCtx = getLocationContext();
711 const ImplicitParamDecl *SelfDecl = LCtx->getSelfDecl();
714 return getState()->getSVal(getState()->getRegion(SelfDecl, LCtx));
717 SVal ObjCMethodCall::getReceiverSVal() const {
718 // FIXME: Is this the best way to handle class receivers?
719 if (!isInstanceMessage())
722 if (const Expr *RecE = getOriginExpr()->getInstanceReceiver())
723 return getSVal(RecE);
725 // An instance message with no expression means we are sending to super.
726 // In this case the object reference is the same as 'self'.
727 assert(getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperInstance);
728 SVal SelfVal = getSelfSVal();
729 assert(SelfVal.isValid() && "Calling super but not in ObjC method");
733 bool ObjCMethodCall::isReceiverSelfOrSuper() const {
734 if (getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperInstance ||
735 getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperClass)
738 if (!isInstanceMessage())
741 SVal RecVal = getSVal(getOriginExpr()->getInstanceReceiver());
743 return (RecVal == getSelfSVal());
746 SourceRange ObjCMethodCall::getSourceRange() const {
747 switch (getMessageKind()) {
749 return getOriginExpr()->getSourceRange();
750 case OCM_PropertyAccess:
752 return getContainingPseudoObjectExpr()->getSourceRange();
754 llvm_unreachable("unknown message kind");
757 typedef llvm::PointerIntPair<const PseudoObjectExpr *, 2> ObjCMessageDataTy;
759 const PseudoObjectExpr *ObjCMethodCall::getContainingPseudoObjectExpr() const {
760 assert(Data && "Lazy lookup not yet performed.");
761 assert(getMessageKind() != OCM_Message && "Explicit message send.");
762 return ObjCMessageDataTy::getFromOpaqueValue(Data).getPointer();
766 getSyntacticFromForPseudoObjectExpr(const PseudoObjectExpr *POE) {
767 const Expr *Syntactic = POE->getSyntacticForm();
769 // This handles the funny case of assigning to the result of a getter.
770 // This can happen if the getter returns a non-const reference.
771 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(Syntactic))
772 Syntactic = BO->getLHS();
777 ObjCMessageKind ObjCMethodCall::getMessageKind() const {
780 // Find the parent, ignoring implicit casts.
781 ParentMap &PM = getLocationContext()->getParentMap();
782 const Stmt *S = PM.getParentIgnoreParenCasts(getOriginExpr());
784 // Check if parent is a PseudoObjectExpr.
785 if (const PseudoObjectExpr *POE = dyn_cast_or_null<PseudoObjectExpr>(S)) {
786 const Expr *Syntactic = getSyntacticFromForPseudoObjectExpr(POE);
789 switch (Syntactic->getStmtClass()) {
790 case Stmt::ObjCPropertyRefExprClass:
791 K = OCM_PropertyAccess;
793 case Stmt::ObjCSubscriptRefExprClass:
797 // FIXME: Can this ever happen?
802 if (K != OCM_Message) {
803 const_cast<ObjCMethodCall *>(this)->Data
804 = ObjCMessageDataTy(POE, K).getOpaqueValue();
805 assert(getMessageKind() == K);
810 const_cast<ObjCMethodCall *>(this)->Data
811 = ObjCMessageDataTy(nullptr, 1).getOpaqueValue();
812 assert(getMessageKind() == OCM_Message);
816 ObjCMessageDataTy Info = ObjCMessageDataTy::getFromOpaqueValue(Data);
817 if (!Info.getPointer())
819 return static_cast<ObjCMessageKind>(Info.getInt());
822 const ObjCPropertyDecl *ObjCMethodCall::getAccessedProperty() const {
823 // Look for properties accessed with property syntax (foo.bar = ...)
824 if ( getMessageKind() == OCM_PropertyAccess) {
825 const PseudoObjectExpr *POE = getContainingPseudoObjectExpr();
826 assert(POE && "Property access without PseudoObjectExpr?");
828 const Expr *Syntactic = getSyntacticFromForPseudoObjectExpr(POE);
829 auto *RefExpr = cast<ObjCPropertyRefExpr>(Syntactic);
831 if (RefExpr->isExplicitProperty())
832 return RefExpr->getExplicitProperty();
835 // Look for properties accessed with method syntax ([foo setBar:...]).
836 const ObjCMethodDecl *MD = getDecl();
837 if (!MD || !MD->isPropertyAccessor())
840 // Note: This is potentially quite slow.
841 return MD->findPropertyDecl();
844 bool ObjCMethodCall::canBeOverridenInSubclass(ObjCInterfaceDecl *IDecl,
845 Selector Sel) const {
847 const SourceManager &SM =
848 getState()->getStateManager().getContext().getSourceManager();
850 // If the class interface is declared inside the main file, assume it is not
852 // TODO: It could actually be subclassed if the subclass is private as well.
853 // This is probably very rare.
854 SourceLocation InterfLoc = IDecl->getEndOfDefinitionLoc();
855 if (InterfLoc.isValid() && SM.isInMainFile(InterfLoc))
858 // Assume that property accessors are not overridden.
859 if (getMessageKind() == OCM_PropertyAccess)
862 // We assume that if the method is public (declared outside of main file) or
863 // has a parent which publicly declares the method, the method could be
864 // overridden in a subclass.
866 // Find the first declaration in the class hierarchy that declares
868 ObjCMethodDecl *D = nullptr;
870 D = IDecl->lookupMethod(Sel, true);
872 // Cannot find a public definition.
876 // If outside the main file,
877 if (D->getLocation().isValid() && !SM.isInMainFile(D->getLocation()))
880 if (D->isOverriding()) {
881 // Search in the superclass on the next iteration.
882 IDecl = D->getClassInterface();
886 IDecl = IDecl->getSuperClass();
896 llvm_unreachable("The while loop should always terminate.");
899 RuntimeDefinition ObjCMethodCall::getRuntimeDefinition() const {
900 const ObjCMessageExpr *E = getOriginExpr();
902 Selector Sel = E->getSelector();
904 if (E->isInstanceMessage()) {
906 // Find the receiver type.
907 const ObjCObjectPointerType *ReceiverT = nullptr;
908 bool CanBeSubClassed = false;
909 QualType SupersType = E->getSuperType();
910 const MemRegion *Receiver = nullptr;
912 if (!SupersType.isNull()) {
913 // Super always means the type of immediate predecessor to the method
914 // where the call occurs.
915 ReceiverT = cast<ObjCObjectPointerType>(SupersType);
917 Receiver = getReceiverSVal().getAsRegion();
919 return RuntimeDefinition();
921 DynamicTypeInfo DTI = getDynamicTypeInfo(getState(), Receiver);
922 QualType DynType = DTI.getType();
923 CanBeSubClassed = DTI.canBeASubClass();
924 ReceiverT = dyn_cast<ObjCObjectPointerType>(DynType);
926 if (ReceiverT && CanBeSubClassed)
927 if (ObjCInterfaceDecl *IDecl = ReceiverT->getInterfaceDecl())
928 if (!canBeOverridenInSubclass(IDecl, Sel))
929 CanBeSubClassed = false;
932 // Lookup the method implementation.
934 if (ObjCInterfaceDecl *IDecl = ReceiverT->getInterfaceDecl()) {
935 // Repeatedly calling lookupPrivateMethod() is expensive, especially
936 // when in many cases it returns null. We cache the results so
937 // that repeated queries on the same ObjCIntefaceDecl and Selector
938 // don't incur the same cost. On some test cases, we can see the
939 // same query being issued thousands of times.
941 // NOTE: This cache is essentially a "global" variable, but it
942 // only gets lazily created when we get here. The value of the
943 // cache probably comes from it being global across ExprEngines,
944 // where the same queries may get issued. If we are worried about
945 // concurrency, or possibly loading/unloading ASTs, etc., we may
946 // need to revisit this someday. In terms of memory, this table
947 // stays around until clang quits, which also may be bad if we
948 // need to release memory.
949 typedef std::pair<const ObjCInterfaceDecl*, Selector>
951 typedef llvm::DenseMap<PrivateMethodKey,
952 Optional<const ObjCMethodDecl *> >
955 static PrivateMethodCache PMC;
956 Optional<const ObjCMethodDecl *> &Val = PMC[std::make_pair(IDecl, Sel)];
958 // Query lookupPrivateMethod() if the cache does not hit.
959 if (!Val.hasValue()) {
960 Val = IDecl->lookupPrivateMethod(Sel);
962 // If the method is a property accessor, we should try to "inline" it
963 // even if we don't actually have an implementation.
965 if (const ObjCMethodDecl *CompileTimeMD = E->getMethodDecl())
966 if (CompileTimeMD->isPropertyAccessor()) {
967 if (!CompileTimeMD->getSelfDecl() &&
968 isa<ObjCCategoryDecl>(CompileTimeMD->getDeclContext())) {
969 // If the method is an accessor in a category, and it doesn't
970 // have a self declaration, first
971 // try to find the method in a class extension. This
972 // works around a bug in Sema where multiple accessors
973 // are synthesized for properties in class
974 // extensions that are redeclared in a category and the
975 // the implicit parameters are not filled in for
976 // the method on the category.
977 // This ensures we find the accessor in the extension, which
978 // has the implicit parameters filled in.
979 auto *ID = CompileTimeMD->getClassInterface();
980 for (auto *CatDecl : ID->visible_extensions()) {
981 Val = CatDecl->getMethod(Sel,
982 CompileTimeMD->isInstanceMethod());
988 Val = IDecl->lookupInstanceMethod(Sel);
992 const ObjCMethodDecl *MD = Val.getValue();
994 return RuntimeDefinition(MD, Receiver);
996 return RuntimeDefinition(MD, nullptr);
1000 // This is a class method.
1001 // If we have type info for the receiver class, we are calling via
1003 if (ObjCInterfaceDecl *IDecl = E->getReceiverInterface()) {
1004 // Find/Return the method implementation.
1005 return RuntimeDefinition(IDecl->lookupPrivateClassMethod(Sel));
1009 return RuntimeDefinition();
1012 bool ObjCMethodCall::argumentsMayEscape() const {
1013 if (isInSystemHeader() && !isInstanceMessage()) {
1014 Selector Sel = getSelector();
1015 if (Sel.getNumArgs() == 1 &&
1016 Sel.getIdentifierInfoForSlot(0)->isStr("valueWithPointer"))
1020 return CallEvent::argumentsMayEscape();
1023 void ObjCMethodCall::getInitialStackFrameContents(
1024 const StackFrameContext *CalleeCtx,
1025 BindingsTy &Bindings) const {
1026 const ObjCMethodDecl *D = cast<ObjCMethodDecl>(CalleeCtx->getDecl());
1027 SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
1028 addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this,
1031 SVal SelfVal = getReceiverSVal();
1032 if (!SelfVal.isUnknown()) {
1033 const VarDecl *SelfD = CalleeCtx->getAnalysisDeclContext()->getSelfDecl();
1034 MemRegionManager &MRMgr = SVB.getRegionManager();
1035 Loc SelfLoc = SVB.makeLoc(MRMgr.getVarRegion(SelfD, CalleeCtx));
1036 Bindings.push_back(std::make_pair(SelfLoc, SelfVal));
1041 CallEventManager::getSimpleCall(const CallExpr *CE, ProgramStateRef State,
1042 const LocationContext *LCtx) {
1043 if (const CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(CE))
1044 return create<CXXMemberCall>(MCE, State, LCtx);
1046 if (const CXXOperatorCallExpr *OpCE = dyn_cast<CXXOperatorCallExpr>(CE)) {
1047 const FunctionDecl *DirectCallee = OpCE->getDirectCallee();
1048 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DirectCallee))
1049 if (MD->isInstance())
1050 return create<CXXMemberOperatorCall>(OpCE, State, LCtx);
1052 } else if (CE->getCallee()->getType()->isBlockPointerType()) {
1053 return create<BlockCall>(CE, State, LCtx);
1056 // Otherwise, it's a normal function call, static member function call, or
1057 // something we can't reason about.
1058 return create<SimpleFunctionCall>(CE, State, LCtx);
1063 CallEventManager::getCaller(const StackFrameContext *CalleeCtx,
1064 ProgramStateRef State) {
1065 const LocationContext *ParentCtx = CalleeCtx->getParent();
1066 const LocationContext *CallerCtx = ParentCtx->getCurrentStackFrame();
1067 assert(CallerCtx && "This should not be used for top-level stack frames");
1069 const Stmt *CallSite = CalleeCtx->getCallSite();
1072 if (const CallExpr *CE = dyn_cast<CallExpr>(CallSite))
1073 return getSimpleCall(CE, State, CallerCtx);
1075 switch (CallSite->getStmtClass()) {
1076 case Stmt::CXXConstructExprClass:
1077 case Stmt::CXXTemporaryObjectExprClass: {
1078 SValBuilder &SVB = State->getStateManager().getSValBuilder();
1079 const CXXMethodDecl *Ctor = cast<CXXMethodDecl>(CalleeCtx->getDecl());
1080 Loc ThisPtr = SVB.getCXXThis(Ctor, CalleeCtx);
1081 SVal ThisVal = State->getSVal(ThisPtr);
1083 return getCXXConstructorCall(cast<CXXConstructExpr>(CallSite),
1084 ThisVal.getAsRegion(), State, CallerCtx);
1086 case Stmt::CXXNewExprClass:
1087 return getCXXAllocatorCall(cast<CXXNewExpr>(CallSite), State, CallerCtx);
1088 case Stmt::ObjCMessageExprClass:
1089 return getObjCMethodCall(cast<ObjCMessageExpr>(CallSite),
1092 llvm_unreachable("This is not an inlineable statement.");
1096 // Fall back to the CFG. The only thing we haven't handled yet is
1097 // destructors, though this could change in the future.
1098 const CFGBlock *B = CalleeCtx->getCallSiteBlock();
1099 CFGElement E = (*B)[CalleeCtx->getIndex()];
1100 assert(E.getAs<CFGImplicitDtor>() &&
1101 "All other CFG elements should have exprs");
1102 assert(!E.getAs<CFGTemporaryDtor>() && "We don't handle temporaries yet");
1104 SValBuilder &SVB = State->getStateManager().getSValBuilder();
1105 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CalleeCtx->getDecl());
1106 Loc ThisPtr = SVB.getCXXThis(Dtor, CalleeCtx);
1107 SVal ThisVal = State->getSVal(ThisPtr);
1109 const Stmt *Trigger;
1110 if (Optional<CFGAutomaticObjDtor> AutoDtor = E.getAs<CFGAutomaticObjDtor>())
1111 Trigger = AutoDtor->getTriggerStmt();
1112 else if (Optional<CFGDeleteDtor> DeleteDtor = E.getAs<CFGDeleteDtor>())
1113 Trigger = cast<Stmt>(DeleteDtor->getDeleteExpr());
1115 Trigger = Dtor->getBody();
1117 return getCXXDestructorCall(Dtor, Trigger, ThisVal.getAsRegion(),
1118 E.getAs<CFGBaseDtor>().hasValue(), State,