BodyFarm.cpp 32 KB

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