1 //===--- Transforms.cpp - Transformations to ARC mode ---------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "Transforms.h"
11 #include "Internals.h"
12 #include "clang/AST/ASTContext.h"
13 #include "clang/AST/RecursiveASTVisitor.h"
14 #include "clang/Analysis/DomainSpecific/CocoaConventions.h"
15 #include "clang/Basic/SourceManager.h"
16 #include "clang/Basic/TargetInfo.h"
17 #include "clang/Lex/Lexer.h"
18 #include "clang/Lex/Preprocessor.h"
19 #include "clang/Sema/Sema.h"
21 using namespace clang;
22 using namespace arcmt;
23 using namespace trans;
25 ASTTraverser::~ASTTraverser() { }
27 bool MigrationPass::CFBridgingFunctionsDefined() {
28 if (!EnableCFBridgeFns.hasValue())
29 EnableCFBridgeFns = SemaRef.isKnownName("CFBridgingRetain") &&
30 SemaRef.isKnownName("CFBridgingRelease");
31 return *EnableCFBridgeFns;
34 //===----------------------------------------------------------------------===//
36 //===----------------------------------------------------------------------===//
38 bool trans::canApplyWeak(ASTContext &Ctx, QualType type,
39 bool AllowOnUnknownClass) {
40 if (!Ctx.getLangOpts().ObjCWeakRuntime)
47 // iOS is always safe to use 'weak'.
48 if (Ctx.getTargetInfo().getTriple().isiOS() ||
49 Ctx.getTargetInfo().getTriple().isWatchOS())
50 AllowOnUnknownClass = true;
52 while (const PointerType *ptr = T->getAs<PointerType>())
53 T = ptr->getPointeeType();
54 if (const ObjCObjectPointerType *ObjT = T->getAs<ObjCObjectPointerType>()) {
55 ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl();
56 if (!AllowOnUnknownClass && (!Class || Class->getName() == "NSObject"))
57 return false; // id/NSObject is not safe for weak.
58 if (!AllowOnUnknownClass && !Class->hasDefinition())
59 return false; // forward classes are not verifiable, therefore not safe.
60 if (Class && Class->isArcWeakrefUnavailable())
67 bool trans::isPlusOneAssign(const BinaryOperator *E) {
68 if (E->getOpcode() != BO_Assign)
71 return isPlusOne(E->getRHS());
74 bool trans::isPlusOne(const Expr *E) {
77 if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(E))
78 E = EWC->getSubExpr();
80 if (const ObjCMessageExpr *
81 ME = dyn_cast<ObjCMessageExpr>(E->IgnoreParenCasts()))
82 if (ME->getMethodFamily() == OMF_retain)
86 callE = dyn_cast<CallExpr>(E->IgnoreParenCasts())) {
87 if (const FunctionDecl *FD = callE->getDirectCallee()) {
88 if (FD->hasAttr<CFReturnsRetainedAttr>())
92 FD->getIdentifier() &&
93 FD->getParent()->isTranslationUnit() &&
94 FD->isExternallyVisible() &&
95 ento::cocoa::isRefType(callE->getType(), "CF",
96 FD->getIdentifier()->getName())) {
97 StringRef fname = FD->getIdentifier()->getName();
98 if (fname.endswith("Retain") ||
99 fname.find("Create") != StringRef::npos ||
100 fname.find("Copy") != StringRef::npos) {
107 const ImplicitCastExpr *implCE = dyn_cast<ImplicitCastExpr>(E);
108 while (implCE && implCE->getCastKind() == CK_BitCast)
109 implCE = dyn_cast<ImplicitCastExpr>(implCE->getSubExpr());
111 return implCE && implCE->getCastKind() == CK_ARCConsumeObject;
114 /// 'Loc' is the end of a statement range. This returns the location
115 /// immediately after the semicolon following the statement.
116 /// If no semicolon is found or the location is inside a macro, the returned
117 /// source location will be invalid.
118 SourceLocation trans::findLocationAfterSemi(SourceLocation loc,
119 ASTContext &Ctx, bool IsDecl) {
120 SourceLocation SemiLoc = findSemiAfterLocation(loc, Ctx, IsDecl);
121 if (SemiLoc.isInvalid())
122 return SourceLocation();
123 return SemiLoc.getLocWithOffset(1);
126 /// \arg Loc is the end of a statement range. This returns the location
127 /// of the semicolon following the statement.
128 /// If no semicolon is found or the location is inside a macro, the returned
129 /// source location will be invalid.
130 SourceLocation trans::findSemiAfterLocation(SourceLocation loc,
133 SourceManager &SM = Ctx.getSourceManager();
134 if (loc.isMacroID()) {
135 if (!Lexer::isAtEndOfMacroExpansion(loc, SM, Ctx.getLangOpts(), &loc))
136 return SourceLocation();
138 loc = Lexer::getLocForEndOfToken(loc, /*Offset=*/0, SM, Ctx.getLangOpts());
140 // Break down the source location.
141 std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(loc);
143 // Try to load the file buffer.
144 bool invalidTemp = false;
145 StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
147 return SourceLocation();
149 const char *tokenBegin = file.data() + locInfo.second;
151 // Lex from the start of the given location.
152 Lexer lexer(SM.getLocForStartOfFile(locInfo.first),
154 file.begin(), tokenBegin, file.end());
156 lexer.LexFromRawLexer(tok);
157 if (tok.isNot(tok::semi)) {
159 return SourceLocation();
160 // Declaration may be followed with other tokens; such as an __attribute,
161 // before ending with a semicolon.
162 return findSemiAfterLocation(tok.getLocation(), Ctx, /*IsDecl*/true);
165 return tok.getLocation();
168 bool trans::hasSideEffects(Expr *E, ASTContext &Ctx) {
169 if (!E || !E->HasSideEffects(Ctx))
172 E = E->IgnoreParenCasts();
173 ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E);
176 switch (ME->getMethodFamily()) {
177 case OMF_autorelease:
181 switch (ME->getReceiverKind()) {
182 case ObjCMessageExpr::SuperInstance:
184 case ObjCMessageExpr::Instance:
185 return hasSideEffects(ME->getInstanceReceiver(), Ctx);
197 bool trans::isGlobalVar(Expr *E) {
198 E = E->IgnoreParenCasts();
199 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
200 return DRE->getDecl()->getDeclContext()->isFileContext() &&
201 DRE->getDecl()->isExternallyVisible();
202 if (ConditionalOperator *condOp = dyn_cast<ConditionalOperator>(E))
203 return isGlobalVar(condOp->getTrueExpr()) &&
204 isGlobalVar(condOp->getFalseExpr());
209 StringRef trans::getNilString(MigrationPass &Pass) {
210 return Pass.SemaRef.PP.isMacroDefined("nil") ? "nil" : "0";
215 class ReferenceClear : public RecursiveASTVisitor<ReferenceClear> {
218 ReferenceClear(ExprSet &refs) : Refs(refs) { }
219 bool VisitDeclRefExpr(DeclRefExpr *E) { Refs.erase(E); return true; }
222 class ReferenceCollector : public RecursiveASTVisitor<ReferenceCollector> {
227 ReferenceCollector(ValueDecl *D, ExprSet &refs)
228 : Dcl(D), Refs(refs) { }
230 bool VisitDeclRefExpr(DeclRefExpr *E) {
231 if (E->getDecl() == Dcl)
237 class RemovablesCollector : public RecursiveASTVisitor<RemovablesCollector> {
241 RemovablesCollector(ExprSet &removables)
242 : Removables(removables) { }
244 bool shouldWalkTypesOfTypeLocs() const { return false; }
246 bool TraverseStmtExpr(StmtExpr *E) {
247 CompoundStmt *S = E->getSubStmt();
248 for (CompoundStmt::body_iterator
249 I = S->body_begin(), E = S->body_end(); I != E; ++I) {
257 bool VisitCompoundStmt(CompoundStmt *S) {
258 for (auto *I : S->body())
263 bool VisitIfStmt(IfStmt *S) {
269 bool VisitWhileStmt(WhileStmt *S) {
274 bool VisitDoStmt(DoStmt *S) {
279 bool VisitForStmt(ForStmt *S) {
290 while (LabelStmt *Label = dyn_cast<LabelStmt>(S))
291 S = Label->getSubStmt();
292 S = S->IgnoreImplicit();
293 if (Expr *E = dyn_cast<Expr>(S))
294 Removables.insert(E);
298 } // end anonymous namespace
300 void trans::clearRefsIn(Stmt *S, ExprSet &refs) {
301 ReferenceClear(refs).TraverseStmt(S);
304 void trans::collectRefs(ValueDecl *D, Stmt *S, ExprSet &refs) {
305 ReferenceCollector(D, refs).TraverseStmt(S);
308 void trans::collectRemovables(Stmt *S, ExprSet &exprs) {
309 RemovablesCollector(exprs).TraverseStmt(S);
312 //===----------------------------------------------------------------------===//
314 //===----------------------------------------------------------------------===//
318 class ASTTransform : public RecursiveASTVisitor<ASTTransform> {
319 MigrationContext &MigrateCtx;
320 typedef RecursiveASTVisitor<ASTTransform> base;
323 ASTTransform(MigrationContext &MigrateCtx) : MigrateCtx(MigrateCtx) { }
325 bool shouldWalkTypesOfTypeLocs() const { return false; }
327 bool TraverseObjCImplementationDecl(ObjCImplementationDecl *D) {
328 ObjCImplementationContext ImplCtx(MigrateCtx, D);
329 for (MigrationContext::traverser_iterator
330 I = MigrateCtx.traversers_begin(),
331 E = MigrateCtx.traversers_end(); I != E; ++I)
332 (*I)->traverseObjCImplementation(ImplCtx);
334 return base::TraverseObjCImplementationDecl(D);
337 bool TraverseStmt(Stmt *rootS) {
341 BodyContext BodyCtx(MigrateCtx, rootS);
342 for (MigrationContext::traverser_iterator
343 I = MigrateCtx.traversers_begin(),
344 E = MigrateCtx.traversers_end(); I != E; ++I)
345 (*I)->traverseBody(BodyCtx);
353 MigrationContext::~MigrationContext() {
354 for (traverser_iterator
355 I = traversers_begin(), E = traversers_end(); I != E; ++I)
359 bool MigrationContext::isGCOwnedNonObjC(QualType T) {
360 while (!T.isNull()) {
361 if (const AttributedType *AttrT = T->getAs<AttributedType>()) {
362 if (AttrT->getAttrKind() == AttributedType::attr_objc_ownership)
363 return !AttrT->getModifiedType()->isObjCRetainableType();
366 if (T->isArrayType())
367 T = Pass.Ctx.getBaseElementType(T);
368 else if (const PointerType *PT = T->getAs<PointerType>())
369 T = PT->getPointeeType();
370 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
371 T = RT->getPointeeType();
379 bool MigrationContext::rewritePropertyAttribute(StringRef fromAttr,
381 SourceLocation atLoc) {
382 if (atLoc.isMacroID())
385 SourceManager &SM = Pass.Ctx.getSourceManager();
387 // Break down the source location.
388 std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(atLoc);
390 // Try to load the file buffer.
391 bool invalidTemp = false;
392 StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
396 const char *tokenBegin = file.data() + locInfo.second;
398 // Lex from the start of the given location.
399 Lexer lexer(SM.getLocForStartOfFile(locInfo.first),
400 Pass.Ctx.getLangOpts(),
401 file.begin(), tokenBegin, file.end());
403 lexer.LexFromRawLexer(tok);
404 if (tok.isNot(tok::at)) return false;
405 lexer.LexFromRawLexer(tok);
406 if (tok.isNot(tok::raw_identifier)) return false;
407 if (tok.getRawIdentifier() != "property")
409 lexer.LexFromRawLexer(tok);
410 if (tok.isNot(tok::l_paren)) return false;
412 Token BeforeTok = tok;
414 AfterTok.startToken();
415 SourceLocation AttrLoc;
417 lexer.LexFromRawLexer(tok);
418 if (tok.is(tok::r_paren))
422 if (tok.isNot(tok::raw_identifier)) return false;
423 if (tok.getRawIdentifier() == fromAttr) {
424 if (!toAttr.empty()) {
425 Pass.TA.replaceText(tok.getLocation(), fromAttr, toAttr);
428 // We want to remove the attribute.
429 AttrLoc = tok.getLocation();
433 lexer.LexFromRawLexer(tok);
434 if (AttrLoc.isValid() && AfterTok.is(tok::unknown))
436 } while (tok.isNot(tok::comma) && tok.isNot(tok::r_paren));
437 if (tok.is(tok::r_paren))
439 if (AttrLoc.isInvalid())
441 lexer.LexFromRawLexer(tok);
444 if (toAttr.empty() && AttrLoc.isValid() && AfterTok.isNot(tok::unknown)) {
445 // We want to remove the attribute.
446 if (BeforeTok.is(tok::l_paren) && AfterTok.is(tok::r_paren)) {
447 Pass.TA.remove(SourceRange(BeforeTok.getLocation(),
448 AfterTok.getLocation()));
449 } else if (BeforeTok.is(tok::l_paren) && AfterTok.is(tok::comma)) {
450 Pass.TA.remove(SourceRange(AttrLoc, AfterTok.getLocation()));
452 Pass.TA.remove(SourceRange(BeforeTok.getLocation(), AttrLoc));
461 bool MigrationContext::addPropertyAttribute(StringRef attr,
462 SourceLocation atLoc) {
463 if (atLoc.isMacroID())
466 SourceManager &SM = Pass.Ctx.getSourceManager();
468 // Break down the source location.
469 std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(atLoc);
471 // Try to load the file buffer.
472 bool invalidTemp = false;
473 StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
477 const char *tokenBegin = file.data() + locInfo.second;
479 // Lex from the start of the given location.
480 Lexer lexer(SM.getLocForStartOfFile(locInfo.first),
481 Pass.Ctx.getLangOpts(),
482 file.begin(), tokenBegin, file.end());
484 lexer.LexFromRawLexer(tok);
485 if (tok.isNot(tok::at)) return false;
486 lexer.LexFromRawLexer(tok);
487 if (tok.isNot(tok::raw_identifier)) return false;
488 if (tok.getRawIdentifier() != "property")
490 lexer.LexFromRawLexer(tok);
492 if (tok.isNot(tok::l_paren)) {
493 Pass.TA.insert(tok.getLocation(), std::string("(") + attr.str() + ") ");
497 lexer.LexFromRawLexer(tok);
498 if (tok.is(tok::r_paren)) {
499 Pass.TA.insert(tok.getLocation(), attr);
503 if (tok.isNot(tok::raw_identifier)) return false;
505 Pass.TA.insert(tok.getLocation(), std::string(attr) + ", ");
509 void MigrationContext::traverse(TranslationUnitDecl *TU) {
510 for (traverser_iterator
511 I = traversers_begin(), E = traversers_end(); I != E; ++I)
512 (*I)->traverseTU(*this);
514 ASTTransform(*this).TraverseDecl(TU);
517 static void GCRewriteFinalize(MigrationPass &pass) {
518 ASTContext &Ctx = pass.Ctx;
519 TransformActions &TA = pass.TA;
520 DeclContext *DC = Ctx.getTranslationUnitDecl();
521 Selector FinalizeSel =
522 Ctx.Selectors.getNullarySelector(&pass.Ctx.Idents.get("finalize"));
524 typedef DeclContext::specific_decl_iterator<ObjCImplementationDecl>
526 for (impl_iterator I = impl_iterator(DC->decls_begin()),
527 E = impl_iterator(DC->decls_end()); I != E; ++I) {
528 for (const auto *MD : I->instance_methods()) {
532 if (MD->isInstanceMethod() && MD->getSelector() == FinalizeSel) {
533 const ObjCMethodDecl *FinalizeM = MD;
534 Transaction Trans(TA);
535 TA.insert(FinalizeM->getSourceRange().getBegin(),
536 "#if !__has_feature(objc_arc)\n");
537 CharSourceRange::getTokenRange(FinalizeM->getSourceRange());
538 const SourceManager &SM = pass.Ctx.getSourceManager();
539 const LangOptions &LangOpts = pass.Ctx.getLangOpts();
541 std::string str = "\n#endif\n";
542 str += Lexer::getSourceText(
543 CharSourceRange::getTokenRange(FinalizeM->getSourceRange()),
544 SM, LangOpts, &Invalid);
545 TA.insertAfterToken(FinalizeM->getSourceRange().getEnd(), str);
553 //===----------------------------------------------------------------------===//
554 // getAllTransformations.
555 //===----------------------------------------------------------------------===//
557 static void traverseAST(MigrationPass &pass) {
558 MigrationContext MigrateCtx(pass);
560 if (pass.isGCMigration()) {
561 MigrateCtx.addTraverser(new GCCollectableCallsTraverser);
562 MigrateCtx.addTraverser(new GCAttrsTraverser());
564 MigrateCtx.addTraverser(new PropertyRewriteTraverser());
565 MigrateCtx.addTraverser(new BlockObjCVariableTraverser());
566 MigrateCtx.addTraverser(new ProtectedScopeTraverser());
568 MigrateCtx.traverse(pass.Ctx.getTranslationUnitDecl());
571 static void independentTransforms(MigrationPass &pass) {
572 rewriteAutoreleasePool(pass);
573 removeRetainReleaseDeallocFinalize(pass);
574 rewriteUnusedInitDelegate(pass);
575 removeZeroOutPropsInDeallocFinalize(pass);
576 makeAssignARCSafe(pass);
577 rewriteUnbridgedCasts(pass);
582 std::vector<TransformFn> arcmt::getAllTransformations(
583 LangOptions::GCMode OrigGCMode,
584 bool NoFinalizeRemoval) {
585 std::vector<TransformFn> transforms;
587 if (OrigGCMode == LangOptions::GCOnly && NoFinalizeRemoval)
588 transforms.push_back(GCRewriteFinalize);
589 transforms.push_back(independentTransforms);
590 // This depends on previous transformations removing various expressions.
591 transforms.push_back(removeEmptyStatementsAndDeallocFinalize);