ARCMT.cpp revision c2e70b46b686c8debb3020891a5593f298b053ae
1//===--- ARCMT.cpp - Migration 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 "Internals.h" 11#include "clang/Frontend/ASTUnit.h" 12#include "clang/Frontend/CompilerInstance.h" 13#include "clang/Frontend/Utils.h" 14#include "clang/AST/ASTConsumer.h" 15#include "clang/Rewrite/Rewriter.h" 16#include "clang/Sema/SemaDiagnostic.h" 17#include "clang/Basic/DiagnosticCategories.h" 18#include "clang/Lex/Preprocessor.h" 19#include "llvm/Support/MemoryBuffer.h" 20#include "llvm/ADT/Triple.h" 21 22using namespace clang; 23using namespace arcmt; 24using llvm::StringRef; 25 26bool CapturedDiagList::clearDiagnostic(llvm::ArrayRef<unsigned> IDs, 27 SourceRange range) { 28 if (range.isInvalid()) 29 return false; 30 31 bool cleared = false; 32 ListTy::iterator I = List.begin(); 33 while (I != List.end()) { 34 FullSourceLoc diagLoc = I->getLocation(); 35 if ((IDs.empty() || // empty means clear all diagnostics in the range. 36 std::find(IDs.begin(), IDs.end(), I->getID()) != IDs.end()) && 37 !diagLoc.isBeforeInTranslationUnitThan(range.getBegin()) && 38 (diagLoc == range.getEnd() || 39 diagLoc.isBeforeInTranslationUnitThan(range.getEnd()))) { 40 cleared = true; 41 ListTy::iterator eraseS = I++; 42 while (I != List.end() && I->getLevel() == Diagnostic::Note) 43 ++I; 44 // Clear the diagnostic and any notes following it. 45 List.erase(eraseS, I); 46 continue; 47 } 48 49 ++I; 50 } 51 52 return cleared; 53} 54 55bool CapturedDiagList::hasDiagnostic(llvm::ArrayRef<unsigned> IDs, 56 SourceRange range) { 57 if (range.isInvalid()) 58 return false; 59 60 ListTy::iterator I = List.begin(); 61 while (I != List.end()) { 62 FullSourceLoc diagLoc = I->getLocation(); 63 if ((IDs.empty() || // empty means any diagnostic in the range. 64 std::find(IDs.begin(), IDs.end(), I->getID()) != IDs.end()) && 65 !diagLoc.isBeforeInTranslationUnitThan(range.getBegin()) && 66 (diagLoc == range.getEnd() || 67 diagLoc.isBeforeInTranslationUnitThan(range.getEnd()))) { 68 return true; 69 } 70 71 ++I; 72 } 73 74 return false; 75} 76 77void CapturedDiagList::reportDiagnostics(Diagnostic &Diags) { 78 for (ListTy::iterator I = List.begin(), E = List.end(); I != E; ++I) 79 Diags.Report(*I); 80} 81 82namespace { 83 84class CaptureDiagnosticClient : public DiagnosticClient { 85 Diagnostic &Diags; 86 CapturedDiagList &CapturedDiags; 87public: 88 CaptureDiagnosticClient(Diagnostic &diags, 89 CapturedDiagList &capturedDiags) 90 : Diags(diags), CapturedDiags(capturedDiags) { } 91 92 virtual void HandleDiagnostic(Diagnostic::Level level, 93 const DiagnosticInfo &Info) { 94 if (arcmt::isARCDiagnostic(Info.getID(), Diags) || 95 level >= Diagnostic::Error || level == Diagnostic::Note) { 96 CapturedDiags.push_back(StoredDiagnostic(level, Info)); 97 return; 98 } 99 100 // Non-ARC warnings are ignored. 101 Diags.setLastDiagnosticIgnored(); 102 } 103}; 104 105} // end anonymous namespace 106 107CompilerInvocation *createInvocationForMigration(CompilerInvocation &origCI) { 108 llvm::OwningPtr<CompilerInvocation> CInvok; 109 CInvok.reset(new CompilerInvocation(origCI)); 110 CInvok->getPreprocessorOpts().ImplicitPCHInclude = std::string(); 111 CInvok->getPreprocessorOpts().ImplicitPTHInclude = std::string(); 112 std::string define = getARCMTMacroName(); 113 define += '='; 114 CInvok->getPreprocessorOpts().addMacroDef(define); 115 CInvok->getLangOpts().ObjCAutoRefCount = true; 116 CInvok->getDiagnosticOpts().ErrorLimit = 0; 117 118 // FIXME: Hackety hack! Try to find out if there is an ARC runtime. 119 bool hasARCRuntime = false; 120 llvm::SmallVector<std::string, 16> args; 121 args.push_back("-x"); 122 args.push_back("objective-c"); 123 args.push_back("-fobjc-arc"); 124 125 llvm::Triple triple(CInvok->getTargetOpts().Triple); 126 if (triple.getOS() == llvm::Triple::IOS || 127 triple.getOS() == llvm::Triple::MacOSX) { 128 args.push_back("-ccc-host-triple"); 129 std::string forcedTriple = triple.getArchName(); 130 forcedTriple += "-apple-darwin10"; 131 args.push_back(forcedTriple); 132 133 unsigned Major, Minor, Micro; 134 triple.getOSVersion(Major, Minor, Micro); 135 llvm::SmallString<100> flag; 136 if (triple.getOS() == llvm::Triple::IOS) 137 flag += "-miphoneos-version-min="; 138 else 139 flag += "-mmacosx-version-min="; 140 llvm::raw_svector_ostream(flag) << Major << '.' << Minor << '.' << Micro; 141 args.push_back(flag.str()); 142 } 143 144 args.push_back(origCI.getFrontendOpts().Inputs[0].second.c_str()); 145 // Also push all defines to deal with the iOS simulator hack. 146 for (unsigned i = 0, e = origCI.getPreprocessorOpts().Macros.size(); 147 i != e; ++i) { 148 std::string &def = origCI.getPreprocessorOpts().Macros[i].first; 149 bool isUndef = origCI.getPreprocessorOpts().Macros[i].second; 150 if (!isUndef) { 151 std::string newdef = "-D"; 152 newdef += def; 153 args.push_back(newdef); 154 } 155 } 156 157 llvm::SmallVector<const char *, 16> cargs; 158 for (unsigned i = 0, e = args.size(); i != e; ++i) 159 cargs.push_back(args[i].c_str()); 160 161 llvm::OwningPtr<CompilerInvocation> checkCI; 162 checkCI.reset(clang::createInvocationFromCommandLine(cargs)); 163 if (checkCI) 164 hasARCRuntime = !checkCI->getLangOpts().ObjCNoAutoRefCountRuntime; 165 166 CInvok->getLangOpts().ObjCNoAutoRefCountRuntime = !hasARCRuntime; 167 168 return CInvok.take(); 169} 170 171//===----------------------------------------------------------------------===// 172// checkForManualIssues. 173//===----------------------------------------------------------------------===// 174 175bool arcmt::checkForManualIssues(CompilerInvocation &origCI, 176 llvm::StringRef Filename, InputKind Kind, 177 DiagnosticClient *DiagClient) { 178 if (!origCI.getLangOpts().ObjC1) 179 return false; 180 181 std::vector<TransformFn> transforms = arcmt::getAllTransformations(); 182 assert(!transforms.empty()); 183 184 llvm::OwningPtr<CompilerInvocation> CInvok; 185 CInvok.reset(createInvocationForMigration(origCI)); 186 CInvok->getFrontendOpts().Inputs.clear(); 187 CInvok->getFrontendOpts().Inputs.push_back(std::make_pair(Kind, Filename)); 188 189 CapturedDiagList capturedDiags; 190 191 assert(DiagClient); 192 llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs()); 193 llvm::IntrusiveRefCntPtr<Diagnostic> Diags( 194 new Diagnostic(DiagID, DiagClient, /*ShouldOwnClient=*/false)); 195 196 // Filter of all diagnostics. 197 CaptureDiagnosticClient errRec(*Diags, capturedDiags); 198 Diags->setClient(&errRec, /*ShouldOwnClient=*/false); 199 200 llvm::OwningPtr<ASTUnit> Unit( 201 ASTUnit::LoadFromCompilerInvocationAction(CInvok.take(), Diags)); 202 if (!Unit) 203 return true; 204 205 // Don't filter diagnostics anymore. 206 Diags->setClient(DiagClient, /*ShouldOwnClient=*/false); 207 208 ASTContext &Ctx = Unit->getASTContext(); 209 210 if (Diags->hasFatalErrorOccurred()) { 211 Diags->Reset(); 212 DiagClient->BeginSourceFile(Ctx.getLangOptions(), &Unit->getPreprocessor()); 213 capturedDiags.reportDiagnostics(*Diags); 214 DiagClient->EndSourceFile(); 215 return true; 216 } 217 218 // After parsing of source files ended, we want to reuse the 219 // diagnostics objects to emit further diagnostics. 220 // We call BeginSourceFile because DiagnosticClient requires that 221 // diagnostics with source range information are emitted only in between 222 // BeginSourceFile() and EndSourceFile(). 223 DiagClient->BeginSourceFile(Ctx.getLangOptions(), &Unit->getPreprocessor()); 224 225 // No macros will be added since we are just checking and we won't modify 226 // source code. 227 std::vector<SourceLocation> ARCMTMacroLocs; 228 229 TransformActions testAct(*Diags, capturedDiags, Ctx, Unit->getPreprocessor()); 230 MigrationPass pass(Ctx, Unit->getSema(), testAct, ARCMTMacroLocs); 231 232 for (unsigned i=0, e = transforms.size(); i != e; ++i) 233 transforms[i](pass); 234 235 capturedDiags.reportDiagnostics(*Diags); 236 237 DiagClient->EndSourceFile(); 238 239 return Diags->getClient()->getNumErrors() > 0; 240} 241 242//===----------------------------------------------------------------------===// 243// applyTransformations. 244//===----------------------------------------------------------------------===// 245 246bool arcmt::applyTransformations(CompilerInvocation &origCI, 247 llvm::StringRef Filename, InputKind Kind, 248 DiagnosticClient *DiagClient) { 249 if (!origCI.getLangOpts().ObjC1) 250 return false; 251 252 // Make sure checking is successful first. 253 CompilerInvocation CInvokForCheck(origCI); 254 if (arcmt::checkForManualIssues(CInvokForCheck, Filename, Kind, DiagClient)) 255 return true; 256 257 CompilerInvocation CInvok(origCI); 258 CInvok.getFrontendOpts().Inputs.clear(); 259 CInvok.getFrontendOpts().Inputs.push_back(std::make_pair(Kind, Filename)); 260 261 MigrationProcess migration(CInvok, DiagClient); 262 263 std::vector<TransformFn> transforms = arcmt::getAllTransformations(); 264 assert(!transforms.empty()); 265 266 for (unsigned i=0, e = transforms.size(); i != e; ++i) { 267 bool err = migration.applyTransform(transforms[i]); 268 if (err) return true; 269 } 270 271 origCI.getLangOpts().ObjCAutoRefCount = true; 272 273 llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs()); 274 llvm::IntrusiveRefCntPtr<Diagnostic> Diags( 275 new Diagnostic(DiagID, DiagClient, /*ShouldOwnClient=*/false)); 276 return migration.getRemapper().overwriteOriginal(*Diags); 277} 278 279//===----------------------------------------------------------------------===// 280// CollectTransformActions. 281//===----------------------------------------------------------------------===// 282 283namespace { 284 285class ARCMTMacroTrackerPPCallbacks : public PPCallbacks { 286 std::vector<SourceLocation> &ARCMTMacroLocs; 287 288public: 289 ARCMTMacroTrackerPPCallbacks(std::vector<SourceLocation> &ARCMTMacroLocs) 290 : ARCMTMacroLocs(ARCMTMacroLocs) { } 291 292 virtual void MacroExpands(const Token &MacroNameTok, const MacroInfo *MI) { 293 if (MacroNameTok.getIdentifierInfo()->getName() == getARCMTMacroName()) 294 ARCMTMacroLocs.push_back(MacroNameTok.getLocation()); 295 } 296}; 297 298class ARCMTMacroTrackerAction : public ASTFrontendAction { 299 std::vector<SourceLocation> &ARCMTMacroLocs; 300 301public: 302 ARCMTMacroTrackerAction(std::vector<SourceLocation> &ARCMTMacroLocs) 303 : ARCMTMacroLocs(ARCMTMacroLocs) { } 304 305 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI, 306 llvm::StringRef InFile) { 307 CI.getPreprocessor().addPPCallbacks( 308 new ARCMTMacroTrackerPPCallbacks(ARCMTMacroLocs)); 309 return new ASTConsumer(); 310 } 311}; 312 313class RewritesApplicator : public TransformActions::RewriteReceiver { 314 Rewriter &rewriter; 315 ASTContext &Ctx; 316 MigrationProcess::RewriteListener *Listener; 317 318public: 319 RewritesApplicator(Rewriter &rewriter, ASTContext &ctx, 320 MigrationProcess::RewriteListener *listener) 321 : rewriter(rewriter), Ctx(ctx), Listener(listener) { 322 if (Listener) 323 Listener->start(ctx); 324 } 325 ~RewritesApplicator() { 326 if (Listener) 327 Listener->finish(); 328 } 329 330 virtual void insert(SourceLocation loc, llvm::StringRef text) { 331 bool err = rewriter.InsertText(loc, text, /*InsertAfter=*/true, 332 /*indentNewLines=*/true); 333 if (!err && Listener) 334 Listener->insert(loc, text); 335 } 336 337 virtual void remove(CharSourceRange range) { 338 Rewriter::RewriteOptions removeOpts; 339 removeOpts.IncludeInsertsAtBeginOfRange = false; 340 removeOpts.IncludeInsertsAtEndOfRange = false; 341 removeOpts.RemoveLineIfEmpty = true; 342 343 bool err = rewriter.RemoveText(range, removeOpts); 344 if (!err && Listener) 345 Listener->remove(range); 346 } 347 348 virtual void increaseIndentation(CharSourceRange range, 349 SourceLocation parentIndent) { 350 rewriter.IncreaseIndentation(range, parentIndent); 351 } 352}; 353 354} // end anonymous namespace. 355 356/// \brief Anchor for VTable. 357MigrationProcess::RewriteListener::~RewriteListener() { } 358 359bool MigrationProcess::applyTransform(TransformFn trans, 360 RewriteListener *listener) { 361 llvm::OwningPtr<CompilerInvocation> CInvok; 362 CInvok.reset(createInvocationForMigration(OrigCI)); 363 CInvok->getDiagnosticOpts().IgnoreWarnings = true; 364 365 Remapper.applyMappings(*CInvok); 366 367 CapturedDiagList capturedDiags; 368 std::vector<SourceLocation> ARCMTMacroLocs; 369 370 assert(DiagClient); 371 llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs()); 372 llvm::IntrusiveRefCntPtr<Diagnostic> Diags( 373 new Diagnostic(DiagID, DiagClient, /*ShouldOwnClient=*/false)); 374 375 // Filter of all diagnostics. 376 CaptureDiagnosticClient errRec(*Diags, capturedDiags); 377 Diags->setClient(&errRec, /*ShouldOwnClient=*/false); 378 379 llvm::OwningPtr<ARCMTMacroTrackerAction> ASTAction; 380 ASTAction.reset(new ARCMTMacroTrackerAction(ARCMTMacroLocs)); 381 382 llvm::OwningPtr<ASTUnit> Unit( 383 ASTUnit::LoadFromCompilerInvocationAction(CInvok.take(), Diags, 384 ASTAction.get())); 385 if (!Unit) 386 return true; 387 Unit->setOwnsRemappedFileBuffers(false); // FileRemapper manages that. 388 389 // Don't filter diagnostics anymore. 390 Diags->setClient(DiagClient, /*ShouldOwnClient=*/false); 391 392 ASTContext &Ctx = Unit->getASTContext(); 393 394 if (Diags->hasFatalErrorOccurred()) { 395 Diags->Reset(); 396 DiagClient->BeginSourceFile(Ctx.getLangOptions(), &Unit->getPreprocessor()); 397 capturedDiags.reportDiagnostics(*Diags); 398 DiagClient->EndSourceFile(); 399 return true; 400 } 401 402 // After parsing of source files ended, we want to reuse the 403 // diagnostics objects to emit further diagnostics. 404 // We call BeginSourceFile because DiagnosticClient requires that 405 // diagnostics with source range information are emitted only in between 406 // BeginSourceFile() and EndSourceFile(). 407 DiagClient->BeginSourceFile(Ctx.getLangOptions(), &Unit->getPreprocessor()); 408 409 Rewriter rewriter(Ctx.getSourceManager(), Ctx.getLangOptions()); 410 TransformActions TA(*Diags, capturedDiags, Ctx, Unit->getPreprocessor()); 411 MigrationPass pass(Ctx, Unit->getSema(), TA, ARCMTMacroLocs); 412 413 trans(pass); 414 415 { 416 RewritesApplicator applicator(rewriter, Ctx, listener); 417 TA.applyRewrites(applicator); 418 } 419 420 DiagClient->EndSourceFile(); 421 422 if (DiagClient->getNumErrors()) 423 return true; 424 425 for (Rewriter::buffer_iterator 426 I = rewriter.buffer_begin(), E = rewriter.buffer_end(); I != E; ++I) { 427 FileID FID = I->first; 428 RewriteBuffer &buf = I->second; 429 const FileEntry *file = Ctx.getSourceManager().getFileEntryForID(FID); 430 assert(file); 431 std::string newFname = file->getName(); 432 newFname += "-trans"; 433 llvm::SmallString<512> newText; 434 llvm::raw_svector_ostream vecOS(newText); 435 buf.write(vecOS); 436 vecOS.flush(); 437 llvm::MemoryBuffer *memBuf = llvm::MemoryBuffer::getMemBufferCopy( 438 llvm::StringRef(newText.data(), newText.size()), newFname); 439 llvm::SmallString<64> filePath(file->getName()); 440 Unit->getFileManager().FixupRelativePath(filePath); 441 Remapper.remap(filePath.str(), memBuf); 442 } 443 444 return false; 445} 446 447//===----------------------------------------------------------------------===// 448// isARCDiagnostic. 449//===----------------------------------------------------------------------===// 450 451bool arcmt::isARCDiagnostic(unsigned diagID, Diagnostic &Diag) { 452 return Diag.getDiagnosticIDs()->getCategoryNumberForDiag(diagID) == 453 diag::DiagCat_Automatic_Reference_Counting_Issue; 454} 455