Home | History | Annotate | Download | only in ARCMigrate
      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/AST/ASTConsumer.h"
     12 #include "clang/Basic/DiagnosticCategories.h"
     13 #include "clang/Frontend/ASTUnit.h"
     14 #include "clang/Frontend/CompilerInstance.h"
     15 #include "clang/Frontend/FrontendAction.h"
     16 #include "clang/Frontend/TextDiagnosticPrinter.h"
     17 #include "clang/Frontend/Utils.h"
     18 #include "clang/Lex/Preprocessor.h"
     19 #include "clang/Rewrite/Core/Rewriter.h"
     20 #include "clang/Sema/SemaDiagnostic.h"
     21 #include "clang/Serialization/ASTReader.h"
     22 #include "llvm/ADT/Triple.h"
     23 #include "llvm/Support/MemoryBuffer.h"
     24 using namespace clang;
     25 using namespace arcmt;
     26 
     27 bool CapturedDiagList::clearDiagnostic(ArrayRef<unsigned> IDs,
     28                                        SourceRange range) {
     29   if (range.isInvalid())
     30     return false;
     31 
     32   bool cleared = false;
     33   ListTy::iterator I = List.begin();
     34   while (I != List.end()) {
     35     FullSourceLoc diagLoc = I->getLocation();
     36     if ((IDs.empty() || // empty means clear all diagnostics in the range.
     37          std::find(IDs.begin(), IDs.end(), I->getID()) != IDs.end()) &&
     38         !diagLoc.isBeforeInTranslationUnitThan(range.getBegin()) &&
     39         (diagLoc == range.getEnd() ||
     40            diagLoc.isBeforeInTranslationUnitThan(range.getEnd()))) {
     41       cleared = true;
     42       ListTy::iterator eraseS = I++;
     43       if (eraseS->getLevel() != DiagnosticsEngine::Note)
     44         while (I != List.end() && I->getLevel() == DiagnosticsEngine::Note)
     45           ++I;
     46       // Clear the diagnostic and any notes following it.
     47       I = List.erase(eraseS, I);
     48       continue;
     49     }
     50 
     51     ++I;
     52   }
     53 
     54   return cleared;
     55 }
     56 
     57 bool CapturedDiagList::hasDiagnostic(ArrayRef<unsigned> IDs,
     58                                      SourceRange range) const {
     59   if (range.isInvalid())
     60     return false;
     61 
     62   ListTy::const_iterator I = List.begin();
     63   while (I != List.end()) {
     64     FullSourceLoc diagLoc = I->getLocation();
     65     if ((IDs.empty() || // empty means any diagnostic in the range.
     66          std::find(IDs.begin(), IDs.end(), I->getID()) != IDs.end()) &&
     67         !diagLoc.isBeforeInTranslationUnitThan(range.getBegin()) &&
     68         (diagLoc == range.getEnd() ||
     69            diagLoc.isBeforeInTranslationUnitThan(range.getEnd()))) {
     70       return true;
     71     }
     72 
     73     ++I;
     74   }
     75 
     76   return false;
     77 }
     78 
     79 void CapturedDiagList::reportDiagnostics(DiagnosticsEngine &Diags) const {
     80   for (ListTy::const_iterator I = List.begin(), E = List.end(); I != E; ++I)
     81     Diags.Report(*I);
     82 }
     83 
     84 bool CapturedDiagList::hasErrors() const {
     85   for (ListTy::const_iterator I = List.begin(), E = List.end(); I != E; ++I)
     86     if (I->getLevel() >= DiagnosticsEngine::Error)
     87       return true;
     88 
     89   return false;
     90 }
     91 
     92 namespace {
     93 
     94 class CaptureDiagnosticConsumer : public DiagnosticConsumer {
     95   DiagnosticsEngine &Diags;
     96   DiagnosticConsumer &DiagClient;
     97   CapturedDiagList &CapturedDiags;
     98   bool HasBegunSourceFile;
     99 public:
    100   CaptureDiagnosticConsumer(DiagnosticsEngine &diags,
    101                             DiagnosticConsumer &client,
    102                             CapturedDiagList &capturedDiags)
    103     : Diags(diags), DiagClient(client), CapturedDiags(capturedDiags),
    104       HasBegunSourceFile(false) { }
    105 
    106   virtual void BeginSourceFile(const LangOptions &Opts,
    107                                const Preprocessor *PP) {
    108     // Pass BeginSourceFile message onto DiagClient on first call.
    109     // The corresponding EndSourceFile call will be made from an
    110     // explicit call to FinishCapture.
    111     if (!HasBegunSourceFile) {
    112       DiagClient.BeginSourceFile(Opts, PP);
    113       HasBegunSourceFile = true;
    114     }
    115   }
    116 
    117   void FinishCapture() {
    118     // Call EndSourceFile on DiagClient on completion of capture to
    119     // enable VerifyDiagnosticConsumer to check diagnostics *after*
    120     // it has received the diagnostic list.
    121     if (HasBegunSourceFile) {
    122       DiagClient.EndSourceFile();
    123       HasBegunSourceFile = false;
    124     }
    125   }
    126 
    127   virtual ~CaptureDiagnosticConsumer() {
    128     assert(!HasBegunSourceFile && "FinishCapture not called!");
    129   }
    130 
    131   virtual void HandleDiagnostic(DiagnosticsEngine::Level level,
    132                                 const Diagnostic &Info) {
    133     if (DiagnosticIDs::isARCDiagnostic(Info.getID()) ||
    134         level >= DiagnosticsEngine::Error || level == DiagnosticsEngine::Note) {
    135       if (Info.getLocation().isValid())
    136         CapturedDiags.push_back(StoredDiagnostic(level, Info));
    137       return;
    138     }
    139 
    140     // Non-ARC warnings are ignored.
    141     Diags.setLastDiagnosticIgnored();
    142   }
    143 };
    144 
    145 } // end anonymous namespace
    146 
    147 static bool HasARCRuntime(CompilerInvocation &origCI) {
    148   // This duplicates some functionality from Darwin::AddDeploymentTarget
    149   // but this function is well defined, so keep it decoupled from the driver
    150   // and avoid unrelated complications.
    151   llvm::Triple triple(origCI.getTargetOpts().Triple);
    152 
    153   if (triple.getOS() == llvm::Triple::IOS)
    154     return triple.getOSMajorVersion() >= 5;
    155 
    156   if (triple.getOS() == llvm::Triple::Darwin)
    157     return triple.getOSMajorVersion() >= 11;
    158 
    159   if (triple.getOS() == llvm::Triple::MacOSX) {
    160     unsigned Major, Minor, Micro;
    161     triple.getOSVersion(Major, Minor, Micro);
    162     return Major > 10 || (Major == 10 && Minor >= 7);
    163   }
    164 
    165   return false;
    166 }
    167 
    168 static CompilerInvocation *
    169 createInvocationForMigration(CompilerInvocation &origCI) {
    170   OwningPtr<CompilerInvocation> CInvok;
    171   CInvok.reset(new CompilerInvocation(origCI));
    172   PreprocessorOptions &PPOpts = CInvok->getPreprocessorOpts();
    173   if (!PPOpts.ImplicitPCHInclude.empty()) {
    174     // We can't use a PCH because it was likely built in non-ARC mode and we
    175     // want to parse in ARC. Include the original header.
    176     FileManager FileMgr(origCI.getFileSystemOpts());
    177     IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
    178     IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
    179         new DiagnosticsEngine(DiagID, &origCI.getDiagnosticOpts(),
    180                               new IgnoringDiagConsumer()));
    181     std::string OriginalFile =
    182         ASTReader::getOriginalSourceFile(PPOpts.ImplicitPCHInclude,
    183                                          FileMgr, *Diags);
    184     if (!OriginalFile.empty())
    185       PPOpts.Includes.insert(PPOpts.Includes.begin(), OriginalFile);
    186     PPOpts.ImplicitPCHInclude.clear();
    187   }
    188   // FIXME: Get the original header of a PTH as well.
    189   CInvok->getPreprocessorOpts().ImplicitPTHInclude.clear();
    190   std::string define = getARCMTMacroName();
    191   define += '=';
    192   CInvok->getPreprocessorOpts().addMacroDef(define);
    193   CInvok->getLangOpts()->ObjCAutoRefCount = true;
    194   CInvok->getLangOpts()->setGC(LangOptions::NonGC);
    195   CInvok->getDiagnosticOpts().ErrorLimit = 0;
    196   CInvok->getDiagnosticOpts().PedanticErrors = 0;
    197 
    198   // Ignore -Werror flags when migrating.
    199   std::vector<std::string> WarnOpts;
    200   for (std::vector<std::string>::iterator
    201          I = CInvok->getDiagnosticOpts().Warnings.begin(),
    202          E = CInvok->getDiagnosticOpts().Warnings.end(); I != E; ++I) {
    203     if (!StringRef(*I).startswith("error"))
    204       WarnOpts.push_back(*I);
    205   }
    206   WarnOpts.push_back("error=arc-unsafe-retained-assign");
    207   CInvok->getDiagnosticOpts().Warnings = llvm_move(WarnOpts);
    208 
    209   CInvok->getLangOpts()->ObjCARCWeak = HasARCRuntime(origCI);
    210 
    211   return CInvok.take();
    212 }
    213 
    214 static void emitPremigrationErrors(const CapturedDiagList &arcDiags,
    215                                    DiagnosticOptions *diagOpts,
    216                                    Preprocessor &PP) {
    217   TextDiagnosticPrinter printer(llvm::errs(), diagOpts);
    218   IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
    219   IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
    220       new DiagnosticsEngine(DiagID, diagOpts, &printer,
    221                             /*ShouldOwnClient=*/false));
    222   Diags->setSourceManager(&PP.getSourceManager());
    223 
    224   printer.BeginSourceFile(PP.getLangOpts(), &PP);
    225   arcDiags.reportDiagnostics(*Diags);
    226   printer.EndSourceFile();
    227 }
    228 
    229 //===----------------------------------------------------------------------===//
    230 // checkForManualIssues.
    231 //===----------------------------------------------------------------------===//
    232 
    233 bool arcmt::checkForManualIssues(CompilerInvocation &origCI,
    234                                  const FrontendInputFile &Input,
    235                                  DiagnosticConsumer *DiagClient,
    236                                  bool emitPremigrationARCErrors,
    237                                  StringRef plistOut) {
    238   if (!origCI.getLangOpts()->ObjC1)
    239     return false;
    240 
    241   LangOptions::GCMode OrigGCMode = origCI.getLangOpts()->getGC();
    242   bool NoNSAllocReallocError = origCI.getMigratorOpts().NoNSAllocReallocError;
    243   bool NoFinalizeRemoval = origCI.getMigratorOpts().NoFinalizeRemoval;
    244 
    245   std::vector<TransformFn> transforms = arcmt::getAllTransformations(OrigGCMode,
    246                                                                      NoFinalizeRemoval);
    247   assert(!transforms.empty());
    248 
    249   OwningPtr<CompilerInvocation> CInvok;
    250   CInvok.reset(createInvocationForMigration(origCI));
    251   CInvok->getFrontendOpts().Inputs.clear();
    252   CInvok->getFrontendOpts().Inputs.push_back(Input);
    253 
    254   CapturedDiagList capturedDiags;
    255 
    256   assert(DiagClient);
    257   IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
    258   IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
    259       new DiagnosticsEngine(DiagID, &origCI.getDiagnosticOpts(),
    260                             DiagClient, /*ShouldOwnClient=*/false));
    261 
    262   // Filter of all diagnostics.
    263   CaptureDiagnosticConsumer errRec(*Diags, *DiagClient, capturedDiags);
    264   Diags->setClient(&errRec, /*ShouldOwnClient=*/false);
    265 
    266   OwningPtr<ASTUnit> Unit(
    267       ASTUnit::LoadFromCompilerInvocationAction(CInvok.take(), Diags));
    268   if (!Unit) {
    269     errRec.FinishCapture();
    270     return true;
    271   }
    272 
    273   bool hadARCErrors = capturedDiags.hasErrors();
    274 
    275   // Don't filter diagnostics anymore.
    276   Diags->setClient(DiagClient, /*ShouldOwnClient=*/false);
    277 
    278   ASTContext &Ctx = Unit->getASTContext();
    279 
    280   if (Diags->hasFatalErrorOccurred()) {
    281     Diags->Reset();
    282     DiagClient->BeginSourceFile(Ctx.getLangOpts(), &Unit->getPreprocessor());
    283     capturedDiags.reportDiagnostics(*Diags);
    284     DiagClient->EndSourceFile();
    285     errRec.FinishCapture();
    286     return true;
    287   }
    288 
    289   if (emitPremigrationARCErrors)
    290     emitPremigrationErrors(capturedDiags, &origCI.getDiagnosticOpts(),
    291                            Unit->getPreprocessor());
    292   if (!plistOut.empty()) {
    293     SmallVector<StoredDiagnostic, 8> arcDiags;
    294     for (CapturedDiagList::iterator
    295            I = capturedDiags.begin(), E = capturedDiags.end(); I != E; ++I)
    296       arcDiags.push_back(*I);
    297     writeARCDiagsToPlist(plistOut, arcDiags,
    298                          Ctx.getSourceManager(), Ctx.getLangOpts());
    299   }
    300 
    301   // After parsing of source files ended, we want to reuse the
    302   // diagnostics objects to emit further diagnostics.
    303   // We call BeginSourceFile because DiagnosticConsumer requires that
    304   // diagnostics with source range information are emitted only in between
    305   // BeginSourceFile() and EndSourceFile().
    306   DiagClient->BeginSourceFile(Ctx.getLangOpts(), &Unit->getPreprocessor());
    307 
    308   // No macros will be added since we are just checking and we won't modify
    309   // source code.
    310   std::vector<SourceLocation> ARCMTMacroLocs;
    311 
    312   TransformActions testAct(*Diags, capturedDiags, Ctx, Unit->getPreprocessor());
    313   MigrationPass pass(Ctx, OrigGCMode, Unit->getSema(), testAct, capturedDiags,
    314                      ARCMTMacroLocs);
    315   pass.setNSAllocReallocError(NoNSAllocReallocError);
    316   pass.setNoFinalizeRemoval(NoFinalizeRemoval);
    317 
    318   for (unsigned i=0, e = transforms.size(); i != e; ++i)
    319     transforms[i](pass);
    320 
    321   capturedDiags.reportDiagnostics(*Diags);
    322 
    323   DiagClient->EndSourceFile();
    324   errRec.FinishCapture();
    325 
    326   if (hadARCErrors) {
    327     // If we are migrating code that gets the '-fobjc-arc' flag, make sure
    328     // to remove it so that we don't get errors from normal compilation.
    329     origCI.getLangOpts()->ObjCAutoRefCount = false;
    330     // Disable auto-synthesize to avoid "@synthesize of 'weak' property is only
    331     // allowed in ARC" errors.
    332     origCI.getLangOpts()->ObjCDefaultSynthProperties = false;
    333   }
    334 
    335   return capturedDiags.hasErrors() || testAct.hasReportedErrors();
    336 }
    337 
    338 //===----------------------------------------------------------------------===//
    339 // applyTransformations.
    340 //===----------------------------------------------------------------------===//
    341 
    342 static bool applyTransforms(CompilerInvocation &origCI,
    343                             const FrontendInputFile &Input,
    344                             DiagnosticConsumer *DiagClient,
    345                             StringRef outputDir,
    346                             bool emitPremigrationARCErrors,
    347                             StringRef plistOut) {
    348   if (!origCI.getLangOpts()->ObjC1)
    349     return false;
    350 
    351   LangOptions::GCMode OrigGCMode = origCI.getLangOpts()->getGC();
    352 
    353   // Make sure checking is successful first.
    354   CompilerInvocation CInvokForCheck(origCI);
    355   if (arcmt::checkForManualIssues(CInvokForCheck, Input, DiagClient,
    356                                   emitPremigrationARCErrors, plistOut))
    357     return true;
    358 
    359   CompilerInvocation CInvok(origCI);
    360   CInvok.getFrontendOpts().Inputs.clear();
    361   CInvok.getFrontendOpts().Inputs.push_back(Input);
    362 
    363   MigrationProcess migration(CInvok, DiagClient, outputDir);
    364   bool NoFinalizeRemoval = origCI.getMigratorOpts().NoFinalizeRemoval;
    365 
    366   std::vector<TransformFn> transforms = arcmt::getAllTransformations(OrigGCMode,
    367                                                                      NoFinalizeRemoval);
    368   assert(!transforms.empty());
    369 
    370   for (unsigned i=0, e = transforms.size(); i != e; ++i) {
    371     bool err = migration.applyTransform(transforms[i]);
    372     if (err) return true;
    373   }
    374 
    375   IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
    376   IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
    377       new DiagnosticsEngine(DiagID, &origCI.getDiagnosticOpts(),
    378                             DiagClient, /*ShouldOwnClient=*/false));
    379 
    380   if (outputDir.empty()) {
    381     origCI.getLangOpts()->ObjCAutoRefCount = true;
    382     return migration.getRemapper().overwriteOriginal(*Diags);
    383   } else {
    384     if (migration.HadARCErrors) {
    385       // If we are migrating code that gets the '-fobjc-arc' flag, make sure
    386       // to remove it so that we don't get errors from normal compilation.
    387       origCI.getLangOpts()->ObjCAutoRefCount = false;
    388       // Disable auto-synthesize to avoid "@synthesize of 'weak' property is only
    389       // allowed in ARC" errors.
    390       origCI.getLangOpts()->ObjCDefaultSynthProperties = false;
    391     }
    392     return migration.getRemapper().flushToDisk(outputDir, *Diags);
    393   }
    394 }
    395 
    396 bool arcmt::applyTransformations(CompilerInvocation &origCI,
    397                                  const FrontendInputFile &Input,
    398                                  DiagnosticConsumer *DiagClient) {
    399   return applyTransforms(origCI, Input, DiagClient,
    400                          StringRef(), false, StringRef());
    401 }
    402 
    403 bool arcmt::migrateWithTemporaryFiles(CompilerInvocation &origCI,
    404                                       const FrontendInputFile &Input,
    405                                       DiagnosticConsumer *DiagClient,
    406                                       StringRef outputDir,
    407                                       bool emitPremigrationARCErrors,
    408                                       StringRef plistOut) {
    409   assert(!outputDir.empty() && "Expected output directory path");
    410   return applyTransforms(origCI, Input, DiagClient,
    411                          outputDir, emitPremigrationARCErrors, plistOut);
    412 }
    413 
    414 bool arcmt::getFileRemappings(std::vector<std::pair<std::string,std::string> > &
    415                                   remap,
    416                               StringRef outputDir,
    417                               DiagnosticConsumer *DiagClient) {
    418   assert(!outputDir.empty());
    419 
    420   IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
    421   IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
    422       new DiagnosticsEngine(DiagID, new DiagnosticOptions,
    423                             DiagClient, /*ShouldOwnClient=*/false));
    424 
    425   FileRemapper remapper;
    426   bool err = remapper.initFromDisk(outputDir, *Diags,
    427                                    /*ignoreIfFilesChanged=*/true);
    428   if (err)
    429     return true;
    430 
    431   PreprocessorOptions PPOpts;
    432   remapper.applyMappings(PPOpts);
    433   remap = PPOpts.RemappedFiles;
    434 
    435   return false;
    436 }
    437 
    438 bool arcmt::getFileRemappingsFromFileList(
    439                         std::vector<std::pair<std::string,std::string> > &remap,
    440                         ArrayRef<StringRef> remapFiles,
    441                         DiagnosticConsumer *DiagClient) {
    442   bool hasErrorOccurred = false;
    443   llvm::StringMap<bool> Uniquer;
    444 
    445   IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
    446   IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
    447       new DiagnosticsEngine(DiagID, new DiagnosticOptions,
    448                             DiagClient, /*ShouldOwnClient=*/false));
    449 
    450   for (ArrayRef<StringRef>::iterator
    451          I = remapFiles.begin(), E = remapFiles.end(); I != E; ++I) {
    452     StringRef file = *I;
    453 
    454     FileRemapper remapper;
    455     bool err = remapper.initFromFile(file, *Diags,
    456                                      /*ignoreIfFilesChanged=*/true);
    457     hasErrorOccurred = hasErrorOccurred || err;
    458     if (err)
    459       continue;
    460 
    461     PreprocessorOptions PPOpts;
    462     remapper.applyMappings(PPOpts);
    463     for (PreprocessorOptions::remapped_file_iterator
    464            RI = PPOpts.remapped_file_begin(), RE = PPOpts.remapped_file_end();
    465            RI != RE; ++RI) {
    466       bool &inserted = Uniquer[RI->first];
    467       if (inserted)
    468         continue;
    469       inserted = true;
    470       remap.push_back(*RI);
    471     }
    472   }
    473 
    474   return hasErrorOccurred;
    475 }
    476 
    477 //===----------------------------------------------------------------------===//
    478 // CollectTransformActions.
    479 //===----------------------------------------------------------------------===//
    480 
    481 namespace {
    482 
    483 class ARCMTMacroTrackerPPCallbacks : public PPCallbacks {
    484   std::vector<SourceLocation> &ARCMTMacroLocs;
    485 
    486 public:
    487   ARCMTMacroTrackerPPCallbacks(std::vector<SourceLocation> &ARCMTMacroLocs)
    488     : ARCMTMacroLocs(ARCMTMacroLocs) { }
    489 
    490   virtual void MacroExpands(const Token &MacroNameTok, const MacroDirective *MD,
    491                             SourceRange Range, const MacroArgs *Args) {
    492     if (MacroNameTok.getIdentifierInfo()->getName() == getARCMTMacroName())
    493       ARCMTMacroLocs.push_back(MacroNameTok.getLocation());
    494   }
    495 };
    496 
    497 class ARCMTMacroTrackerAction : public ASTFrontendAction {
    498   std::vector<SourceLocation> &ARCMTMacroLocs;
    499 
    500 public:
    501   ARCMTMacroTrackerAction(std::vector<SourceLocation> &ARCMTMacroLocs)
    502     : ARCMTMacroLocs(ARCMTMacroLocs) { }
    503 
    504   virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
    505                                          StringRef InFile) {
    506     CI.getPreprocessor().addPPCallbacks(
    507                               new ARCMTMacroTrackerPPCallbacks(ARCMTMacroLocs));
    508     return new ASTConsumer();
    509   }
    510 };
    511 
    512 class RewritesApplicator : public TransformActions::RewriteReceiver {
    513   Rewriter &rewriter;
    514   MigrationProcess::RewriteListener *Listener;
    515 
    516 public:
    517   RewritesApplicator(Rewriter &rewriter, ASTContext &ctx,
    518                      MigrationProcess::RewriteListener *listener)
    519     : rewriter(rewriter), Listener(listener) {
    520     if (Listener)
    521       Listener->start(ctx);
    522   }
    523   ~RewritesApplicator() {
    524     if (Listener)
    525       Listener->finish();
    526   }
    527 
    528   virtual void insert(SourceLocation loc, StringRef text) {
    529     bool err = rewriter.InsertText(loc, text, /*InsertAfter=*/true,
    530                                    /*indentNewLines=*/true);
    531     if (!err && Listener)
    532       Listener->insert(loc, text);
    533   }
    534 
    535   virtual void remove(CharSourceRange range) {
    536     Rewriter::RewriteOptions removeOpts;
    537     removeOpts.IncludeInsertsAtBeginOfRange = false;
    538     removeOpts.IncludeInsertsAtEndOfRange = false;
    539     removeOpts.RemoveLineIfEmpty = true;
    540 
    541     bool err = rewriter.RemoveText(range, removeOpts);
    542     if (!err && Listener)
    543       Listener->remove(range);
    544   }
    545 
    546   virtual void increaseIndentation(CharSourceRange range,
    547                                     SourceLocation parentIndent) {
    548     rewriter.IncreaseIndentation(range, parentIndent);
    549   }
    550 };
    551 
    552 } // end anonymous namespace.
    553 
    554 /// \brief Anchor for VTable.
    555 MigrationProcess::RewriteListener::~RewriteListener() { }
    556 
    557 MigrationProcess::MigrationProcess(const CompilerInvocation &CI,
    558                                    DiagnosticConsumer *diagClient,
    559                                    StringRef outputDir)
    560   : OrigCI(CI), DiagClient(diagClient), HadARCErrors(false) {
    561   if (!outputDir.empty()) {
    562     IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
    563     IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
    564       new DiagnosticsEngine(DiagID, &CI.getDiagnosticOpts(),
    565                             DiagClient, /*ShouldOwnClient=*/false));
    566     Remapper.initFromDisk(outputDir, *Diags, /*ignoreIfFilesChanges=*/true);
    567   }
    568 }
    569 
    570 bool MigrationProcess::applyTransform(TransformFn trans,
    571                                       RewriteListener *listener) {
    572   OwningPtr<CompilerInvocation> CInvok;
    573   CInvok.reset(createInvocationForMigration(OrigCI));
    574   CInvok->getDiagnosticOpts().IgnoreWarnings = true;
    575 
    576   Remapper.applyMappings(CInvok->getPreprocessorOpts());
    577 
    578   CapturedDiagList capturedDiags;
    579   std::vector<SourceLocation> ARCMTMacroLocs;
    580 
    581   assert(DiagClient);
    582   IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
    583   IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
    584       new DiagnosticsEngine(DiagID, new DiagnosticOptions,
    585                             DiagClient, /*ShouldOwnClient=*/false));
    586 
    587   // Filter of all diagnostics.
    588   CaptureDiagnosticConsumer errRec(*Diags, *DiagClient, capturedDiags);
    589   Diags->setClient(&errRec, /*ShouldOwnClient=*/false);
    590 
    591   OwningPtr<ARCMTMacroTrackerAction> ASTAction;
    592   ASTAction.reset(new ARCMTMacroTrackerAction(ARCMTMacroLocs));
    593 
    594   OwningPtr<ASTUnit> Unit(
    595       ASTUnit::LoadFromCompilerInvocationAction(CInvok.take(), Diags,
    596                                                 ASTAction.get()));
    597   if (!Unit) {
    598     errRec.FinishCapture();
    599     return true;
    600   }
    601   Unit->setOwnsRemappedFileBuffers(false); // FileRemapper manages that.
    602 
    603   HadARCErrors = HadARCErrors || capturedDiags.hasErrors();
    604 
    605   // Don't filter diagnostics anymore.
    606   Diags->setClient(DiagClient, /*ShouldOwnClient=*/false);
    607 
    608   ASTContext &Ctx = Unit->getASTContext();
    609 
    610   if (Diags->hasFatalErrorOccurred()) {
    611     Diags->Reset();
    612     DiagClient->BeginSourceFile(Ctx.getLangOpts(), &Unit->getPreprocessor());
    613     capturedDiags.reportDiagnostics(*Diags);
    614     DiagClient->EndSourceFile();
    615     errRec.FinishCapture();
    616     return true;
    617   }
    618 
    619   // After parsing of source files ended, we want to reuse the
    620   // diagnostics objects to emit further diagnostics.
    621   // We call BeginSourceFile because DiagnosticConsumer requires that
    622   // diagnostics with source range information are emitted only in between
    623   // BeginSourceFile() and EndSourceFile().
    624   DiagClient->BeginSourceFile(Ctx.getLangOpts(), &Unit->getPreprocessor());
    625 
    626   Rewriter rewriter(Ctx.getSourceManager(), Ctx.getLangOpts());
    627   TransformActions TA(*Diags, capturedDiags, Ctx, Unit->getPreprocessor());
    628   MigrationPass pass(Ctx, OrigCI.getLangOpts()->getGC(),
    629                      Unit->getSema(), TA, capturedDiags, ARCMTMacroLocs);
    630 
    631   trans(pass);
    632 
    633   {
    634     RewritesApplicator applicator(rewriter, Ctx, listener);
    635     TA.applyRewrites(applicator);
    636   }
    637 
    638   DiagClient->EndSourceFile();
    639   errRec.FinishCapture();
    640 
    641   if (DiagClient->getNumErrors())
    642     return true;
    643 
    644   for (Rewriter::buffer_iterator
    645         I = rewriter.buffer_begin(), E = rewriter.buffer_end(); I != E; ++I) {
    646     FileID FID = I->first;
    647     RewriteBuffer &buf = I->second;
    648     const FileEntry *file = Ctx.getSourceManager().getFileEntryForID(FID);
    649     assert(file);
    650     std::string newFname = file->getName();
    651     newFname += "-trans";
    652     SmallString<512> newText;
    653     llvm::raw_svector_ostream vecOS(newText);
    654     buf.write(vecOS);
    655     vecOS.flush();
    656     llvm::MemoryBuffer *memBuf = llvm::MemoryBuffer::getMemBufferCopy(
    657                    StringRef(newText.data(), newText.size()), newFname);
    658     SmallString<64> filePath(file->getName());
    659     Unit->getFileManager().FixupRelativePath(filePath);
    660     Remapper.remap(filePath.str(), memBuf);
    661   }
    662 
    663   return false;
    664 }
    665