clang  6.0.0svn
BodyFarm.cpp
Go to the documentation of this file.
1 //== BodyFarm.cpp - Factory for conjuring up fake bodies ----------*- C++ -*-//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // BodyFarm is a factory for creating faux implementations for functions/methods
11 // for analysis purposes.
12 //
13 //===----------------------------------------------------------------------===//
14 
16 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/Decl.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/AST/ExprCXX.h"
21 #include "clang/AST/ExprObjC.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 static bool isDispatchBlock(QualType Ty) {
37  // Is it a block pointer?
38  const BlockPointerType *BPT = Ty->getAs<BlockPointerType>();
39  if (!BPT)
40  return false;
41 
42  // Check if the block pointer type takes no arguments and
43  // returns void.
44  const FunctionProtoType *FT =
46  return FT && FT->getReturnType()->isVoidType() && FT->getNumParams() == 0;
47 }
48 
49 namespace {
50 class ASTMaker {
51 public:
52  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,
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.
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 an Objective-C bool literal.
91  ObjCBoolLiteralExpr *makeObjCBool(bool Val);
92 
93  /// Create an Objective-C ivar reference.
94  ObjCIvarRefExpr *makeObjCIvarRef(const Expr *Base, const ObjCIvarDecl *IVar);
95 
96  /// Create a Return statement.
97  ReturnStmt *makeReturn(const Expr *RetVal);
98 
99  /// Create an integer literal expression of the given type.
100  IntegerLiteral *makeIntegerLiteral(uint64_t Value, QualType Ty);
101 
102  /// Create a member expression.
103  MemberExpr *makeMemberExpression(Expr *base, ValueDecl *MemberDecl,
104  bool IsArrow = false,
105  ExprValueKind ValueKind = VK_LValue);
106 
107  /// Returns a *first* member field of a record declaration with a given name.
108  /// \return an nullptr if no member with such a name exists.
109  ValueDecl *findMemberField(const RecordDecl *RD, StringRef Name);
110 
111 private:
112  ASTContext &C;
113 };
114 }
115 
116 BinaryOperator *ASTMaker::makeAssignment(const Expr *LHS, const Expr *RHS,
117  QualType Ty) {
118  return new (C) BinaryOperator(const_cast<Expr*>(LHS), const_cast<Expr*>(RHS),
119  BO_Assign, Ty, VK_RValue,
121 }
122 
123 BinaryOperator *ASTMaker::makeComparison(const Expr *LHS, const Expr *RHS,
125  assert(BinaryOperator::isLogicalOp(Op) ||
127  return new (C) BinaryOperator(const_cast<Expr*>(LHS),
128  const_cast<Expr*>(RHS),
129  Op,
130  C.getLogicalOperationType(),
131  VK_RValue,
133 }
134 
135 CompoundStmt *ASTMaker::makeCompound(ArrayRef<Stmt *> Stmts) {
136  return new (C) CompoundStmt(C, Stmts, SourceLocation(), SourceLocation());
137 }
138 
139 DeclRefExpr *ASTMaker::makeDeclRefExpr(
140  const VarDecl *D,
141  bool RefersToEnclosingVariableOrCapture) {
143 
145  C, NestedNameSpecifierLoc(), SourceLocation(), const_cast<VarDecl *>(D),
146  RefersToEnclosingVariableOrCapture, SourceLocation(), Type, VK_LValue);
147  return DR;
148 }
149 
150 UnaryOperator *ASTMaker::makeDereference(const Expr *Arg, QualType Ty) {
151  return new (C) UnaryOperator(const_cast<Expr*>(Arg), UO_Deref, Ty,
153 }
154 
155 ImplicitCastExpr *ASTMaker::makeLvalueToRvalue(const Expr *Arg, QualType Ty) {
156  return makeImplicitCast(Arg, Ty, CK_LValueToRValue);
157 }
158 
160 ASTMaker::makeLvalueToRvalue(const VarDecl *Arg,
161  bool RefersToEnclosingVariableOrCapture) {
163  return makeLvalueToRvalue(makeDeclRefExpr(Arg,
164  RefersToEnclosingVariableOrCapture),
165  Type);
166 }
167 
168 ImplicitCastExpr *ASTMaker::makeImplicitCast(const Expr *Arg, QualType Ty,
169  CastKind CK) {
170  return ImplicitCastExpr::Create(C, Ty,
171  /* CastKind=*/ CK,
172  /* Expr=*/ const_cast<Expr *>(Arg),
173  /* CXXCastPath=*/ nullptr,
174  /* ExprValueKind=*/ VK_RValue);
175 }
176 
177 Expr *ASTMaker::makeIntegralCast(const Expr *Arg, QualType Ty) {
178  if (Arg->getType() == Ty)
179  return const_cast<Expr*>(Arg);
180 
181  return ImplicitCastExpr::Create(C, Ty, CK_IntegralCast,
182  const_cast<Expr*>(Arg), nullptr, VK_RValue);
183 }
184 
185 ImplicitCastExpr *ASTMaker::makeIntegralCastToBoolean(const Expr *Arg) {
186  return ImplicitCastExpr::Create(C, C.BoolTy, CK_IntegralToBoolean,
187  const_cast<Expr*>(Arg), nullptr, VK_RValue);
188 }
189 
190 ObjCBoolLiteralExpr *ASTMaker::makeObjCBool(bool Val) {
191  QualType Ty = C.getBOOLDecl() ? C.getBOOLType() : C.ObjCBuiltinBoolTy;
192  return new (C) ObjCBoolLiteralExpr(Val, Ty, SourceLocation());
193 }
194 
195 ObjCIvarRefExpr *ASTMaker::makeObjCIvarRef(const Expr *Base,
196  const ObjCIvarDecl *IVar) {
197  return new (C) ObjCIvarRefExpr(const_cast<ObjCIvarDecl*>(IVar),
198  IVar->getType(), SourceLocation(),
199  SourceLocation(), const_cast<Expr*>(Base),
200  /*arrow=*/true, /*free=*/false);
201 }
202 
203 
204 ReturnStmt *ASTMaker::makeReturn(const Expr *RetVal) {
205  return new (C) ReturnStmt(SourceLocation(), const_cast<Expr*>(RetVal),
206  nullptr);
207 }
208 
209 IntegerLiteral *ASTMaker::makeIntegerLiteral(uint64_t Value, QualType Ty) {
210  llvm::APInt APValue = llvm::APInt(C.getTypeSize(Ty), Value);
211  return IntegerLiteral::Create(C, APValue, Ty, SourceLocation());
212 }
213 
214 MemberExpr *ASTMaker::makeMemberExpression(Expr *base, ValueDecl *MemberDecl,
215  bool IsArrow,
216  ExprValueKind ValueKind) {
217 
218  DeclAccessPair FoundDecl = DeclAccessPair::make(MemberDecl, AS_public);
219  return MemberExpr::Create(
220  C, base, IsArrow, SourceLocation(), NestedNameSpecifierLoc(),
221  SourceLocation(), MemberDecl, FoundDecl,
223  /* TemplateArgumentListInfo=*/ nullptr, MemberDecl->getType(), ValueKind,
224  OK_Ordinary);
225 }
226 
227 ValueDecl *ASTMaker::findMemberField(const RecordDecl *RD, StringRef Name) {
228 
229  CXXBasePaths Paths(
230  /* FindAmbiguities=*/false,
231  /* RecordPaths=*/false,
232  /* DetectVirtual=*/ false);
233  const IdentifierInfo &II = C.Idents.get(Name);
234  DeclarationName DeclName = C.DeclarationNames.getIdentifier(&II);
235 
236  DeclContextLookupResult Decls = RD->lookup(DeclName);
237  for (NamedDecl *FoundDecl : Decls)
238  if (!FoundDecl->getDeclContext()->isFunctionOrMethod())
239  return cast<ValueDecl>(FoundDecl);
240 
241  return nullptr;
242 }
243 
244 //===----------------------------------------------------------------------===//
245 // Creation functions for faux ASTs.
246 //===----------------------------------------------------------------------===//
247 
248 typedef Stmt *(*FunctionFarmer)(ASTContext &C, const FunctionDecl *D);
249 
251  const ParmVarDecl *Callback,
252  ArrayRef<Expr *> CallArgs) {
253 
254  QualType Ty = Callback->getType();
255  DeclRefExpr *Call = M.makeDeclRefExpr(Callback);
256  CastKind CK;
257  if (Ty->isRValueReferenceType()) {
258  CK = CK_LValueToRValue;
259  } else {
260  assert(Ty->isLValueReferenceType());
261  CK = CK_FunctionToPointerDecay;
262  Ty = C.getPointerType(Ty.getNonReferenceType());
263  }
264 
265  return new (C)
266  CallExpr(C, M.makeImplicitCast(Call, Ty.getNonReferenceType(), CK),
267  /*args=*/CallArgs,
268  /*QualType=*/C.VoidTy,
269  /*ExprValueType=*/VK_RValue,
270  /*SourceLocation=*/SourceLocation());
271 }
272 
274  const ParmVarDecl *Callback,
275  CXXRecordDecl *CallbackDecl,
276  ArrayRef<Expr *> CallArgs) {
277  assert(CallbackDecl != nullptr);
278  assert(CallbackDecl->isLambda());
279  FunctionDecl *callOperatorDecl = CallbackDecl->getLambdaCallOperator();
280  assert(callOperatorDecl != nullptr);
281 
282  DeclRefExpr *callOperatorDeclRef =
283  DeclRefExpr::Create(/* Ctx =*/ C,
284  /* QualifierLoc =*/ NestedNameSpecifierLoc(),
285  /* TemplateKWLoc =*/ SourceLocation(),
286  const_cast<FunctionDecl *>(callOperatorDecl),
287  /* RefersToEnclosingVariableOrCapture=*/ false,
288  /* NameLoc =*/ SourceLocation(),
289  /* T =*/ callOperatorDecl->getType(),
290  /* VK =*/ VK_LValue);
291 
292  return new (C)
293  CXXOperatorCallExpr(/*AstContext=*/C, OO_Call, callOperatorDeclRef,
294  /*args=*/CallArgs,
295  /*QualType=*/C.VoidTy,
296  /*ExprValueType=*/VK_RValue,
297  /*SourceLocation=*/SourceLocation(), FPOptions());
298 }
299 
300 /// Create a fake body for std::call_once.
301 /// Emulates the following function body:
302 ///
303 /// \code
304 /// typedef struct once_flag_s {
305 /// unsigned long __state = 0;
306 /// } once_flag;
307 /// template<class Callable>
308 /// void call_once(once_flag& o, Callable func) {
309 /// if (!o.__state) {
310 /// func();
311 /// }
312 /// o.__state = 1;
313 /// }
314 /// \endcode
316  DEBUG(llvm::dbgs() << "Generating body for call_once\n");
317 
318  // We need at least two parameters.
319  if (D->param_size() < 2)
320  return nullptr;
321 
322  ASTMaker M(C);
323 
324  const ParmVarDecl *Flag = D->getParamDecl(0);
325  const ParmVarDecl *Callback = D->getParamDecl(1);
326 
327  if (!Callback->getType()->isReferenceType()) {
328  llvm::dbgs() << "libcxx03 std::call_once implementation, skipping.\n";
329  return nullptr;
330  }
331  if (!Flag->getType()->isReferenceType()) {
332  llvm::dbgs() << "unknown std::call_once implementation, skipping.\n";
333  return nullptr;
334  }
335 
336  QualType CallbackType = Callback->getType().getNonReferenceType();
337 
338  // Nullable pointer, non-null iff function is a CXXRecordDecl.
339  CXXRecordDecl *CallbackRecordDecl = CallbackType->getAsCXXRecordDecl();
340  QualType FlagType = Flag->getType().getNonReferenceType();
341  auto *FlagRecordDecl = dyn_cast_or_null<RecordDecl>(FlagType->getAsTagDecl());
342 
343  if (!FlagRecordDecl) {
344  DEBUG(llvm::dbgs() << "Flag field is not a record: "
345  << "unknown std::call_once implementation, "
346  << "ignoring the call.\n");
347  return nullptr;
348  }
349 
350  // We initially assume libc++ implementation of call_once,
351  // where the once_flag struct has a field `__state_`.
352  ValueDecl *FlagFieldDecl = M.findMemberField(FlagRecordDecl, "__state_");
353 
354  // Otherwise, try libstdc++ implementation, with a field
355  // `_M_once`
356  if (!FlagFieldDecl) {
357  FlagFieldDecl = M.findMemberField(FlagRecordDecl, "_M_once");
358  }
359 
360  if (!FlagFieldDecl) {
361  DEBUG(llvm::dbgs() << "No field _M_once or __state_ found on "
362  << "std::once_flag struct: unknown std::call_once "
363  << "implementation, ignoring the call.");
364  return nullptr;
365  }
366 
367  bool isLambdaCall = CallbackRecordDecl && CallbackRecordDecl->isLambda();
368  if (CallbackRecordDecl && !isLambdaCall) {
369  DEBUG(llvm::dbgs() << "Not supported: synthesizing body for functors when "
370  << "body farming std::call_once, ignoring the call.");
371  return nullptr;
372  }
373 
374  SmallVector<Expr *, 5> CallArgs;
375  const FunctionProtoType *CallbackFunctionType;
376  if (isLambdaCall) {
377 
378  // Lambda requires callback itself inserted as a first parameter.
379  CallArgs.push_back(
380  M.makeDeclRefExpr(Callback,
381  /* RefersToEnclosingVariableOrCapture=*/ true));
382  CallbackFunctionType = CallbackRecordDecl->getLambdaCallOperator()
383  ->getType()
385  } else if (!CallbackType->getPointeeType().isNull()) {
386  CallbackFunctionType =
387  CallbackType->getPointeeType()->getAs<FunctionProtoType>();
388  } else {
389  CallbackFunctionType = CallbackType->getAs<FunctionProtoType>();
390  }
391 
392  if (!CallbackFunctionType)
393  return nullptr;
394 
395  // First two arguments are used for the flag and for the callback.
396  if (D->getNumParams() != CallbackFunctionType->getNumParams() + 2) {
397  DEBUG(llvm::dbgs() << "Types of params of the callback do not match "
398  << "params passed to std::call_once, "
399  << "ignoring the call\n");
400  return nullptr;
401  }
402 
403  // All arguments past first two ones are passed to the callback,
404  // and we turn lvalues into rvalues if the argument is not passed by
405  // reference.
406  for (unsigned int ParamIdx = 2; ParamIdx < D->getNumParams(); ParamIdx++) {
407  const ParmVarDecl *PDecl = D->getParamDecl(ParamIdx);
408  Expr *ParamExpr = M.makeDeclRefExpr(PDecl);
409  if (!CallbackFunctionType->getParamType(ParamIdx - 2)->isReferenceType()) {
410  QualType PTy = PDecl->getType().getNonReferenceType();
411  ParamExpr = M.makeLvalueToRvalue(ParamExpr, PTy);
412  }
413  CallArgs.push_back(ParamExpr);
414  }
415 
416  CallExpr *CallbackCall;
417  if (isLambdaCall) {
418 
419  CallbackCall = create_call_once_lambda_call(C, M, Callback,
420  CallbackRecordDecl, CallArgs);
421  } else {
422 
423  // Function pointer case.
424  CallbackCall = create_call_once_funcptr_call(C, M, Callback, CallArgs);
425  }
426 
427  DeclRefExpr *FlagDecl =
428  M.makeDeclRefExpr(Flag,
429  /* RefersToEnclosingVariableOrCapture=*/true);
430 
431 
432  MemberExpr *Deref = M.makeMemberExpression(FlagDecl, FlagFieldDecl);
433  assert(Deref->isLValue());
434  QualType DerefType = Deref->getType();
435 
436  // Negation predicate.
437  UnaryOperator *FlagCheck = new (C) UnaryOperator(
438  /* input=*/
439  M.makeImplicitCast(M.makeLvalueToRvalue(Deref, DerefType), DerefType,
440  CK_IntegralToBoolean),
441  /* opc=*/ UO_LNot,
442  /* QualType=*/ C.IntTy,
443  /* ExprValueKind=*/ VK_RValue,
444  /* ExprObjectKind=*/ OK_Ordinary, SourceLocation());
445 
446  // Create assignment.
447  BinaryOperator *FlagAssignment = M.makeAssignment(
448  Deref, M.makeIntegralCast(M.makeIntegerLiteral(1, C.IntTy), DerefType),
449  DerefType);
450 
451  IfStmt *Out = new (C)
452  IfStmt(C, SourceLocation(),
453  /* IsConstexpr=*/ false,
454  /* init=*/ nullptr,
455  /* var=*/ nullptr,
456  /* cond=*/ FlagCheck,
457  /* then=*/ M.makeCompound({CallbackCall, FlagAssignment}));
458 
459  return Out;
460 }
461 
462 /// Create a fake body for dispatch_once.
464  // Check if we have at least two parameters.
465  if (D->param_size() != 2)
466  return nullptr;
467 
468  // Check if the first parameter is a pointer to integer type.
469  const ParmVarDecl *Predicate = D->getParamDecl(0);
470  QualType PredicateQPtrTy = Predicate->getType();
471  const PointerType *PredicatePtrTy = PredicateQPtrTy->getAs<PointerType>();
472  if (!PredicatePtrTy)
473  return nullptr;
474  QualType PredicateTy = PredicatePtrTy->getPointeeType();
475  if (!PredicateTy->isIntegerType())
476  return nullptr;
477 
478  // Check if the second parameter is the proper block type.
479  const ParmVarDecl *Block = D->getParamDecl(1);
480  QualType Ty = Block->getType();
481  if (!isDispatchBlock(Ty))
482  return nullptr;
483 
484  // Everything checks out. Create a fakse body that checks the predicate,
485  // sets it, and calls the block. Basically, an AST dump of:
486  //
487  // void dispatch_once(dispatch_once_t *predicate, dispatch_block_t block) {
488  // if (*predicate != ~0l) {
489  // *predicate = ~0l;
490  // block();
491  // }
492  // }
493 
494  ASTMaker M(C);
495 
496  // (1) Create the call.
497  CallExpr *CE = new (C) CallExpr(
498  /*ASTContext=*/C,
499  /*StmtClass=*/M.makeLvalueToRvalue(/*Expr=*/Block),
500  /*args=*/None,
501  /*QualType=*/C.VoidTy,
502  /*ExprValueType=*/VK_RValue,
503  /*SourceLocation=*/SourceLocation());
504 
505  // (2) Create the assignment to the predicate.
506  Expr *DoneValue =
507  new (C) UnaryOperator(M.makeIntegerLiteral(0, C.LongTy), UO_Not, C.LongTy,
509 
510  BinaryOperator *B =
511  M.makeAssignment(
512  M.makeDereference(
513  M.makeLvalueToRvalue(
514  M.makeDeclRefExpr(Predicate), PredicateQPtrTy),
515  PredicateTy),
516  M.makeIntegralCast(DoneValue, PredicateTy),
517  PredicateTy);
518 
519  // (3) Create the compound statement.
520  Stmt *Stmts[] = { B, CE };
521  CompoundStmt *CS = M.makeCompound(Stmts);
522 
523  // (4) Create the 'if' condition.
524  ImplicitCastExpr *LValToRval =
525  M.makeLvalueToRvalue(
526  M.makeDereference(
527  M.makeLvalueToRvalue(
528  M.makeDeclRefExpr(Predicate),
529  PredicateQPtrTy),
530  PredicateTy),
531  PredicateTy);
532 
533  Expr *GuardCondition = M.makeComparison(LValToRval, DoneValue, BO_NE);
534  // (5) Create the 'if' statement.
535  IfStmt *If = new (C) IfStmt(C, SourceLocation(),
536  /* IsConstexpr=*/ false,
537  /* init=*/ nullptr,
538  /* var=*/ nullptr,
539  /* cond=*/ GuardCondition,
540  /* then=*/ CS);
541  return If;
542 }
543 
544 /// Create a fake body for dispatch_sync.
546  // Check if we have at least two parameters.
547  if (D->param_size() != 2)
548  return nullptr;
549 
550  // Check if the second parameter is a block.
551  const ParmVarDecl *PV = D->getParamDecl(1);
552  QualType Ty = PV->getType();
553  if (!isDispatchBlock(Ty))
554  return nullptr;
555 
556  // Everything checks out. Create a fake body that just calls the block.
557  // This is basically just an AST dump of:
558  //
559  // void dispatch_sync(dispatch_queue_t queue, void (^block)(void)) {
560  // block();
561  // }
562  //
563  ASTMaker M(C);
564  DeclRefExpr *DR = M.makeDeclRefExpr(PV);
565  ImplicitCastExpr *ICE = M.makeLvalueToRvalue(DR, Ty);
566  CallExpr *CE = new (C) CallExpr(C, ICE, None, C.VoidTy, VK_RValue,
567  SourceLocation());
568  return CE;
569 }
570 
572 {
573  // There are exactly 3 arguments.
574  if (D->param_size() != 3)
575  return nullptr;
576 
577  // Signature:
578  // _Bool OSAtomicCompareAndSwapPtr(void *__oldValue,
579  // void *__newValue,
580  // void * volatile *__theValue)
581  // Generate body:
582  // if (oldValue == *theValue) {
583  // *theValue = newValue;
584  // return YES;
585  // }
586  // else return NO;
587 
588  QualType ResultTy = D->getReturnType();
589  bool isBoolean = ResultTy->isBooleanType();
590  if (!isBoolean && !ResultTy->isIntegralType(C))
591  return nullptr;
592 
593  const ParmVarDecl *OldValue = D->getParamDecl(0);
594  QualType OldValueTy = OldValue->getType();
595 
596  const ParmVarDecl *NewValue = D->getParamDecl(1);
597  QualType NewValueTy = NewValue->getType();
598 
599  assert(OldValueTy == NewValueTy);
600 
601  const ParmVarDecl *TheValue = D->getParamDecl(2);
602  QualType TheValueTy = TheValue->getType();
603  const PointerType *PT = TheValueTy->getAs<PointerType>();
604  if (!PT)
605  return nullptr;
606  QualType PointeeTy = PT->getPointeeType();
607 
608  ASTMaker M(C);
609  // Construct the comparison.
610  Expr *Comparison =
611  M.makeComparison(
612  M.makeLvalueToRvalue(M.makeDeclRefExpr(OldValue), OldValueTy),
613  M.makeLvalueToRvalue(
614  M.makeDereference(
615  M.makeLvalueToRvalue(M.makeDeclRefExpr(TheValue), TheValueTy),
616  PointeeTy),
617  PointeeTy),
618  BO_EQ);
619 
620  // Construct the body of the IfStmt.
621  Stmt *Stmts[2];
622  Stmts[0] =
623  M.makeAssignment(
624  M.makeDereference(
625  M.makeLvalueToRvalue(M.makeDeclRefExpr(TheValue), TheValueTy),
626  PointeeTy),
627  M.makeLvalueToRvalue(M.makeDeclRefExpr(NewValue), NewValueTy),
628  NewValueTy);
629 
630  Expr *BoolVal = M.makeObjCBool(true);
631  Expr *RetVal = isBoolean ? M.makeIntegralCastToBoolean(BoolVal)
632  : M.makeIntegralCast(BoolVal, ResultTy);
633  Stmts[1] = M.makeReturn(RetVal);
634  CompoundStmt *Body = M.makeCompound(Stmts);
635 
636  // Construct the else clause.
637  BoolVal = M.makeObjCBool(false);
638  RetVal = isBoolean ? M.makeIntegralCastToBoolean(BoolVal)
639  : M.makeIntegralCast(BoolVal, ResultTy);
640  Stmt *Else = M.makeReturn(RetVal);
641 
642  /// Construct the If.
643  Stmt *If = new (C) IfStmt(C, SourceLocation(), false, nullptr, nullptr,
644  Comparison, Body, SourceLocation(), Else);
645 
646  return If;
647 }
648 
650  D = D->getCanonicalDecl();
651 
652  Optional<Stmt *> &Val = Bodies[D];
653  if (Val.hasValue())
654  return Val.getValue();
655 
656  Val = nullptr;
657 
658  if (D->getIdentifier() == nullptr)
659  return nullptr;
660 
661  StringRef Name = D->getName();
662  if (Name.empty())
663  return nullptr;
664 
665  FunctionFarmer FF;
666 
667  if (Name.startswith("OSAtomicCompareAndSwap") ||
668  Name.startswith("objc_atomicCompareAndSwap")) {
670  } else if (Name == "call_once" && D->getDeclContext()->isStdNamespace()) {
671  FF = create_call_once;
672  } else {
673  FF = llvm::StringSwitch<FunctionFarmer>(Name)
674  .Case("dispatch_sync", create_dispatch_sync)
675  .Case("dispatch_once", create_dispatch_once)
676  .Default(nullptr);
677  }
678 
679  if (FF) { Val = FF(C, D); }
680  else if (Injector) { Val = Injector->getBody(D); }
681  return Val.getValue();
682 }
683 
684 static const ObjCIvarDecl *findBackingIvar(const ObjCPropertyDecl *Prop) {
685  const ObjCIvarDecl *IVar = Prop->getPropertyIvarDecl();
686 
687  if (IVar)
688  return IVar;
689 
690  // When a readonly property is shadowed in a class extensions with a
691  // a readwrite property, the instance variable belongs to the shadowing
692  // property rather than the shadowed property. If there is no instance
693  // variable on a readonly property, check to see whether the property is
694  // shadowed and if so try to get the instance variable from shadowing
695  // property.
696  if (!Prop->isReadOnly())
697  return nullptr;
698 
699  auto *Container = cast<ObjCContainerDecl>(Prop->getDeclContext());
700  const ObjCInterfaceDecl *PrimaryInterface = nullptr;
701  if (auto *InterfaceDecl = dyn_cast<ObjCInterfaceDecl>(Container)) {
702  PrimaryInterface = InterfaceDecl;
703  } else if (auto *CategoryDecl = dyn_cast<ObjCCategoryDecl>(Container)) {
704  PrimaryInterface = CategoryDecl->getClassInterface();
705  } else if (auto *ImplDecl = dyn_cast<ObjCImplDecl>(Container)) {
706  PrimaryInterface = ImplDecl->getClassInterface();
707  } else {
708  return nullptr;
709  }
710 
711  // FindPropertyVisibleInPrimaryClass() looks first in class extensions, so it
712  // is guaranteed to find the shadowing property, if it exists, rather than
713  // the shadowed property.
714  auto *ShadowingProp = PrimaryInterface->FindPropertyVisibleInPrimaryClass(
715  Prop->getIdentifier(), Prop->getQueryKind());
716  if (ShadowingProp && ShadowingProp != Prop) {
717  IVar = ShadowingProp->getPropertyIvarDecl();
718  }
719 
720  return IVar;
721 }
722 
724  const ObjCPropertyDecl *Prop) {
725  // First, find the backing ivar.
726  const ObjCIvarDecl *IVar = findBackingIvar(Prop);
727  if (!IVar)
728  return nullptr;
729 
730  // Ignore weak variables, which have special behavior.
732  return nullptr;
733 
734  // Look to see if Sema has synthesized a body for us. This happens in
735  // Objective-C++ because the return value may be a C++ class type with a
736  // non-trivial copy constructor. We can only do this if we can find the
737  // @synthesize for this property, though (or if we know it's been auto-
738  // synthesized).
739  const ObjCImplementationDecl *ImplDecl =
741  if (ImplDecl) {
742  for (const auto *I : ImplDecl->property_impls()) {
743  if (I->getPropertyDecl() != Prop)
744  continue;
745 
746  if (I->getGetterCXXConstructor()) {
747  ASTMaker M(Ctx);
748  return M.makeReturn(I->getGetterCXXConstructor());
749  }
750  }
751  }
752 
753  // Sanity check that the property is the same type as the ivar, or a
754  // reference to it, and that it is either an object pointer or trivially
755  // copyable.
756  if (!Ctx.hasSameUnqualifiedType(IVar->getType(),
757  Prop->getType().getNonReferenceType()))
758  return nullptr;
759  if (!IVar->getType()->isObjCLifetimeType() &&
760  !IVar->getType().isTriviallyCopyableType(Ctx))
761  return nullptr;
762 
763  // Generate our body:
764  // return self->_ivar;
765  ASTMaker M(Ctx);
766 
767  const VarDecl *selfVar = Prop->getGetterMethodDecl()->getSelfDecl();
768  if (!selfVar)
769  return nullptr;
770 
771  Expr *loadedIVar =
772  M.makeObjCIvarRef(
773  M.makeLvalueToRvalue(
774  M.makeDeclRefExpr(selfVar),
775  selfVar->getType()),
776  IVar);
777 
778  if (!Prop->getType()->isReferenceType())
779  loadedIVar = M.makeLvalueToRvalue(loadedIVar, IVar->getType());
780 
781  return M.makeReturn(loadedIVar);
782 }
783 
785  // We currently only know how to synthesize property accessors.
786  if (!D->isPropertyAccessor())
787  return nullptr;
788 
789  D = D->getCanonicalDecl();
790 
791  Optional<Stmt *> &Val = Bodies[D];
792  if (Val.hasValue())
793  return Val.getValue();
794  Val = nullptr;
795 
796  const ObjCPropertyDecl *Prop = D->findPropertyDecl();
797  if (!Prop)
798  return nullptr;
799 
800  // For now, we only synthesize getters.
801  // Synthesizing setters would cause false negatives in the
802  // RetainCountChecker because the method body would bind the parameter
803  // to an instance variable, causing it to escape. This would prevent
804  // warning in the following common scenario:
805  //
806  // id foo = [[NSObject alloc] init];
807  // self.foo = foo; // We should warn that foo leaks here.
808  //
809  if (D->param_size() != 0)
810  return nullptr;
811 
812  Val = createObjCPropertyGetter(C, Prop);
813 
814  return Val.getValue();
815 }
816 
A call to an overloaded operator written using operator syntax.
Definition: ExprCXX.h:52
Defines the clang::ASTContext interface.
ObjCPropertyQueryKind getQueryKind() const
Definition: DeclObjC.h:837
FunctionDecl - An instance of this class is created to represent a function declaration or definition...
Definition: Decl.h:1698
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2228
QualType getPointeeType() const
Definition: Type.h:2242
A (possibly-)qualified type.
Definition: Type.h:614
unsigned param_size() const
Definition: DeclObjC.h:348
Stmt - This represents one statement.
Definition: Stmt.h:66
IfStmt - This represents an if/then/else.
Definition: Stmt.h:929
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee...
Definition: Type.cpp:435
bool isLogicalOp() const
Definition: Expr.h:3184
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
static Stmt * create_call_once(ASTContext &C, const FunctionDecl *D)
Create a fake body for std::call_once.
Definition: BodyFarm.cpp:315
static CallExpr * create_call_once_funcptr_call(ASTContext &C, ASTMaker M, const ParmVarDecl *Callback, ArrayRef< Expr *> CallArgs)
Definition: BodyFarm.cpp:250
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition: Type.h:5722
The base class of the type hierarchy.
Definition: Type.h:1306
CanQualType LongTy
Definition: ASTContext.h:973
Floating point control options.
Definition: LangOptions.h:208
size_t param_size() const
Definition: Decl.h:2180
static bool isDispatchBlock(QualType Ty)
Definition: BodyFarm.cpp:36
VarDecl - An instance of this class is created to represent a variable declaration or definition...
Definition: Decl.h:807
QualType getReturnType() const
Definition: Decl.h:2205
unsigned getNumParams() const
Definition: Type.h:3399
const T * getAs() const
Member-template getAs<specific type>&#39;.
Definition: Type.h:6105
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:113
ParmVarDecl - Represents a parameter to a function.
Definition: Decl.h:1514
Defines the clang::Expr interface and subclasses for C++ expressions.
IdentifierInfo * getIdentifier() const
getIdentifier - Get the identifier that names this declaration, if there is one.
Definition: Decl.h:265
RecordDecl - Represents a struct/union/class.
Definition: Decl.h:3482
DeclarationName getDeclName() const
getDeclName - Get the actual, stored name of the declaration, which may be a special name...
Definition: Decl.h:291
One of these records is kept for each identifier that is lexed.
QualType getPointeeType() const
Definition: Type.h:2345
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:128
A C++ nested-name-specifier augmented with source location information.
The results of name lookup within a DeclContext.
Definition: DeclBase.h:1178
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:3953
Defines the clang::CodeInjector interface which is responsible for injecting AST of function definiti...
bool isReferenceType() const
Definition: Type.h:5781
static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD=nullptr, const TemplateArgumentListInfo *TemplateArgs=nullptr)
Definition: Expr.cpp:424
An r-value expression (a pr-value in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:107
BinaryOperatorKind
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition: Type.cpp:2131
PropertyAttributeKind getPropertyAttributes() const
Definition: DeclObjC.h:799
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3061
bool isRValueReferenceType() const
Definition: Type.h:5787
bool isReadOnly() const
isReadOnly - Return true iff the property has a setter.
Definition: DeclObjC.h:820
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition: DeclCXX.h:1152
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value &#39;V&#39; and type &#39;type&#39;.
Definition: Expr.cpp:783
An ordinary object is located at an address in memory.
Definition: Specifiers.h:123
Represents an ObjC class declaration.
Definition: DeclObjC.h:1108
Stmt *(* FunctionFarmer)(ASTContext &C, const FunctionDecl *D)
Definition: BodyFarm.cpp:248
ObjCMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclObjC.cpp:897
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1521
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:595
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1569
Represents a prototype with parameter type info, e.g.
Definition: Type.h:3176
CastKind
CastKind - The kind of operation required for a conversion.
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat)
Definition: Expr.cpp:1747
static const ObjCIvarDecl * findBackingIvar(const ObjCPropertyDecl *Prop)
Definition: BodyFarm.cpp:684
ValueDecl - Represent the declaration of a variable (in which case it is an lvalue) a function (in wh...
Definition: Decl.h:628
Expr - This represents one expression.
Definition: Expr.h:119
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:104
Defines an enumeration for C++ overloaded operators.
DeclContext * getDeclContext()
Definition: DeclBase.h:425
ObjCPropertyDecl * FindPropertyVisibleInPrimaryClass(IdentifierInfo *PropertyId, ObjCPropertyQueryKind QueryKind) const
FindPropertyVisibleInPrimaryClass - Finds declaration of the property with name &#39;PropertyId&#39; in the p...
Definition: DeclObjC.cpp:346
QualType getType() const
Definition: Expr.h:140
bool isFunctionOrMethod() const
Definition: DeclBase.h:1380
TagDecl * getAsTagDecl() const
Retrieves the TagDecl that this type refers to, either because the type is a TagType or because it is...
Definition: Type.cpp:1573
propimpl_range property_impls() const
Definition: DeclObjC.h:2367
ReturnStmt - This represents a return, optionally of an expression: return; return 4;...
Definition: Stmt.h:1413
static Stmt * create_OSAtomicCompareAndSwap(ASTContext &C, const FunctionDecl *D)
Definition: BodyFarm.cpp:571
UnaryOperator - This represents the unary-expression&#39;s (except sizeof and alignof), the postinc/postdec operators from postfix-expression, and various extensions.
Definition: Expr.h:1760
static Stmt * createObjCPropertyGetter(ASTContext &Ctx, const ObjCPropertyDecl *Prop)
Definition: BodyFarm.cpp:723
bool isNull() const
Return true if this QualType doesn&#39;t point to a type yet.
Definition: Type.h:681
ImplicitParamDecl * getSelfDecl() const
Definition: DeclObjC.h:408
QualType getType() const
Definition: DeclObjC.h:788
bool isComparisonOp() const
Definition: Expr.h:3154
Encodes a location in the source.
QualType getReturnType() const
Definition: Type.h:3112
static Stmt * create_dispatch_sync(ASTContext &C, const FunctionDecl *D)
Create a fake body for dispatch_sync.
Definition: BodyFarm.cpp:545
static CallExpr * create_call_once_lambda_call(ASTContext &C, ASTMaker M, const ParmVarDecl *Callback, CXXRecordDecl *CallbackDecl, ArrayRef< Expr *> CallArgs)
Definition: BodyFarm.cpp:273
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:1684
bool isStdNamespace() const
Definition: DeclBase.cpp:1010
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2187
CanQualType VoidTy
Definition: ASTContext.h:965
Represents one property declaration in an Objective-C interface.
Definition: DeclObjC.h:704
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:2894
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language...
Definition: Expr.h:261
ObjCImplementationDecl * getImplementation() const
Definition: DeclObjC.cpp:1503
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2165
static MemberExpr * Create(const ASTContext &C, Expr *base, bool isarrow, SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *memberdecl, DeclAccessPair founddecl, DeclarationNameInfo MemberNameInfo, const TemplateArgumentListInfo *targs, QualType ty, ExprValueKind VK, ExprObjectKind OK)
Definition: Expr.cpp:1468
A POD class for pairing a NamedDecl* with an access specifier.
static Stmt * create_dispatch_once(ASTContext &C, const FunctionDecl *D)
Create a fake body for dispatch_once.
Definition: BodyFarm.cpp:463
Dataflow Directional Tag Classes.
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition: DeclCXX.cpp:1121
DeclarationName - The name of a declaration.
bool isBooleanType() const
Definition: Type.h:6032
Stmt * getBody(const FunctionDecl *D)
Factory method for creating bodies for ordinary functions.
Definition: BodyFarm.cpp:649
const ObjCInterfaceDecl * getContainingInterface() const
Return the class interface that this ivar is logically contained in; this is either the interface whe...
Definition: DeclObjC.cpp:1741
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspnd...
Pointer to a block type.
Definition: Type.h:2331
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition: DeclObjC.h:2448
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:5991
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat]...
Definition: APValue.h:38
ObjCIvarRefExpr - A reference to an ObjC instance variable.
Definition: ExprObjC.h:479
bool isLValueReferenceType() const
Definition: Type.h:5784
const ObjCPropertyDecl * findPropertyDecl(bool CheckOverrides=true) const
Returns the property associated with this method&#39;s selector.
Definition: DeclObjC.cpp:1249
QualType getParamType(unsigned i) const
Definition: Type.h:3400
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:2451
Represents a C++ struct/union/class.
Definition: DeclCXX.h:299
bool isVoidType() const
Definition: Type.h:5969
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1866
ObjCIvarDecl * getPropertyIvarDecl() const
Definition: DeclObjC.h:895
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2270
StringRef getName() const
getName - Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:270
CanQualType IntTy
Definition: ASTContext.h:973
ObjCBoolLiteralExpr - Objective-C Boolean Literal.
Definition: ExprObjC.h:60
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:982
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
QualType getType() const
Definition: Decl.h:639
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:111
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:2834
ObjCMethodDecl * getGetterMethodDecl() const
Definition: DeclObjC.h:875
NamedDecl - This represents a decl with a name.
Definition: Decl.h:245
bool isPropertyAccessor() const
Definition: DeclObjC.h:423
unsigned getNumParams() const
getNumParams - Return the number of parameters this function must have based on its FunctionType...
Definition: Decl.cpp:2899
Comparison