Coverage Report

Created: 2022-05-17 06:19

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