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 
15 #include "BodyFarm.h"
16 #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"
21 
22 using namespace clang;
23 
24 //===----------------------------------------------------------------------===//
25 // Helper creation functions for constructing faux ASTs.
26 //===----------------------------------------------------------------------===//
27 
28 static 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>();
38   if (!FT || !FT->getReturnType()->isVoidType() || FT->getNumParams() != 0)
39     return false;
40 
41   return true;
42 }
43 
44 namespace {
45 class ASTMaker {
46 public:
47   ASTMaker(ASTContext &C) : C(C) {}
48 
49   /// Create a new BinaryOperator representing a simple assignment.
50   BinaryOperator *makeAssignment(const Expr *LHS, const Expr *RHS, QualType Ty);
51 
52   /// 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 
59   /// Create a new DeclRefExpr for the referenced variable.
60   DeclRefExpr *makeDeclRefExpr(const VarDecl *D);
61 
62   /// Create a new UnaryOperator representing a dereference.
63   UnaryOperator *makeDereference(const Expr *Arg, QualType Ty);
64 
65   /// Create an implicit cast for an integer conversion.
66   Expr *makeIntegralCast(const Expr *Arg, QualType Ty);
67 
68   /// Create an implicit cast to a builtin boolean type.
69   ImplicitCastExpr *makeIntegralCastToBoolean(const Expr *Arg);
70 
71   // Create an implicit cast for lvalue-to-rvaluate conversions.
72   ImplicitCastExpr *makeLvalueToRvalue(const Expr *Arg, QualType Ty);
73 
74   /// Create an Objective-C bool literal.
75   ObjCBoolLiteralExpr *makeObjCBool(bool Val);
76 
77   /// Create an Objective-C ivar reference.
78   ObjCIvarRefExpr *makeObjCIvarRef(const Expr *Base, const ObjCIvarDecl *IVar);
79 
80   /// Create a Return statement.
81   ReturnStmt *makeReturn(const Expr *RetVal);
82 
83 private:
84   ASTContext &C;
85 };
86 }
87 
88 BinaryOperator *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,
92                                OK_Ordinary, SourceLocation(), false);
93 }
94 
95 BinaryOperator *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 
107 CompoundStmt *ASTMaker::makeCompound(ArrayRef<Stmt *> Stmts) {
108   return new (C) CompoundStmt(C, Stmts, SourceLocation(), SourceLocation());
109 }
110 
111 DeclRefExpr *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 
124 UnaryOperator *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 
129 ImplicitCastExpr *ASTMaker::makeLvalueToRvalue(const Expr *Arg, QualType Ty) {
130   return ImplicitCastExpr::Create(C, Ty, CK_LValueToRValue,
131                                   const_cast<Expr*>(Arg), nullptr, VK_RValue);
132 }
133 
134 Expr *ASTMaker::makeIntegralCast(const Expr *Arg, QualType Ty) {
135   if (Arg->getType() == Ty)
136     return const_cast<Expr*>(Arg);
137 
138   return ImplicitCastExpr::Create(C, Ty, CK_IntegralCast,
139                                   const_cast<Expr*>(Arg), nullptr, VK_RValue);
140 }
141 
142 ImplicitCastExpr *ASTMaker::makeIntegralCastToBoolean(const Expr *Arg) {
143   return ImplicitCastExpr::Create(C, C.BoolTy, CK_IntegralToBoolean,
144                                   const_cast<Expr*>(Arg), nullptr, VK_RValue);
145 }
146 
147 ObjCBoolLiteralExpr *ASTMaker::makeObjCBool(bool Val) {
148   QualType Ty = C.getBOOLDecl() ? C.getBOOLType() : C.ObjCBuiltinBoolTy;
149   return new (C) ObjCBoolLiteralExpr(Val, Ty, SourceLocation());
150 }
151 
152 ObjCIvarRefExpr *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 
161 ReturnStmt *ASTMaker::makeReturn(const Expr *RetVal) {
162   return new (C) ReturnStmt(SourceLocation(), const_cast<Expr*>(RetVal),
163                             nullptr);
164 }
165 
166 //===----------------------------------------------------------------------===//
167 // Creation functions for faux ASTs.
168 //===----------------------------------------------------------------------===//
169 
170 typedef Stmt *(*FunctionFarmer)(ASTContext &C, const FunctionDecl *D);
171 
172 /// Create a fake body for dispatch_once.
173 static Stmt *create_dispatch_once(ASTContext &C, const FunctionDecl *D) {
174   // Check if we have at least two parameters.
175   if (D->param_size() != 2)
176     return nullptr;
177 
178   // Check if the first parameter is a pointer to integer type.
179   const ParmVarDecl *Predicate = D->getParamDecl(0);
180   QualType PredicateQPtrTy = Predicate->getType();
181   const PointerType *PredicatePtrTy = PredicateQPtrTy->getAs<PointerType>();
182   if (!PredicatePtrTy)
183     return nullptr;
184   QualType PredicateTy = PredicatePtrTy->getPointeeType();
185   if (!PredicateTy->isIntegerType())
186     return nullptr;
187 
188   // Check if the second parameter is the proper block type.
189   const ParmVarDecl *Block = D->getParamDecl(1);
190   QualType Ty = Block->getType();
191   if (!isDispatchBlock(Ty))
192     return nullptr;
193 
194   // Everything checks out.  Create a fakse body that checks the predicate,
195   // sets it, and calls the block.  Basically, an AST dump of:
196   //
197   // void dispatch_once(dispatch_once_t *predicate, dispatch_block_t block) {
198   //  if (!*predicate) {
199   //    *predicate = 1;
200   //    block();
201   //  }
202   // }
203 
204   ASTMaker M(C);
205 
206   // (1) Create the call.
207   DeclRefExpr *DR = M.makeDeclRefExpr(Block);
208   ImplicitCastExpr *ICE = M.makeLvalueToRvalue(DR, Ty);
209   CallExpr *CE = new (C) CallExpr(C, ICE, None, C.VoidTy, VK_RValue,
210                                   SourceLocation());
211 
212   // (2) Create the assignment to the predicate.
213   IntegerLiteral *IL =
214     IntegerLiteral::Create(C, llvm::APInt(C.getTypeSize(C.IntTy), (uint64_t) 1),
215                            C.IntTy, SourceLocation());
216   BinaryOperator *B =
217     M.makeAssignment(
218        M.makeDereference(
219           M.makeLvalueToRvalue(
220             M.makeDeclRefExpr(Predicate), PredicateQPtrTy),
221             PredicateTy),
222        M.makeIntegralCast(IL, PredicateTy),
223        PredicateTy);
224 
225   // (3) Create the compound statement.
226   Stmt *Stmts[] = { B, CE };
227   CompoundStmt *CS = M.makeCompound(Stmts);
228 
229   // (4) Create the 'if' condition.
230   ImplicitCastExpr *LValToRval =
231     M.makeLvalueToRvalue(
232       M.makeDereference(
233         M.makeLvalueToRvalue(
234           M.makeDeclRefExpr(Predicate),
235           PredicateQPtrTy),
236         PredicateTy),
237     PredicateTy);
238 
239   UnaryOperator *UO = new (C) UnaryOperator(LValToRval, UO_LNot, C.IntTy,
240                                            VK_RValue, OK_Ordinary,
241                                            SourceLocation());
242 
243   // (5) Create the 'if' statement.
244   IfStmt *If = new (C) IfStmt(C, SourceLocation(), nullptr, UO, CS);
245   return If;
246 }
247 
248 /// Create a fake body for dispatch_sync.
249 static Stmt *create_dispatch_sync(ASTContext &C, const FunctionDecl *D) {
250   // Check if we have at least two parameters.
251   if (D->param_size() != 2)
252     return nullptr;
253 
254   // Check if the second parameter is a block.
255   const ParmVarDecl *PV = D->getParamDecl(1);
256   QualType Ty = PV->getType();
257   if (!isDispatchBlock(Ty))
258     return nullptr;
259 
260   // Everything checks out.  Create a fake body that just calls the block.
261   // This is basically just an AST dump of:
262   //
263   // void dispatch_sync(dispatch_queue_t queue, void (^block)(void)) {
264   //   block();
265   // }
266   //
267   ASTMaker M(C);
268   DeclRefExpr *DR = M.makeDeclRefExpr(PV);
269   ImplicitCastExpr *ICE = M.makeLvalueToRvalue(DR, Ty);
270   CallExpr *CE = new (C) CallExpr(C, ICE, None, C.VoidTy, VK_RValue,
271                                   SourceLocation());
272   return CE;
273 }
274 
275 static Stmt *create_OSAtomicCompareAndSwap(ASTContext &C, const FunctionDecl *D)
276 {
277   // There are exactly 3 arguments.
278   if (D->param_size() != 3)
279     return nullptr;
280 
281   // Signature:
282   // _Bool OSAtomicCompareAndSwapPtr(void *__oldValue,
283   //                                 void *__newValue,
284   //                                 void * volatile *__theValue)
285   // Generate body:
286   //   if (oldValue == *theValue) {
287   //    *theValue = newValue;
288   //    return YES;
289   //   }
290   //   else return NO;
291 
292   QualType ResultTy = D->getReturnType();
293   bool isBoolean = ResultTy->isBooleanType();
294   if (!isBoolean && !ResultTy->isIntegralType(C))
295     return nullptr;
296 
297   const ParmVarDecl *OldValue = D->getParamDecl(0);
298   QualType OldValueTy = OldValue->getType();
299 
300   const ParmVarDecl *NewValue = D->getParamDecl(1);
301   QualType NewValueTy = NewValue->getType();
302 
303   assert(OldValueTy == NewValueTy);
304 
305   const ParmVarDecl *TheValue = D->getParamDecl(2);
306   QualType TheValueTy = TheValue->getType();
307   const PointerType *PT = TheValueTy->getAs<PointerType>();
308   if (!PT)
309     return nullptr;
310   QualType PointeeTy = PT->getPointeeType();
311 
312   ASTMaker M(C);
313   // Construct the comparison.
314   Expr *Comparison =
315     M.makeComparison(
316       M.makeLvalueToRvalue(M.makeDeclRefExpr(OldValue), OldValueTy),
317       M.makeLvalueToRvalue(
318         M.makeDereference(
319           M.makeLvalueToRvalue(M.makeDeclRefExpr(TheValue), TheValueTy),
320           PointeeTy),
321         PointeeTy),
322       BO_EQ);
323 
324   // Construct the body of the IfStmt.
325   Stmt *Stmts[2];
326   Stmts[0] =
327     M.makeAssignment(
328       M.makeDereference(
329         M.makeLvalueToRvalue(M.makeDeclRefExpr(TheValue), TheValueTy),
330         PointeeTy),
331       M.makeLvalueToRvalue(M.makeDeclRefExpr(NewValue), NewValueTy),
332       NewValueTy);
333 
334   Expr *BoolVal = M.makeObjCBool(true);
335   Expr *RetVal = isBoolean ? M.makeIntegralCastToBoolean(BoolVal)
336                            : M.makeIntegralCast(BoolVal, ResultTy);
337   Stmts[1] = M.makeReturn(RetVal);
338   CompoundStmt *Body = M.makeCompound(Stmts);
339 
340   // Construct the else clause.
341   BoolVal = M.makeObjCBool(false);
342   RetVal = isBoolean ? M.makeIntegralCastToBoolean(BoolVal)
343                      : M.makeIntegralCast(BoolVal, ResultTy);
344   Stmt *Else = M.makeReturn(RetVal);
345 
346   /// Construct the If.
347   Stmt *If =
348     new (C) IfStmt(C, SourceLocation(), nullptr, Comparison, Body,
349                    SourceLocation(), Else);
350 
351   return If;
352 }
353 
354 Stmt *BodyFarm::getBody(const FunctionDecl *D) {
355   D = D->getCanonicalDecl();
356 
357   Optional<Stmt *> &Val = Bodies[D];
358   if (Val.hasValue())
359     return Val.getValue();
360 
361   Val = nullptr;
362 
363   if (D->getIdentifier() == nullptr)
364     return nullptr;
365 
366   StringRef Name = D->getName();
367   if (Name.empty())
368     return nullptr;
369 
370   FunctionFarmer FF;
371 
372   if (Name.startswith("OSAtomicCompareAndSwap") ||
373       Name.startswith("objc_atomicCompareAndSwap")) {
374     FF = create_OSAtomicCompareAndSwap;
375   }
376   else {
377     FF = llvm::StringSwitch<FunctionFarmer>(Name)
378           .Case("dispatch_sync", create_dispatch_sync)
379           .Case("dispatch_once", create_dispatch_once)
380           .Default(nullptr);
381   }
382 
383   if (FF) { Val = FF(C, D); }
384   return Val.getValue();
385 }
386 
387 static Stmt *createObjCPropertyGetter(ASTContext &Ctx,
388                                       const ObjCPropertyDecl *Prop) {
389   // First, find the backing ivar.
390   const ObjCIvarDecl *IVar = Prop->getPropertyIvarDecl();
391   if (!IVar)
392     return nullptr;
393 
394   // Ignore weak variables, which have special behavior.
395   if (Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
396     return nullptr;
397 
398   // Look to see if Sema has synthesized a body for us. This happens in
399   // Objective-C++ because the return value may be a C++ class type with a
400   // non-trivial copy constructor. We can only do this if we can find the
401   // @synthesize for this property, though (or if we know it's been auto-
402   // synthesized).
403   const ObjCImplementationDecl *ImplDecl =
404     IVar->getContainingInterface()->getImplementation();
405   if (ImplDecl) {
406     for (const auto *I : ImplDecl->property_impls()) {
407       if (I->getPropertyDecl() != Prop)
408         continue;
409 
410       if (I->getGetterCXXConstructor()) {
411         ASTMaker M(Ctx);
412         return M.makeReturn(I->getGetterCXXConstructor());
413       }
414     }
415   }
416 
417   // Sanity check that the property is the same type as the ivar, or a
418   // reference to it, and that it is either an object pointer or trivially
419   // copyable.
420   if (!Ctx.hasSameUnqualifiedType(IVar->getType(),
421                                   Prop->getType().getNonReferenceType()))
422     return nullptr;
423   if (!IVar->getType()->isObjCLifetimeType() &&
424       !IVar->getType().isTriviallyCopyableType(Ctx))
425     return nullptr;
426 
427   // Generate our body:
428   //   return self->_ivar;
429   ASTMaker M(Ctx);
430 
431   const VarDecl *selfVar = Prop->getGetterMethodDecl()->getSelfDecl();
432 
433   Expr *loadedIVar =
434     M.makeObjCIvarRef(
435       M.makeLvalueToRvalue(
436         M.makeDeclRefExpr(selfVar),
437         selfVar->getType()),
438       IVar);
439 
440   if (!Prop->getType()->isReferenceType())
441     loadedIVar = M.makeLvalueToRvalue(loadedIVar, IVar->getType());
442 
443   return M.makeReturn(loadedIVar);
444 }
445 
446 Stmt *BodyFarm::getBody(const ObjCMethodDecl *D) {
447   // We currently only know how to synthesize property accessors.
448   if (!D->isPropertyAccessor())
449     return nullptr;
450 
451   D = D->getCanonicalDecl();
452 
453   Optional<Stmt *> &Val = Bodies[D];
454   if (Val.hasValue())
455     return Val.getValue();
456   Val = nullptr;
457 
458   const ObjCPropertyDecl *Prop = D->findPropertyDecl();
459   if (!Prop)
460     return nullptr;
461 
462   // For now, we only synthesize getters.
463   if (D->param_size() != 0)
464     return nullptr;
465 
466   Val = createObjCPropertyGetter(C, Prop);
467 
468   return Val.getValue();
469 }
470 
471