Coverage Report

Created: 2022-07-16 07:03

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