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   void BeginSourceFile(const LangOptions &Opts,
107                        const Preprocessor *PP) override {
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   ~CaptureDiagnosticConsumer() override {
128     assert(!HasBegunSourceFile && "FinishCapture not called!");
129   }
130 
131   void HandleDiagnostic(DiagnosticsEngine::Level level,
132                         const Diagnostic &Info) override {
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.isiOS())
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                              const PCHContainerReader &PCHContainerRdr) {
171   std::unique_ptr<CompilerInvocation> CInvok;
172   CInvok.reset(new CompilerInvocation(origCI));
173   PreprocessorOptions &PPOpts = CInvok->getPreprocessorOpts();
174   if (!PPOpts.ImplicitPCHInclude.empty()) {
175     // We can't use a PCH because it was likely built in non-ARC mode and we
176     // want to parse in ARC. Include the original header.
177     FileManager FileMgr(origCI.getFileSystemOpts());
178     IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
179     IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
180         new DiagnosticsEngine(DiagID, &origCI.getDiagnosticOpts(),
181                               new IgnoringDiagConsumer()));
182     std::string OriginalFile = ASTReader::getOriginalSourceFile(
183         PPOpts.ImplicitPCHInclude, FileMgr, PCHContainerRdr, *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 = std::move(WarnOpts);
208 
209   CInvok->getLangOpts()->ObjCWeakRuntime = HasARCRuntime(origCI);
210   CInvok->getLangOpts()->ObjCWeak = CInvok->getLangOpts()->ObjCWeakRuntime;
211 
212   return CInvok.release();
213 }
214 
215 static void emitPremigrationErrors(const CapturedDiagList &arcDiags,
216                                    DiagnosticOptions *diagOpts,
217                                    Preprocessor &PP) {
218   TextDiagnosticPrinter printer(llvm::errs(), diagOpts);
219   IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
220   IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
221       new DiagnosticsEngine(DiagID, diagOpts, &printer,
222                             /*ShouldOwnClient=*/false));
223   Diags->setSourceManager(&PP.getSourceManager());
224 
225   printer.BeginSourceFile(PP.getLangOpts(), &PP);
226   arcDiags.reportDiagnostics(*Diags);
227   printer.EndSourceFile();
228 }
229 
230 //===----------------------------------------------------------------------===//
231 // checkForManualIssues.
232 //===----------------------------------------------------------------------===//
233 
234 bool arcmt::checkForManualIssues(
235     CompilerInvocation &origCI, const FrontendInputFile &Input,
236     std::shared_ptr<PCHContainerOperations> PCHContainerOps,
237     DiagnosticConsumer *DiagClient, bool emitPremigrationARCErrors,
238     StringRef plistOut) {
239   if (!origCI.getLangOpts()->ObjC1)
240     return false;
241 
242   LangOptions::GCMode OrigGCMode = origCI.getLangOpts()->getGC();
243   bool NoNSAllocReallocError = origCI.getMigratorOpts().NoNSAllocReallocError;
244   bool NoFinalizeRemoval = origCI.getMigratorOpts().NoFinalizeRemoval;
245 
246   std::vector<TransformFn> transforms = arcmt::getAllTransformations(OrigGCMode,
247                                                                      NoFinalizeRemoval);
248   assert(!transforms.empty());
249 
250   std::unique_ptr<CompilerInvocation> CInvok;
251   CInvok.reset(
252       createInvocationForMigration(origCI, PCHContainerOps->getRawReader()));
253   CInvok->getFrontendOpts().Inputs.clear();
254   CInvok->getFrontendOpts().Inputs.push_back(Input);
255 
256   CapturedDiagList capturedDiags;
257 
258   assert(DiagClient);
259   IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
260   IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
261       new DiagnosticsEngine(DiagID, &origCI.getDiagnosticOpts(),
262                             DiagClient, /*ShouldOwnClient=*/false));
263 
264   // Filter of all diagnostics.
265   CaptureDiagnosticConsumer errRec(*Diags, *DiagClient, capturedDiags);
266   Diags->setClient(&errRec, /*ShouldOwnClient=*/false);
267 
268   std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCompilerInvocationAction(
269       CInvok.release(), PCHContainerOps, Diags));
270   if (!Unit) {
271     errRec.FinishCapture();
272     return true;
273   }
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.setNoFinalizeRemoval(NoFinalizeRemoval);
316   if (!NoNSAllocReallocError)
317     Diags->setSeverity(diag::warn_arcmt_nsalloc_realloc, diag::Severity::Error,
318                        SourceLocation());
319 
320   for (unsigned i=0, e = transforms.size(); i != e; ++i)
321     transforms[i](pass);
322 
323   capturedDiags.reportDiagnostics(*Diags);
324 
325   DiagClient->EndSourceFile();
326   errRec.FinishCapture();
327 
328   return capturedDiags.hasErrors() || testAct.hasReportedErrors();
329 }
330 
331 //===----------------------------------------------------------------------===//
332 // applyTransformations.
333 //===----------------------------------------------------------------------===//
334 
335 static bool
336 applyTransforms(CompilerInvocation &origCI, const FrontendInputFile &Input,
337                 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
338                 DiagnosticConsumer *DiagClient, StringRef outputDir,
339                 bool emitPremigrationARCErrors, StringRef plistOut) {
340   if (!origCI.getLangOpts()->ObjC1)
341     return false;
342 
343   LangOptions::GCMode OrigGCMode = origCI.getLangOpts()->getGC();
344 
345   // Make sure checking is successful first.
346   CompilerInvocation CInvokForCheck(origCI);
347   if (arcmt::checkForManualIssues(CInvokForCheck, Input, PCHContainerOps,
348                                   DiagClient, emitPremigrationARCErrors,
349                                   plistOut))
350     return true;
351 
352   CompilerInvocation CInvok(origCI);
353   CInvok.getFrontendOpts().Inputs.clear();
354   CInvok.getFrontendOpts().Inputs.push_back(Input);
355 
356   MigrationProcess migration(CInvok, PCHContainerOps, DiagClient, outputDir);
357   bool NoFinalizeRemoval = origCI.getMigratorOpts().NoFinalizeRemoval;
358 
359   std::vector<TransformFn> transforms = arcmt::getAllTransformations(OrigGCMode,
360                                                                      NoFinalizeRemoval);
361   assert(!transforms.empty());
362 
363   for (unsigned i=0, e = transforms.size(); i != e; ++i) {
364     bool err = migration.applyTransform(transforms[i]);
365     if (err) return true;
366   }
367 
368   IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
369   IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
370       new DiagnosticsEngine(DiagID, &origCI.getDiagnosticOpts(),
371                             DiagClient, /*ShouldOwnClient=*/false));
372 
373   if (outputDir.empty()) {
374     origCI.getLangOpts()->ObjCAutoRefCount = true;
375     return migration.getRemapper().overwriteOriginal(*Diags);
376   } else {
377     return migration.getRemapper().flushToDisk(outputDir, *Diags);
378   }
379 }
380 
381 bool arcmt::applyTransformations(
382     CompilerInvocation &origCI, const FrontendInputFile &Input,
383     std::shared_ptr<PCHContainerOperations> PCHContainerOps,
384     DiagnosticConsumer *DiagClient) {
385   return applyTransforms(origCI, Input, PCHContainerOps, DiagClient,
386                          StringRef(), false, StringRef());
387 }
388 
389 bool arcmt::migrateWithTemporaryFiles(
390     CompilerInvocation &origCI, const FrontendInputFile &Input,
391     std::shared_ptr<PCHContainerOperations> PCHContainerOps,
392     DiagnosticConsumer *DiagClient, StringRef outputDir,
393     bool emitPremigrationARCErrors, StringRef plistOut) {
394   assert(!outputDir.empty() && "Expected output directory path");
395   return applyTransforms(origCI, Input, PCHContainerOps, DiagClient, outputDir,
396                          emitPremigrationARCErrors, plistOut);
397 }
398 
399 bool arcmt::getFileRemappings(std::vector<std::pair<std::string,std::string> > &
400                                   remap,
401                               StringRef outputDir,
402                               DiagnosticConsumer *DiagClient) {
403   assert(!outputDir.empty());
404 
405   IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
406   IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
407       new DiagnosticsEngine(DiagID, new DiagnosticOptions,
408                             DiagClient, /*ShouldOwnClient=*/false));
409 
410   FileRemapper remapper;
411   bool err = remapper.initFromDisk(outputDir, *Diags,
412                                    /*ignoreIfFilesChanged=*/true);
413   if (err)
414     return true;
415 
416   PreprocessorOptions PPOpts;
417   remapper.applyMappings(PPOpts);
418   remap = PPOpts.RemappedFiles;
419 
420   return false;
421 }
422 
423 
424 //===----------------------------------------------------------------------===//
425 // CollectTransformActions.
426 //===----------------------------------------------------------------------===//
427 
428 namespace {
429 
430 class ARCMTMacroTrackerPPCallbacks : public PPCallbacks {
431   std::vector<SourceLocation> &ARCMTMacroLocs;
432 
433 public:
434   ARCMTMacroTrackerPPCallbacks(std::vector<SourceLocation> &ARCMTMacroLocs)
435     : ARCMTMacroLocs(ARCMTMacroLocs) { }
436 
437   void MacroExpands(const Token &MacroNameTok, const MacroDefinition &MD,
438                     SourceRange Range, const MacroArgs *Args) override {
439     if (MacroNameTok.getIdentifierInfo()->getName() == getARCMTMacroName())
440       ARCMTMacroLocs.push_back(MacroNameTok.getLocation());
441   }
442 };
443 
444 class ARCMTMacroTrackerAction : public ASTFrontendAction {
445   std::vector<SourceLocation> &ARCMTMacroLocs;
446 
447 public:
448   ARCMTMacroTrackerAction(std::vector<SourceLocation> &ARCMTMacroLocs)
449     : ARCMTMacroLocs(ARCMTMacroLocs) { }
450 
451   std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
452                                                  StringRef InFile) override {
453     CI.getPreprocessor().addPPCallbacks(
454                llvm::make_unique<ARCMTMacroTrackerPPCallbacks>(ARCMTMacroLocs));
455     return llvm::make_unique<ASTConsumer>();
456   }
457 };
458 
459 class RewritesApplicator : public TransformActions::RewriteReceiver {
460   Rewriter &rewriter;
461   MigrationProcess::RewriteListener *Listener;
462 
463 public:
464   RewritesApplicator(Rewriter &rewriter, ASTContext &ctx,
465                      MigrationProcess::RewriteListener *listener)
466     : rewriter(rewriter), Listener(listener) {
467     if (Listener)
468       Listener->start(ctx);
469   }
470   ~RewritesApplicator() override {
471     if (Listener)
472       Listener->finish();
473   }
474 
475   void insert(SourceLocation loc, StringRef text) override {
476     bool err = rewriter.InsertText(loc, text, /*InsertAfter=*/true,
477                                    /*indentNewLines=*/true);
478     if (!err && Listener)
479       Listener->insert(loc, text);
480   }
481 
482   void remove(CharSourceRange range) override {
483     Rewriter::RewriteOptions removeOpts;
484     removeOpts.IncludeInsertsAtBeginOfRange = false;
485     removeOpts.IncludeInsertsAtEndOfRange = false;
486     removeOpts.RemoveLineIfEmpty = true;
487 
488     bool err = rewriter.RemoveText(range, removeOpts);
489     if (!err && Listener)
490       Listener->remove(range);
491   }
492 
493   void increaseIndentation(CharSourceRange range,
494                             SourceLocation parentIndent) override {
495     rewriter.IncreaseIndentation(range, parentIndent);
496   }
497 };
498 
499 } // end anonymous namespace.
500 
501 /// \brief Anchor for VTable.
502 MigrationProcess::RewriteListener::~RewriteListener() { }
503 
504 MigrationProcess::MigrationProcess(
505     const CompilerInvocation &CI,
506     std::shared_ptr<PCHContainerOperations> PCHContainerOps,
507     DiagnosticConsumer *diagClient, StringRef outputDir)
508     : OrigCI(CI), PCHContainerOps(PCHContainerOps), DiagClient(diagClient),
509       HadARCErrors(false) {
510   if (!outputDir.empty()) {
511     IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
512     IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
513       new DiagnosticsEngine(DiagID, &CI.getDiagnosticOpts(),
514                             DiagClient, /*ShouldOwnClient=*/false));
515     Remapper.initFromDisk(outputDir, *Diags, /*ignoreIfFilesChanges=*/true);
516   }
517 }
518 
519 bool MigrationProcess::applyTransform(TransformFn trans,
520                                       RewriteListener *listener) {
521   std::unique_ptr<CompilerInvocation> CInvok;
522   CInvok.reset(
523       createInvocationForMigration(OrigCI, PCHContainerOps->getRawReader()));
524   CInvok->getDiagnosticOpts().IgnoreWarnings = true;
525 
526   Remapper.applyMappings(CInvok->getPreprocessorOpts());
527 
528   CapturedDiagList capturedDiags;
529   std::vector<SourceLocation> ARCMTMacroLocs;
530 
531   assert(DiagClient);
532   IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
533   IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
534       new DiagnosticsEngine(DiagID, new DiagnosticOptions,
535                             DiagClient, /*ShouldOwnClient=*/false));
536 
537   // Filter of all diagnostics.
538   CaptureDiagnosticConsumer errRec(*Diags, *DiagClient, capturedDiags);
539   Diags->setClient(&errRec, /*ShouldOwnClient=*/false);
540 
541   std::unique_ptr<ARCMTMacroTrackerAction> ASTAction;
542   ASTAction.reset(new ARCMTMacroTrackerAction(ARCMTMacroLocs));
543 
544   std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCompilerInvocationAction(
545       CInvok.release(), PCHContainerOps, Diags, ASTAction.get()));
546   if (!Unit) {
547     errRec.FinishCapture();
548     return true;
549   }
550   Unit->setOwnsRemappedFileBuffers(false); // FileRemapper manages that.
551 
552   HadARCErrors = HadARCErrors || capturedDiags.hasErrors();
553 
554   // Don't filter diagnostics anymore.
555   Diags->setClient(DiagClient, /*ShouldOwnClient=*/false);
556 
557   ASTContext &Ctx = Unit->getASTContext();
558 
559   if (Diags->hasFatalErrorOccurred()) {
560     Diags->Reset();
561     DiagClient->BeginSourceFile(Ctx.getLangOpts(), &Unit->getPreprocessor());
562     capturedDiags.reportDiagnostics(*Diags);
563     DiagClient->EndSourceFile();
564     errRec.FinishCapture();
565     return true;
566   }
567 
568   // After parsing of source files ended, we want to reuse the
569   // diagnostics objects to emit further diagnostics.
570   // We call BeginSourceFile because DiagnosticConsumer requires that
571   // diagnostics with source range information are emitted only in between
572   // BeginSourceFile() and EndSourceFile().
573   DiagClient->BeginSourceFile(Ctx.getLangOpts(), &Unit->getPreprocessor());
574 
575   Rewriter rewriter(Ctx.getSourceManager(), Ctx.getLangOpts());
576   TransformActions TA(*Diags, capturedDiags, Ctx, Unit->getPreprocessor());
577   MigrationPass pass(Ctx, OrigCI.getLangOpts()->getGC(),
578                      Unit->getSema(), TA, capturedDiags, ARCMTMacroLocs);
579 
580   trans(pass);
581 
582   {
583     RewritesApplicator applicator(rewriter, Ctx, listener);
584     TA.applyRewrites(applicator);
585   }
586 
587   DiagClient->EndSourceFile();
588   errRec.FinishCapture();
589 
590   if (DiagClient->getNumErrors())
591     return true;
592 
593   for (Rewriter::buffer_iterator
594         I = rewriter.buffer_begin(), E = rewriter.buffer_end(); I != E; ++I) {
595     FileID FID = I->first;
596     RewriteBuffer &buf = I->second;
597     const FileEntry *file = Ctx.getSourceManager().getFileEntryForID(FID);
598     assert(file);
599     std::string newFname = file->getName();
600     newFname += "-trans";
601     SmallString<512> newText;
602     llvm::raw_svector_ostream vecOS(newText);
603     buf.write(vecOS);
604     std::unique_ptr<llvm::MemoryBuffer> memBuf(
605         llvm::MemoryBuffer::getMemBufferCopy(
606             StringRef(newText.data(), newText.size()), newFname));
607     SmallString<64> filePath(file->getName());
608     Unit->getFileManager().FixupRelativePath(filePath);
609     Remapper.remap(filePath.str(), std::move(memBuf));
610   }
611 
612   return false;
613 }
614