TransAutoreleasePool.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. //===--- TransAutoreleasePool.cpp - Transformations to ARC mode -----------===//
  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. // rewriteAutoreleasePool:
  11. //
  12. // Calls to NSAutoreleasePools will be rewritten as an @autorelease scope.
  13. //
  14. // NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
  15. // ...
  16. // [pool release];
  17. // ---->
  18. // @autorelease {
  19. // ...
  20. // }
  21. //
  22. // An NSAutoreleasePool will not be touched if:
  23. // - There is not a corresponding -release/-drain in the same scope
  24. // - Not all references of the NSAutoreleasePool variable can be removed
  25. // - There is a variable that is declared inside the intended @autorelease scope
  26. // which is also used outside it.
  27. //
  28. //===----------------------------------------------------------------------===//
  29. #include "Transforms.h"
  30. #include "Internals.h"
  31. #include "clang/AST/ASTContext.h"
  32. #include "clang/Basic/SourceManager.h"
  33. #include "clang/Sema/SemaDiagnostic.h"
  34. #include <map>
  35. using namespace clang;
  36. using namespace arcmt;
  37. using namespace trans;
  38. namespace {
  39. class ReleaseCollector : public RecursiveASTVisitor<ReleaseCollector> {
  40. Decl *Dcl;
  41. SmallVectorImpl<ObjCMessageExpr *> &Releases;
  42. public:
  43. ReleaseCollector(Decl *D, SmallVectorImpl<ObjCMessageExpr *> &releases)
  44. : Dcl(D), Releases(releases) { }
  45. bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
  46. if (!E->isInstanceMessage())
  47. return true;
  48. if (E->getMethodFamily() != OMF_release)
  49. return true;
  50. Expr *instance = E->getInstanceReceiver()->IgnoreParenCasts();
  51. if (DeclRefExpr *DE = dyn_cast<DeclRefExpr>(instance)) {
  52. if (DE->getDecl() == Dcl)
  53. Releases.push_back(E);
  54. }
  55. return true;
  56. }
  57. };
  58. }
  59. namespace {
  60. class AutoreleasePoolRewriter
  61. : public RecursiveASTVisitor<AutoreleasePoolRewriter> {
  62. public:
  63. AutoreleasePoolRewriter(MigrationPass &pass)
  64. : Body(nullptr), Pass(pass) {
  65. PoolII = &pass.Ctx.Idents.get("NSAutoreleasePool");
  66. DrainSel = pass.Ctx.Selectors.getNullarySelector(
  67. &pass.Ctx.Idents.get("drain"));
  68. }
  69. void transformBody(Stmt *body, Decl *ParentD) {
  70. Body = body;
  71. TraverseStmt(body);
  72. }
  73. ~AutoreleasePoolRewriter() {
  74. SmallVector<VarDecl *, 8> VarsToHandle;
  75. for (std::map<VarDecl *, PoolVarInfo>::iterator
  76. I = PoolVars.begin(), E = PoolVars.end(); I != E; ++I) {
  77. VarDecl *var = I->first;
  78. PoolVarInfo &info = I->second;
  79. // Check that we can handle/rewrite all references of the pool.
  80. clearRefsIn(info.Dcl, info.Refs);
  81. for (SmallVectorImpl<PoolScope>::iterator
  82. scpI = info.Scopes.begin(),
  83. scpE = info.Scopes.end(); scpI != scpE; ++scpI) {
  84. PoolScope &scope = *scpI;
  85. clearRefsIn(*scope.Begin, info.Refs);
  86. clearRefsIn(*scope.End, info.Refs);
  87. clearRefsIn(scope.Releases.begin(), scope.Releases.end(), info.Refs);
  88. }
  89. // Even if one reference is not handled we will not do anything about that
  90. // pool variable.
  91. if (info.Refs.empty())
  92. VarsToHandle.push_back(var);
  93. }
  94. for (unsigned i = 0, e = VarsToHandle.size(); i != e; ++i) {
  95. PoolVarInfo &info = PoolVars[VarsToHandle[i]];
  96. Transaction Trans(Pass.TA);
  97. clearUnavailableDiags(info.Dcl);
  98. Pass.TA.removeStmt(info.Dcl);
  99. // Add "@autoreleasepool { }"
  100. for (SmallVectorImpl<PoolScope>::iterator
  101. scpI = info.Scopes.begin(),
  102. scpE = info.Scopes.end(); scpI != scpE; ++scpI) {
  103. PoolScope &scope = *scpI;
  104. clearUnavailableDiags(*scope.Begin);
  105. clearUnavailableDiags(*scope.End);
  106. if (scope.IsFollowedBySimpleReturnStmt) {
  107. // Include the return in the scope.
  108. Pass.TA.replaceStmt(*scope.Begin, "@autoreleasepool {");
  109. Pass.TA.removeStmt(*scope.End);
  110. Stmt::child_iterator retI = scope.End;
  111. ++retI;
  112. SourceLocation afterSemi = findLocationAfterSemi((*retI)->getLocEnd(),
  113. Pass.Ctx);
  114. assert(afterSemi.isValid() &&
  115. "Didn't we check before setting IsFollowedBySimpleReturnStmt "
  116. "to true?");
  117. Pass.TA.insertAfterToken(afterSemi, "\n}");
  118. Pass.TA.increaseIndentation(
  119. SourceRange(scope.getIndentedRange().getBegin(),
  120. (*retI)->getLocEnd()),
  121. scope.CompoundParent->getLocStart());
  122. } else {
  123. Pass.TA.replaceStmt(*scope.Begin, "@autoreleasepool {");
  124. Pass.TA.replaceStmt(*scope.End, "}");
  125. Pass.TA.increaseIndentation(scope.getIndentedRange(),
  126. scope.CompoundParent->getLocStart());
  127. }
  128. }
  129. // Remove rest of pool var references.
  130. for (SmallVectorImpl<PoolScope>::iterator
  131. scpI = info.Scopes.begin(),
  132. scpE = info.Scopes.end(); scpI != scpE; ++scpI) {
  133. PoolScope &scope = *scpI;
  134. for (SmallVectorImpl<ObjCMessageExpr *>::iterator
  135. relI = scope.Releases.begin(),
  136. relE = scope.Releases.end(); relI != relE; ++relI) {
  137. clearUnavailableDiags(*relI);
  138. Pass.TA.removeStmt(*relI);
  139. }
  140. }
  141. }
  142. }
  143. bool VisitCompoundStmt(CompoundStmt *S) {
  144. SmallVector<PoolScope, 4> Scopes;
  145. for (Stmt::child_iterator
  146. I = S->body_begin(), E = S->body_end(); I != E; ++I) {
  147. Stmt *child = getEssential(*I);
  148. if (DeclStmt *DclS = dyn_cast<DeclStmt>(child)) {
  149. if (DclS->isSingleDecl()) {
  150. if (VarDecl *VD = dyn_cast<VarDecl>(DclS->getSingleDecl())) {
  151. if (isNSAutoreleasePool(VD->getType())) {
  152. PoolVarInfo &info = PoolVars[VD];
  153. info.Dcl = DclS;
  154. collectRefs(VD, S, info.Refs);
  155. // Does this statement follow the pattern:
  156. // NSAutoreleasePool * pool = [NSAutoreleasePool new];
  157. if (isPoolCreation(VD->getInit())) {
  158. Scopes.push_back(PoolScope());
  159. Scopes.back().PoolVar = VD;
  160. Scopes.back().CompoundParent = S;
  161. Scopes.back().Begin = I;
  162. }
  163. }
  164. }
  165. }
  166. } else if (BinaryOperator *bop = dyn_cast<BinaryOperator>(child)) {
  167. if (DeclRefExpr *dref = dyn_cast<DeclRefExpr>(bop->getLHS())) {
  168. if (VarDecl *VD = dyn_cast<VarDecl>(dref->getDecl())) {
  169. // Does this statement follow the pattern:
  170. // pool = [NSAutoreleasePool new];
  171. if (isNSAutoreleasePool(VD->getType()) &&
  172. isPoolCreation(bop->getRHS())) {
  173. Scopes.push_back(PoolScope());
  174. Scopes.back().PoolVar = VD;
  175. Scopes.back().CompoundParent = S;
  176. Scopes.back().Begin = I;
  177. }
  178. }
  179. }
  180. }
  181. if (Scopes.empty())
  182. continue;
  183. if (isPoolDrain(Scopes.back().PoolVar, child)) {
  184. PoolScope &scope = Scopes.back();
  185. scope.End = I;
  186. handlePoolScope(scope, S);
  187. Scopes.pop_back();
  188. }
  189. }
  190. return true;
  191. }
  192. private:
  193. void clearUnavailableDiags(Stmt *S) {
  194. if (S)
  195. Pass.TA.clearDiagnostic(diag::err_unavailable,
  196. diag::err_unavailable_message,
  197. S->getSourceRange());
  198. }
  199. struct PoolScope {
  200. VarDecl *PoolVar;
  201. CompoundStmt *CompoundParent;
  202. Stmt::child_iterator Begin;
  203. Stmt::child_iterator End;
  204. bool IsFollowedBySimpleReturnStmt;
  205. SmallVector<ObjCMessageExpr *, 4> Releases;
  206. PoolScope() : PoolVar(nullptr), CompoundParent(nullptr), Begin(), End(),
  207. IsFollowedBySimpleReturnStmt(false) { }
  208. SourceRange getIndentedRange() const {
  209. Stmt::child_iterator rangeS = Begin;
  210. ++rangeS;
  211. if (rangeS == End)
  212. return SourceRange();
  213. Stmt::child_iterator rangeE = Begin;
  214. for (Stmt::child_iterator I = rangeS; I != End; ++I)
  215. ++rangeE;
  216. return SourceRange((*rangeS)->getLocStart(), (*rangeE)->getLocEnd());
  217. }
  218. };
  219. class NameReferenceChecker : public RecursiveASTVisitor<NameReferenceChecker>{
  220. ASTContext &Ctx;
  221. SourceRange ScopeRange;
  222. SourceLocation &referenceLoc, &declarationLoc;
  223. public:
  224. NameReferenceChecker(ASTContext &ctx, PoolScope &scope,
  225. SourceLocation &referenceLoc,
  226. SourceLocation &declarationLoc)
  227. : Ctx(ctx), referenceLoc(referenceLoc),
  228. declarationLoc(declarationLoc) {
  229. ScopeRange = SourceRange((*scope.Begin)->getLocStart(),
  230. (*scope.End)->getLocStart());
  231. }
  232. bool VisitDeclRefExpr(DeclRefExpr *E) {
  233. return checkRef(E->getLocation(), E->getDecl()->getLocation());
  234. }
  235. bool VisitTypedefTypeLoc(TypedefTypeLoc TL) {
  236. return checkRef(TL.getBeginLoc(), TL.getTypedefNameDecl()->getLocation());
  237. }
  238. bool VisitTagTypeLoc(TagTypeLoc TL) {
  239. return checkRef(TL.getBeginLoc(), TL.getDecl()->getLocation());
  240. }
  241. private:
  242. bool checkRef(SourceLocation refLoc, SourceLocation declLoc) {
  243. if (isInScope(declLoc)) {
  244. referenceLoc = refLoc;
  245. declarationLoc = declLoc;
  246. return false;
  247. }
  248. return true;
  249. }
  250. bool isInScope(SourceLocation loc) {
  251. if (loc.isInvalid())
  252. return false;
  253. SourceManager &SM = Ctx.getSourceManager();
  254. if (SM.isBeforeInTranslationUnit(loc, ScopeRange.getBegin()))
  255. return false;
  256. return SM.isBeforeInTranslationUnit(loc, ScopeRange.getEnd());
  257. }
  258. };
  259. void handlePoolScope(PoolScope &scope, CompoundStmt *compoundS) {
  260. // Check that all names declared inside the scope are not used
  261. // outside the scope.
  262. {
  263. bool nameUsedOutsideScope = false;
  264. SourceLocation referenceLoc, declarationLoc;
  265. Stmt::child_iterator SI = scope.End, SE = compoundS->body_end();
  266. ++SI;
  267. // Check if the autoreleasepool scope is followed by a simple return
  268. // statement, in which case we will include the return in the scope.
  269. if (SI != SE)
  270. if (ReturnStmt *retS = dyn_cast<ReturnStmt>(*SI))
  271. if ((retS->getRetValue() == nullptr ||
  272. isa<DeclRefExpr>(retS->getRetValue()->IgnoreParenCasts())) &&
  273. findLocationAfterSemi(retS->getLocEnd(), Pass.Ctx).isValid()) {
  274. scope.IsFollowedBySimpleReturnStmt = true;
  275. ++SI; // the return will be included in scope, don't check it.
  276. }
  277. for (; SI != SE; ++SI) {
  278. nameUsedOutsideScope = !NameReferenceChecker(Pass.Ctx, scope,
  279. referenceLoc,
  280. declarationLoc).TraverseStmt(*SI);
  281. if (nameUsedOutsideScope)
  282. break;
  283. }
  284. // If not all references were cleared it means some variables/typenames/etc
  285. // declared inside the pool scope are used outside of it.
  286. // We won't try to rewrite the pool.
  287. if (nameUsedOutsideScope) {
  288. Pass.TA.reportError("a name is referenced outside the "
  289. "NSAutoreleasePool scope that it was declared in", referenceLoc);
  290. Pass.TA.reportNote("name declared here", declarationLoc);
  291. Pass.TA.reportNote("intended @autoreleasepool scope begins here",
  292. (*scope.Begin)->getLocStart());
  293. Pass.TA.reportNote("intended @autoreleasepool scope ends here",
  294. (*scope.End)->getLocStart());
  295. return;
  296. }
  297. }
  298. // Collect all releases of the pool; they will be removed.
  299. {
  300. ReleaseCollector releaseColl(scope.PoolVar, scope.Releases);
  301. Stmt::child_iterator I = scope.Begin;
  302. ++I;
  303. for (; I != scope.End; ++I)
  304. releaseColl.TraverseStmt(*I);
  305. }
  306. PoolVars[scope.PoolVar].Scopes.push_back(scope);
  307. }
  308. bool isPoolCreation(Expr *E) {
  309. if (!E) return false;
  310. E = getEssential(E);
  311. ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E);
  312. if (!ME) return false;
  313. if (ME->getMethodFamily() == OMF_new &&
  314. ME->getReceiverKind() == ObjCMessageExpr::Class &&
  315. isNSAutoreleasePool(ME->getReceiverInterface()))
  316. return true;
  317. if (ME->getReceiverKind() == ObjCMessageExpr::Instance &&
  318. ME->getMethodFamily() == OMF_init) {
  319. Expr *rec = getEssential(ME->getInstanceReceiver());
  320. if (ObjCMessageExpr *recME = dyn_cast_or_null<ObjCMessageExpr>(rec)) {
  321. if (recME->getMethodFamily() == OMF_alloc &&
  322. recME->getReceiverKind() == ObjCMessageExpr::Class &&
  323. isNSAutoreleasePool(recME->getReceiverInterface()))
  324. return true;
  325. }
  326. }
  327. return false;
  328. }
  329. bool isPoolDrain(VarDecl *poolVar, Stmt *S) {
  330. if (!S) return false;
  331. S = getEssential(S);
  332. ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S);
  333. if (!ME) return false;
  334. if (ME->getReceiverKind() == ObjCMessageExpr::Instance) {
  335. Expr *rec = getEssential(ME->getInstanceReceiver());
  336. if (DeclRefExpr *dref = dyn_cast<DeclRefExpr>(rec))
  337. if (dref->getDecl() == poolVar)
  338. return ME->getMethodFamily() == OMF_release ||
  339. ME->getSelector() == DrainSel;
  340. }
  341. return false;
  342. }
  343. bool isNSAutoreleasePool(ObjCInterfaceDecl *IDecl) {
  344. return IDecl && IDecl->getIdentifier() == PoolII;
  345. }
  346. bool isNSAutoreleasePool(QualType Ty) {
  347. QualType pointee = Ty->getPointeeType();
  348. if (pointee.isNull())
  349. return false;
  350. if (const ObjCInterfaceType *interT = pointee->getAs<ObjCInterfaceType>())
  351. return isNSAutoreleasePool(interT->getDecl());
  352. return false;
  353. }
  354. static Expr *getEssential(Expr *E) {
  355. return cast<Expr>(getEssential((Stmt*)E));
  356. }
  357. static Stmt *getEssential(Stmt *S) {
  358. if (ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(S))
  359. S = EWC->getSubExpr();
  360. if (Expr *E = dyn_cast<Expr>(S))
  361. S = E->IgnoreParenCasts();
  362. return S;
  363. }
  364. Stmt *Body;
  365. MigrationPass &Pass;
  366. IdentifierInfo *PoolII;
  367. Selector DrainSel;
  368. struct PoolVarInfo {
  369. DeclStmt *Dcl;
  370. ExprSet Refs;
  371. SmallVector<PoolScope, 2> Scopes;
  372. PoolVarInfo() : Dcl(nullptr) { }
  373. };
  374. std::map<VarDecl *, PoolVarInfo> PoolVars;
  375. };
  376. } // anonymous namespace
  377. void trans::rewriteAutoreleasePool(MigrationPass &pass) {
  378. BodyTransform<AutoreleasePoolRewriter> trans(pass);
  379. trans.TraverseDecl(pass.Ctx.getTranslationUnitDecl());
  380. }