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 "llvm/ADT/StringSwitch.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/Expr.h"
18 #include "clang/AST/Decl.h"
19 #include "BodyFarm.h"
20 
21 using namespace clang;
22 
23 //===----------------------------------------------------------------------===//
24 // Helper creation functions for constructing faux ASTs.
25 //===----------------------------------------------------------------------===//
26 
27 static bool isDispatchBlock(QualType Ty) {
28   // Is it a block pointer?
29   const BlockPointerType *BPT = Ty->getAs<BlockPointerType>();
30   if (!BPT)
31     return false;
32 
33   // Check if the block pointer type takes no arguments and
34   // returns void.
35   const FunctionProtoType *FT =
36   BPT->getPointeeType()->getAs<FunctionProtoType>();
37   if (!FT || !FT->getResultType()->isVoidType()  ||
38       FT->getNumArgs() != 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 DeclRefExpr for the referenced variable.
53   DeclRefExpr *makeDeclRefExpr(const VarDecl *D);
54 
55   /// Create a new UnaryOperator representing a dereference.
56   UnaryOperator *makeDereference(const Expr *Arg, QualType Ty);
57 
58   /// Create an implicit cast for an integer conversion.
59   ImplicitCastExpr *makeIntegralCast(const Expr *Arg, QualType Ty);
60 
61   // Create an implicit cast for lvalue-to-rvaluate conversions.
62   ImplicitCastExpr *makeLvalueToRvalue(const Expr *Arg, QualType Ty);
63 
64 private:
65   ASTContext &C;
66 };
67 }
68 
69 BinaryOperator *ASTMaker::makeAssignment(const Expr *LHS, const Expr *RHS,
70                                          QualType Ty) {
71  return new (C) BinaryOperator(const_cast<Expr*>(LHS), const_cast<Expr*>(RHS),
72                                BO_Assign, Ty, VK_RValue,
73                                OK_Ordinary, SourceLocation(), false);
74 }
75 
76 DeclRefExpr *ASTMaker::makeDeclRefExpr(const VarDecl *D) {
77   DeclRefExpr *DR =
78     DeclRefExpr::Create(/* Ctx = */ C,
79                         /* QualifierLoc = */ NestedNameSpecifierLoc(),
80                         /* TemplateKWLoc = */ SourceLocation(),
81                         /* D = */ const_cast<VarDecl*>(D),
82                         /* isEnclosingLocal = */ false,
83                         /* NameLoc = */ SourceLocation(),
84                         /* T = */ D->getType(),
85                         /* VK = */ VK_LValue);
86   return DR;
87 }
88 
89 UnaryOperator *ASTMaker::makeDereference(const Expr *Arg, QualType Ty) {
90   return new (C) UnaryOperator(const_cast<Expr*>(Arg), UO_Deref, Ty,
91                                VK_LValue, OK_Ordinary, SourceLocation());
92 }
93 
94 ImplicitCastExpr *ASTMaker::makeLvalueToRvalue(const Expr *Arg, QualType Ty) {
95   return ImplicitCastExpr::Create(C, Ty, CK_LValueToRValue,
96                                   const_cast<Expr*>(Arg), 0, VK_RValue);
97 }
98 
99 ImplicitCastExpr *ASTMaker::makeIntegralCast(const Expr *Arg, QualType Ty) {
100   return ImplicitCastExpr::Create(C, Ty, CK_IntegralCast,
101                                   const_cast<Expr*>(Arg), 0, VK_RValue);
102 }
103 
104 //===----------------------------------------------------------------------===//
105 // Creation functions for faux ASTs.
106 //===----------------------------------------------------------------------===//
107 
108 typedef Stmt *(*FunctionFarmer)(ASTContext &C, const FunctionDecl *D);
109 
110 /// Create a fake body for dispatch_once.
111 static Stmt *create_dispatch_once(ASTContext &C, const FunctionDecl *D) {
112   // Check if we have at least two parameters.
113   if (D->param_size() != 2)
114     return 0;
115 
116   // Check if the first parameter is a pointer to integer type.
117   const ParmVarDecl *Predicate = D->getParamDecl(0);
118   QualType PredicateQPtrTy = Predicate->getType();
119   const PointerType *PredicatePtrTy = PredicateQPtrTy->getAs<PointerType>();
120   if (!PredicatePtrTy)
121     return 0;
122   QualType PredicateTy = PredicatePtrTy->getPointeeType();
123   if (!PredicateTy->isIntegerType())
124     return 0;
125 
126   // Check if the second parameter is the proper block type.
127   const ParmVarDecl *Block = D->getParamDecl(1);
128   QualType Ty = Block->getType();
129   if (!isDispatchBlock(Ty))
130     return 0;
131 
132   // Everything checks out.  Create a fakse body that checks the predicate,
133   // sets it, and calls the block.  Basically, an AST dump of:
134   //
135   // void dispatch_once(dispatch_once_t *predicate, dispatch_block_t block) {
136   //  if (!*predicate) {
137   //    *predicate = 1;
138   //    block();
139   //  }
140   // }
141 
142   ASTMaker M(C);
143 
144   // (1) Create the call.
145   DeclRefExpr *DR = M.makeDeclRefExpr(Block);
146   ImplicitCastExpr *ICE = M.makeLvalueToRvalue(DR, Ty);
147   CallExpr *CE = new (C) CallExpr(C, ICE, ArrayRef<Expr*>(), C.VoidTy,
148                                   VK_RValue, SourceLocation());
149 
150   // (2) Create the assignment to the predicate.
151   IntegerLiteral *IL =
152     IntegerLiteral::Create(C, llvm::APInt(C.getTypeSize(C.IntTy), (uint64_t) 1),
153                            C.IntTy, SourceLocation());
154   BinaryOperator *B =
155     M.makeAssignment(
156        M.makeDereference(
157           M.makeLvalueToRvalue(
158             M.makeDeclRefExpr(Predicate), PredicateQPtrTy),
159             PredicateTy),
160        M.makeIntegralCast(IL, PredicateTy),
161        PredicateTy);
162 
163   // (3) Create the compound statement.
164   Stmt *Stmts[2];
165   Stmts[0] = B;
166   Stmts[1] = CE;
167   CompoundStmt *CS = new (C) CompoundStmt(C, Stmts, 2, SourceLocation(),
168                                           SourceLocation());
169 
170   // (4) Create the 'if' condition.
171   ImplicitCastExpr *LValToRval =
172     M.makeLvalueToRvalue(
173       M.makeDereference(
174         M.makeLvalueToRvalue(
175           M.makeDeclRefExpr(Predicate),
176           PredicateQPtrTy),
177         PredicateTy),
178     PredicateTy);
179 
180   UnaryOperator *UO = new (C) UnaryOperator(LValToRval, UO_LNot, C.IntTy,
181                                            VK_RValue, OK_Ordinary,
182                                            SourceLocation());
183 
184   // (5) Create the 'if' statement.
185   IfStmt *If = new (C) IfStmt(C, SourceLocation(), 0, UO, CS);
186   return If;
187 }
188 
189 /// Create a fake body for dispatch_sync.
190 static Stmt *create_dispatch_sync(ASTContext &C, const FunctionDecl *D) {
191   // Check if we have at least two parameters.
192   if (D->param_size() != 2)
193     return 0;
194 
195   // Check if the second parameter is a block.
196   const ParmVarDecl *PV = D->getParamDecl(1);
197   QualType Ty = PV->getType();
198   if (!isDispatchBlock(Ty))
199     return 0;
200 
201   // Everything checks out.  Create a fake body that just calls the block.
202   // This is basically just an AST dump of:
203   //
204   // void dispatch_sync(dispatch_queue_t queue, void (^block)(void)) {
205   //   block();
206   // }
207   //
208   ASTMaker M(C);
209   DeclRefExpr *DR = M.makeDeclRefExpr(PV);
210   ImplicitCastExpr *ICE = M.makeLvalueToRvalue(DR, Ty);
211   CallExpr *CE = new (C) CallExpr(C, ICE, ArrayRef<Expr*>(), C.VoidTy,
212                                   VK_RValue, SourceLocation());
213   return CE;
214 }
215 
216 Stmt *BodyFarm::getBody(const FunctionDecl *D) {
217   D = D->getCanonicalDecl();
218 
219   llvm::Optional<Stmt *> &Val = Bodies[D];
220   if (Val.hasValue())
221     return Val.getValue();
222 
223   Val = 0;
224 
225   if (D->getIdentifier() == 0)
226     return 0;
227 
228   StringRef Name = D->getName();
229   if (Name.empty())
230     return 0;
231 
232   FunctionFarmer FF =
233     llvm::StringSwitch<FunctionFarmer>(Name)
234       .Case("dispatch_sync", create_dispatch_sync)
235       .Case("dispatch_once", create_dispatch_once)
236       .Default(NULL);
237 
238   if (FF) {
239     Val = FF(C, D);
240   }
241 
242   return Val.getValue();
243 }
244 
245