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