Home | History | Annotate | Line # | Download | only in ARCMigrate
      1 //===--- Transforms.cpp - Transformations to ARC mode ---------------------===//
      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 #include "Transforms.h"
     10 #include "Internals.h"
     11 #include "clang/ARCMigrate/ARCMT.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"
     20 
     21 using namespace clang;
     22 using namespace arcmt;
     23 using namespace trans;
     24 
     25 ASTTraverser::~ASTTraverser() { }
     26 
     27 bool MigrationPass::CFBridgingFunctionsDefined() {
     28   if (!EnableCFBridgeFns.hasValue())
     29     EnableCFBridgeFns = SemaRef.isKnownName("CFBridgingRetain") &&
     30                         SemaRef.isKnownName("CFBridgingRelease");
     31   return *EnableCFBridgeFns;
     32 }
     33 
     34 //===----------------------------------------------------------------------===//
     35 // Helpers.
     36 //===----------------------------------------------------------------------===//
     37 
     38 bool trans::canApplyWeak(ASTContext &Ctx, QualType type,
     39                          bool AllowOnUnknownClass) {
     40   if (!Ctx.getLangOpts().ObjCWeakRuntime)
     41     return false;
     42 
     43   QualType T = type;
     44   if (T.isNull())
     45     return false;
     46 
     47   // iOS is always safe to use 'weak'.
     48   if (Ctx.getTargetInfo().getTriple().isiOS() ||
     49       Ctx.getTargetInfo().getTriple().isWatchOS())
     50     AllowOnUnknownClass = true;
     51 
     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())
     61       return false;
     62   }
     63 
     64   return true;
     65 }
     66 
     67 bool trans::isPlusOneAssign(const BinaryOperator *E) {
     68   if (E->getOpcode() != BO_Assign)
     69     return false;
     70 
     71   return isPlusOne(E->getRHS());
     72 }
     73 
     74 bool trans::isPlusOne(const Expr *E) {
     75   if (!E)
     76     return false;
     77   if (const FullExpr *FE = dyn_cast<FullExpr>(E))
     78     E = FE->getSubExpr();
     79 
     80   if (const ObjCMessageExpr *
     81         ME = dyn_cast<ObjCMessageExpr>(E->IgnoreParenCasts()))
     82     if (ME->getMethodFamily() == OMF_retain)
     83       return true;
     84 
     85   if (const CallExpr *
     86         callE = dyn_cast<CallExpr>(E->IgnoreParenCasts())) {
     87     if (const FunctionDecl *FD = callE->getDirectCallee()) {
     88       if (FD->hasAttr<CFReturnsRetainedAttr>())
     89         return true;
     90 
     91       if (FD->isGlobal() &&
     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) {
    101           return true;
    102         }
    103       }
    104     }
    105   }
    106 
    107   const ImplicitCastExpr *implCE = dyn_cast<ImplicitCastExpr>(E);
    108   while (implCE && implCE->getCastKind() ==  CK_BitCast)
    109     implCE = dyn_cast<ImplicitCastExpr>(implCE->getSubExpr());
    110 
    111   return implCE && implCE->getCastKind() == CK_ARCConsumeObject;
    112 }
    113 
    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);
    124 }
    125 
    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,
    131                                             ASTContext &Ctx,
    132                                             bool IsDecl) {
    133   SourceManager &SM = Ctx.getSourceManager();
    134   if (loc.isMacroID()) {
    135     if (!Lexer::isAtEndOfMacroExpansion(loc, SM, Ctx.getLangOpts(), &loc))
    136       return SourceLocation();
    137   }
    138   loc = Lexer::getLocForEndOfToken(loc, /*Offset=*/0, SM, Ctx.getLangOpts());
    139 
    140   // Break down the source location.
    141   std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(loc);
    142 
    143   // Try to load the file buffer.
    144   bool invalidTemp = false;
    145   StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
    146   if (invalidTemp)
    147     return SourceLocation();
    148 
    149   const char *tokenBegin = file.data() + locInfo.second;
    150 
    151   // Lex from the start of the given location.
    152   Lexer lexer(SM.getLocForStartOfFile(locInfo.first),
    153               Ctx.getLangOpts(),
    154               file.begin(), tokenBegin, file.end());
    155   Token tok;
    156   lexer.LexFromRawLexer(tok);
    157   if (tok.isNot(tok::semi)) {
    158     if (!IsDecl)
    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);
    163   }
    164 
    165   return tok.getLocation();
    166 }
    167 
    168 bool trans::hasSideEffects(Expr *E, ASTContext &Ctx) {
    169   if (!E || !E->HasSideEffects(Ctx))
    170     return false;
    171 
    172   E = E->IgnoreParenCasts();
    173   ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E);
    174   if (!ME)
    175     return true;
    176   switch (ME->getMethodFamily()) {
    177   case OMF_autorelease:
    178   case OMF_dealloc:
    179   case OMF_release:
    180   case OMF_retain:
    181     switch (ME->getReceiverKind()) {
    182     case ObjCMessageExpr::SuperInstance:
    183       return false;
    184     case ObjCMessageExpr::Instance:
    185       return hasSideEffects(ME->getInstanceReceiver(), Ctx);
    186     default:
    187       break;
    188     }
    189     break;
    190   default:
    191     break;
    192   }
    193 
    194   return true;
    195 }
    196 
    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());
    205 
    206   return false;
    207 }
    208 
    209 StringRef trans::getNilString(MigrationPass &Pass) {
    210   return Pass.SemaRef.PP.isMacroDefined("nil") ? "nil" : "0";
    211 }
    212 
    213 namespace {
    214 
    215 class ReferenceClear : public RecursiveASTVisitor<ReferenceClear> {
    216   ExprSet &Refs;
    217 public:
    218   ReferenceClear(ExprSet &refs) : Refs(refs) { }
    219   bool VisitDeclRefExpr(DeclRefExpr *E) { Refs.erase(E); return true; }
    220 };
    221 
    222 class ReferenceCollector : public RecursiveASTVisitor<ReferenceCollector> {
    223   ValueDecl *Dcl;
    224   ExprSet &Refs;
    225 
    226 public:
    227   ReferenceCollector(ValueDecl *D, ExprSet &refs)
    228     : Dcl(D), Refs(refs) { }
    229 
    230   bool VisitDeclRefExpr(DeclRefExpr *E) {
    231     if (E->getDecl() == Dcl)
    232       Refs.insert(E);
    233     return true;
    234   }
    235 };
    236 
    237 class RemovablesCollector : public RecursiveASTVisitor<RemovablesCollector> {
    238   ExprSet &Removables;
    239 
    240 public:
    241   RemovablesCollector(ExprSet &removables)
    242   : Removables(removables) { }
    243 
    244   bool shouldWalkTypesOfTypeLocs() const { return false; }
    245 
    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) {
    250       if (I != E - 1)
    251         mark(*I);
    252       TraverseStmt(*I);
    253     }
    254     return true;
    255   }
    256 
    257   bool VisitCompoundStmt(CompoundStmt *S) {
    258     for (auto *I : S->body())
    259       mark(I);
    260     return true;
    261   }
    262 
    263   bool VisitIfStmt(IfStmt *S) {
    264     mark(S->getThen());
    265     mark(S->getElse());
    266     return true;
    267   }
    268 
    269   bool VisitWhileStmt(WhileStmt *S) {
    270     mark(S->getBody());
    271     return true;
    272   }
    273 
    274   bool VisitDoStmt(DoStmt *S) {
    275     mark(S->getBody());
    276     return true;
    277   }
    278 
    279   bool VisitForStmt(ForStmt *S) {
    280     mark(S->getInit());
    281     mark(S->getInc());
    282     mark(S->getBody());
    283     return true;
    284   }
    285 
    286 private:
    287   void mark(Stmt *S) {
    288     if (!S) return;
    289 
    290     while (auto *Label = dyn_cast<LabelStmt>(S))
    291       S = Label->getSubStmt();
    292     if (auto *E = dyn_cast<Expr>(S))
    293       S = E->IgnoreImplicit();
    294     if (auto *E = dyn_cast<Expr>(S))
    295       Removables.insert(E);
    296   }
    297 };
    298 
    299 } // end anonymous namespace
    300 
    301 void trans::clearRefsIn(Stmt *S, ExprSet &refs) {
    302   ReferenceClear(refs).TraverseStmt(S);
    303 }
    304 
    305 void trans::collectRefs(ValueDecl *D, Stmt *S, ExprSet &refs) {
    306   ReferenceCollector(D, refs).TraverseStmt(S);
    307 }
    308 
    309 void trans::collectRemovables(Stmt *S, ExprSet &exprs) {
    310   RemovablesCollector(exprs).TraverseStmt(S);
    311 }
    312 
    313 //===----------------------------------------------------------------------===//
    314 // MigrationContext
    315 //===----------------------------------------------------------------------===//
    316 
    317 namespace {
    318 
    319 class ASTTransform : public RecursiveASTVisitor<ASTTransform> {
    320   MigrationContext &MigrateCtx;
    321   typedef RecursiveASTVisitor<ASTTransform> base;
    322 
    323 public:
    324   ASTTransform(MigrationContext &MigrateCtx) : MigrateCtx(MigrateCtx) { }
    325 
    326   bool shouldWalkTypesOfTypeLocs() const { return false; }
    327 
    328   bool TraverseObjCImplementationDecl(ObjCImplementationDecl *D) {
    329     ObjCImplementationContext ImplCtx(MigrateCtx, D);
    330     for (MigrationContext::traverser_iterator
    331            I = MigrateCtx.traversers_begin(),
    332            E = MigrateCtx.traversers_end(); I != E; ++I)
    333       (*I)->traverseObjCImplementation(ImplCtx);
    334 
    335     return base::TraverseObjCImplementationDecl(D);
    336   }
    337 
    338   bool TraverseStmt(Stmt *rootS) {
    339     if (!rootS)
    340       return true;
    341 
    342     BodyContext BodyCtx(MigrateCtx, rootS);
    343     for (MigrationContext::traverser_iterator
    344            I = MigrateCtx.traversers_begin(),
    345            E = MigrateCtx.traversers_end(); I != E; ++I)
    346       (*I)->traverseBody(BodyCtx);
    347 
    348     return true;
    349   }
    350 };
    351 
    352 }
    353 
    354 MigrationContext::~MigrationContext() {
    355   for (traverser_iterator
    356          I = traversers_begin(), E = traversers_end(); I != E; ++I)
    357     delete *I;
    358 }
    359 
    360 bool MigrationContext::isGCOwnedNonObjC(QualType T) {
    361   while (!T.isNull()) {
    362     if (const AttributedType *AttrT = T->getAs<AttributedType>()) {
    363       if (AttrT->getAttrKind() == attr::ObjCOwnership)
    364         return !AttrT->getModifiedType()->isObjCRetainableType();
    365     }
    366 
    367     if (T->isArrayType())
    368       T = Pass.Ctx.getBaseElementType(T);
    369     else if (const PointerType *PT = T->getAs<PointerType>())
    370       T = PT->getPointeeType();
    371     else if (const ReferenceType *RT = T->getAs<ReferenceType>())
    372       T = RT->getPointeeType();
    373     else
    374       break;
    375   }
    376 
    377   return false;
    378 }
    379 
    380 bool MigrationContext::rewritePropertyAttribute(StringRef fromAttr,
    381                                                 StringRef toAttr,
    382                                                 SourceLocation atLoc) {
    383   if (atLoc.isMacroID())
    384     return false;
    385 
    386   SourceManager &SM = Pass.Ctx.getSourceManager();
    387 
    388   // Break down the source location.
    389   std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(atLoc);
    390 
    391   // Try to load the file buffer.
    392   bool invalidTemp = false;
    393   StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
    394   if (invalidTemp)
    395     return false;
    396 
    397   const char *tokenBegin = file.data() + locInfo.second;
    398 
    399   // Lex from the start of the given location.
    400   Lexer lexer(SM.getLocForStartOfFile(locInfo.first),
    401               Pass.Ctx.getLangOpts(),
    402               file.begin(), tokenBegin, file.end());
    403   Token tok;
    404   lexer.LexFromRawLexer(tok);
    405   if (tok.isNot(tok::at)) return false;
    406   lexer.LexFromRawLexer(tok);
    407   if (tok.isNot(tok::raw_identifier)) return false;
    408   if (tok.getRawIdentifier() != "property")
    409     return false;
    410   lexer.LexFromRawLexer(tok);
    411   if (tok.isNot(tok::l_paren)) return false;
    412 
    413   Token BeforeTok = tok;
    414   Token AfterTok;
    415   AfterTok.startToken();
    416   SourceLocation AttrLoc;
    417 
    418   lexer.LexFromRawLexer(tok);
    419   if (tok.is(tok::r_paren))
    420     return false;
    421 
    422   while (1) {
    423     if (tok.isNot(tok::raw_identifier)) return false;
    424     if (tok.getRawIdentifier() == fromAttr) {
    425       if (!toAttr.empty()) {
    426         Pass.TA.replaceText(tok.getLocation(), fromAttr, toAttr);
    427         return true;
    428       }
    429       // We want to remove the attribute.
    430       AttrLoc = tok.getLocation();
    431     }
    432 
    433     do {
    434       lexer.LexFromRawLexer(tok);
    435       if (AttrLoc.isValid() && AfterTok.is(tok::unknown))
    436         AfterTok = tok;
    437     } while (tok.isNot(tok::comma) && tok.isNot(tok::r_paren));
    438     if (tok.is(tok::r_paren))
    439       break;
    440     if (AttrLoc.isInvalid())
    441       BeforeTok = tok;
    442     lexer.LexFromRawLexer(tok);
    443   }
    444 
    445   if (toAttr.empty() && AttrLoc.isValid() && AfterTok.isNot(tok::unknown)) {
    446     // We want to remove the attribute.
    447     if (BeforeTok.is(tok::l_paren) && AfterTok.is(tok::r_paren)) {
    448       Pass.TA.remove(SourceRange(BeforeTok.getLocation(),
    449                                  AfterTok.getLocation()));
    450     } else if (BeforeTok.is(tok::l_paren) && AfterTok.is(tok::comma)) {
    451       Pass.TA.remove(SourceRange(AttrLoc, AfterTok.getLocation()));
    452     } else {
    453       Pass.TA.remove(SourceRange(BeforeTok.getLocation(), AttrLoc));
    454     }
    455 
    456     return true;
    457   }
    458 
    459   return false;
    460 }
    461 
    462 bool MigrationContext::addPropertyAttribute(StringRef attr,
    463                                             SourceLocation atLoc) {
    464   if (atLoc.isMacroID())
    465     return false;
    466 
    467   SourceManager &SM = Pass.Ctx.getSourceManager();
    468 
    469   // Break down the source location.
    470   std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(atLoc);
    471 
    472   // Try to load the file buffer.
    473   bool invalidTemp = false;
    474   StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
    475   if (invalidTemp)
    476     return false;
    477 
    478   const char *tokenBegin = file.data() + locInfo.second;
    479 
    480   // Lex from the start of the given location.
    481   Lexer lexer(SM.getLocForStartOfFile(locInfo.first),
    482               Pass.Ctx.getLangOpts(),
    483               file.begin(), tokenBegin, file.end());
    484   Token tok;
    485   lexer.LexFromRawLexer(tok);
    486   if (tok.isNot(tok::at)) return false;
    487   lexer.LexFromRawLexer(tok);
    488   if (tok.isNot(tok::raw_identifier)) return false;
    489   if (tok.getRawIdentifier() != "property")
    490     return false;
    491   lexer.LexFromRawLexer(tok);
    492 
    493   if (tok.isNot(tok::l_paren)) {
    494     Pass.TA.insert(tok.getLocation(), std::string("(") + attr.str() + ") ");
    495     return true;
    496   }
    497 
    498   lexer.LexFromRawLexer(tok);
    499   if (tok.is(tok::r_paren)) {
    500     Pass.TA.insert(tok.getLocation(), attr);
    501     return true;
    502   }
    503 
    504   if (tok.isNot(tok::raw_identifier)) return false;
    505 
    506   Pass.TA.insert(tok.getLocation(), std::string(attr) + ", ");
    507   return true;
    508 }
    509 
    510 void MigrationContext::traverse(TranslationUnitDecl *TU) {
    511   for (traverser_iterator
    512          I = traversers_begin(), E = traversers_end(); I != E; ++I)
    513     (*I)->traverseTU(*this);
    514 
    515   ASTTransform(*this).TraverseDecl(TU);
    516 }
    517 
    518 static void GCRewriteFinalize(MigrationPass &pass) {
    519   ASTContext &Ctx = pass.Ctx;
    520   TransformActions &TA = pass.TA;
    521   DeclContext *DC = Ctx.getTranslationUnitDecl();
    522   Selector FinalizeSel =
    523    Ctx.Selectors.getNullarySelector(&pass.Ctx.Idents.get("finalize"));
    524 
    525   typedef DeclContext::specific_decl_iterator<ObjCImplementationDecl>
    526   impl_iterator;
    527   for (impl_iterator I = impl_iterator(DC->decls_begin()),
    528        E = impl_iterator(DC->decls_end()); I != E; ++I) {
    529     for (const auto *MD : I->instance_methods()) {
    530       if (!MD->hasBody())
    531         continue;
    532 
    533       if (MD->isInstanceMethod() && MD->getSelector() == FinalizeSel) {
    534         const ObjCMethodDecl *FinalizeM = MD;
    535         Transaction Trans(TA);
    536         TA.insert(FinalizeM->getSourceRange().getBegin(),
    537                   "#if !__has_feature(objc_arc)\n");
    538         CharSourceRange::getTokenRange(FinalizeM->getSourceRange());
    539         const SourceManager &SM = pass.Ctx.getSourceManager();
    540         const LangOptions &LangOpts = pass.Ctx.getLangOpts();
    541         bool Invalid;
    542         std::string str = "\n#endif\n";
    543         str += Lexer::getSourceText(
    544                   CharSourceRange::getTokenRange(FinalizeM->getSourceRange()),
    545                                     SM, LangOpts, &Invalid);
    546         TA.insertAfterToken(FinalizeM->getSourceRange().getEnd(), str);
    547 
    548         break;
    549       }
    550     }
    551   }
    552 }
    553 
    554 //===----------------------------------------------------------------------===//
    555 // getAllTransformations.
    556 //===----------------------------------------------------------------------===//
    557 
    558 static void traverseAST(MigrationPass &pass) {
    559   MigrationContext MigrateCtx(pass);
    560 
    561   if (pass.isGCMigration()) {
    562     MigrateCtx.addTraverser(new GCCollectableCallsTraverser);
    563     MigrateCtx.addTraverser(new GCAttrsTraverser());
    564   }
    565   MigrateCtx.addTraverser(new PropertyRewriteTraverser());
    566   MigrateCtx.addTraverser(new BlockObjCVariableTraverser());
    567   MigrateCtx.addTraverser(new ProtectedScopeTraverser());
    568 
    569   MigrateCtx.traverse(pass.Ctx.getTranslationUnitDecl());
    570 }
    571 
    572 static void independentTransforms(MigrationPass &pass) {
    573   rewriteAutoreleasePool(pass);
    574   removeRetainReleaseDeallocFinalize(pass);
    575   rewriteUnusedInitDelegate(pass);
    576   removeZeroOutPropsInDeallocFinalize(pass);
    577   makeAssignARCSafe(pass);
    578   rewriteUnbridgedCasts(pass);
    579   checkAPIUses(pass);
    580   traverseAST(pass);
    581 }
    582 
    583 std::vector<TransformFn> arcmt::getAllTransformations(
    584                                                LangOptions::GCMode OrigGCMode,
    585                                                bool NoFinalizeRemoval) {
    586   std::vector<TransformFn> transforms;
    587 
    588   if (OrigGCMode ==  LangOptions::GCOnly && NoFinalizeRemoval)
    589     transforms.push_back(GCRewriteFinalize);
    590   transforms.push_back(independentTransforms);
    591   // This depends on previous transformations removing various expressions.
    592   transforms.push_back(removeEmptyStatementsAndDeallocFinalize);
    593 
    594   return transforms;
    595 }
    596