Coverage Report

Created: 2019-07-24 05:18

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