BodyFarm.cpp 29 KB

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