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