blob: 039911e3e2aadcc5cebcbf2d1d71933357de0d37 [file] [log] [blame]
Ted Kremeneka43df952012-09-21 00:09:11 +00001//== 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
Ted Kremeneka43df952012-09-21 00:09:11 +000015#include "BodyFarm.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000016#include "clang/AST/ASTContext.h"
17#include "clang/AST/Decl.h"
18#include "clang/AST/Expr.h"
19#include "clang/AST/ExprObjC.h"
20#include "llvm/ADT/StringSwitch.h"
Ted Kremeneka43df952012-09-21 00:09:11 +000021
22using namespace clang;
23
Ted Kremenek0a4c0982012-09-21 17:54:32 +000024//===----------------------------------------------------------------------===//
25// Helper creation functions for constructing faux ASTs.
26//===----------------------------------------------------------------------===//
Ted Kremeneka43df952012-09-21 00:09:11 +000027
Ted Kremenekcc85d212012-09-21 00:52:24 +000028static bool isDispatchBlock(QualType Ty) {
29 // Is it a block pointer?
30 const BlockPointerType *BPT = Ty->getAs<BlockPointerType>();
31 if (!BPT)
32 return false;
33
34 // Check if the block pointer type takes no arguments and
35 // returns void.
36 const FunctionProtoType *FT =
37 BPT->getPointeeType()->getAs<FunctionProtoType>();
Stephen Hines651f13c2014-04-23 16:59:28 -070038 if (!FT || !FT->getReturnType()->isVoidType() || FT->getNumParams() != 0)
Ted Kremenekcc85d212012-09-21 00:52:24 +000039 return false;
40
41 return true;
42}
43
Ted Kremenek016c33d2012-09-21 17:54:35 +000044namespace {
45class ASTMaker {
46public:
47 ASTMaker(ASTContext &C) : C(C) {}
48
Ted Kremenekb80e5bb2012-09-21 18:33:54 +000049 /// Create a new BinaryOperator representing a simple assignment.
50 BinaryOperator *makeAssignment(const Expr *LHS, const Expr *RHS, QualType Ty);
51
Ted Kremenek48fa1362012-10-11 20:58:18 +000052 /// Create a new BinaryOperator representing a comparison.
53 BinaryOperator *makeComparison(const Expr *LHS, const Expr *RHS,
54 BinaryOperator::Opcode Op);
55
56 /// Create a new compound stmt using the provided statements.
57 CompoundStmt *makeCompound(ArrayRef<Stmt*>);
58
Ted Kremeneka6d62a12012-09-21 18:13:23 +000059 /// Create a new DeclRefExpr for the referenced variable.
Ted Kremenek016c33d2012-09-21 17:54:35 +000060 DeclRefExpr *makeDeclRefExpr(const VarDecl *D);
61
Ted Kremenek0b5c5e42012-09-21 18:33:52 +000062 /// Create a new UnaryOperator representing a dereference.
63 UnaryOperator *makeDereference(const Expr *Arg, QualType Ty);
64
Ted Kremeneka6d62a12012-09-21 18:13:23 +000065 /// Create an implicit cast for an integer conversion.
Ted Kremenek5dbd9902012-10-12 00:18:19 +000066 Expr *makeIntegralCast(const Expr *Arg, QualType Ty);
Ted Kremeneka6d62a12012-09-21 18:13:23 +000067
Ted Kremenek48fa1362012-10-11 20:58:18 +000068 /// Create an implicit cast to a builtin boolean type.
69 ImplicitCastExpr *makeIntegralCastToBoolean(const Expr *Arg);
70
Ted Kremenek9ba05cd2012-09-21 18:13:27 +000071 // Create an implicit cast for lvalue-to-rvaluate conversions.
72 ImplicitCastExpr *makeLvalueToRvalue(const Expr *Arg, QualType Ty);
73
Ted Kremenek48fa1362012-10-11 20:58:18 +000074 /// Create an Objective-C bool literal.
75 ObjCBoolLiteralExpr *makeObjCBool(bool Val);
Stephen Hines651f13c2014-04-23 16:59:28 -070076
77 /// Create an Objective-C ivar reference.
78 ObjCIvarRefExpr *makeObjCIvarRef(const Expr *Base, const ObjCIvarDecl *IVar);
Ted Kremenek48fa1362012-10-11 20:58:18 +000079
80 /// Create a Return statement.
81 ReturnStmt *makeReturn(const Expr *RetVal);
82
Ted Kremenek016c33d2012-09-21 17:54:35 +000083private:
84 ASTContext &C;
85};
86}
87
Ted Kremenekb80e5bb2012-09-21 18:33:54 +000088BinaryOperator *ASTMaker::makeAssignment(const Expr *LHS, const Expr *RHS,
89 QualType Ty) {
90 return new (C) BinaryOperator(const_cast<Expr*>(LHS), const_cast<Expr*>(RHS),
91 BO_Assign, Ty, VK_RValue,
Lang Hamesbe9af122012-10-02 04:45:10 +000092 OK_Ordinary, SourceLocation(), false);
Ted Kremenekb80e5bb2012-09-21 18:33:54 +000093}
94
Ted Kremenek48fa1362012-10-11 20:58:18 +000095BinaryOperator *ASTMaker::makeComparison(const Expr *LHS, const Expr *RHS,
96 BinaryOperator::Opcode Op) {
97 assert(BinaryOperator::isLogicalOp(Op) ||
98 BinaryOperator::isComparisonOp(Op));
99 return new (C) BinaryOperator(const_cast<Expr*>(LHS),
100 const_cast<Expr*>(RHS),
101 Op,
102 C.getLogicalOperationType(),
103 VK_RValue,
104 OK_Ordinary, SourceLocation(), false);
105}
106
107CompoundStmt *ASTMaker::makeCompound(ArrayRef<Stmt *> Stmts) {
Nico Weberd36aa352012-12-29 20:03:39 +0000108 return new (C) CompoundStmt(C, Stmts, SourceLocation(), SourceLocation());
Ted Kremenek48fa1362012-10-11 20:58:18 +0000109}
110
Ted Kremenek016c33d2012-09-21 17:54:35 +0000111DeclRefExpr *ASTMaker::makeDeclRefExpr(const VarDecl *D) {
112 DeclRefExpr *DR =
113 DeclRefExpr::Create(/* Ctx = */ C,
114 /* QualifierLoc = */ NestedNameSpecifierLoc(),
115 /* TemplateKWLoc = */ SourceLocation(),
116 /* D = */ const_cast<VarDecl*>(D),
117 /* isEnclosingLocal = */ false,
118 /* NameLoc = */ SourceLocation(),
119 /* T = */ D->getType(),
120 /* VK = */ VK_LValue);
121 return DR;
122}
123
Ted Kremenek0b5c5e42012-09-21 18:33:52 +0000124UnaryOperator *ASTMaker::makeDereference(const Expr *Arg, QualType Ty) {
125 return new (C) UnaryOperator(const_cast<Expr*>(Arg), UO_Deref, Ty,
126 VK_LValue, OK_Ordinary, SourceLocation());
127}
128
Ted Kremenek9ba05cd2012-09-21 18:13:27 +0000129ImplicitCastExpr *ASTMaker::makeLvalueToRvalue(const Expr *Arg, QualType Ty) {
130 return ImplicitCastExpr::Create(C, Ty, CK_LValueToRValue,
131 const_cast<Expr*>(Arg), 0, VK_RValue);
132}
133
Ted Kremenek5dbd9902012-10-12 00:18:19 +0000134Expr *ASTMaker::makeIntegralCast(const Expr *Arg, QualType Ty) {
135 if (Arg->getType() == Ty)
136 return const_cast<Expr*>(Arg);
137
Ted Kremeneka6d62a12012-09-21 18:13:23 +0000138 return ImplicitCastExpr::Create(C, Ty, CK_IntegralCast,
139 const_cast<Expr*>(Arg), 0, VK_RValue);
140}
141
Ted Kremenek48fa1362012-10-11 20:58:18 +0000142ImplicitCastExpr *ASTMaker::makeIntegralCastToBoolean(const Expr *Arg) {
143 return ImplicitCastExpr::Create(C, C.BoolTy, CK_IntegralToBoolean,
144 const_cast<Expr*>(Arg), 0, VK_RValue);
145}
146
147ObjCBoolLiteralExpr *ASTMaker::makeObjCBool(bool Val) {
148 QualType Ty = C.getBOOLDecl() ? C.getBOOLType() : C.ObjCBuiltinBoolTy;
149 return new (C) ObjCBoolLiteralExpr(Val, Ty, SourceLocation());
150}
151
Stephen Hines651f13c2014-04-23 16:59:28 -0700152ObjCIvarRefExpr *ASTMaker::makeObjCIvarRef(const Expr *Base,
153 const ObjCIvarDecl *IVar) {
154 return new (C) ObjCIvarRefExpr(const_cast<ObjCIvarDecl*>(IVar),
155 IVar->getType(), SourceLocation(),
156 SourceLocation(), const_cast<Expr*>(Base),
157 /*arrow=*/true, /*free=*/false);
158}
159
160
Ted Kremenek48fa1362012-10-11 20:58:18 +0000161ReturnStmt *ASTMaker::makeReturn(const Expr *RetVal) {
162 return new (C) ReturnStmt(SourceLocation(), const_cast<Expr*>(RetVal), 0);
163}
164
Ted Kremenek0a4c0982012-09-21 17:54:32 +0000165//===----------------------------------------------------------------------===//
166// Creation functions for faux ASTs.
167//===----------------------------------------------------------------------===//
168
169typedef Stmt *(*FunctionFarmer)(ASTContext &C, const FunctionDecl *D);
170
Ted Kremenekcc85d212012-09-21 00:52:24 +0000171/// Create a fake body for dispatch_once.
172static Stmt *create_dispatch_once(ASTContext &C, const FunctionDecl *D) {
173 // Check if we have at least two parameters.
174 if (D->param_size() != 2)
175 return 0;
176
177 // Check if the first parameter is a pointer to integer type.
178 const ParmVarDecl *Predicate = D->getParamDecl(0);
179 QualType PredicateQPtrTy = Predicate->getType();
180 const PointerType *PredicatePtrTy = PredicateQPtrTy->getAs<PointerType>();
181 if (!PredicatePtrTy)
182 return 0;
183 QualType PredicateTy = PredicatePtrTy->getPointeeType();
184 if (!PredicateTy->isIntegerType())
185 return 0;
186
187 // Check if the second parameter is the proper block type.
188 const ParmVarDecl *Block = D->getParamDecl(1);
189 QualType Ty = Block->getType();
190 if (!isDispatchBlock(Ty))
191 return 0;
192
193 // Everything checks out. Create a fakse body that checks the predicate,
194 // sets it, and calls the block. Basically, an AST dump of:
195 //
196 // void dispatch_once(dispatch_once_t *predicate, dispatch_block_t block) {
197 // if (!*predicate) {
198 // *predicate = 1;
199 // block();
200 // }
201 // }
202
Ted Kremenek016c33d2012-09-21 17:54:35 +0000203 ASTMaker M(C);
204
Ted Kremenekcc85d212012-09-21 00:52:24 +0000205 // (1) Create the call.
Ted Kremenek016c33d2012-09-21 17:54:35 +0000206 DeclRefExpr *DR = M.makeDeclRefExpr(Block);
Ted Kremenek9ba05cd2012-09-21 18:13:27 +0000207 ImplicitCastExpr *ICE = M.makeLvalueToRvalue(DR, Ty);
Dmitri Gribenko55431692013-05-05 00:41:58 +0000208 CallExpr *CE = new (C) CallExpr(C, ICE, None, C.VoidTy, VK_RValue,
209 SourceLocation());
Ted Kremenekcc85d212012-09-21 00:52:24 +0000210
211 // (2) Create the assignment to the predicate.
212 IntegerLiteral *IL =
213 IntegerLiteral::Create(C, llvm::APInt(C.getTypeSize(C.IntTy), (uint64_t) 1),
214 C.IntTy, SourceLocation());
Ted Kremenekfcf8eba2012-09-21 18:33:56 +0000215 BinaryOperator *B =
216 M.makeAssignment(
217 M.makeDereference(
218 M.makeLvalueToRvalue(
219 M.makeDeclRefExpr(Predicate), PredicateQPtrTy),
220 PredicateTy),
221 M.makeIntegralCast(IL, PredicateTy),
222 PredicateTy);
223
Ted Kremenekcc85d212012-09-21 00:52:24 +0000224 // (3) Create the compound statement.
225 Stmt *Stmts[2];
226 Stmts[0] = B;
Ted Kremenek48fa1362012-10-11 20:58:18 +0000227 Stmts[1] = CE;
228 CompoundStmt *CS = M.makeCompound(ArrayRef<Stmt*>(Stmts, 2));
Ted Kremenekcc85d212012-09-21 00:52:24 +0000229
230 // (4) Create the 'if' condition.
Ted Kremenekfcf8eba2012-09-21 18:33:56 +0000231 ImplicitCastExpr *LValToRval =
232 M.makeLvalueToRvalue(
233 M.makeDereference(
234 M.makeLvalueToRvalue(
235 M.makeDeclRefExpr(Predicate),
236 PredicateQPtrTy),
237 PredicateTy),
238 PredicateTy);
239
240 UnaryOperator *UO = new (C) UnaryOperator(LValToRval, UO_LNot, C.IntTy,
241 VK_RValue, OK_Ordinary,
242 SourceLocation());
Ted Kremenekcc85d212012-09-21 00:52:24 +0000243
244 // (5) Create the 'if' statement.
245 IfStmt *If = new (C) IfStmt(C, SourceLocation(), 0, UO, CS);
246 return If;
247}
248
Ted Kremeneka43df952012-09-21 00:09:11 +0000249/// Create a fake body for dispatch_sync.
250static Stmt *create_dispatch_sync(ASTContext &C, const FunctionDecl *D) {
251 // Check if we have at least two parameters.
252 if (D->param_size() != 2)
253 return 0;
254
255 // Check if the second parameter is a block.
256 const ParmVarDecl *PV = D->getParamDecl(1);
257 QualType Ty = PV->getType();
Ted Kremenekcc85d212012-09-21 00:52:24 +0000258 if (!isDispatchBlock(Ty))
Ted Kremeneka43df952012-09-21 00:09:11 +0000259 return 0;
Ted Kremenek016c33d2012-09-21 17:54:35 +0000260
Ted Kremeneka43df952012-09-21 00:09:11 +0000261 // Everything checks out. Create a fake body that just calls the block.
262 // This is basically just an AST dump of:
263 //
264 // void dispatch_sync(dispatch_queue_t queue, void (^block)(void)) {
265 // block();
266 // }
Ted Kremenek016c33d2012-09-21 17:54:35 +0000267 //
268 ASTMaker M(C);
269 DeclRefExpr *DR = M.makeDeclRefExpr(PV);
Ted Kremenek0b5c5e42012-09-21 18:33:52 +0000270 ImplicitCastExpr *ICE = M.makeLvalueToRvalue(DR, Ty);
Dmitri Gribenko55431692013-05-05 00:41:58 +0000271 CallExpr *CE = new (C) CallExpr(C, ICE, None, C.VoidTy, VK_RValue,
272 SourceLocation());
Ted Kremeneka43df952012-09-21 00:09:11 +0000273 return CE;
274}
275
Ted Kremenek48fa1362012-10-11 20:58:18 +0000276static Stmt *create_OSAtomicCompareAndSwap(ASTContext &C, const FunctionDecl *D)
277{
278 // There are exactly 3 arguments.
279 if (D->param_size() != 3)
280 return 0;
281
Anna Zaksef95aea2013-02-05 19:52:26 +0000282 // Signature:
283 // _Bool OSAtomicCompareAndSwapPtr(void *__oldValue,
284 // void *__newValue,
285 // void * volatile *__theValue)
286 // Generate body:
Ted Kremenek48fa1362012-10-11 20:58:18 +0000287 // if (oldValue == *theValue) {
288 // *theValue = newValue;
289 // return YES;
290 // }
291 // else return NO;
Stephen Hines651f13c2014-04-23 16:59:28 -0700292
293 QualType ResultTy = D->getReturnType();
Ted Kremenek5dbd9902012-10-12 00:18:19 +0000294 bool isBoolean = ResultTy->isBooleanType();
295 if (!isBoolean && !ResultTy->isIntegralType(C))
296 return 0;
297
Ted Kremenek48fa1362012-10-11 20:58:18 +0000298 const ParmVarDecl *OldValue = D->getParamDecl(0);
299 QualType OldValueTy = OldValue->getType();
300
301 const ParmVarDecl *NewValue = D->getParamDecl(1);
302 QualType NewValueTy = NewValue->getType();
303
304 assert(OldValueTy == NewValueTy);
305
306 const ParmVarDecl *TheValue = D->getParamDecl(2);
307 QualType TheValueTy = TheValue->getType();
308 const PointerType *PT = TheValueTy->getAs<PointerType>();
309 if (!PT)
310 return 0;
311 QualType PointeeTy = PT->getPointeeType();
312
313 ASTMaker M(C);
314 // Construct the comparison.
315 Expr *Comparison =
316 M.makeComparison(
317 M.makeLvalueToRvalue(M.makeDeclRefExpr(OldValue), OldValueTy),
318 M.makeLvalueToRvalue(
319 M.makeDereference(
320 M.makeLvalueToRvalue(M.makeDeclRefExpr(TheValue), TheValueTy),
321 PointeeTy),
322 PointeeTy),
323 BO_EQ);
324
325 // Construct the body of the IfStmt.
326 Stmt *Stmts[2];
327 Stmts[0] =
328 M.makeAssignment(
329 M.makeDereference(
330 M.makeLvalueToRvalue(M.makeDeclRefExpr(TheValue), TheValueTy),
331 PointeeTy),
332 M.makeLvalueToRvalue(M.makeDeclRefExpr(NewValue), NewValueTy),
333 NewValueTy);
Ted Kremenek5dbd9902012-10-12 00:18:19 +0000334
335 Expr *BoolVal = M.makeObjCBool(true);
336 Expr *RetVal = isBoolean ? M.makeIntegralCastToBoolean(BoolVal)
337 : M.makeIntegralCast(BoolVal, ResultTy);
338 Stmts[1] = M.makeReturn(RetVal);
Ted Kremenek48fa1362012-10-11 20:58:18 +0000339 CompoundStmt *Body = M.makeCompound(ArrayRef<Stmt*>(Stmts, 2));
340
341 // Construct the else clause.
Ted Kremenek5dbd9902012-10-12 00:18:19 +0000342 BoolVal = M.makeObjCBool(false);
343 RetVal = isBoolean ? M.makeIntegralCastToBoolean(BoolVal)
344 : M.makeIntegralCast(BoolVal, ResultTy);
345 Stmt *Else = M.makeReturn(RetVal);
Ted Kremenek48fa1362012-10-11 20:58:18 +0000346
347 /// Construct the If.
348 Stmt *If =
349 new (C) IfStmt(C, SourceLocation(), 0, Comparison, Body,
350 SourceLocation(), Else);
351
352 return If;
353}
354
Ted Kremeneka43df952012-09-21 00:09:11 +0000355Stmt *BodyFarm::getBody(const FunctionDecl *D) {
356 D = D->getCanonicalDecl();
357
David Blaikiedc84cd52013-02-20 22:23:23 +0000358 Optional<Stmt *> &Val = Bodies[D];
Ted Kremeneka43df952012-09-21 00:09:11 +0000359 if (Val.hasValue())
360 return Val.getValue();
361
362 Val = 0;
363
364 if (D->getIdentifier() == 0)
365 return 0;
366
367 StringRef Name = D->getName();
368 if (Name.empty())
369 return 0;
Ted Kremenek48fa1362012-10-11 20:58:18 +0000370
371 FunctionFarmer FF;
372
373 if (Name.startswith("OSAtomicCompareAndSwap") ||
374 Name.startswith("objc_atomicCompareAndSwap")) {
375 FF = create_OSAtomicCompareAndSwap;
376 }
377 else {
378 FF = llvm::StringSwitch<FunctionFarmer>(Name)
379 .Case("dispatch_sync", create_dispatch_sync)
380 .Case("dispatch_once", create_dispatch_once)
381 .Default(NULL);
Ted Kremeneka43df952012-09-21 00:09:11 +0000382 }
383
Ted Kremenek48fa1362012-10-11 20:58:18 +0000384 if (FF) { Val = FF(C, D); }
Ted Kremeneka43df952012-09-21 00:09:11 +0000385 return Val.getValue();
386}
387
Stephen Hines651f13c2014-04-23 16:59:28 -0700388static Stmt *createObjCPropertyGetter(ASTContext &Ctx,
389 const ObjCPropertyDecl *Prop) {
390 // First, find the backing ivar.
391 const ObjCIvarDecl *IVar = Prop->getPropertyIvarDecl();
392 if (!IVar)
393 return 0;
394
395 // Ignore weak variables, which have special behavior.
396 if (Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
397 return 0;
398
399 // Look to see if Sema has synthesized a body for us. This happens in
400 // Objective-C++ because the return value may be a C++ class type with a
401 // non-trivial copy constructor. We can only do this if we can find the
402 // @synthesize for this property, though (or if we know it's been auto-
403 // synthesized).
404 const ObjCImplementationDecl *ImplDecl =
405 IVar->getContainingInterface()->getImplementation();
406 if (ImplDecl) {
407 for (const auto *I : ImplDecl->property_impls()) {
408 if (I->getPropertyDecl() != Prop)
409 continue;
410
411 if (I->getGetterCXXConstructor()) {
412 ASTMaker M(Ctx);
413 return M.makeReturn(I->getGetterCXXConstructor());
414 }
415 }
416 }
417
418 // Sanity check that the property is the same type as the ivar, or a
419 // reference to it, and that it is either an object pointer or trivially
420 // copyable.
421 if (!Ctx.hasSameUnqualifiedType(IVar->getType(),
422 Prop->getType().getNonReferenceType()))
423 return 0;
424 if (!IVar->getType()->isObjCLifetimeType() &&
425 !IVar->getType().isTriviallyCopyableType(Ctx))
426 return 0;
427
428 // Generate our body:
429 // return self->_ivar;
430 ASTMaker M(Ctx);
431
432 const VarDecl *selfVar = Prop->getGetterMethodDecl()->getSelfDecl();
433
434 Expr *loadedIVar =
435 M.makeObjCIvarRef(
436 M.makeLvalueToRvalue(
437 M.makeDeclRefExpr(selfVar),
438 selfVar->getType()),
439 IVar);
440
441 if (!Prop->getType()->isReferenceType())
442 loadedIVar = M.makeLvalueToRvalue(loadedIVar, IVar->getType());
443
444 return M.makeReturn(loadedIVar);
445}
446
447Stmt *BodyFarm::getBody(const ObjCMethodDecl *D) {
448 // We currently only know how to synthesize property accessors.
449 if (!D->isPropertyAccessor())
450 return 0;
451
452 D = D->getCanonicalDecl();
453
454 Optional<Stmt *> &Val = Bodies[D];
455 if (Val.hasValue())
456 return Val.getValue();
457 Val = 0;
458
459 const ObjCPropertyDecl *Prop = D->findPropertyDecl();
460 if (!Prop)
461 return 0;
462
463 // For now, we only synthesize getters.
464 if (D->param_size() != 0)
465 return 0;
466
467 Val = createObjCPropertyGetter(C, Prop);
468
469 return Val.getValue();
470}
471