17330f729Sjoerg //== BodyFarm.cpp - Factory for conjuring up fake bodies ----------*- C++ -*-//
27330f729Sjoerg //
37330f729Sjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
47330f729Sjoerg // See https://llvm.org/LICENSE.txt for license information.
57330f729Sjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
67330f729Sjoerg //
77330f729Sjoerg //===----------------------------------------------------------------------===//
87330f729Sjoerg //
97330f729Sjoerg // BodyFarm is a factory for creating faux implementations for functions/methods
107330f729Sjoerg // for analysis purposes.
117330f729Sjoerg //
127330f729Sjoerg //===----------------------------------------------------------------------===//
137330f729Sjoerg
147330f729Sjoerg #include "clang/Analysis/BodyFarm.h"
157330f729Sjoerg #include "clang/AST/ASTContext.h"
167330f729Sjoerg #include "clang/AST/CXXInheritance.h"
177330f729Sjoerg #include "clang/AST/Decl.h"
187330f729Sjoerg #include "clang/AST/Expr.h"
197330f729Sjoerg #include "clang/AST/ExprCXX.h"
207330f729Sjoerg #include "clang/AST/ExprObjC.h"
217330f729Sjoerg #include "clang/AST/NestedNameSpecifier.h"
227330f729Sjoerg #include "clang/Analysis/CodeInjector.h"
237330f729Sjoerg #include "clang/Basic/OperatorKinds.h"
247330f729Sjoerg #include "llvm/ADT/StringSwitch.h"
257330f729Sjoerg #include "llvm/Support/Debug.h"
267330f729Sjoerg
277330f729Sjoerg #define DEBUG_TYPE "body-farm"
287330f729Sjoerg
297330f729Sjoerg using namespace clang;
307330f729Sjoerg
317330f729Sjoerg //===----------------------------------------------------------------------===//
327330f729Sjoerg // Helper creation functions for constructing faux ASTs.
337330f729Sjoerg //===----------------------------------------------------------------------===//
347330f729Sjoerg
isDispatchBlock(QualType Ty)357330f729Sjoerg static bool isDispatchBlock(QualType Ty) {
367330f729Sjoerg // Is it a block pointer?
377330f729Sjoerg const BlockPointerType *BPT = Ty->getAs<BlockPointerType>();
387330f729Sjoerg if (!BPT)
397330f729Sjoerg return false;
407330f729Sjoerg
417330f729Sjoerg // Check if the block pointer type takes no arguments and
427330f729Sjoerg // returns void.
437330f729Sjoerg const FunctionProtoType *FT =
447330f729Sjoerg BPT->getPointeeType()->getAs<FunctionProtoType>();
457330f729Sjoerg return FT && FT->getReturnType()->isVoidType() && FT->getNumParams() == 0;
467330f729Sjoerg }
477330f729Sjoerg
487330f729Sjoerg namespace {
497330f729Sjoerg class ASTMaker {
507330f729Sjoerg public:
ASTMaker(ASTContext & C)517330f729Sjoerg ASTMaker(ASTContext &C) : C(C) {}
527330f729Sjoerg
537330f729Sjoerg /// Create a new BinaryOperator representing a simple assignment.
547330f729Sjoerg BinaryOperator *makeAssignment(const Expr *LHS, const Expr *RHS, QualType Ty);
557330f729Sjoerg
567330f729Sjoerg /// Create a new BinaryOperator representing a comparison.
577330f729Sjoerg BinaryOperator *makeComparison(const Expr *LHS, const Expr *RHS,
587330f729Sjoerg BinaryOperator::Opcode Op);
597330f729Sjoerg
607330f729Sjoerg /// Create a new compound stmt using the provided statements.
617330f729Sjoerg CompoundStmt *makeCompound(ArrayRef<Stmt*>);
627330f729Sjoerg
637330f729Sjoerg /// Create a new DeclRefExpr for the referenced variable.
647330f729Sjoerg DeclRefExpr *makeDeclRefExpr(const VarDecl *D,
657330f729Sjoerg bool RefersToEnclosingVariableOrCapture = false);
667330f729Sjoerg
677330f729Sjoerg /// Create a new UnaryOperator representing a dereference.
687330f729Sjoerg UnaryOperator *makeDereference(const Expr *Arg, QualType Ty);
697330f729Sjoerg
707330f729Sjoerg /// Create an implicit cast for an integer conversion.
717330f729Sjoerg Expr *makeIntegralCast(const Expr *Arg, QualType Ty);
727330f729Sjoerg
737330f729Sjoerg /// Create an implicit cast to a builtin boolean type.
747330f729Sjoerg ImplicitCastExpr *makeIntegralCastToBoolean(const Expr *Arg);
757330f729Sjoerg
767330f729Sjoerg /// Create an implicit cast for lvalue-to-rvaluate conversions.
777330f729Sjoerg ImplicitCastExpr *makeLvalueToRvalue(const Expr *Arg, QualType Ty);
787330f729Sjoerg
797330f729Sjoerg /// Make RValue out of variable declaration, creating a temporary
807330f729Sjoerg /// DeclRefExpr in the process.
817330f729Sjoerg ImplicitCastExpr *
827330f729Sjoerg makeLvalueToRvalue(const VarDecl *Decl,
837330f729Sjoerg bool RefersToEnclosingVariableOrCapture = false);
847330f729Sjoerg
857330f729Sjoerg /// Create an implicit cast of the given type.
867330f729Sjoerg ImplicitCastExpr *makeImplicitCast(const Expr *Arg, QualType Ty,
877330f729Sjoerg CastKind CK = CK_LValueToRValue);
887330f729Sjoerg
897330f729Sjoerg /// Create an Objective-C bool literal.
907330f729Sjoerg ObjCBoolLiteralExpr *makeObjCBool(bool Val);
917330f729Sjoerg
927330f729Sjoerg /// Create an Objective-C ivar reference.
937330f729Sjoerg ObjCIvarRefExpr *makeObjCIvarRef(const Expr *Base, const ObjCIvarDecl *IVar);
947330f729Sjoerg
957330f729Sjoerg /// Create a Return statement.
967330f729Sjoerg ReturnStmt *makeReturn(const Expr *RetVal);
977330f729Sjoerg
987330f729Sjoerg /// Create an integer literal expression of the given type.
997330f729Sjoerg IntegerLiteral *makeIntegerLiteral(uint64_t Value, QualType Ty);
1007330f729Sjoerg
1017330f729Sjoerg /// Create a member expression.
1027330f729Sjoerg MemberExpr *makeMemberExpression(Expr *base, ValueDecl *MemberDecl,
1037330f729Sjoerg bool IsArrow = false,
1047330f729Sjoerg ExprValueKind ValueKind = VK_LValue);
1057330f729Sjoerg
1067330f729Sjoerg /// Returns a *first* member field of a record declaration with a given name.
1077330f729Sjoerg /// \return an nullptr if no member with such a name exists.
1087330f729Sjoerg ValueDecl *findMemberField(const RecordDecl *RD, StringRef Name);
1097330f729Sjoerg
1107330f729Sjoerg private:
1117330f729Sjoerg ASTContext &C;
1127330f729Sjoerg };
1137330f729Sjoerg }
1147330f729Sjoerg
makeAssignment(const Expr * LHS,const Expr * RHS,QualType Ty)1157330f729Sjoerg BinaryOperator *ASTMaker::makeAssignment(const Expr *LHS, const Expr *RHS,
1167330f729Sjoerg QualType Ty) {
117*e038c9c4Sjoerg return BinaryOperator::Create(
118*e038c9c4Sjoerg C, const_cast<Expr *>(LHS), const_cast<Expr *>(RHS), BO_Assign, Ty,
119*e038c9c4Sjoerg VK_RValue, OK_Ordinary, SourceLocation(), FPOptionsOverride());
1207330f729Sjoerg }
1217330f729Sjoerg
makeComparison(const Expr * LHS,const Expr * RHS,BinaryOperator::Opcode Op)1227330f729Sjoerg BinaryOperator *ASTMaker::makeComparison(const Expr *LHS, const Expr *RHS,
1237330f729Sjoerg BinaryOperator::Opcode Op) {
1247330f729Sjoerg assert(BinaryOperator::isLogicalOp(Op) ||
1257330f729Sjoerg BinaryOperator::isComparisonOp(Op));
126*e038c9c4Sjoerg return BinaryOperator::Create(
127*e038c9c4Sjoerg C, const_cast<Expr *>(LHS), const_cast<Expr *>(RHS), Op,
128*e038c9c4Sjoerg C.getLogicalOperationType(), VK_RValue, OK_Ordinary, SourceLocation(),
129*e038c9c4Sjoerg FPOptionsOverride());
1307330f729Sjoerg }
1317330f729Sjoerg
makeCompound(ArrayRef<Stmt * > Stmts)1327330f729Sjoerg CompoundStmt *ASTMaker::makeCompound(ArrayRef<Stmt *> Stmts) {
1337330f729Sjoerg return CompoundStmt::Create(C, Stmts, SourceLocation(), SourceLocation());
1347330f729Sjoerg }
1357330f729Sjoerg
makeDeclRefExpr(const VarDecl * D,bool RefersToEnclosingVariableOrCapture)1367330f729Sjoerg DeclRefExpr *ASTMaker::makeDeclRefExpr(
1377330f729Sjoerg const VarDecl *D,
1387330f729Sjoerg bool RefersToEnclosingVariableOrCapture) {
1397330f729Sjoerg QualType Type = D->getType().getNonReferenceType();
1407330f729Sjoerg
1417330f729Sjoerg DeclRefExpr *DR = DeclRefExpr::Create(
1427330f729Sjoerg C, NestedNameSpecifierLoc(), SourceLocation(), const_cast<VarDecl *>(D),
1437330f729Sjoerg RefersToEnclosingVariableOrCapture, SourceLocation(), Type, VK_LValue);
1447330f729Sjoerg return DR;
1457330f729Sjoerg }
1467330f729Sjoerg
makeDereference(const Expr * Arg,QualType Ty)1477330f729Sjoerg UnaryOperator *ASTMaker::makeDereference(const Expr *Arg, QualType Ty) {
148*e038c9c4Sjoerg return UnaryOperator::Create(C, const_cast<Expr *>(Arg), UO_Deref, Ty,
1497330f729Sjoerg VK_LValue, OK_Ordinary, SourceLocation(),
150*e038c9c4Sjoerg /*CanOverflow*/ false, FPOptionsOverride());
1517330f729Sjoerg }
1527330f729Sjoerg
makeLvalueToRvalue(const Expr * Arg,QualType Ty)1537330f729Sjoerg ImplicitCastExpr *ASTMaker::makeLvalueToRvalue(const Expr *Arg, QualType Ty) {
1547330f729Sjoerg return makeImplicitCast(Arg, Ty, CK_LValueToRValue);
1557330f729Sjoerg }
1567330f729Sjoerg
1577330f729Sjoerg ImplicitCastExpr *
makeLvalueToRvalue(const VarDecl * Arg,bool RefersToEnclosingVariableOrCapture)1587330f729Sjoerg ASTMaker::makeLvalueToRvalue(const VarDecl *Arg,
1597330f729Sjoerg bool RefersToEnclosingVariableOrCapture) {
1607330f729Sjoerg QualType Type = Arg->getType().getNonReferenceType();
1617330f729Sjoerg return makeLvalueToRvalue(makeDeclRefExpr(Arg,
1627330f729Sjoerg RefersToEnclosingVariableOrCapture),
1637330f729Sjoerg Type);
1647330f729Sjoerg }
1657330f729Sjoerg
makeImplicitCast(const Expr * Arg,QualType Ty,CastKind CK)1667330f729Sjoerg ImplicitCastExpr *ASTMaker::makeImplicitCast(const Expr *Arg, QualType Ty,
1677330f729Sjoerg CastKind CK) {
1687330f729Sjoerg return ImplicitCastExpr::Create(C, Ty,
1697330f729Sjoerg /* CastKind=*/CK,
1707330f729Sjoerg /* Expr=*/const_cast<Expr *>(Arg),
1717330f729Sjoerg /* CXXCastPath=*/nullptr,
172*e038c9c4Sjoerg /* ExprValueKind=*/VK_RValue,
173*e038c9c4Sjoerg /* FPFeatures */ FPOptionsOverride());
1747330f729Sjoerg }
1757330f729Sjoerg
makeIntegralCast(const Expr * Arg,QualType Ty)1767330f729Sjoerg Expr *ASTMaker::makeIntegralCast(const Expr *Arg, QualType Ty) {
1777330f729Sjoerg if (Arg->getType() == Ty)
1787330f729Sjoerg return const_cast<Expr*>(Arg);
179*e038c9c4Sjoerg return makeImplicitCast(Arg, Ty, CK_IntegralCast);
1807330f729Sjoerg }
1817330f729Sjoerg
makeIntegralCastToBoolean(const Expr * Arg)1827330f729Sjoerg ImplicitCastExpr *ASTMaker::makeIntegralCastToBoolean(const Expr *Arg) {
183*e038c9c4Sjoerg return makeImplicitCast(Arg, C.BoolTy, CK_IntegralToBoolean);
1847330f729Sjoerg }
1857330f729Sjoerg
makeObjCBool(bool Val)1867330f729Sjoerg ObjCBoolLiteralExpr *ASTMaker::makeObjCBool(bool Val) {
1877330f729Sjoerg QualType Ty = C.getBOOLDecl() ? C.getBOOLType() : C.ObjCBuiltinBoolTy;
1887330f729Sjoerg return new (C) ObjCBoolLiteralExpr(Val, Ty, SourceLocation());
1897330f729Sjoerg }
1907330f729Sjoerg
makeObjCIvarRef(const Expr * Base,const ObjCIvarDecl * IVar)1917330f729Sjoerg ObjCIvarRefExpr *ASTMaker::makeObjCIvarRef(const Expr *Base,
1927330f729Sjoerg const ObjCIvarDecl *IVar) {
1937330f729Sjoerg return new (C) ObjCIvarRefExpr(const_cast<ObjCIvarDecl*>(IVar),
1947330f729Sjoerg IVar->getType(), SourceLocation(),
1957330f729Sjoerg SourceLocation(), const_cast<Expr*>(Base),
1967330f729Sjoerg /*arrow=*/true, /*free=*/false);
1977330f729Sjoerg }
1987330f729Sjoerg
makeReturn(const Expr * RetVal)1997330f729Sjoerg ReturnStmt *ASTMaker::makeReturn(const Expr *RetVal) {
2007330f729Sjoerg return ReturnStmt::Create(C, SourceLocation(), const_cast<Expr *>(RetVal),
2017330f729Sjoerg /* NRVOCandidate=*/nullptr);
2027330f729Sjoerg }
2037330f729Sjoerg
makeIntegerLiteral(uint64_t Value,QualType Ty)2047330f729Sjoerg IntegerLiteral *ASTMaker::makeIntegerLiteral(uint64_t Value, QualType Ty) {
2057330f729Sjoerg llvm::APInt APValue = llvm::APInt(C.getTypeSize(Ty), Value);
2067330f729Sjoerg return IntegerLiteral::Create(C, APValue, Ty, SourceLocation());
2077330f729Sjoerg }
2087330f729Sjoerg
makeMemberExpression(Expr * base,ValueDecl * MemberDecl,bool IsArrow,ExprValueKind ValueKind)2097330f729Sjoerg MemberExpr *ASTMaker::makeMemberExpression(Expr *base, ValueDecl *MemberDecl,
2107330f729Sjoerg bool IsArrow,
2117330f729Sjoerg ExprValueKind ValueKind) {
2127330f729Sjoerg
2137330f729Sjoerg DeclAccessPair FoundDecl = DeclAccessPair::make(MemberDecl, AS_public);
2147330f729Sjoerg return MemberExpr::Create(
2157330f729Sjoerg C, base, IsArrow, SourceLocation(), NestedNameSpecifierLoc(),
2167330f729Sjoerg SourceLocation(), MemberDecl, FoundDecl,
2177330f729Sjoerg DeclarationNameInfo(MemberDecl->getDeclName(), SourceLocation()),
2187330f729Sjoerg /* TemplateArgumentListInfo=*/ nullptr, MemberDecl->getType(), ValueKind,
2197330f729Sjoerg OK_Ordinary, NOUR_None);
2207330f729Sjoerg }
2217330f729Sjoerg
findMemberField(const RecordDecl * RD,StringRef Name)2227330f729Sjoerg ValueDecl *ASTMaker::findMemberField(const RecordDecl *RD, StringRef Name) {
2237330f729Sjoerg
2247330f729Sjoerg CXXBasePaths Paths(
2257330f729Sjoerg /* FindAmbiguities=*/false,
2267330f729Sjoerg /* RecordPaths=*/false,
2277330f729Sjoerg /* DetectVirtual=*/ false);
2287330f729Sjoerg const IdentifierInfo &II = C.Idents.get(Name);
2297330f729Sjoerg DeclarationName DeclName = C.DeclarationNames.getIdentifier(&II);
2307330f729Sjoerg
2317330f729Sjoerg DeclContextLookupResult Decls = RD->lookup(DeclName);
2327330f729Sjoerg for (NamedDecl *FoundDecl : Decls)
2337330f729Sjoerg if (!FoundDecl->getDeclContext()->isFunctionOrMethod())
2347330f729Sjoerg return cast<ValueDecl>(FoundDecl);
2357330f729Sjoerg
2367330f729Sjoerg return nullptr;
2377330f729Sjoerg }
2387330f729Sjoerg
2397330f729Sjoerg //===----------------------------------------------------------------------===//
2407330f729Sjoerg // Creation functions for faux ASTs.
2417330f729Sjoerg //===----------------------------------------------------------------------===//
2427330f729Sjoerg
2437330f729Sjoerg typedef Stmt *(*FunctionFarmer)(ASTContext &C, const FunctionDecl *D);
2447330f729Sjoerg
create_call_once_funcptr_call(ASTContext & C,ASTMaker M,const ParmVarDecl * Callback,ArrayRef<Expr * > CallArgs)2457330f729Sjoerg static CallExpr *create_call_once_funcptr_call(ASTContext &C, ASTMaker M,
2467330f729Sjoerg const ParmVarDecl *Callback,
2477330f729Sjoerg ArrayRef<Expr *> CallArgs) {
2487330f729Sjoerg
2497330f729Sjoerg QualType Ty = Callback->getType();
2507330f729Sjoerg DeclRefExpr *Call = M.makeDeclRefExpr(Callback);
2517330f729Sjoerg Expr *SubExpr;
2527330f729Sjoerg if (Ty->isRValueReferenceType()) {
2537330f729Sjoerg SubExpr = M.makeImplicitCast(
2547330f729Sjoerg Call, Ty.getNonReferenceType(), CK_LValueToRValue);
2557330f729Sjoerg } else if (Ty->isLValueReferenceType() &&
2567330f729Sjoerg Call->getType()->isFunctionType()) {
2577330f729Sjoerg Ty = C.getPointerType(Ty.getNonReferenceType());
2587330f729Sjoerg SubExpr = M.makeImplicitCast(Call, Ty, CK_FunctionToPointerDecay);
2597330f729Sjoerg } else if (Ty->isLValueReferenceType()
2607330f729Sjoerg && Call->getType()->isPointerType()
2617330f729Sjoerg && Call->getType()->getPointeeType()->isFunctionType()){
2627330f729Sjoerg SubExpr = Call;
2637330f729Sjoerg } else {
2647330f729Sjoerg llvm_unreachable("Unexpected state");
2657330f729Sjoerg }
2667330f729Sjoerg
2677330f729Sjoerg return CallExpr::Create(C, SubExpr, CallArgs, C.VoidTy, VK_RValue,
268*e038c9c4Sjoerg SourceLocation(), FPOptionsOverride());
2697330f729Sjoerg }
2707330f729Sjoerg
create_call_once_lambda_call(ASTContext & C,ASTMaker M,const ParmVarDecl * Callback,CXXRecordDecl * CallbackDecl,ArrayRef<Expr * > CallArgs)2717330f729Sjoerg static CallExpr *create_call_once_lambda_call(ASTContext &C, ASTMaker M,
2727330f729Sjoerg const ParmVarDecl *Callback,
2737330f729Sjoerg CXXRecordDecl *CallbackDecl,
2747330f729Sjoerg ArrayRef<Expr *> CallArgs) {
2757330f729Sjoerg assert(CallbackDecl != nullptr);
2767330f729Sjoerg assert(CallbackDecl->isLambda());
2777330f729Sjoerg FunctionDecl *callOperatorDecl = CallbackDecl->getLambdaCallOperator();
2787330f729Sjoerg assert(callOperatorDecl != nullptr);
2797330f729Sjoerg
2807330f729Sjoerg DeclRefExpr *callOperatorDeclRef =
2817330f729Sjoerg DeclRefExpr::Create(/* Ctx =*/ C,
2827330f729Sjoerg /* QualifierLoc =*/ NestedNameSpecifierLoc(),
2837330f729Sjoerg /* TemplateKWLoc =*/ SourceLocation(),
2847330f729Sjoerg const_cast<FunctionDecl *>(callOperatorDecl),
2857330f729Sjoerg /* RefersToEnclosingVariableOrCapture=*/ false,
2867330f729Sjoerg /* NameLoc =*/ SourceLocation(),
2877330f729Sjoerg /* T =*/ callOperatorDecl->getType(),
2887330f729Sjoerg /* VK =*/ VK_LValue);
2897330f729Sjoerg
2907330f729Sjoerg return CXXOperatorCallExpr::Create(
2917330f729Sjoerg /*AstContext=*/C, OO_Call, callOperatorDeclRef,
2927330f729Sjoerg /*Args=*/CallArgs,
2937330f729Sjoerg /*QualType=*/C.VoidTy,
2947330f729Sjoerg /*ExprValueType=*/VK_RValue,
295*e038c9c4Sjoerg /*SourceLocation=*/SourceLocation(),
296*e038c9c4Sjoerg /*FPFeatures=*/FPOptionsOverride());
2977330f729Sjoerg }
2987330f729Sjoerg
2997330f729Sjoerg /// Create a fake body for std::call_once.
3007330f729Sjoerg /// Emulates the following function body:
3017330f729Sjoerg ///
3027330f729Sjoerg /// \code
3037330f729Sjoerg /// typedef struct once_flag_s {
3047330f729Sjoerg /// unsigned long __state = 0;
3057330f729Sjoerg /// } once_flag;
3067330f729Sjoerg /// template<class Callable>
3077330f729Sjoerg /// void call_once(once_flag& o, Callable func) {
3087330f729Sjoerg /// if (!o.__state) {
3097330f729Sjoerg /// func();
3107330f729Sjoerg /// }
3117330f729Sjoerg /// o.__state = 1;
3127330f729Sjoerg /// }
3137330f729Sjoerg /// \endcode
create_call_once(ASTContext & C,const FunctionDecl * D)3147330f729Sjoerg static Stmt *create_call_once(ASTContext &C, const FunctionDecl *D) {
3157330f729Sjoerg LLVM_DEBUG(llvm::dbgs() << "Generating body for call_once\n");
3167330f729Sjoerg
3177330f729Sjoerg // We need at least two parameters.
3187330f729Sjoerg if (D->param_size() < 2)
3197330f729Sjoerg return nullptr;
3207330f729Sjoerg
3217330f729Sjoerg ASTMaker M(C);
3227330f729Sjoerg
3237330f729Sjoerg const ParmVarDecl *Flag = D->getParamDecl(0);
3247330f729Sjoerg const ParmVarDecl *Callback = D->getParamDecl(1);
3257330f729Sjoerg
3267330f729Sjoerg if (!Callback->getType()->isReferenceType()) {
3277330f729Sjoerg llvm::dbgs() << "libcxx03 std::call_once implementation, skipping.\n";
3287330f729Sjoerg return nullptr;
3297330f729Sjoerg }
3307330f729Sjoerg if (!Flag->getType()->isReferenceType()) {
3317330f729Sjoerg llvm::dbgs() << "unknown std::call_once implementation, skipping.\n";
3327330f729Sjoerg return nullptr;
3337330f729Sjoerg }
3347330f729Sjoerg
3357330f729Sjoerg QualType CallbackType = Callback->getType().getNonReferenceType();
3367330f729Sjoerg
3377330f729Sjoerg // Nullable pointer, non-null iff function is a CXXRecordDecl.
3387330f729Sjoerg CXXRecordDecl *CallbackRecordDecl = CallbackType->getAsCXXRecordDecl();
3397330f729Sjoerg QualType FlagType = Flag->getType().getNonReferenceType();
3407330f729Sjoerg auto *FlagRecordDecl = FlagType->getAsRecordDecl();
3417330f729Sjoerg
3427330f729Sjoerg if (!FlagRecordDecl) {
3437330f729Sjoerg LLVM_DEBUG(llvm::dbgs() << "Flag field is not a record: "
3447330f729Sjoerg << "unknown std::call_once implementation, "
3457330f729Sjoerg << "ignoring the call.\n");
3467330f729Sjoerg return nullptr;
3477330f729Sjoerg }
3487330f729Sjoerg
3497330f729Sjoerg // We initially assume libc++ implementation of call_once,
3507330f729Sjoerg // where the once_flag struct has a field `__state_`.
3517330f729Sjoerg ValueDecl *FlagFieldDecl = M.findMemberField(FlagRecordDecl, "__state_");
3527330f729Sjoerg
3537330f729Sjoerg // Otherwise, try libstdc++ implementation, with a field
3547330f729Sjoerg // `_M_once`
3557330f729Sjoerg if (!FlagFieldDecl) {
3567330f729Sjoerg FlagFieldDecl = M.findMemberField(FlagRecordDecl, "_M_once");
3577330f729Sjoerg }
3587330f729Sjoerg
3597330f729Sjoerg if (!FlagFieldDecl) {
3607330f729Sjoerg LLVM_DEBUG(llvm::dbgs() << "No field _M_once or __state_ found on "
3617330f729Sjoerg << "std::once_flag struct: unknown std::call_once "
3627330f729Sjoerg << "implementation, ignoring the call.");
3637330f729Sjoerg return nullptr;
3647330f729Sjoerg }
3657330f729Sjoerg
3667330f729Sjoerg bool isLambdaCall = CallbackRecordDecl && CallbackRecordDecl->isLambda();
3677330f729Sjoerg if (CallbackRecordDecl && !isLambdaCall) {
3687330f729Sjoerg LLVM_DEBUG(llvm::dbgs()
3697330f729Sjoerg << "Not supported: synthesizing body for functors when "
3707330f729Sjoerg << "body farming std::call_once, ignoring the call.");
3717330f729Sjoerg return nullptr;
3727330f729Sjoerg }
3737330f729Sjoerg
3747330f729Sjoerg SmallVector<Expr *, 5> CallArgs;
3757330f729Sjoerg const FunctionProtoType *CallbackFunctionType;
3767330f729Sjoerg if (isLambdaCall) {
3777330f729Sjoerg
3787330f729Sjoerg // Lambda requires callback itself inserted as a first parameter.
3797330f729Sjoerg CallArgs.push_back(
3807330f729Sjoerg M.makeDeclRefExpr(Callback,
3817330f729Sjoerg /* RefersToEnclosingVariableOrCapture=*/ true));
3827330f729Sjoerg CallbackFunctionType = CallbackRecordDecl->getLambdaCallOperator()
3837330f729Sjoerg ->getType()
3847330f729Sjoerg ->getAs<FunctionProtoType>();
3857330f729Sjoerg } else if (!CallbackType->getPointeeType().isNull()) {
3867330f729Sjoerg CallbackFunctionType =
3877330f729Sjoerg CallbackType->getPointeeType()->getAs<FunctionProtoType>();
3887330f729Sjoerg } else {
3897330f729Sjoerg CallbackFunctionType = CallbackType->getAs<FunctionProtoType>();
3907330f729Sjoerg }
3917330f729Sjoerg
3927330f729Sjoerg if (!CallbackFunctionType)
3937330f729Sjoerg return nullptr;
3947330f729Sjoerg
3957330f729Sjoerg // First two arguments are used for the flag and for the callback.
3967330f729Sjoerg if (D->getNumParams() != CallbackFunctionType->getNumParams() + 2) {
3977330f729Sjoerg LLVM_DEBUG(llvm::dbgs() << "Types of params of the callback do not match "
3987330f729Sjoerg << "params passed to std::call_once, "
3997330f729Sjoerg << "ignoring the call\n");
4007330f729Sjoerg return nullptr;
4017330f729Sjoerg }
4027330f729Sjoerg
4037330f729Sjoerg // All arguments past first two ones are passed to the callback,
4047330f729Sjoerg // and we turn lvalues into rvalues if the argument is not passed by
4057330f729Sjoerg // reference.
4067330f729Sjoerg for (unsigned int ParamIdx = 2; ParamIdx < D->getNumParams(); ParamIdx++) {
4077330f729Sjoerg const ParmVarDecl *PDecl = D->getParamDecl(ParamIdx);
4087330f729Sjoerg assert(PDecl);
4097330f729Sjoerg if (CallbackFunctionType->getParamType(ParamIdx - 2)
4107330f729Sjoerg .getNonReferenceType()
4117330f729Sjoerg .getCanonicalType() !=
4127330f729Sjoerg PDecl->getType().getNonReferenceType().getCanonicalType()) {
4137330f729Sjoerg LLVM_DEBUG(llvm::dbgs() << "Types of params of the callback do not match "
4147330f729Sjoerg << "params passed to std::call_once, "
4157330f729Sjoerg << "ignoring the call\n");
4167330f729Sjoerg return nullptr;
4177330f729Sjoerg }
4187330f729Sjoerg Expr *ParamExpr = M.makeDeclRefExpr(PDecl);
4197330f729Sjoerg if (!CallbackFunctionType->getParamType(ParamIdx - 2)->isReferenceType()) {
4207330f729Sjoerg QualType PTy = PDecl->getType().getNonReferenceType();
4217330f729Sjoerg ParamExpr = M.makeLvalueToRvalue(ParamExpr, PTy);
4227330f729Sjoerg }
4237330f729Sjoerg CallArgs.push_back(ParamExpr);
4247330f729Sjoerg }
4257330f729Sjoerg
4267330f729Sjoerg CallExpr *CallbackCall;
4277330f729Sjoerg if (isLambdaCall) {
4287330f729Sjoerg
4297330f729Sjoerg CallbackCall = create_call_once_lambda_call(C, M, Callback,
4307330f729Sjoerg CallbackRecordDecl, CallArgs);
4317330f729Sjoerg } else {
4327330f729Sjoerg
4337330f729Sjoerg // Function pointer case.
4347330f729Sjoerg CallbackCall = create_call_once_funcptr_call(C, M, Callback, CallArgs);
4357330f729Sjoerg }
4367330f729Sjoerg
4377330f729Sjoerg DeclRefExpr *FlagDecl =
4387330f729Sjoerg M.makeDeclRefExpr(Flag,
4397330f729Sjoerg /* RefersToEnclosingVariableOrCapture=*/true);
4407330f729Sjoerg
4417330f729Sjoerg
4427330f729Sjoerg MemberExpr *Deref = M.makeMemberExpression(FlagDecl, FlagFieldDecl);
4437330f729Sjoerg assert(Deref->isLValue());
4447330f729Sjoerg QualType DerefType = Deref->getType();
4457330f729Sjoerg
4467330f729Sjoerg // Negation predicate.
447*e038c9c4Sjoerg UnaryOperator *FlagCheck = UnaryOperator::Create(
448*e038c9c4Sjoerg C,
4497330f729Sjoerg /* input=*/
4507330f729Sjoerg M.makeImplicitCast(M.makeLvalueToRvalue(Deref, DerefType), DerefType,
4517330f729Sjoerg CK_IntegralToBoolean),
4527330f729Sjoerg /* opc=*/UO_LNot,
4537330f729Sjoerg /* QualType=*/C.IntTy,
4547330f729Sjoerg /* ExprValueKind=*/VK_RValue,
4557330f729Sjoerg /* ExprObjectKind=*/OK_Ordinary, SourceLocation(),
456*e038c9c4Sjoerg /* CanOverflow*/ false, FPOptionsOverride());
4577330f729Sjoerg
4587330f729Sjoerg // Create assignment.
4597330f729Sjoerg BinaryOperator *FlagAssignment = M.makeAssignment(
4607330f729Sjoerg Deref, M.makeIntegralCast(M.makeIntegerLiteral(1, C.IntTy), DerefType),
4617330f729Sjoerg DerefType);
4627330f729Sjoerg
4637330f729Sjoerg auto *Out =
4647330f729Sjoerg IfStmt::Create(C, SourceLocation(),
4657330f729Sjoerg /* IsConstexpr=*/false,
4667330f729Sjoerg /* Init=*/nullptr,
4677330f729Sjoerg /* Var=*/nullptr,
4687330f729Sjoerg /* Cond=*/FlagCheck,
469*e038c9c4Sjoerg /* LPL=*/SourceLocation(),
470*e038c9c4Sjoerg /* RPL=*/SourceLocation(),
4717330f729Sjoerg /* Then=*/M.makeCompound({CallbackCall, FlagAssignment}));
4727330f729Sjoerg
4737330f729Sjoerg return Out;
4747330f729Sjoerg }
4757330f729Sjoerg
4767330f729Sjoerg /// Create a fake body for dispatch_once.
create_dispatch_once(ASTContext & C,const FunctionDecl * D)4777330f729Sjoerg static Stmt *create_dispatch_once(ASTContext &C, const FunctionDecl *D) {
4787330f729Sjoerg // Check if we have at least two parameters.
4797330f729Sjoerg if (D->param_size() != 2)
4807330f729Sjoerg return nullptr;
4817330f729Sjoerg
4827330f729Sjoerg // Check if the first parameter is a pointer to integer type.
4837330f729Sjoerg const ParmVarDecl *Predicate = D->getParamDecl(0);
4847330f729Sjoerg QualType PredicateQPtrTy = Predicate->getType();
4857330f729Sjoerg const PointerType *PredicatePtrTy = PredicateQPtrTy->getAs<PointerType>();
4867330f729Sjoerg if (!PredicatePtrTy)
4877330f729Sjoerg return nullptr;
4887330f729Sjoerg QualType PredicateTy = PredicatePtrTy->getPointeeType();
4897330f729Sjoerg if (!PredicateTy->isIntegerType())
4907330f729Sjoerg return nullptr;
4917330f729Sjoerg
4927330f729Sjoerg // Check if the second parameter is the proper block type.
4937330f729Sjoerg const ParmVarDecl *Block = D->getParamDecl(1);
4947330f729Sjoerg QualType Ty = Block->getType();
4957330f729Sjoerg if (!isDispatchBlock(Ty))
4967330f729Sjoerg return nullptr;
4977330f729Sjoerg
4987330f729Sjoerg // Everything checks out. Create a fakse body that checks the predicate,
4997330f729Sjoerg // sets it, and calls the block. Basically, an AST dump of:
5007330f729Sjoerg //
5017330f729Sjoerg // void dispatch_once(dispatch_once_t *predicate, dispatch_block_t block) {
5027330f729Sjoerg // if (*predicate != ~0l) {
5037330f729Sjoerg // *predicate = ~0l;
5047330f729Sjoerg // block();
5057330f729Sjoerg // }
5067330f729Sjoerg // }
5077330f729Sjoerg
5087330f729Sjoerg ASTMaker M(C);
5097330f729Sjoerg
5107330f729Sjoerg // (1) Create the call.
5117330f729Sjoerg CallExpr *CE = CallExpr::Create(
5127330f729Sjoerg /*ASTContext=*/C,
5137330f729Sjoerg /*StmtClass=*/M.makeLvalueToRvalue(/*Expr=*/Block),
5147330f729Sjoerg /*Args=*/None,
5157330f729Sjoerg /*QualType=*/C.VoidTy,
5167330f729Sjoerg /*ExprValueType=*/VK_RValue,
517*e038c9c4Sjoerg /*SourceLocation=*/SourceLocation(), FPOptionsOverride());
5187330f729Sjoerg
5197330f729Sjoerg // (2) Create the assignment to the predicate.
5207330f729Sjoerg Expr *DoneValue =
521*e038c9c4Sjoerg UnaryOperator::Create(C, M.makeIntegerLiteral(0, C.LongTy), UO_Not,
522*e038c9c4Sjoerg C.LongTy, VK_RValue, OK_Ordinary, SourceLocation(),
523*e038c9c4Sjoerg /*CanOverflow*/ false, FPOptionsOverride());
5247330f729Sjoerg
5257330f729Sjoerg BinaryOperator *B =
5267330f729Sjoerg M.makeAssignment(
5277330f729Sjoerg M.makeDereference(
5287330f729Sjoerg M.makeLvalueToRvalue(
5297330f729Sjoerg M.makeDeclRefExpr(Predicate), PredicateQPtrTy),
5307330f729Sjoerg PredicateTy),
5317330f729Sjoerg M.makeIntegralCast(DoneValue, PredicateTy),
5327330f729Sjoerg PredicateTy);
5337330f729Sjoerg
5347330f729Sjoerg // (3) Create the compound statement.
5357330f729Sjoerg Stmt *Stmts[] = { B, CE };
5367330f729Sjoerg CompoundStmt *CS = M.makeCompound(Stmts);
5377330f729Sjoerg
5387330f729Sjoerg // (4) Create the 'if' condition.
5397330f729Sjoerg ImplicitCastExpr *LValToRval =
5407330f729Sjoerg M.makeLvalueToRvalue(
5417330f729Sjoerg M.makeDereference(
5427330f729Sjoerg M.makeLvalueToRvalue(
5437330f729Sjoerg M.makeDeclRefExpr(Predicate),
5447330f729Sjoerg PredicateQPtrTy),
5457330f729Sjoerg PredicateTy),
5467330f729Sjoerg PredicateTy);
5477330f729Sjoerg
5487330f729Sjoerg Expr *GuardCondition = M.makeComparison(LValToRval, DoneValue, BO_NE);
5497330f729Sjoerg // (5) Create the 'if' statement.
5507330f729Sjoerg auto *If = IfStmt::Create(C, SourceLocation(),
5517330f729Sjoerg /* IsConstexpr=*/false,
5527330f729Sjoerg /* Init=*/nullptr,
5537330f729Sjoerg /* Var=*/nullptr,
5547330f729Sjoerg /* Cond=*/GuardCondition,
555*e038c9c4Sjoerg /* LPL=*/SourceLocation(),
556*e038c9c4Sjoerg /* RPL=*/SourceLocation(),
5577330f729Sjoerg /* Then=*/CS);
5587330f729Sjoerg return If;
5597330f729Sjoerg }
5607330f729Sjoerg
5617330f729Sjoerg /// Create a fake body for dispatch_sync.
create_dispatch_sync(ASTContext & C,const FunctionDecl * D)5627330f729Sjoerg static Stmt *create_dispatch_sync(ASTContext &C, const FunctionDecl *D) {
5637330f729Sjoerg // Check if we have at least two parameters.
5647330f729Sjoerg if (D->param_size() != 2)
5657330f729Sjoerg return nullptr;
5667330f729Sjoerg
5677330f729Sjoerg // Check if the second parameter is a block.
5687330f729Sjoerg const ParmVarDecl *PV = D->getParamDecl(1);
5697330f729Sjoerg QualType Ty = PV->getType();
5707330f729Sjoerg if (!isDispatchBlock(Ty))
5717330f729Sjoerg return nullptr;
5727330f729Sjoerg
5737330f729Sjoerg // Everything checks out. Create a fake body that just calls the block.
5747330f729Sjoerg // This is basically just an AST dump of:
5757330f729Sjoerg //
5767330f729Sjoerg // void dispatch_sync(dispatch_queue_t queue, void (^block)(void)) {
5777330f729Sjoerg // block();
5787330f729Sjoerg // }
5797330f729Sjoerg //
5807330f729Sjoerg ASTMaker M(C);
5817330f729Sjoerg DeclRefExpr *DR = M.makeDeclRefExpr(PV);
5827330f729Sjoerg ImplicitCastExpr *ICE = M.makeLvalueToRvalue(DR, Ty);
583*e038c9c4Sjoerg CallExpr *CE = CallExpr::Create(C, ICE, None, C.VoidTy, VK_RValue,
584*e038c9c4Sjoerg SourceLocation(), FPOptionsOverride());
5857330f729Sjoerg return CE;
5867330f729Sjoerg }
5877330f729Sjoerg
create_OSAtomicCompareAndSwap(ASTContext & C,const FunctionDecl * D)5887330f729Sjoerg static Stmt *create_OSAtomicCompareAndSwap(ASTContext &C, const FunctionDecl *D)
5897330f729Sjoerg {
5907330f729Sjoerg // There are exactly 3 arguments.
5917330f729Sjoerg if (D->param_size() != 3)
5927330f729Sjoerg return nullptr;
5937330f729Sjoerg
5947330f729Sjoerg // Signature:
5957330f729Sjoerg // _Bool OSAtomicCompareAndSwapPtr(void *__oldValue,
5967330f729Sjoerg // void *__newValue,
5977330f729Sjoerg // void * volatile *__theValue)
5987330f729Sjoerg // Generate body:
5997330f729Sjoerg // if (oldValue == *theValue) {
6007330f729Sjoerg // *theValue = newValue;
6017330f729Sjoerg // return YES;
6027330f729Sjoerg // }
6037330f729Sjoerg // else return NO;
6047330f729Sjoerg
6057330f729Sjoerg QualType ResultTy = D->getReturnType();
6067330f729Sjoerg bool isBoolean = ResultTy->isBooleanType();
6077330f729Sjoerg if (!isBoolean && !ResultTy->isIntegralType(C))
6087330f729Sjoerg return nullptr;
6097330f729Sjoerg
6107330f729Sjoerg const ParmVarDecl *OldValue = D->getParamDecl(0);
6117330f729Sjoerg QualType OldValueTy = OldValue->getType();
6127330f729Sjoerg
6137330f729Sjoerg const ParmVarDecl *NewValue = D->getParamDecl(1);
6147330f729Sjoerg QualType NewValueTy = NewValue->getType();
6157330f729Sjoerg
6167330f729Sjoerg assert(OldValueTy == NewValueTy);
6177330f729Sjoerg
6187330f729Sjoerg const ParmVarDecl *TheValue = D->getParamDecl(2);
6197330f729Sjoerg QualType TheValueTy = TheValue->getType();
6207330f729Sjoerg const PointerType *PT = TheValueTy->getAs<PointerType>();
6217330f729Sjoerg if (!PT)
6227330f729Sjoerg return nullptr;
6237330f729Sjoerg QualType PointeeTy = PT->getPointeeType();
6247330f729Sjoerg
6257330f729Sjoerg ASTMaker M(C);
6267330f729Sjoerg // Construct the comparison.
6277330f729Sjoerg Expr *Comparison =
6287330f729Sjoerg M.makeComparison(
6297330f729Sjoerg M.makeLvalueToRvalue(M.makeDeclRefExpr(OldValue), OldValueTy),
6307330f729Sjoerg M.makeLvalueToRvalue(
6317330f729Sjoerg M.makeDereference(
6327330f729Sjoerg M.makeLvalueToRvalue(M.makeDeclRefExpr(TheValue), TheValueTy),
6337330f729Sjoerg PointeeTy),
6347330f729Sjoerg PointeeTy),
6357330f729Sjoerg BO_EQ);
6367330f729Sjoerg
6377330f729Sjoerg // Construct the body of the IfStmt.
6387330f729Sjoerg Stmt *Stmts[2];
6397330f729Sjoerg Stmts[0] =
6407330f729Sjoerg M.makeAssignment(
6417330f729Sjoerg M.makeDereference(
6427330f729Sjoerg M.makeLvalueToRvalue(M.makeDeclRefExpr(TheValue), TheValueTy),
6437330f729Sjoerg PointeeTy),
6447330f729Sjoerg M.makeLvalueToRvalue(M.makeDeclRefExpr(NewValue), NewValueTy),
6457330f729Sjoerg NewValueTy);
6467330f729Sjoerg
6477330f729Sjoerg Expr *BoolVal = M.makeObjCBool(true);
6487330f729Sjoerg Expr *RetVal = isBoolean ? M.makeIntegralCastToBoolean(BoolVal)
6497330f729Sjoerg : M.makeIntegralCast(BoolVal, ResultTy);
6507330f729Sjoerg Stmts[1] = M.makeReturn(RetVal);
6517330f729Sjoerg CompoundStmt *Body = M.makeCompound(Stmts);
6527330f729Sjoerg
6537330f729Sjoerg // Construct the else clause.
6547330f729Sjoerg BoolVal = M.makeObjCBool(false);
6557330f729Sjoerg RetVal = isBoolean ? M.makeIntegralCastToBoolean(BoolVal)
6567330f729Sjoerg : M.makeIntegralCast(BoolVal, ResultTy);
6577330f729Sjoerg Stmt *Else = M.makeReturn(RetVal);
6587330f729Sjoerg
6597330f729Sjoerg /// Construct the If.
660*e038c9c4Sjoerg auto *If =
661*e038c9c4Sjoerg IfStmt::Create(C, SourceLocation(),
6627330f729Sjoerg /* IsConstexpr=*/false,
6637330f729Sjoerg /* Init=*/nullptr,
664*e038c9c4Sjoerg /* Var=*/nullptr, Comparison,
665*e038c9c4Sjoerg /* LPL=*/SourceLocation(),
666*e038c9c4Sjoerg /* RPL=*/SourceLocation(), Body, SourceLocation(), Else);
6677330f729Sjoerg
6687330f729Sjoerg return If;
6697330f729Sjoerg }
6707330f729Sjoerg
getBody(const FunctionDecl * D)6717330f729Sjoerg Stmt *BodyFarm::getBody(const FunctionDecl *D) {
6727330f729Sjoerg Optional<Stmt *> &Val = Bodies[D];
6737330f729Sjoerg if (Val.hasValue())
6747330f729Sjoerg return Val.getValue();
6757330f729Sjoerg
6767330f729Sjoerg Val = nullptr;
6777330f729Sjoerg
6787330f729Sjoerg if (D->getIdentifier() == nullptr)
6797330f729Sjoerg return nullptr;
6807330f729Sjoerg
6817330f729Sjoerg StringRef Name = D->getName();
6827330f729Sjoerg if (Name.empty())
6837330f729Sjoerg return nullptr;
6847330f729Sjoerg
6857330f729Sjoerg FunctionFarmer FF;
6867330f729Sjoerg
6877330f729Sjoerg if (Name.startswith("OSAtomicCompareAndSwap") ||
6887330f729Sjoerg Name.startswith("objc_atomicCompareAndSwap")) {
6897330f729Sjoerg FF = create_OSAtomicCompareAndSwap;
6907330f729Sjoerg } else if (Name == "call_once" && D->getDeclContext()->isStdNamespace()) {
6917330f729Sjoerg FF = create_call_once;
6927330f729Sjoerg } else {
6937330f729Sjoerg FF = llvm::StringSwitch<FunctionFarmer>(Name)
6947330f729Sjoerg .Case("dispatch_sync", create_dispatch_sync)
6957330f729Sjoerg .Case("dispatch_once", create_dispatch_once)
6967330f729Sjoerg .Default(nullptr);
6977330f729Sjoerg }
6987330f729Sjoerg
6997330f729Sjoerg if (FF) { Val = FF(C, D); }
7007330f729Sjoerg else if (Injector) { Val = Injector->getBody(D); }
7017330f729Sjoerg return Val.getValue();
7027330f729Sjoerg }
7037330f729Sjoerg
findBackingIvar(const ObjCPropertyDecl * Prop)7047330f729Sjoerg static const ObjCIvarDecl *findBackingIvar(const ObjCPropertyDecl *Prop) {
7057330f729Sjoerg const ObjCIvarDecl *IVar = Prop->getPropertyIvarDecl();
7067330f729Sjoerg
7077330f729Sjoerg if (IVar)
7087330f729Sjoerg return IVar;
7097330f729Sjoerg
7107330f729Sjoerg // When a readonly property is shadowed in a class extensions with a
7117330f729Sjoerg // a readwrite property, the instance variable belongs to the shadowing
7127330f729Sjoerg // property rather than the shadowed property. If there is no instance
7137330f729Sjoerg // variable on a readonly property, check to see whether the property is
7147330f729Sjoerg // shadowed and if so try to get the instance variable from shadowing
7157330f729Sjoerg // property.
7167330f729Sjoerg if (!Prop->isReadOnly())
7177330f729Sjoerg return nullptr;
7187330f729Sjoerg
7197330f729Sjoerg auto *Container = cast<ObjCContainerDecl>(Prop->getDeclContext());
7207330f729Sjoerg const ObjCInterfaceDecl *PrimaryInterface = nullptr;
7217330f729Sjoerg if (auto *InterfaceDecl = dyn_cast<ObjCInterfaceDecl>(Container)) {
7227330f729Sjoerg PrimaryInterface = InterfaceDecl;
7237330f729Sjoerg } else if (auto *CategoryDecl = dyn_cast<ObjCCategoryDecl>(Container)) {
7247330f729Sjoerg PrimaryInterface = CategoryDecl->getClassInterface();
7257330f729Sjoerg } else if (auto *ImplDecl = dyn_cast<ObjCImplDecl>(Container)) {
7267330f729Sjoerg PrimaryInterface = ImplDecl->getClassInterface();
7277330f729Sjoerg } else {
7287330f729Sjoerg return nullptr;
7297330f729Sjoerg }
7307330f729Sjoerg
7317330f729Sjoerg // FindPropertyVisibleInPrimaryClass() looks first in class extensions, so it
7327330f729Sjoerg // is guaranteed to find the shadowing property, if it exists, rather than
7337330f729Sjoerg // the shadowed property.
7347330f729Sjoerg auto *ShadowingProp = PrimaryInterface->FindPropertyVisibleInPrimaryClass(
7357330f729Sjoerg Prop->getIdentifier(), Prop->getQueryKind());
7367330f729Sjoerg if (ShadowingProp && ShadowingProp != Prop) {
7377330f729Sjoerg IVar = ShadowingProp->getPropertyIvarDecl();
7387330f729Sjoerg }
7397330f729Sjoerg
7407330f729Sjoerg return IVar;
7417330f729Sjoerg }
7427330f729Sjoerg
createObjCPropertyGetter(ASTContext & Ctx,const ObjCMethodDecl * MD)7437330f729Sjoerg static Stmt *createObjCPropertyGetter(ASTContext &Ctx,
744*e038c9c4Sjoerg const ObjCMethodDecl *MD) {
7457330f729Sjoerg // First, find the backing ivar.
746*e038c9c4Sjoerg const ObjCIvarDecl *IVar = nullptr;
747*e038c9c4Sjoerg const ObjCPropertyDecl *Prop = nullptr;
748*e038c9c4Sjoerg
749*e038c9c4Sjoerg // Property accessor stubs sometimes do not correspond to any property decl
750*e038c9c4Sjoerg // in the current interface (but in a superclass). They still have a
751*e038c9c4Sjoerg // corresponding property impl decl in this case.
752*e038c9c4Sjoerg if (MD->isSynthesizedAccessorStub()) {
753*e038c9c4Sjoerg const ObjCInterfaceDecl *IntD = MD->getClassInterface();
754*e038c9c4Sjoerg const ObjCImplementationDecl *ImpD = IntD->getImplementation();
755*e038c9c4Sjoerg for (const auto *PI : ImpD->property_impls()) {
756*e038c9c4Sjoerg if (const ObjCPropertyDecl *Candidate = PI->getPropertyDecl()) {
757*e038c9c4Sjoerg if (Candidate->getGetterName() == MD->getSelector()) {
758*e038c9c4Sjoerg Prop = Candidate;
759*e038c9c4Sjoerg IVar = Prop->getPropertyIvarDecl();
760*e038c9c4Sjoerg }
761*e038c9c4Sjoerg }
762*e038c9c4Sjoerg }
763*e038c9c4Sjoerg }
764*e038c9c4Sjoerg
765*e038c9c4Sjoerg if (!IVar) {
766*e038c9c4Sjoerg Prop = MD->findPropertyDecl();
767*e038c9c4Sjoerg IVar = findBackingIvar(Prop);
768*e038c9c4Sjoerg }
769*e038c9c4Sjoerg
770*e038c9c4Sjoerg if (!IVar || !Prop)
7717330f729Sjoerg return nullptr;
7727330f729Sjoerg
7737330f729Sjoerg // Ignore weak variables, which have special behavior.
774*e038c9c4Sjoerg if (Prop->getPropertyAttributes() & ObjCPropertyAttribute::kind_weak)
7757330f729Sjoerg return nullptr;
7767330f729Sjoerg
7777330f729Sjoerg // Look to see if Sema has synthesized a body for us. This happens in
7787330f729Sjoerg // Objective-C++ because the return value may be a C++ class type with a
7797330f729Sjoerg // non-trivial copy constructor. We can only do this if we can find the
7807330f729Sjoerg // @synthesize for this property, though (or if we know it's been auto-
7817330f729Sjoerg // synthesized).
7827330f729Sjoerg const ObjCImplementationDecl *ImplDecl =
7837330f729Sjoerg IVar->getContainingInterface()->getImplementation();
7847330f729Sjoerg if (ImplDecl) {
7857330f729Sjoerg for (const auto *I : ImplDecl->property_impls()) {
7867330f729Sjoerg if (I->getPropertyDecl() != Prop)
7877330f729Sjoerg continue;
7887330f729Sjoerg
7897330f729Sjoerg if (I->getGetterCXXConstructor()) {
7907330f729Sjoerg ASTMaker M(Ctx);
7917330f729Sjoerg return M.makeReturn(I->getGetterCXXConstructor());
7927330f729Sjoerg }
7937330f729Sjoerg }
7947330f729Sjoerg }
7957330f729Sjoerg
7967330f729Sjoerg // Sanity check that the property is the same type as the ivar, or a
7977330f729Sjoerg // reference to it, and that it is either an object pointer or trivially
7987330f729Sjoerg // copyable.
7997330f729Sjoerg if (!Ctx.hasSameUnqualifiedType(IVar->getType(),
8007330f729Sjoerg Prop->getType().getNonReferenceType()))
8017330f729Sjoerg return nullptr;
8027330f729Sjoerg if (!IVar->getType()->isObjCLifetimeType() &&
8037330f729Sjoerg !IVar->getType().isTriviallyCopyableType(Ctx))
8047330f729Sjoerg return nullptr;
8057330f729Sjoerg
8067330f729Sjoerg // Generate our body:
8077330f729Sjoerg // return self->_ivar;
8087330f729Sjoerg ASTMaker M(Ctx);
8097330f729Sjoerg
810*e038c9c4Sjoerg const VarDecl *selfVar = MD->getSelfDecl();
8117330f729Sjoerg if (!selfVar)
8127330f729Sjoerg return nullptr;
8137330f729Sjoerg
814*e038c9c4Sjoerg Expr *loadedIVar = M.makeObjCIvarRef(
815*e038c9c4Sjoerg M.makeLvalueToRvalue(M.makeDeclRefExpr(selfVar), selfVar->getType()),
8167330f729Sjoerg IVar);
8177330f729Sjoerg
818*e038c9c4Sjoerg if (!MD->getReturnType()->isReferenceType())
8197330f729Sjoerg loadedIVar = M.makeLvalueToRvalue(loadedIVar, IVar->getType());
8207330f729Sjoerg
8217330f729Sjoerg return M.makeReturn(loadedIVar);
8227330f729Sjoerg }
8237330f729Sjoerg
getBody(const ObjCMethodDecl * D)8247330f729Sjoerg Stmt *BodyFarm::getBody(const ObjCMethodDecl *D) {
8257330f729Sjoerg // We currently only know how to synthesize property accessors.
8267330f729Sjoerg if (!D->isPropertyAccessor())
8277330f729Sjoerg return nullptr;
8287330f729Sjoerg
8297330f729Sjoerg D = D->getCanonicalDecl();
8307330f729Sjoerg
8317330f729Sjoerg // We should not try to synthesize explicitly redefined accessors.
8327330f729Sjoerg // We do not know for sure how they behave.
8337330f729Sjoerg if (!D->isImplicit())
8347330f729Sjoerg return nullptr;
8357330f729Sjoerg
8367330f729Sjoerg Optional<Stmt *> &Val = Bodies[D];
8377330f729Sjoerg if (Val.hasValue())
8387330f729Sjoerg return Val.getValue();
8397330f729Sjoerg Val = nullptr;
8407330f729Sjoerg
8417330f729Sjoerg // For now, we only synthesize getters.
8427330f729Sjoerg // Synthesizing setters would cause false negatives in the
8437330f729Sjoerg // RetainCountChecker because the method body would bind the parameter
8447330f729Sjoerg // to an instance variable, causing it to escape. This would prevent
8457330f729Sjoerg // warning in the following common scenario:
8467330f729Sjoerg //
8477330f729Sjoerg // id foo = [[NSObject alloc] init];
8487330f729Sjoerg // self.foo = foo; // We should warn that foo leaks here.
8497330f729Sjoerg //
8507330f729Sjoerg if (D->param_size() != 0)
8517330f729Sjoerg return nullptr;
8527330f729Sjoerg
853*e038c9c4Sjoerg // If the property was defined in an extension, search the extensions for
854*e038c9c4Sjoerg // overrides.
855*e038c9c4Sjoerg const ObjCInterfaceDecl *OID = D->getClassInterface();
856*e038c9c4Sjoerg if (dyn_cast<ObjCInterfaceDecl>(D->getParent()) != OID)
857*e038c9c4Sjoerg for (auto *Ext : OID->known_extensions()) {
858*e038c9c4Sjoerg auto *OMD = Ext->getInstanceMethod(D->getSelector());
859*e038c9c4Sjoerg if (OMD && !OMD->isImplicit())
860*e038c9c4Sjoerg return nullptr;
861*e038c9c4Sjoerg }
862*e038c9c4Sjoerg
863*e038c9c4Sjoerg Val = createObjCPropertyGetter(C, D);
8647330f729Sjoerg
8657330f729Sjoerg return Val.getValue();
8667330f729Sjoerg }
867