1 //== BodyFarm.cpp  - Factory for conjuring up fake bodies ----------*- C++ -*-//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // BodyFarm is a factory for creating faux implementations for functions/methods
10 // for analysis purposes.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Analysis/BodyFarm.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/CXXInheritance.h"
17 #include "clang/AST/Decl.h"
18 #include "clang/AST/Expr.h"
19 #include "clang/AST/ExprCXX.h"
20 #include "clang/AST/ExprObjC.h"
21 #include "clang/AST/NestedNameSpecifier.h"
22 #include "clang/Analysis/CodeInjector.h"
23 #include "clang/Basic/OperatorKinds.h"
24 #include "llvm/ADT/StringSwitch.h"
25 #include "llvm/Support/Debug.h"
26 
27 #define DEBUG_TYPE "body-farm"
28 
29 using namespace clang;
30 
31 //===----------------------------------------------------------------------===//
32 // Helper creation functions for constructing faux ASTs.
33 //===----------------------------------------------------------------------===//
34 
35 static bool isDispatchBlock(QualType Ty) {
36   // Is it a block pointer?
37   const BlockPointerType *BPT = Ty->getAs<BlockPointerType>();
38   if (!BPT)
39     return false;
40 
41   // Check if the block pointer type takes no arguments and
42   // returns void.
43   const FunctionProtoType *FT =
44   BPT->getPointeeType()->getAs<FunctionProtoType>();
45   return FT && FT->getReturnType()->isVoidType() && FT->getNumParams() == 0;
46 }
47 
48 namespace {
49 class ASTMaker {
50 public:
51   ASTMaker(ASTContext &C) : C(C) {}
52 
53   /// Create a new BinaryOperator representing a simple assignment.
54   BinaryOperator *makeAssignment(const Expr *LHS, const Expr *RHS, QualType Ty);
55 
56   /// Create a new BinaryOperator representing a comparison.
57   BinaryOperator *makeComparison(const Expr *LHS, const Expr *RHS,
58                                  BinaryOperator::Opcode Op);
59 
60   /// Create a new compound stmt using the provided statements.
61   CompoundStmt *makeCompound(ArrayRef<Stmt*>);
62 
63   /// Create a new DeclRefExpr for the referenced variable.
64   DeclRefExpr *makeDeclRefExpr(const VarDecl *D,
65                                bool RefersToEnclosingVariableOrCapture = false);
66 
67   /// Create a new UnaryOperator representing a dereference.
68   UnaryOperator *makeDereference(const Expr *Arg, QualType Ty);
69 
70   /// Create an implicit cast for an integer conversion.
71   Expr *makeIntegralCast(const Expr *Arg, QualType Ty);
72 
73   /// Create an implicit cast to a builtin boolean type.
74   ImplicitCastExpr *makeIntegralCastToBoolean(const Expr *Arg);
75 
76   /// Create an implicit cast for lvalue-to-rvaluate conversions.
77   ImplicitCastExpr *makeLvalueToRvalue(const Expr *Arg, QualType Ty);
78 
79   /// Make RValue out of variable declaration, creating a temporary
80   /// DeclRefExpr in the process.
81   ImplicitCastExpr *
82   makeLvalueToRvalue(const VarDecl *Decl,
83                      bool RefersToEnclosingVariableOrCapture = false);
84 
85   /// Create an implicit cast of the given type.
86   ImplicitCastExpr *makeImplicitCast(const Expr *Arg, QualType Ty,
87                                      CastKind CK = CK_LValueToRValue);
88 
89   /// Create an Objective-C bool literal.
90   ObjCBoolLiteralExpr *makeObjCBool(bool Val);
91 
92   /// Create an Objective-C ivar reference.
93   ObjCIvarRefExpr *makeObjCIvarRef(const Expr *Base, const ObjCIvarDecl *IVar);
94 
95   /// Create a Return statement.
96   ReturnStmt *makeReturn(const Expr *RetVal);
97 
98   /// Create an integer literal expression of the given type.
99   IntegerLiteral *makeIntegerLiteral(uint64_t Value, QualType Ty);
100 
101   /// Create a member expression.
102   MemberExpr *makeMemberExpression(Expr *base, ValueDecl *MemberDecl,
103                                    bool IsArrow = false,
104                                    ExprValueKind ValueKind = VK_LValue);
105 
106   /// Returns a *first* member field of a record declaration with a given name.
107   /// \return an nullptr if no member with such a name exists.
108   ValueDecl *findMemberField(const RecordDecl *RD, StringRef Name);
109 
110 private:
111   ASTContext &C;
112 };
113 }
114 
115 BinaryOperator *ASTMaker::makeAssignment(const Expr *LHS, const Expr *RHS,
116                                          QualType Ty) {
117   return BinaryOperator::Create(
118       C, const_cast<Expr *>(LHS), const_cast<Expr *>(RHS), BO_Assign, Ty,
119       VK_RValue, OK_Ordinary, SourceLocation(), FPOptions(C.getLangOpts()));
120 }
121 
122 BinaryOperator *ASTMaker::makeComparison(const Expr *LHS, const Expr *RHS,
123                                          BinaryOperator::Opcode Op) {
124   assert(BinaryOperator::isLogicalOp(Op) ||
125          BinaryOperator::isComparisonOp(Op));
126   return BinaryOperator::Create(C, const_cast<Expr *>(LHS),
127                                 const_cast<Expr *>(RHS), Op,
128                                 C.getLogicalOperationType(), VK_RValue,
129                                 OK_Ordinary, SourceLocation(),
130                                 FPOptions(C.getLangOpts()));
131 }
132 
133 CompoundStmt *ASTMaker::makeCompound(ArrayRef<Stmt *> Stmts) {
134   return CompoundStmt::Create(C, Stmts, SourceLocation(), SourceLocation());
135 }
136 
137 DeclRefExpr *ASTMaker::makeDeclRefExpr(
138     const VarDecl *D,
139     bool RefersToEnclosingVariableOrCapture) {
140   QualType Type = D->getType().getNonReferenceType();
141 
142   DeclRefExpr *DR = DeclRefExpr::Create(
143       C, NestedNameSpecifierLoc(), SourceLocation(), const_cast<VarDecl *>(D),
144       RefersToEnclosingVariableOrCapture, SourceLocation(), Type, VK_LValue);
145   return DR;
146 }
147 
148 UnaryOperator *ASTMaker::makeDereference(const Expr *Arg, QualType Ty) {
149   return UnaryOperator::Create(C, const_cast<Expr *>(Arg), UO_Deref, Ty,
150                                VK_LValue, OK_Ordinary, SourceLocation(),
151                                /*CanOverflow*/ false,
152                                FPOptions(C.getLangOpts()));
153 }
154 
155 ImplicitCastExpr *ASTMaker::makeLvalueToRvalue(const Expr *Arg, QualType Ty) {
156   return makeImplicitCast(Arg, Ty, CK_LValueToRValue);
157 }
158 
159 ImplicitCastExpr *
160 ASTMaker::makeLvalueToRvalue(const VarDecl *Arg,
161                              bool RefersToEnclosingVariableOrCapture) {
162   QualType Type = Arg->getType().getNonReferenceType();
163   return makeLvalueToRvalue(makeDeclRefExpr(Arg,
164                                             RefersToEnclosingVariableOrCapture),
165                             Type);
166 }
167 
168 ImplicitCastExpr *ASTMaker::makeImplicitCast(const Expr *Arg, QualType Ty,
169                                              CastKind CK) {
170   return ImplicitCastExpr::Create(C, Ty,
171                                   /* CastKind=*/ CK,
172                                   /* Expr=*/ const_cast<Expr *>(Arg),
173                                   /* CXXCastPath=*/ nullptr,
174                                   /* ExprValueKind=*/ VK_RValue);
175 }
176 
177 Expr *ASTMaker::makeIntegralCast(const Expr *Arg, QualType Ty) {
178   if (Arg->getType() == Ty)
179     return const_cast<Expr*>(Arg);
180 
181   return ImplicitCastExpr::Create(C, Ty, CK_IntegralCast,
182                                   const_cast<Expr*>(Arg), nullptr, VK_RValue);
183 }
184 
185 ImplicitCastExpr *ASTMaker::makeIntegralCastToBoolean(const Expr *Arg) {
186   return ImplicitCastExpr::Create(C, C.BoolTy, CK_IntegralToBoolean,
187                                   const_cast<Expr*>(Arg), nullptr, VK_RValue);
188 }
189 
190 ObjCBoolLiteralExpr *ASTMaker::makeObjCBool(bool Val) {
191   QualType Ty = C.getBOOLDecl() ? C.getBOOLType() : C.ObjCBuiltinBoolTy;
192   return new (C) ObjCBoolLiteralExpr(Val, Ty, SourceLocation());
193 }
194 
195 ObjCIvarRefExpr *ASTMaker::makeObjCIvarRef(const Expr *Base,
196                                            const ObjCIvarDecl *IVar) {
197   return new (C) ObjCIvarRefExpr(const_cast<ObjCIvarDecl*>(IVar),
198                                  IVar->getType(), SourceLocation(),
199                                  SourceLocation(), const_cast<Expr*>(Base),
200                                  /*arrow=*/true, /*free=*/false);
201 }
202 
203 ReturnStmt *ASTMaker::makeReturn(const Expr *RetVal) {
204   return ReturnStmt::Create(C, SourceLocation(), const_cast<Expr *>(RetVal),
205                             /* NRVOCandidate=*/nullptr);
206 }
207 
208 IntegerLiteral *ASTMaker::makeIntegerLiteral(uint64_t Value, QualType Ty) {
209   llvm::APInt APValue = llvm::APInt(C.getTypeSize(Ty), Value);
210   return IntegerLiteral::Create(C, APValue, Ty, SourceLocation());
211 }
212 
213 MemberExpr *ASTMaker::makeMemberExpression(Expr *base, ValueDecl *MemberDecl,
214                                            bool IsArrow,
215                                            ExprValueKind ValueKind) {
216 
217   DeclAccessPair FoundDecl = DeclAccessPair::make(MemberDecl, AS_public);
218   return MemberExpr::Create(
219       C, base, IsArrow, SourceLocation(), NestedNameSpecifierLoc(),
220       SourceLocation(), MemberDecl, FoundDecl,
221       DeclarationNameInfo(MemberDecl->getDeclName(), SourceLocation()),
222       /* TemplateArgumentListInfo=*/ nullptr, MemberDecl->getType(), ValueKind,
223       OK_Ordinary, NOUR_None);
224 }
225 
226 ValueDecl *ASTMaker::findMemberField(const RecordDecl *RD, StringRef Name) {
227 
228   CXXBasePaths Paths(
229       /* FindAmbiguities=*/false,
230       /* RecordPaths=*/false,
231       /* DetectVirtual=*/ false);
232   const IdentifierInfo &II = C.Idents.get(Name);
233   DeclarationName DeclName = C.DeclarationNames.getIdentifier(&II);
234 
235   DeclContextLookupResult Decls = RD->lookup(DeclName);
236   for (NamedDecl *FoundDecl : Decls)
237     if (!FoundDecl->getDeclContext()->isFunctionOrMethod())
238       return cast<ValueDecl>(FoundDecl);
239 
240   return nullptr;
241 }
242 
243 //===----------------------------------------------------------------------===//
244 // Creation functions for faux ASTs.
245 //===----------------------------------------------------------------------===//
246 
247 typedef Stmt *(*FunctionFarmer)(ASTContext &C, const FunctionDecl *D);
248 
249 static CallExpr *create_call_once_funcptr_call(ASTContext &C, ASTMaker M,
250                                                const ParmVarDecl *Callback,
251                                                ArrayRef<Expr *> CallArgs) {
252 
253   QualType Ty = Callback->getType();
254   DeclRefExpr *Call = M.makeDeclRefExpr(Callback);
255   Expr *SubExpr;
256   if (Ty->isRValueReferenceType()) {
257     SubExpr = M.makeImplicitCast(
258         Call, Ty.getNonReferenceType(), CK_LValueToRValue);
259   } else if (Ty->isLValueReferenceType() &&
260              Call->getType()->isFunctionType()) {
261     Ty = C.getPointerType(Ty.getNonReferenceType());
262     SubExpr = M.makeImplicitCast(Call, Ty, CK_FunctionToPointerDecay);
263   } else if (Ty->isLValueReferenceType()
264              && Call->getType()->isPointerType()
265              && Call->getType()->getPointeeType()->isFunctionType()){
266     SubExpr = Call;
267   } else {
268     llvm_unreachable("Unexpected state");
269   }
270 
271   return CallExpr::Create(C, SubExpr, CallArgs, C.VoidTy, VK_RValue,
272                           SourceLocation());
273 }
274 
275 static CallExpr *create_call_once_lambda_call(ASTContext &C, ASTMaker M,
276                                               const ParmVarDecl *Callback,
277                                               CXXRecordDecl *CallbackDecl,
278                                               ArrayRef<Expr *> CallArgs) {
279   assert(CallbackDecl != nullptr);
280   assert(CallbackDecl->isLambda());
281   FunctionDecl *callOperatorDecl = CallbackDecl->getLambdaCallOperator();
282   assert(callOperatorDecl != nullptr);
283 
284   DeclRefExpr *callOperatorDeclRef =
285       DeclRefExpr::Create(/* Ctx =*/ C,
286                           /* QualifierLoc =*/ NestedNameSpecifierLoc(),
287                           /* TemplateKWLoc =*/ SourceLocation(),
288                           const_cast<FunctionDecl *>(callOperatorDecl),
289                           /* RefersToEnclosingVariableOrCapture=*/ false,
290                           /* NameLoc =*/ SourceLocation(),
291                           /* T =*/ callOperatorDecl->getType(),
292                           /* VK =*/ VK_LValue);
293 
294   return CXXOperatorCallExpr::Create(
295       /*AstContext=*/C, OO_Call, callOperatorDeclRef,
296       /*Args=*/CallArgs,
297       /*QualType=*/C.VoidTy,
298       /*ExprValueType=*/VK_RValue,
299       /*SourceLocation=*/SourceLocation(),
300       /*FPFeatures=*/FPOptions(C.getLangOpts()));
301 }
302 
303 /// Create a fake body for std::call_once.
304 /// Emulates the following function body:
305 ///
306 /// \code
307 /// typedef struct once_flag_s {
308 ///   unsigned long __state = 0;
309 /// } once_flag;
310 /// template<class Callable>
311 /// void call_once(once_flag& o, Callable func) {
312 ///   if (!o.__state) {
313 ///     func();
314 ///   }
315 ///   o.__state = 1;
316 /// }
317 /// \endcode
318 static Stmt *create_call_once(ASTContext &C, const FunctionDecl *D) {
319   LLVM_DEBUG(llvm::dbgs() << "Generating body for call_once\n");
320 
321   // We need at least two parameters.
322   if (D->param_size() < 2)
323     return nullptr;
324 
325   ASTMaker M(C);
326 
327   const ParmVarDecl *Flag = D->getParamDecl(0);
328   const ParmVarDecl *Callback = D->getParamDecl(1);
329 
330   if (!Callback->getType()->isReferenceType()) {
331     llvm::dbgs() << "libcxx03 std::call_once implementation, skipping.\n";
332     return nullptr;
333   }
334   if (!Flag->getType()->isReferenceType()) {
335     llvm::dbgs() << "unknown std::call_once implementation, skipping.\n";
336     return nullptr;
337   }
338 
339   QualType CallbackType = Callback->getType().getNonReferenceType();
340 
341   // Nullable pointer, non-null iff function is a CXXRecordDecl.
342   CXXRecordDecl *CallbackRecordDecl = CallbackType->getAsCXXRecordDecl();
343   QualType FlagType = Flag->getType().getNonReferenceType();
344   auto *FlagRecordDecl = FlagType->getAsRecordDecl();
345 
346   if (!FlagRecordDecl) {
347     LLVM_DEBUG(llvm::dbgs() << "Flag field is not a record: "
348                             << "unknown std::call_once implementation, "
349                             << "ignoring the call.\n");
350     return nullptr;
351   }
352 
353   // We initially assume libc++ implementation of call_once,
354   // where the once_flag struct has a field `__state_`.
355   ValueDecl *FlagFieldDecl = M.findMemberField(FlagRecordDecl, "__state_");
356 
357   // Otherwise, try libstdc++ implementation, with a field
358   // `_M_once`
359   if (!FlagFieldDecl) {
360     FlagFieldDecl = M.findMemberField(FlagRecordDecl, "_M_once");
361   }
362 
363   if (!FlagFieldDecl) {
364     LLVM_DEBUG(llvm::dbgs() << "No field _M_once or __state_ found on "
365                             << "std::once_flag struct: unknown std::call_once "
366                             << "implementation, ignoring the call.");
367     return nullptr;
368   }
369 
370   bool isLambdaCall = CallbackRecordDecl && CallbackRecordDecl->isLambda();
371   if (CallbackRecordDecl && !isLambdaCall) {
372     LLVM_DEBUG(llvm::dbgs()
373                << "Not supported: synthesizing body for functors when "
374                << "body farming std::call_once, ignoring the call.");
375     return nullptr;
376   }
377 
378   SmallVector<Expr *, 5> CallArgs;
379   const FunctionProtoType *CallbackFunctionType;
380   if (isLambdaCall) {
381 
382     // Lambda requires callback itself inserted as a first parameter.
383     CallArgs.push_back(
384         M.makeDeclRefExpr(Callback,
385                           /* RefersToEnclosingVariableOrCapture=*/ true));
386     CallbackFunctionType = CallbackRecordDecl->getLambdaCallOperator()
387                                ->getType()
388                                ->getAs<FunctionProtoType>();
389   } else if (!CallbackType->getPointeeType().isNull()) {
390     CallbackFunctionType =
391         CallbackType->getPointeeType()->getAs<FunctionProtoType>();
392   } else {
393     CallbackFunctionType = CallbackType->getAs<FunctionProtoType>();
394   }
395 
396   if (!CallbackFunctionType)
397     return nullptr;
398 
399   // First two arguments are used for the flag and for the callback.
400   if (D->getNumParams() != CallbackFunctionType->getNumParams() + 2) {
401     LLVM_DEBUG(llvm::dbgs() << "Types of params of the callback do not match "
402                             << "params passed to std::call_once, "
403                             << "ignoring the call\n");
404     return nullptr;
405   }
406 
407   // All arguments past first two ones are passed to the callback,
408   // and we turn lvalues into rvalues if the argument is not passed by
409   // reference.
410   for (unsigned int ParamIdx = 2; ParamIdx < D->getNumParams(); ParamIdx++) {
411     const ParmVarDecl *PDecl = D->getParamDecl(ParamIdx);
412     assert(PDecl);
413     if (CallbackFunctionType->getParamType(ParamIdx - 2)
414                 .getNonReferenceType()
415                 .getCanonicalType() !=
416             PDecl->getType().getNonReferenceType().getCanonicalType()) {
417       LLVM_DEBUG(llvm::dbgs() << "Types of params of the callback do not match "
418                               << "params passed to std::call_once, "
419                               << "ignoring the call\n");
420       return nullptr;
421     }
422     Expr *ParamExpr = M.makeDeclRefExpr(PDecl);
423     if (!CallbackFunctionType->getParamType(ParamIdx - 2)->isReferenceType()) {
424       QualType PTy = PDecl->getType().getNonReferenceType();
425       ParamExpr = M.makeLvalueToRvalue(ParamExpr, PTy);
426     }
427     CallArgs.push_back(ParamExpr);
428   }
429 
430   CallExpr *CallbackCall;
431   if (isLambdaCall) {
432 
433     CallbackCall = create_call_once_lambda_call(C, M, Callback,
434                                                 CallbackRecordDecl, CallArgs);
435   } else {
436 
437     // Function pointer case.
438     CallbackCall = create_call_once_funcptr_call(C, M, Callback, CallArgs);
439   }
440 
441   DeclRefExpr *FlagDecl =
442       M.makeDeclRefExpr(Flag,
443                         /* RefersToEnclosingVariableOrCapture=*/true);
444 
445 
446   MemberExpr *Deref = M.makeMemberExpression(FlagDecl, FlagFieldDecl);
447   assert(Deref->isLValue());
448   QualType DerefType = Deref->getType();
449 
450   // Negation predicate.
451   UnaryOperator *FlagCheck = UnaryOperator::Create(
452       C,
453       /* input=*/
454       M.makeImplicitCast(M.makeLvalueToRvalue(Deref, DerefType), DerefType,
455                          CK_IntegralToBoolean),
456       /* opc=*/UO_LNot,
457       /* QualType=*/C.IntTy,
458       /* ExprValueKind=*/VK_RValue,
459       /* ExprObjectKind=*/OK_Ordinary, SourceLocation(),
460       /* CanOverflow*/ false, FPOptions(C.getLangOpts()));
461 
462   // Create assignment.
463   BinaryOperator *FlagAssignment = M.makeAssignment(
464       Deref, M.makeIntegralCast(M.makeIntegerLiteral(1, C.IntTy), DerefType),
465       DerefType);
466 
467   auto *Out =
468       IfStmt::Create(C, SourceLocation(),
469                      /* IsConstexpr=*/false,
470                      /* Init=*/nullptr,
471                      /* Var=*/nullptr,
472                      /* Cond=*/FlagCheck,
473                      /* Then=*/M.makeCompound({CallbackCall, FlagAssignment}));
474 
475   return Out;
476 }
477 
478 /// Create a fake body for dispatch_once.
479 static Stmt *create_dispatch_once(ASTContext &C, const FunctionDecl *D) {
480   // Check if we have at least two parameters.
481   if (D->param_size() != 2)
482     return nullptr;
483 
484   // Check if the first parameter is a pointer to integer type.
485   const ParmVarDecl *Predicate = D->getParamDecl(0);
486   QualType PredicateQPtrTy = Predicate->getType();
487   const PointerType *PredicatePtrTy = PredicateQPtrTy->getAs<PointerType>();
488   if (!PredicatePtrTy)
489     return nullptr;
490   QualType PredicateTy = PredicatePtrTy->getPointeeType();
491   if (!PredicateTy->isIntegerType())
492     return nullptr;
493 
494   // Check if the second parameter is the proper block type.
495   const ParmVarDecl *Block = D->getParamDecl(1);
496   QualType Ty = Block->getType();
497   if (!isDispatchBlock(Ty))
498     return nullptr;
499 
500   // Everything checks out.  Create a fakse body that checks the predicate,
501   // sets it, and calls the block.  Basically, an AST dump of:
502   //
503   // void dispatch_once(dispatch_once_t *predicate, dispatch_block_t block) {
504   //  if (*predicate != ~0l) {
505   //    *predicate = ~0l;
506   //    block();
507   //  }
508   // }
509 
510   ASTMaker M(C);
511 
512   // (1) Create the call.
513   CallExpr *CE = CallExpr::Create(
514       /*ASTContext=*/C,
515       /*StmtClass=*/M.makeLvalueToRvalue(/*Expr=*/Block),
516       /*Args=*/None,
517       /*QualType=*/C.VoidTy,
518       /*ExprValueType=*/VK_RValue,
519       /*SourceLocation=*/SourceLocation());
520 
521   // (2) Create the assignment to the predicate.
522   Expr *DoneValue =
523       UnaryOperator::Create(C, M.makeIntegerLiteral(0, C.LongTy), UO_Not,
524                             C.LongTy, VK_RValue, OK_Ordinary, SourceLocation(),
525                             /*CanOverflow*/ false, FPOptions(C.getLangOpts()));
526 
527   BinaryOperator *B =
528     M.makeAssignment(
529        M.makeDereference(
530           M.makeLvalueToRvalue(
531             M.makeDeclRefExpr(Predicate), PredicateQPtrTy),
532             PredicateTy),
533        M.makeIntegralCast(DoneValue, PredicateTy),
534        PredicateTy);
535 
536   // (3) Create the compound statement.
537   Stmt *Stmts[] = { B, CE };
538   CompoundStmt *CS = M.makeCompound(Stmts);
539 
540   // (4) Create the 'if' condition.
541   ImplicitCastExpr *LValToRval =
542     M.makeLvalueToRvalue(
543       M.makeDereference(
544         M.makeLvalueToRvalue(
545           M.makeDeclRefExpr(Predicate),
546           PredicateQPtrTy),
547         PredicateTy),
548     PredicateTy);
549 
550   Expr *GuardCondition = M.makeComparison(LValToRval, DoneValue, BO_NE);
551   // (5) Create the 'if' statement.
552   auto *If = IfStmt::Create(C, SourceLocation(),
553                             /* IsConstexpr=*/false,
554                             /* Init=*/nullptr,
555                             /* Var=*/nullptr,
556                             /* Cond=*/GuardCondition,
557                             /* Then=*/CS);
558   return If;
559 }
560 
561 /// Create a fake body for dispatch_sync.
562 static Stmt *create_dispatch_sync(ASTContext &C, const FunctionDecl *D) {
563   // Check if we have at least two parameters.
564   if (D->param_size() != 2)
565     return nullptr;
566 
567   // Check if the second parameter is a block.
568   const ParmVarDecl *PV = D->getParamDecl(1);
569   QualType Ty = PV->getType();
570   if (!isDispatchBlock(Ty))
571     return nullptr;
572 
573   // Everything checks out.  Create a fake body that just calls the block.
574   // This is basically just an AST dump of:
575   //
576   // void dispatch_sync(dispatch_queue_t queue, void (^block)(void)) {
577   //   block();
578   // }
579   //
580   ASTMaker M(C);
581   DeclRefExpr *DR = M.makeDeclRefExpr(PV);
582   ImplicitCastExpr *ICE = M.makeLvalueToRvalue(DR, Ty);
583   CallExpr *CE =
584       CallExpr::Create(C, ICE, None, C.VoidTy, VK_RValue, SourceLocation());
585   return CE;
586 }
587 
588 static Stmt *create_OSAtomicCompareAndSwap(ASTContext &C, const FunctionDecl *D)
589 {
590   // There are exactly 3 arguments.
591   if (D->param_size() != 3)
592     return nullptr;
593 
594   // Signature:
595   // _Bool OSAtomicCompareAndSwapPtr(void *__oldValue,
596   //                                 void *__newValue,
597   //                                 void * volatile *__theValue)
598   // Generate body:
599   //   if (oldValue == *theValue) {
600   //    *theValue = newValue;
601   //    return YES;
602   //   }
603   //   else return NO;
604 
605   QualType ResultTy = D->getReturnType();
606   bool isBoolean = ResultTy->isBooleanType();
607   if (!isBoolean && !ResultTy->isIntegralType(C))
608     return nullptr;
609 
610   const ParmVarDecl *OldValue = D->getParamDecl(0);
611   QualType OldValueTy = OldValue->getType();
612 
613   const ParmVarDecl *NewValue = D->getParamDecl(1);
614   QualType NewValueTy = NewValue->getType();
615 
616   assert(OldValueTy == NewValueTy);
617 
618   const ParmVarDecl *TheValue = D->getParamDecl(2);
619   QualType TheValueTy = TheValue->getType();
620   const PointerType *PT = TheValueTy->getAs<PointerType>();
621   if (!PT)
622     return nullptr;
623   QualType PointeeTy = PT->getPointeeType();
624 
625   ASTMaker M(C);
626   // Construct the comparison.
627   Expr *Comparison =
628     M.makeComparison(
629       M.makeLvalueToRvalue(M.makeDeclRefExpr(OldValue), OldValueTy),
630       M.makeLvalueToRvalue(
631         M.makeDereference(
632           M.makeLvalueToRvalue(M.makeDeclRefExpr(TheValue), TheValueTy),
633           PointeeTy),
634         PointeeTy),
635       BO_EQ);
636 
637   // Construct the body of the IfStmt.
638   Stmt *Stmts[2];
639   Stmts[0] =
640     M.makeAssignment(
641       M.makeDereference(
642         M.makeLvalueToRvalue(M.makeDeclRefExpr(TheValue), TheValueTy),
643         PointeeTy),
644       M.makeLvalueToRvalue(M.makeDeclRefExpr(NewValue), NewValueTy),
645       NewValueTy);
646 
647   Expr *BoolVal = M.makeObjCBool(true);
648   Expr *RetVal = isBoolean ? M.makeIntegralCastToBoolean(BoolVal)
649                            : M.makeIntegralCast(BoolVal, ResultTy);
650   Stmts[1] = M.makeReturn(RetVal);
651   CompoundStmt *Body = M.makeCompound(Stmts);
652 
653   // Construct the else clause.
654   BoolVal = M.makeObjCBool(false);
655   RetVal = isBoolean ? M.makeIntegralCastToBoolean(BoolVal)
656                      : M.makeIntegralCast(BoolVal, ResultTy);
657   Stmt *Else = M.makeReturn(RetVal);
658 
659   /// Construct the If.
660   auto *If = IfStmt::Create(C, SourceLocation(),
661                             /* IsConstexpr=*/false,
662                             /* Init=*/nullptr,
663                             /* Var=*/nullptr, Comparison, Body,
664                             SourceLocation(), Else);
665 
666   return If;
667 }
668 
669 Stmt *BodyFarm::getBody(const FunctionDecl *D) {
670   Optional<Stmt *> &Val = Bodies[D];
671   if (Val.hasValue())
672     return Val.getValue();
673 
674   Val = nullptr;
675 
676   if (D->getIdentifier() == nullptr)
677     return nullptr;
678 
679   StringRef Name = D->getName();
680   if (Name.empty())
681     return nullptr;
682 
683   FunctionFarmer FF;
684 
685   if (Name.startswith("OSAtomicCompareAndSwap") ||
686       Name.startswith("objc_atomicCompareAndSwap")) {
687     FF = create_OSAtomicCompareAndSwap;
688   } else if (Name == "call_once" && D->getDeclContext()->isStdNamespace()) {
689     FF = create_call_once;
690   } else {
691     FF = llvm::StringSwitch<FunctionFarmer>(Name)
692           .Case("dispatch_sync", create_dispatch_sync)
693           .Case("dispatch_once", create_dispatch_once)
694           .Default(nullptr);
695   }
696 
697   if (FF) { Val = FF(C, D); }
698   else if (Injector) { Val = Injector->getBody(D); }
699   return Val.getValue();
700 }
701 
702 static const ObjCIvarDecl *findBackingIvar(const ObjCPropertyDecl *Prop) {
703   const ObjCIvarDecl *IVar = Prop->getPropertyIvarDecl();
704 
705   if (IVar)
706     return IVar;
707 
708   // When a readonly property is shadowed in a class extensions with a
709   // a readwrite property, the instance variable belongs to the shadowing
710   // property rather than the shadowed property. If there is no instance
711   // variable on a readonly property, check to see whether the property is
712   // shadowed and if so try to get the instance variable from shadowing
713   // property.
714   if (!Prop->isReadOnly())
715     return nullptr;
716 
717   auto *Container = cast<ObjCContainerDecl>(Prop->getDeclContext());
718   const ObjCInterfaceDecl *PrimaryInterface = nullptr;
719   if (auto *InterfaceDecl = dyn_cast<ObjCInterfaceDecl>(Container)) {
720     PrimaryInterface = InterfaceDecl;
721   } else if (auto *CategoryDecl = dyn_cast<ObjCCategoryDecl>(Container)) {
722     PrimaryInterface = CategoryDecl->getClassInterface();
723   } else if (auto *ImplDecl = dyn_cast<ObjCImplDecl>(Container)) {
724     PrimaryInterface = ImplDecl->getClassInterface();
725   } else {
726     return nullptr;
727   }
728 
729   // FindPropertyVisibleInPrimaryClass() looks first in class extensions, so it
730   // is guaranteed to find the shadowing property, if it exists, rather than
731   // the shadowed property.
732   auto *ShadowingProp = PrimaryInterface->FindPropertyVisibleInPrimaryClass(
733       Prop->getIdentifier(), Prop->getQueryKind());
734   if (ShadowingProp && ShadowingProp != Prop) {
735     IVar = ShadowingProp->getPropertyIvarDecl();
736   }
737 
738   return IVar;
739 }
740 
741 static Stmt *createObjCPropertyGetter(ASTContext &Ctx,
742                                       const ObjCMethodDecl *MD) {
743     // First, find the backing ivar.
744   const ObjCIvarDecl *IVar = nullptr;
745 
746   // Property accessor stubs sometimes do not correspond to any property decl
747   // in the current interface (but in a superclass). They still have a
748   // corresponding property impl decl in this case.
749   if (MD->isSynthesizedAccessorStub()) {
750     const ObjCInterfaceDecl *IntD = MD->getClassInterface();
751     const ObjCImplementationDecl *ImpD = IntD->getImplementation();
752     for (const auto *PI: ImpD->property_impls()) {
753       if (const ObjCPropertyDecl *P = PI->getPropertyDecl()) {
754         if (P->getGetterName() == MD->getSelector())
755           IVar = P->getPropertyIvarDecl();
756       }
757     }
758   }
759 
760   if (!IVar) {
761     const ObjCPropertyDecl *Prop = MD->findPropertyDecl();
762     IVar = findBackingIvar(Prop);
763     if (!IVar)
764       return nullptr;
765 
766     // Ignore weak variables, which have special behavior.
767     if (Prop->getPropertyAttributes() & ObjCPropertyAttribute::kind_weak)
768       return nullptr;
769 
770     // Look to see if Sema has synthesized a body for us. This happens in
771     // Objective-C++ because the return value may be a C++ class type with a
772     // non-trivial copy constructor. We can only do this if we can find the
773     // @synthesize for this property, though (or if we know it's been auto-
774     // synthesized).
775     const ObjCImplementationDecl *ImplDecl =
776       IVar->getContainingInterface()->getImplementation();
777     if (ImplDecl) {
778       for (const auto *I : ImplDecl->property_impls()) {
779         if (I->getPropertyDecl() != Prop)
780           continue;
781 
782         if (I->getGetterCXXConstructor()) {
783           ASTMaker M(Ctx);
784           return M.makeReturn(I->getGetterCXXConstructor());
785         }
786       }
787     }
788 
789     // Sanity check that the property is the same type as the ivar, or a
790     // reference to it, and that it is either an object pointer or trivially
791     // copyable.
792     if (!Ctx.hasSameUnqualifiedType(IVar->getType(),
793                                     Prop->getType().getNonReferenceType()))
794       return nullptr;
795     if (!IVar->getType()->isObjCLifetimeType() &&
796         !IVar->getType().isTriviallyCopyableType(Ctx))
797       return nullptr;
798   }
799 
800   // Generate our body:
801   //   return self->_ivar;
802   ASTMaker M(Ctx);
803 
804   const VarDecl *selfVar = MD->getSelfDecl();
805   if (!selfVar)
806     return nullptr;
807 
808   Expr *loadedIVar =
809     M.makeObjCIvarRef(
810       M.makeLvalueToRvalue(
811         M.makeDeclRefExpr(selfVar),
812         selfVar->getType()),
813       IVar);
814 
815   if (!MD->getReturnType()->isReferenceType())
816     loadedIVar = M.makeLvalueToRvalue(loadedIVar, IVar->getType());
817 
818   return M.makeReturn(loadedIVar);
819 }
820 
821 Stmt *BodyFarm::getBody(const ObjCMethodDecl *D) {
822   // We currently only know how to synthesize property accessors.
823   if (!D->isPropertyAccessor())
824     return nullptr;
825 
826   D = D->getCanonicalDecl();
827 
828   // We should not try to synthesize explicitly redefined accessors.
829   // We do not know for sure how they behave.
830   if (!D->isImplicit())
831     return nullptr;
832 
833   Optional<Stmt *> &Val = Bodies[D];
834   if (Val.hasValue())
835     return Val.getValue();
836   Val = nullptr;
837 
838   // For now, we only synthesize getters.
839   // Synthesizing setters would cause false negatives in the
840   // RetainCountChecker because the method body would bind the parameter
841   // to an instance variable, causing it to escape. This would prevent
842   // warning in the following common scenario:
843   //
844   //  id foo = [[NSObject alloc] init];
845   //  self.foo = foo; // We should warn that foo leaks here.
846   //
847   if (D->param_size() != 0)
848     return nullptr;
849 
850   // If the property was defined in an extension, search the extensions for
851   // overrides.
852   const ObjCInterfaceDecl *OID = D->getClassInterface();
853   if (dyn_cast<ObjCInterfaceDecl>(D->getParent()) != OID)
854     for (auto *Ext : OID->known_extensions()) {
855       auto *OMD = Ext->getInstanceMethod(D->getSelector());
856       if (OMD && !OMD->isImplicit())
857         return nullptr;
858     }
859 
860   Val = createObjCPropertyGetter(C, D);
861 
862   return Val.getValue();
863 }
864