1 //===--- Tranforms.cpp - Tranformations 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/Sema/SemaDiagnostic.h"
13 #include "clang/AST/RecursiveASTVisitor.h"
14 #include "clang/AST/StmtVisitor.h"
15 #include "clang/AST/ParentMap.h"
16 #include "clang/Analysis/DomainSpecific/CocoaConventions.h"
17 #include "clang/Lex/Lexer.h"
18 #include "clang/Basic/SourceManager.h"
19 #include "llvm/ADT/StringSwitch.h"
20 #include "llvm/ADT/DenseSet.h"
23 using namespace clang;
24 using namespace arcmt;
25 using namespace trans;
27 //===----------------------------------------------------------------------===//
29 //===----------------------------------------------------------------------===//
31 /// \brief True if the class is one that does not support weak.
32 static bool isClassInWeakBlacklist(ObjCInterfaceDecl *cls) {
36 bool inList = llvm::StringSwitch<bool>(cls->getName())
37 .Case("NSColorSpace", true)
39 .Case("NSFontPanel", true)
40 .Case("NSImage", true)
41 .Case("NSLazyBrowserCell", true)
42 .Case("NSWindow", true)
43 .Case("NSWindowController", true)
44 .Case("NSMenuView", true)
45 .Case("NSPersistentUIWindowInfo", true)
46 .Case("NSTableCellView", true)
47 .Case("NSATSTypeSetter", true)
48 .Case("NSATSGlyphStorage", true)
49 .Case("NSLineFragmentRenderingContext", true)
50 .Case("NSAttributeDictionary", true)
51 .Case("NSParagraphStyle", true)
52 .Case("NSTextTab", true)
53 .Case("NSSimpleHorizontalTypesetter", true)
54 .Case("_NSCachedAttributedString", true)
55 .Case("NSStringDrawingTextStorage", true)
56 .Case("NSTextView", true)
57 .Case("NSSubTextStorage", true)
63 return isClassInWeakBlacklist(cls->getSuperClass());
66 bool trans::canApplyWeak(ASTContext &Ctx, QualType type) {
67 if (!Ctx.getLangOptions().ObjCRuntimeHasWeak)
71 while (const PointerType *ptr = T->getAs<PointerType>())
72 T = ptr->getPointeeType();
73 if (const ObjCObjectPointerType *ObjT = T->getAs<ObjCObjectPointerType>()) {
74 ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl();
75 if (!Class || Class->getName() == "NSObject")
76 return false; // id/NSObject is not safe for weak.
77 if (Class->isForwardDecl())
78 return false; // forward classes are not verifiable, therefore not safe.
79 if (Class->isArcWeakrefUnavailable())
81 if (isClassInWeakBlacklist(Class))
88 /// \brief 'Loc' is the end of a statement range. This returns the location
89 /// immediately after the semicolon following the statement.
90 /// If no semicolon is found or the location is inside a macro, the returned
91 /// source location will be invalid.
92 SourceLocation trans::findLocationAfterSemi(SourceLocation loc,
94 SourceLocation SemiLoc = findSemiAfterLocation(loc, Ctx);
95 if (SemiLoc.isInvalid())
96 return SourceLocation();
97 return SemiLoc.getLocWithOffset(1);
100 /// \brief \arg Loc is the end of a statement range. This returns the location
101 /// of the semicolon following the statement.
102 /// If no semicolon is found or the location is inside a macro, the returned
103 /// source location will be invalid.
104 SourceLocation trans::findSemiAfterLocation(SourceLocation loc,
106 SourceManager &SM = Ctx.getSourceManager();
107 if (loc.isMacroID()) {
108 if (!Lexer::isAtEndOfMacroExpansion(loc, SM, Ctx.getLangOptions()))
109 return SourceLocation();
110 loc = SM.getExpansionRange(loc).second;
112 loc = Lexer::getLocForEndOfToken(loc, /*Offset=*/0, SM, Ctx.getLangOptions());
114 // Break down the source location.
115 std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(loc);
117 // Try to load the file buffer.
118 bool invalidTemp = false;
119 StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
121 return SourceLocation();
123 const char *tokenBegin = file.data() + locInfo.second;
125 // Lex from the start of the given location.
126 Lexer lexer(SM.getLocForStartOfFile(locInfo.first),
127 Ctx.getLangOptions(),
128 file.begin(), tokenBegin, file.end());
130 lexer.LexFromRawLexer(tok);
131 if (tok.isNot(tok::semi))
132 return SourceLocation();
134 return tok.getLocation();
137 bool trans::hasSideEffects(Expr *E, ASTContext &Ctx) {
138 if (!E || !E->HasSideEffects(Ctx))
141 E = E->IgnoreParenCasts();
142 ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E);
145 switch (ME->getMethodFamily()) {
146 case OMF_autorelease:
150 switch (ME->getReceiverKind()) {
151 case ObjCMessageExpr::SuperInstance:
153 case ObjCMessageExpr::Instance:
154 return hasSideEffects(ME->getInstanceReceiver(), Ctx);
166 bool trans::isGlobalVar(Expr *E) {
167 E = E->IgnoreParenCasts();
168 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
169 return DRE->getDecl()->getDeclContext()->isFileContext() &&
170 DRE->getDecl()->getLinkage() == ExternalLinkage;
171 if (ConditionalOperator *condOp = dyn_cast<ConditionalOperator>(E))
172 return isGlobalVar(condOp->getTrueExpr()) &&
173 isGlobalVar(condOp->getFalseExpr());
178 StringRef trans::getNilString(ASTContext &Ctx) {
179 if (Ctx.Idents.get("nil").hasMacroDefinition())
187 class ReferenceClear : public RecursiveASTVisitor<ReferenceClear> {
190 ReferenceClear(ExprSet &refs) : Refs(refs) { }
191 bool VisitDeclRefExpr(DeclRefExpr *E) { Refs.erase(E); return true; }
192 bool VisitBlockDeclRefExpr(BlockDeclRefExpr *E) { Refs.erase(E); return true; }
195 class ReferenceCollector : public RecursiveASTVisitor<ReferenceCollector> {
200 ReferenceCollector(ValueDecl *D, ExprSet &refs)
201 : Dcl(D), Refs(refs) { }
203 bool VisitDeclRefExpr(DeclRefExpr *E) {
204 if (E->getDecl() == Dcl)
209 bool VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
210 if (E->getDecl() == Dcl)
216 class RemovablesCollector : public RecursiveASTVisitor<RemovablesCollector> {
220 RemovablesCollector(ExprSet &removables)
221 : Removables(removables) { }
223 bool shouldWalkTypesOfTypeLocs() const { return false; }
225 bool TraverseStmtExpr(StmtExpr *E) {
226 CompoundStmt *S = E->getSubStmt();
227 for (CompoundStmt::body_iterator
228 I = S->body_begin(), E = S->body_end(); I != E; ++I) {
236 bool VisitCompoundStmt(CompoundStmt *S) {
237 for (CompoundStmt::body_iterator
238 I = S->body_begin(), E = S->body_end(); I != E; ++I)
243 bool VisitIfStmt(IfStmt *S) {
249 bool VisitWhileStmt(WhileStmt *S) {
254 bool VisitDoStmt(DoStmt *S) {
259 bool VisitForStmt(ForStmt *S) {
270 while (LabelStmt *Label = dyn_cast<LabelStmt>(S))
271 S = Label->getSubStmt();
272 S = S->IgnoreImplicit();
273 if (Expr *E = dyn_cast<Expr>(S))
274 Removables.insert(E);
278 } // end anonymous namespace
280 void trans::clearRefsIn(Stmt *S, ExprSet &refs) {
281 ReferenceClear(refs).TraverseStmt(S);
284 void trans::collectRefs(ValueDecl *D, Stmt *S, ExprSet &refs) {
285 ReferenceCollector(D, refs).TraverseStmt(S);
288 void trans::collectRemovables(Stmt *S, ExprSet &exprs) {
289 RemovablesCollector(exprs).TraverseStmt(S);
292 //===----------------------------------------------------------------------===//
293 // getAllTransformations.
294 //===----------------------------------------------------------------------===//
296 static void independentTransforms(MigrationPass &pass) {
297 rewriteAutoreleasePool(pass);
298 rewriteProperties(pass);
299 removeRetainReleaseDealloc(pass);
300 rewriteUnusedInitDelegate(pass);
301 removeZeroOutPropsInDealloc(pass);
302 makeAssignARCSafe(pass);
303 rewriteUnbridgedCasts(pass);
304 rewriteBlockObjCVariable(pass);
308 std::vector<TransformFn> arcmt::getAllTransformations() {
309 std::vector<TransformFn> transforms;
311 transforms.push_back(independentTransforms);
312 // This depends on previous transformations removing various expressions.
313 transforms.push_back(removeEmptyStatementsAndDealloc);