blob: 477e327071a8dffc64083e17feb76f6534dbdbe0 [file] [log] [blame]
John McCalld70fb982011-06-15 23:25:17 +00001//===--- 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"
Chandler Carruth3a022472012-12-04 09:13:33 +000011#include "clang/AST/ASTConsumer.h"
12#include "clang/Basic/DiagnosticCategories.h"
John McCalld70fb982011-06-15 23:25:17 +000013#include "clang/Frontend/ASTUnit.h"
14#include "clang/Frontend/CompilerInstance.h"
Douglas Gregor32fbe312012-01-20 16:28:04 +000015#include "clang/Frontend/FrontendAction.h"
Argyrios Kyrtzidisd5713632011-07-19 17:20:03 +000016#include "clang/Frontend/TextDiagnosticPrinter.h"
John McCalld70fb982011-06-15 23:25:17 +000017#include "clang/Frontend/Utils.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "clang/Lex/Preprocessor.h"
Ted Kremenekcdf81492012-09-01 05:09:24 +000019#include "clang/Rewrite/Core/Rewriter.h"
John McCalld70fb982011-06-15 23:25:17 +000020#include "clang/Sema/SemaDiagnostic.h"
Argyrios Kyrtzidis88c0d3b2013-02-05 16:37:00 +000021#include "clang/Serialization/ASTReader.h"
John McCalld70fb982011-06-15 23:25:17 +000022#include "llvm/ADT/Triple.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000023#include "llvm/Support/MemoryBuffer.h"
John McCalld70fb982011-06-15 23:25:17 +000024using namespace clang;
25using namespace arcmt;
John McCalld70fb982011-06-15 23:25:17 +000026
Chris Lattner54b16772011-07-23 17:14:25 +000027bool CapturedDiagList::clearDiagnostic(ArrayRef<unsigned> IDs,
John McCalld70fb982011-06-15 23:25:17 +000028 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++;
Argyrios Kyrtzidis03fbe3e2013-01-04 18:30:08 +000043 if (eraseS->getLevel() != DiagnosticsEngine::Note)
44 while (I != List.end() && I->getLevel() == DiagnosticsEngine::Note)
45 ++I;
John McCalld70fb982011-06-15 23:25:17 +000046 // Clear the diagnostic and any notes following it.
Joao Matos0e167f72012-08-31 17:28:09 +000047 I = List.erase(eraseS, I);
John McCalld70fb982011-06-15 23:25:17 +000048 continue;
49 }
50
51 ++I;
52 }
53
54 return cleared;
55}
56
Chris Lattner54b16772011-07-23 17:14:25 +000057bool CapturedDiagList::hasDiagnostic(ArrayRef<unsigned> IDs,
Argyrios Kyrtzidis0f3f9f72011-06-18 00:53:34 +000058 SourceRange range) const {
John McCalld70fb982011-06-15 23:25:17 +000059 if (range.isInvalid())
60 return false;
61
Argyrios Kyrtzidis0f3f9f72011-06-18 00:53:34 +000062 ListTy::const_iterator I = List.begin();
John McCalld70fb982011-06-15 23:25:17 +000063 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
David Blaikie9c902b52011-09-25 23:23:43 +000079void CapturedDiagList::reportDiagnostics(DiagnosticsEngine &Diags) const {
Argyrios Kyrtzidis0f3f9f72011-06-18 00:53:34 +000080 for (ListTy::const_iterator I = List.begin(), E = List.end(); I != E; ++I)
John McCalld70fb982011-06-15 23:25:17 +000081 Diags.Report(*I);
82}
83
Argyrios Kyrtzidis90b6a2a2011-06-18 00:53:41 +000084bool CapturedDiagList::hasErrors() const {
85 for (ListTy::const_iterator I = List.begin(), E = List.end(); I != E; ++I)
David Blaikie9c902b52011-09-25 23:23:43 +000086 if (I->getLevel() >= DiagnosticsEngine::Error)
Argyrios Kyrtzidis90b6a2a2011-06-18 00:53:41 +000087 return true;
88
89 return false;
90}
91
John McCalld70fb982011-06-15 23:25:17 +000092namespace {
93
David Blaikiea24a0bc2011-09-25 23:54:33 +000094class CaptureDiagnosticConsumer : public DiagnosticConsumer {
David Blaikie9c902b52011-09-25 23:23:43 +000095 DiagnosticsEngine &Diags;
Jordan Roseb00073d2012-08-10 01:06:16 +000096 DiagnosticConsumer &DiagClient;
John McCalld70fb982011-06-15 23:25:17 +000097 CapturedDiagList &CapturedDiags;
Jordan Roseb00073d2012-08-10 01:06:16 +000098 bool HasBegunSourceFile;
John McCalld70fb982011-06-15 23:25:17 +000099public:
David Blaikiea24a0bc2011-09-25 23:54:33 +0000100 CaptureDiagnosticConsumer(DiagnosticsEngine &diags,
Jordan Roseb00073d2012-08-10 01:06:16 +0000101 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 }
John McCalld70fb982011-06-15 23:25:17 +0000130
David Blaikie9c902b52011-09-25 23:23:43 +0000131 virtual void HandleDiagnostic(DiagnosticsEngine::Level level,
David Blaikieb5784322011-09-26 01:18:08 +0000132 const Diagnostic &Info) {
Ted Kremenek337c5b82011-10-20 05:07:47 +0000133 if (DiagnosticIDs::isARCDiagnostic(Info.getID()) ||
David Blaikie9c902b52011-09-25 23:23:43 +0000134 level >= DiagnosticsEngine::Error || level == DiagnosticsEngine::Note) {
Argyrios Kyrtzidis1f732162012-12-12 22:48:28 +0000135 if (Info.getLocation().isValid())
136 CapturedDiags.push_back(StoredDiagnostic(level, Info));
John McCalld70fb982011-06-15 23:25:17 +0000137 return;
138 }
139
140 // Non-ARC warnings are ignored.
141 Diags.setLastDiagnosticIgnored();
142 }
143};
144
145} // end anonymous namespace
146
Argyrios Kyrtzidis81a35902011-06-20 19:59:52 +0000147static 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.
Argyrios Kyrtzidis81a35902011-06-20 19:59:52 +0000151 llvm::Triple triple(origCI.getTargetOpts().Triple);
152
Cameron Esfahani556d91e2013-09-14 01:09:11 +0000153 if (triple.isiOS())
Argyrios Kyrtzidis81a35902011-06-20 19:59:52 +0000154 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
Benjamin Kramer3c05b7c2011-08-02 04:50:49 +0000168static CompilerInvocation *
169createInvocationForMigration(CompilerInvocation &origCI) {
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000170 OwningPtr<CompilerInvocation> CInvok;
John McCalld70fb982011-06-15 23:25:17 +0000171 CInvok.reset(new CompilerInvocation(origCI));
Argyrios Kyrtzidis88c0d3b2013-02-05 16:37:00 +0000172 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();
John McCalld70fb982011-06-15 23:25:17 +0000190 std::string define = getARCMTMacroName();
191 define += '=';
192 CInvok->getPreprocessorOpts().addMacroDef(define);
Ted Kremenek8cf47df2011-11-17 23:01:24 +0000193 CInvok->getLangOpts()->ObjCAutoRefCount = true;
194 CInvok->getLangOpts()->setGC(LangOptions::NonGC);
John McCalld70fb982011-06-15 23:25:17 +0000195 CInvok->getDiagnosticOpts().ErrorLimit = 0;
Argyrios Kyrtzidisaa38f692012-06-20 01:46:26 +0000196 CInvok->getDiagnosticOpts().PedanticErrors = 0;
Argyrios Kyrtzidis692bf8c2012-06-20 01:10:40 +0000197
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");
Argyrios Kyrtzidisaa38f692012-06-20 01:46:26 +0000207 CInvok->getDiagnosticOpts().Warnings = llvm_move(WarnOpts);
Argyrios Kyrtzidis692bf8c2012-06-20 01:10:40 +0000208
John McCall3deb1ad2012-08-21 02:47:43 +0000209 CInvok->getLangOpts()->ObjCARCWeak = HasARCRuntime(origCI);
John McCalld70fb982011-06-15 23:25:17 +0000210
211 return CInvok.take();
212}
213
Benjamin Kramer3c05b7c2011-08-02 04:50:49 +0000214static void emitPremigrationErrors(const CapturedDiagList &arcDiags,
Douglas Gregor811db4e2012-10-23 22:26:28 +0000215 DiagnosticOptions *diagOpts,
Benjamin Kramer3c05b7c2011-08-02 04:50:49 +0000216 Preprocessor &PP) {
Argyrios Kyrtzidisd5713632011-07-19 17:20:03 +0000217 TextDiagnosticPrinter printer(llvm::errs(), diagOpts);
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000218 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
219 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
Douglas Gregor811db4e2012-10-23 22:26:28 +0000220 new DiagnosticsEngine(DiagID, diagOpts, &printer,
221 /*ShouldOwnClient=*/false));
Argyrios Kyrtzidisd5713632011-07-19 17:20:03 +0000222 Diags->setSourceManager(&PP.getSourceManager());
223
David Blaikiebbafb8a2012-03-11 07:00:24 +0000224 printer.BeginSourceFile(PP.getLangOpts(), &PP);
Argyrios Kyrtzidisd5713632011-07-19 17:20:03 +0000225 arcDiags.reportDiagnostics(*Diags);
226 printer.EndSourceFile();
227}
228
John McCalld70fb982011-06-15 23:25:17 +0000229//===----------------------------------------------------------------------===//
230// checkForManualIssues.
231//===----------------------------------------------------------------------===//
232
233bool arcmt::checkForManualIssues(CompilerInvocation &origCI,
Douglas Gregor32fbe312012-01-20 16:28:04 +0000234 const FrontendInputFile &Input,
David Blaikiee2eefae2011-09-25 23:39:51 +0000235 DiagnosticConsumer *DiagClient,
Argyrios Kyrtzidisd5713632011-07-19 17:20:03 +0000236 bool emitPremigrationARCErrors,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000237 StringRef plistOut) {
Ted Kremenek8cf47df2011-11-17 23:01:24 +0000238 if (!origCI.getLangOpts()->ObjC1)
John McCalld70fb982011-06-15 23:25:17 +0000239 return false;
240
Ted Kremenek8cf47df2011-11-17 23:01:24 +0000241 LangOptions::GCMode OrigGCMode = origCI.getLangOpts()->getGC();
Fariborz Jahanianaa7b9aa2012-01-25 00:20:29 +0000242 bool NoNSAllocReallocError = origCI.getMigratorOpts().NoNSAllocReallocError;
Fariborz Jahanian0c859d62012-01-26 00:08:04 +0000243 bool NoFinalizeRemoval = origCI.getMigratorOpts().NoFinalizeRemoval;
Argyrios Kyrtzidisd208ef92011-11-04 15:58:08 +0000244
Fariborz Jahanian48fd81b2012-01-26 20:57:58 +0000245 std::vector<TransformFn> transforms = arcmt::getAllTransformations(OrigGCMode,
246 NoFinalizeRemoval);
John McCalld70fb982011-06-15 23:25:17 +0000247 assert(!transforms.empty());
248
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000249 OwningPtr<CompilerInvocation> CInvok;
John McCalld70fb982011-06-15 23:25:17 +0000250 CInvok.reset(createInvocationForMigration(origCI));
251 CInvok->getFrontendOpts().Inputs.clear();
Douglas Gregor32fbe312012-01-20 16:28:04 +0000252 CInvok->getFrontendOpts().Inputs.push_back(Input);
John McCalld70fb982011-06-15 23:25:17 +0000253
254 CapturedDiagList capturedDiags;
255
256 assert(DiagClient);
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000257 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
258 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
Douglas Gregor811db4e2012-10-23 22:26:28 +0000259 new DiagnosticsEngine(DiagID, &origCI.getDiagnosticOpts(),
260 DiagClient, /*ShouldOwnClient=*/false));
John McCalld70fb982011-06-15 23:25:17 +0000261
262 // Filter of all diagnostics.
Jordan Roseb00073d2012-08-10 01:06:16 +0000263 CaptureDiagnosticConsumer errRec(*Diags, *DiagClient, capturedDiags);
John McCalld70fb982011-06-15 23:25:17 +0000264 Diags->setClient(&errRec, /*ShouldOwnClient=*/false);
265
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000266 OwningPtr<ASTUnit> Unit(
John McCalld70fb982011-06-15 23:25:17 +0000267 ASTUnit::LoadFromCompilerInvocationAction(CInvok.take(), Diags));
Jordan Roseb00073d2012-08-10 01:06:16 +0000268 if (!Unit) {
269 errRec.FinishCapture();
John McCalld70fb982011-06-15 23:25:17 +0000270 return true;
Jordan Roseb00073d2012-08-10 01:06:16 +0000271 }
John McCalld70fb982011-06-15 23:25:17 +0000272
Argyrios Kyrtzidisec852d92013-07-22 18:13:54 +0000273 bool hadARCErrors = capturedDiags.hasErrors();
274
John McCalld70fb982011-06-15 23:25:17 +0000275 // 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();
David Blaikiebbafb8a2012-03-11 07:00:24 +0000282 DiagClient->BeginSourceFile(Ctx.getLangOpts(), &Unit->getPreprocessor());
John McCalld70fb982011-06-15 23:25:17 +0000283 capturedDiags.reportDiagnostics(*Diags);
284 DiagClient->EndSourceFile();
Jordan Roseb00073d2012-08-10 01:06:16 +0000285 errRec.FinishCapture();
John McCalld70fb982011-06-15 23:25:17 +0000286 return true;
287 }
288
Argyrios Kyrtzidisd5713632011-07-19 17:20:03 +0000289 if (emitPremigrationARCErrors)
Douglas Gregor811db4e2012-10-23 22:26:28 +0000290 emitPremigrationErrors(capturedDiags, &origCI.getDiagnosticOpts(),
Argyrios Kyrtzidisd5713632011-07-19 17:20:03 +0000291 Unit->getPreprocessor());
292 if (!plistOut.empty()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000293 SmallVector<StoredDiagnostic, 8> arcDiags;
Argyrios Kyrtzidisd5713632011-07-19 17:20:03 +0000294 for (CapturedDiagList::iterator
295 I = capturedDiags.begin(), E = capturedDiags.end(); I != E; ++I)
296 arcDiags.push_back(*I);
297 writeARCDiagsToPlist(plistOut, arcDiags,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000298 Ctx.getSourceManager(), Ctx.getLangOpts());
Argyrios Kyrtzidisd5713632011-07-19 17:20:03 +0000299 }
300
John McCalld70fb982011-06-15 23:25:17 +0000301 // After parsing of source files ended, we want to reuse the
302 // diagnostics objects to emit further diagnostics.
David Blaikiee2eefae2011-09-25 23:39:51 +0000303 // We call BeginSourceFile because DiagnosticConsumer requires that
John McCalld70fb982011-06-15 23:25:17 +0000304 // diagnostics with source range information are emitted only in between
305 // BeginSourceFile() and EndSourceFile().
David Blaikiebbafb8a2012-03-11 07:00:24 +0000306 DiagClient->BeginSourceFile(Ctx.getLangOpts(), &Unit->getPreprocessor());
John McCalld70fb982011-06-15 23:25:17 +0000307
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());
Argyrios Kyrtzidis03fbe3e2013-01-04 18:30:08 +0000313 MigrationPass pass(Ctx, OrigGCMode, Unit->getSema(), testAct, capturedDiags,
314 ARCMTMacroLocs);
Fariborz Jahanianaa7b9aa2012-01-25 00:20:29 +0000315 pass.setNSAllocReallocError(NoNSAllocReallocError);
Fariborz Jahanian0c859d62012-01-26 00:08:04 +0000316 pass.setNoFinalizeRemoval(NoFinalizeRemoval);
John McCalld70fb982011-06-15 23:25:17 +0000317
318 for (unsigned i=0, e = transforms.size(); i != e; ++i)
319 transforms[i](pass);
320
321 capturedDiags.reportDiagnostics(*Diags);
322
323 DiagClient->EndSourceFile();
Jordan Roseb00073d2012-08-10 01:06:16 +0000324 errRec.FinishCapture();
John McCalld70fb982011-06-15 23:25:17 +0000325
Argyrios Kyrtzidisec852d92013-07-22 18:13:54 +0000326 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 }
Argyrios Kyrtzidise2e40b42011-07-14 00:17:54 +0000334
Argyrios Kyrtzidis73a0d322011-07-18 07:44:45 +0000335 return capturedDiags.hasErrors() || testAct.hasReportedErrors();
John McCalld70fb982011-06-15 23:25:17 +0000336}
337
338//===----------------------------------------------------------------------===//
339// applyTransformations.
340//===----------------------------------------------------------------------===//
341
Argyrios Kyrtzidis7fbd97f2011-07-09 20:00:58 +0000342static bool applyTransforms(CompilerInvocation &origCI,
Douglas Gregor32fbe312012-01-20 16:28:04 +0000343 const FrontendInputFile &Input,
David Blaikiee2eefae2011-09-25 23:39:51 +0000344 DiagnosticConsumer *DiagClient,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000345 StringRef outputDir,
Argyrios Kyrtzidisd5713632011-07-19 17:20:03 +0000346 bool emitPremigrationARCErrors,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000347 StringRef plistOut) {
Ted Kremenek8cf47df2011-11-17 23:01:24 +0000348 if (!origCI.getLangOpts()->ObjC1)
John McCalld70fb982011-06-15 23:25:17 +0000349 return false;
350
Ted Kremenek8cf47df2011-11-17 23:01:24 +0000351 LangOptions::GCMode OrigGCMode = origCI.getLangOpts()->getGC();
Argyrios Kyrtzidisd208ef92011-11-04 15:58:08 +0000352
John McCalld70fb982011-06-15 23:25:17 +0000353 // Make sure checking is successful first.
354 CompilerInvocation CInvokForCheck(origCI);
Douglas Gregor32fbe312012-01-20 16:28:04 +0000355 if (arcmt::checkForManualIssues(CInvokForCheck, Input, DiagClient,
Argyrios Kyrtzidisd5713632011-07-19 17:20:03 +0000356 emitPremigrationARCErrors, plistOut))
John McCalld70fb982011-06-15 23:25:17 +0000357 return true;
358
359 CompilerInvocation CInvok(origCI);
360 CInvok.getFrontendOpts().Inputs.clear();
Douglas Gregor32fbe312012-01-20 16:28:04 +0000361 CInvok.getFrontendOpts().Inputs.push_back(Input);
John McCalld70fb982011-06-15 23:25:17 +0000362
Argyrios Kyrtzidis7fbd97f2011-07-09 20:00:58 +0000363 MigrationProcess migration(CInvok, DiagClient, outputDir);
Fariborz Jahanian48fd81b2012-01-26 20:57:58 +0000364 bool NoFinalizeRemoval = origCI.getMigratorOpts().NoFinalizeRemoval;
John McCalld70fb982011-06-15 23:25:17 +0000365
Fariborz Jahanian48fd81b2012-01-26 20:57:58 +0000366 std::vector<TransformFn> transforms = arcmt::getAllTransformations(OrigGCMode,
367 NoFinalizeRemoval);
John McCalld70fb982011-06-15 23:25:17 +0000368 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
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000375 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
376 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
Douglas Gregor811db4e2012-10-23 22:26:28 +0000377 new DiagnosticsEngine(DiagID, &origCI.getDiagnosticOpts(),
378 DiagClient, /*ShouldOwnClient=*/false));
Argyrios Kyrtzidis7fbd97f2011-07-09 20:00:58 +0000379
380 if (outputDir.empty()) {
Ted Kremenek8cf47df2011-11-17 23:01:24 +0000381 origCI.getLangOpts()->ObjCAutoRefCount = true;
Argyrios Kyrtzidis7fbd97f2011-07-09 20:00:58 +0000382 return migration.getRemapper().overwriteOriginal(*Diags);
Argyrios Kyrtzidise2e40b42011-07-14 00:17:54 +0000383 } else {
Argyrios Kyrtzidisec852d92013-07-22 18:13:54 +0000384 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 }
Argyrios Kyrtzidis7fbd97f2011-07-09 20:00:58 +0000392 return migration.getRemapper().flushToDisk(outputDir, *Diags);
Argyrios Kyrtzidise2e40b42011-07-14 00:17:54 +0000393 }
Argyrios Kyrtzidis7fbd97f2011-07-09 20:00:58 +0000394}
395
396bool arcmt::applyTransformations(CompilerInvocation &origCI,
Douglas Gregor32fbe312012-01-20 16:28:04 +0000397 const FrontendInputFile &Input,
David Blaikiee2eefae2011-09-25 23:39:51 +0000398 DiagnosticConsumer *DiagClient) {
Douglas Gregor32fbe312012-01-20 16:28:04 +0000399 return applyTransforms(origCI, Input, DiagClient,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000400 StringRef(), false, StringRef());
Argyrios Kyrtzidis7fbd97f2011-07-09 20:00:58 +0000401}
402
403bool arcmt::migrateWithTemporaryFiles(CompilerInvocation &origCI,
Douglas Gregor32fbe312012-01-20 16:28:04 +0000404 const FrontendInputFile &Input,
David Blaikiee2eefae2011-09-25 23:39:51 +0000405 DiagnosticConsumer *DiagClient,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000406 StringRef outputDir,
Argyrios Kyrtzidisd5713632011-07-19 17:20:03 +0000407 bool emitPremigrationARCErrors,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000408 StringRef plistOut) {
Argyrios Kyrtzidis7fbd97f2011-07-09 20:00:58 +0000409 assert(!outputDir.empty() && "Expected output directory path");
Douglas Gregor32fbe312012-01-20 16:28:04 +0000410 return applyTransforms(origCI, Input, DiagClient,
Argyrios Kyrtzidisd5713632011-07-19 17:20:03 +0000411 outputDir, emitPremigrationARCErrors, plistOut);
Argyrios Kyrtzidis7fbd97f2011-07-09 20:00:58 +0000412}
413
414bool arcmt::getFileRemappings(std::vector<std::pair<std::string,std::string> > &
415 remap,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000416 StringRef outputDir,
David Blaikiee2eefae2011-09-25 23:39:51 +0000417 DiagnosticConsumer *DiagClient) {
Argyrios Kyrtzidis7fbd97f2011-07-09 20:00:58 +0000418 assert(!outputDir.empty());
John McCalld70fb982011-06-15 23:25:17 +0000419
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000420 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
421 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
Douglas Gregor811db4e2012-10-23 22:26:28 +0000422 new DiagnosticsEngine(DiagID, new DiagnosticOptions,
423 DiagClient, /*ShouldOwnClient=*/false));
Argyrios Kyrtzidis7fbd97f2011-07-09 20:00:58 +0000424
425 FileRemapper remapper;
426 bool err = remapper.initFromDisk(outputDir, *Diags,
427 /*ignoreIfFilesChanged=*/true);
428 if (err)
429 return true;
430
Ted Kremenekf7639e12012-03-06 20:06:33 +0000431 PreprocessorOptions PPOpts;
432 remapper.applyMappings(PPOpts);
433 remap = PPOpts.RemappedFiles;
Argyrios Kyrtzidis7fbd97f2011-07-09 20:00:58 +0000434
435 return false;
John McCalld70fb982011-06-15 23:25:17 +0000436}
437
Ted Kremenekf7639e12012-03-06 20:06:33 +0000438bool 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
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000445 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
446 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
Douglas Gregor811db4e2012-10-23 22:26:28 +0000447 new DiagnosticsEngine(DiagID, new DiagnosticOptions,
448 DiagClient, /*ShouldOwnClient=*/false));
Ted Kremenekf7639e12012-03-06 20:06:33 +0000449
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
John McCalld70fb982011-06-15 23:25:17 +0000477//===----------------------------------------------------------------------===//
John McCalld70fb982011-06-15 23:25:17 +0000478// CollectTransformActions.
479//===----------------------------------------------------------------------===//
480
481namespace {
482
483class ARCMTMacroTrackerPPCallbacks : public PPCallbacks {
484 std::vector<SourceLocation> &ARCMTMacroLocs;
485
486public:
487 ARCMTMacroTrackerPPCallbacks(std::vector<SourceLocation> &ARCMTMacroLocs)
488 : ARCMTMacroLocs(ARCMTMacroLocs) { }
489
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +0000490 virtual void MacroExpands(const Token &MacroNameTok, const MacroDirective *MD,
Argyrios Kyrtzidis37e48ff2013-05-03 22:31:32 +0000491 SourceRange Range, const MacroArgs *Args) {
John McCalld70fb982011-06-15 23:25:17 +0000492 if (MacroNameTok.getIdentifierInfo()->getName() == getARCMTMacroName())
493 ARCMTMacroLocs.push_back(MacroNameTok.getLocation());
494 }
495};
496
497class ARCMTMacroTrackerAction : public ASTFrontendAction {
498 std::vector<SourceLocation> &ARCMTMacroLocs;
499
500public:
501 ARCMTMacroTrackerAction(std::vector<SourceLocation> &ARCMTMacroLocs)
502 : ARCMTMacroLocs(ARCMTMacroLocs) { }
503
504 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000505 StringRef InFile) {
John McCalld70fb982011-06-15 23:25:17 +0000506 CI.getPreprocessor().addPPCallbacks(
507 new ARCMTMacroTrackerPPCallbacks(ARCMTMacroLocs));
508 return new ASTConsumer();
509 }
510};
511
512class RewritesApplicator : public TransformActions::RewriteReceiver {
513 Rewriter &rewriter;
John McCalld70fb982011-06-15 23:25:17 +0000514 MigrationProcess::RewriteListener *Listener;
515
516public:
517 RewritesApplicator(Rewriter &rewriter, ASTContext &ctx,
518 MigrationProcess::RewriteListener *listener)
Benjamin Kramerd1d76b22012-06-06 17:32:50 +0000519 : rewriter(rewriter), Listener(listener) {
John McCalld70fb982011-06-15 23:25:17 +0000520 if (Listener)
521 Listener->start(ctx);
522 }
523 ~RewritesApplicator() {
524 if (Listener)
525 Listener->finish();
526 }
527
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000528 virtual void insert(SourceLocation loc, StringRef text) {
John McCalld70fb982011-06-15 23:25:17 +0000529 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.
555MigrationProcess::RewriteListener::~RewriteListener() { }
556
Argyrios Kyrtzidis7fbd97f2011-07-09 20:00:58 +0000557MigrationProcess::MigrationProcess(const CompilerInvocation &CI,
David Blaikiee2eefae2011-09-25 23:39:51 +0000558 DiagnosticConsumer *diagClient,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000559 StringRef outputDir)
Argyrios Kyrtzidisec852d92013-07-22 18:13:54 +0000560 : OrigCI(CI), DiagClient(diagClient), HadARCErrors(false) {
Argyrios Kyrtzidis7fbd97f2011-07-09 20:00:58 +0000561 if (!outputDir.empty()) {
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000562 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
563 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
Douglas Gregor811db4e2012-10-23 22:26:28 +0000564 new DiagnosticsEngine(DiagID, &CI.getDiagnosticOpts(),
565 DiagClient, /*ShouldOwnClient=*/false));
Argyrios Kyrtzidis7fbd97f2011-07-09 20:00:58 +0000566 Remapper.initFromDisk(outputDir, *Diags, /*ignoreIfFilesChanges=*/true);
567 }
568}
569
John McCalld70fb982011-06-15 23:25:17 +0000570bool MigrationProcess::applyTransform(TransformFn trans,
571 RewriteListener *listener) {
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000572 OwningPtr<CompilerInvocation> CInvok;
John McCalld70fb982011-06-15 23:25:17 +0000573 CInvok.reset(createInvocationForMigration(OrigCI));
574 CInvok->getDiagnosticOpts().IgnoreWarnings = true;
575
Ted Kremenekf7639e12012-03-06 20:06:33 +0000576 Remapper.applyMappings(CInvok->getPreprocessorOpts());
John McCalld70fb982011-06-15 23:25:17 +0000577
578 CapturedDiagList capturedDiags;
579 std::vector<SourceLocation> ARCMTMacroLocs;
580
581 assert(DiagClient);
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000582 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
583 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
Douglas Gregor811db4e2012-10-23 22:26:28 +0000584 new DiagnosticsEngine(DiagID, new DiagnosticOptions,
585 DiagClient, /*ShouldOwnClient=*/false));
John McCalld70fb982011-06-15 23:25:17 +0000586
587 // Filter of all diagnostics.
Jordan Roseb00073d2012-08-10 01:06:16 +0000588 CaptureDiagnosticConsumer errRec(*Diags, *DiagClient, capturedDiags);
John McCalld70fb982011-06-15 23:25:17 +0000589 Diags->setClient(&errRec, /*ShouldOwnClient=*/false);
590
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000591 OwningPtr<ARCMTMacroTrackerAction> ASTAction;
John McCalld70fb982011-06-15 23:25:17 +0000592 ASTAction.reset(new ARCMTMacroTrackerAction(ARCMTMacroLocs));
593
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000594 OwningPtr<ASTUnit> Unit(
John McCalld70fb982011-06-15 23:25:17 +0000595 ASTUnit::LoadFromCompilerInvocationAction(CInvok.take(), Diags,
596 ASTAction.get()));
Jordan Roseb00073d2012-08-10 01:06:16 +0000597 if (!Unit) {
598 errRec.FinishCapture();
John McCalld70fb982011-06-15 23:25:17 +0000599 return true;
Jordan Roseb00073d2012-08-10 01:06:16 +0000600 }
John McCalld70fb982011-06-15 23:25:17 +0000601 Unit->setOwnsRemappedFileBuffers(false); // FileRemapper manages that.
602
Argyrios Kyrtzidisec852d92013-07-22 18:13:54 +0000603 HadARCErrors = HadARCErrors || capturedDiags.hasErrors();
604
John McCalld70fb982011-06-15 23:25:17 +0000605 // 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();
David Blaikiebbafb8a2012-03-11 07:00:24 +0000612 DiagClient->BeginSourceFile(Ctx.getLangOpts(), &Unit->getPreprocessor());
John McCalld70fb982011-06-15 23:25:17 +0000613 capturedDiags.reportDiagnostics(*Diags);
614 DiagClient->EndSourceFile();
Jordan Roseb00073d2012-08-10 01:06:16 +0000615 errRec.FinishCapture();
John McCalld70fb982011-06-15 23:25:17 +0000616 return true;
617 }
618
619 // After parsing of source files ended, we want to reuse the
620 // diagnostics objects to emit further diagnostics.
David Blaikiee2eefae2011-09-25 23:39:51 +0000621 // We call BeginSourceFile because DiagnosticConsumer requires that
John McCalld70fb982011-06-15 23:25:17 +0000622 // diagnostics with source range information are emitted only in between
623 // BeginSourceFile() and EndSourceFile().
David Blaikiebbafb8a2012-03-11 07:00:24 +0000624 DiagClient->BeginSourceFile(Ctx.getLangOpts(), &Unit->getPreprocessor());
John McCalld70fb982011-06-15 23:25:17 +0000625
David Blaikiebbafb8a2012-03-11 07:00:24 +0000626 Rewriter rewriter(Ctx.getSourceManager(), Ctx.getLangOpts());
John McCalld70fb982011-06-15 23:25:17 +0000627 TransformActions TA(*Diags, capturedDiags, Ctx, Unit->getPreprocessor());
Ted Kremenek8cf47df2011-11-17 23:01:24 +0000628 MigrationPass pass(Ctx, OrigCI.getLangOpts()->getGC(),
Argyrios Kyrtzidis03fbe3e2013-01-04 18:30:08 +0000629 Unit->getSema(), TA, capturedDiags, ARCMTMacroLocs);
John McCalld70fb982011-06-15 23:25:17 +0000630
631 trans(pass);
632
633 {
634 RewritesApplicator applicator(rewriter, Ctx, listener);
635 TA.applyRewrites(applicator);
636 }
637
638 DiagClient->EndSourceFile();
Jordan Roseb00073d2012-08-10 01:06:16 +0000639 errRec.FinishCapture();
John McCalld70fb982011-06-15 23:25:17 +0000640
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";
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000652 SmallString<512> newText;
John McCalld70fb982011-06-15 23:25:17 +0000653 llvm::raw_svector_ostream vecOS(newText);
654 buf.write(vecOS);
655 vecOS.flush();
656 llvm::MemoryBuffer *memBuf = llvm::MemoryBuffer::getMemBufferCopy(
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000657 StringRef(newText.data(), newText.size()), newFname);
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000658 SmallString<64> filePath(file->getName());
John McCalld70fb982011-06-15 23:25:17 +0000659 Unit->getFileManager().FixupRelativePath(filePath);
660 Remapper.remap(filePath.str(), memBuf);
661 }
662
663 return false;
664}