blob: 09752f0d612c8a0dc26985e366e50abe72614553 [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"
11#include "clang/Frontend/ASTUnit.h"
12#include "clang/Frontend/CompilerInstance.h"
Douglas Gregor32fbe312012-01-20 16:28:04 +000013#include "clang/Frontend/FrontendAction.h"
Argyrios Kyrtzidisd5713632011-07-19 17:20:03 +000014#include "clang/Frontend/TextDiagnosticPrinter.h"
John McCalld70fb982011-06-15 23:25:17 +000015#include "clang/Frontend/Utils.h"
16#include "clang/AST/ASTConsumer.h"
17#include "clang/Rewrite/Rewriter.h"
18#include "clang/Sema/SemaDiagnostic.h"
19#include "clang/Basic/DiagnosticCategories.h"
20#include "clang/Lex/Preprocessor.h"
21#include "llvm/Support/MemoryBuffer.h"
22#include "llvm/ADT/Triple.h"
John McCalld70fb982011-06-15 23:25:17 +000023using namespace clang;
24using namespace arcmt;
John McCalld70fb982011-06-15 23:25:17 +000025
Chris Lattner54b16772011-07-23 17:14:25 +000026bool CapturedDiagList::clearDiagnostic(ArrayRef<unsigned> IDs,
John McCalld70fb982011-06-15 23:25:17 +000027 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++;
David Blaikie9c902b52011-09-25 23:23:43 +000042 while (I != List.end() && I->getLevel() == DiagnosticsEngine::Note)
John McCalld70fb982011-06-15 23:25:17 +000043 ++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
Chris Lattner54b16772011-07-23 17:14:25 +000055bool CapturedDiagList::hasDiagnostic(ArrayRef<unsigned> IDs,
Argyrios Kyrtzidis0f3f9f72011-06-18 00:53:34 +000056 SourceRange range) const {
John McCalld70fb982011-06-15 23:25:17 +000057 if (range.isInvalid())
58 return false;
59
Argyrios Kyrtzidis0f3f9f72011-06-18 00:53:34 +000060 ListTy::const_iterator I = List.begin();
John McCalld70fb982011-06-15 23:25:17 +000061 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
David Blaikie9c902b52011-09-25 23:23:43 +000077void CapturedDiagList::reportDiagnostics(DiagnosticsEngine &Diags) const {
Argyrios Kyrtzidis0f3f9f72011-06-18 00:53:34 +000078 for (ListTy::const_iterator I = List.begin(), E = List.end(); I != E; ++I)
John McCalld70fb982011-06-15 23:25:17 +000079 Diags.Report(*I);
80}
81
Argyrios Kyrtzidis90b6a2a2011-06-18 00:53:41 +000082bool CapturedDiagList::hasErrors() const {
83 for (ListTy::const_iterator I = List.begin(), E = List.end(); I != E; ++I)
David Blaikie9c902b52011-09-25 23:23:43 +000084 if (I->getLevel() >= DiagnosticsEngine::Error)
Argyrios Kyrtzidis90b6a2a2011-06-18 00:53:41 +000085 return true;
86
87 return false;
88}
89
John McCalld70fb982011-06-15 23:25:17 +000090namespace {
91
David Blaikiea24a0bc2011-09-25 23:54:33 +000092class CaptureDiagnosticConsumer : public DiagnosticConsumer {
David Blaikie9c902b52011-09-25 23:23:43 +000093 DiagnosticsEngine &Diags;
John McCalld70fb982011-06-15 23:25:17 +000094 CapturedDiagList &CapturedDiags;
95public:
David Blaikiea24a0bc2011-09-25 23:54:33 +000096 CaptureDiagnosticConsumer(DiagnosticsEngine &diags,
Douglas Gregord0e9e3a2011-09-29 00:38:00 +000097 CapturedDiagList &capturedDiags)
John McCalld70fb982011-06-15 23:25:17 +000098 : Diags(diags), CapturedDiags(capturedDiags) { }
99
David Blaikie9c902b52011-09-25 23:23:43 +0000100 virtual void HandleDiagnostic(DiagnosticsEngine::Level level,
David Blaikieb5784322011-09-26 01:18:08 +0000101 const Diagnostic &Info) {
Ted Kremenek337c5b82011-10-20 05:07:47 +0000102 if (DiagnosticIDs::isARCDiagnostic(Info.getID()) ||
David Blaikie9c902b52011-09-25 23:23:43 +0000103 level >= DiagnosticsEngine::Error || level == DiagnosticsEngine::Note) {
John McCalld70fb982011-06-15 23:25:17 +0000104 CapturedDiags.push_back(StoredDiagnostic(level, Info));
105 return;
106 }
107
108 // Non-ARC warnings are ignored.
109 Diags.setLastDiagnosticIgnored();
110 }
Douglas Gregord0e9e3a2011-09-29 00:38:00 +0000111
112 DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
113 // Just drop any diagnostics that come from cloned consumers; they'll
114 // have different source managers anyway.
115 return new IgnoringDiagConsumer();
116 }
John McCalld70fb982011-06-15 23:25:17 +0000117};
118
119} // end anonymous namespace
120
Argyrios Kyrtzidis697729a2011-10-18 00:22:49 +0000121static inline StringRef SimulatorVersionDefineName() {
122 return "__IPHONE_OS_VERSION_MIN_REQUIRED=";
123}
124
125/// \brief Parse the simulator version define:
126/// __IPHONE_OS_VERSION_MIN_REQUIRED=([0-9])([0-9][0-9])([0-9][0-9])
127// and return the grouped values as integers, e.g:
128// __IPHONE_OS_VERSION_MIN_REQUIRED=40201
129// will return Major=4, Minor=2, Micro=1.
130static bool GetVersionFromSimulatorDefine(StringRef define,
131 unsigned &Major, unsigned &Minor,
132 unsigned &Micro) {
133 assert(define.startswith(SimulatorVersionDefineName()));
134 StringRef name, version;
135 llvm::tie(name, version) = define.split('=');
136 if (version.empty())
137 return false;
138 std::string verstr = version.str();
139 char *end;
140 unsigned num = (unsigned) strtol(verstr.c_str(), &end, 10);
141 if (*end != '\0')
142 return false;
143 Major = num / 10000;
144 num = num % 10000;
145 Minor = num / 100;
146 Micro = num % 100;
147 return true;
148}
149
Argyrios Kyrtzidis81a35902011-06-20 19:59:52 +0000150static bool HasARCRuntime(CompilerInvocation &origCI) {
151 // This duplicates some functionality from Darwin::AddDeploymentTarget
152 // but this function is well defined, so keep it decoupled from the driver
153 // and avoid unrelated complications.
154
Argyrios Kyrtzidis697729a2011-10-18 00:22:49 +0000155 for (unsigned i = 0, e = origCI.getPreprocessorOpts().Macros.size();
156 i != e; ++i) {
157 StringRef define = origCI.getPreprocessorOpts().Macros[i].first;
158 bool isUndef = origCI.getPreprocessorOpts().Macros[i].second;
159 if (isUndef)
160 continue;
161 if (!define.startswith(SimulatorVersionDefineName()))
162 continue;
163 unsigned Major = 0, Minor = 0, Micro = 0;
164 if (GetVersionFromSimulatorDefine(define, Major, Minor, Micro) &&
165 Major < 10 && Minor < 100 && Micro < 100)
166 return Major >= 5;
167 }
168
Argyrios Kyrtzidis81a35902011-06-20 19:59:52 +0000169 llvm::Triple triple(origCI.getTargetOpts().Triple);
170
171 if (triple.getOS() == llvm::Triple::IOS)
172 return triple.getOSMajorVersion() >= 5;
173
174 if (triple.getOS() == llvm::Triple::Darwin)
175 return triple.getOSMajorVersion() >= 11;
176
177 if (triple.getOS() == llvm::Triple::MacOSX) {
178 unsigned Major, Minor, Micro;
179 triple.getOSVersion(Major, Minor, Micro);
180 return Major > 10 || (Major == 10 && Minor >= 7);
181 }
182
183 return false;
184}
185
Benjamin Kramer3c05b7c2011-08-02 04:50:49 +0000186static CompilerInvocation *
187createInvocationForMigration(CompilerInvocation &origCI) {
John McCalld70fb982011-06-15 23:25:17 +0000188 llvm::OwningPtr<CompilerInvocation> CInvok;
189 CInvok.reset(new CompilerInvocation(origCI));
190 CInvok->getPreprocessorOpts().ImplicitPCHInclude = std::string();
191 CInvok->getPreprocessorOpts().ImplicitPTHInclude = std::string();
192 std::string define = getARCMTMacroName();
193 define += '=';
194 CInvok->getPreprocessorOpts().addMacroDef(define);
Ted Kremenek8cf47df2011-11-17 23:01:24 +0000195 CInvok->getLangOpts()->ObjCAutoRefCount = true;
196 CInvok->getLangOpts()->setGC(LangOptions::NonGC);
John McCalld70fb982011-06-15 23:25:17 +0000197 CInvok->getDiagnosticOpts().ErrorLimit = 0;
Argyrios Kyrtzidis59b5f352011-06-22 18:03:59 +0000198 CInvok->getDiagnosticOpts().Warnings.push_back(
199 "error=arc-unsafe-retained-assign");
Ted Kremenek8cf47df2011-11-17 23:01:24 +0000200 CInvok->getLangOpts()->ObjCRuntimeHasWeak = HasARCRuntime(origCI);
John McCalld70fb982011-06-15 23:25:17 +0000201
202 return CInvok.take();
203}
204
Benjamin Kramer3c05b7c2011-08-02 04:50:49 +0000205static void emitPremigrationErrors(const CapturedDiagList &arcDiags,
206 const DiagnosticOptions &diagOpts,
207 Preprocessor &PP) {
Argyrios Kyrtzidisd5713632011-07-19 17:20:03 +0000208 TextDiagnosticPrinter printer(llvm::errs(), diagOpts);
209 llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
David Blaikie9c902b52011-09-25 23:23:43 +0000210 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
211 new DiagnosticsEngine(DiagID, &printer, /*ShouldOwnClient=*/false));
Argyrios Kyrtzidisd5713632011-07-19 17:20:03 +0000212 Diags->setSourceManager(&PP.getSourceManager());
213
214 printer.BeginSourceFile(PP.getLangOptions(), &PP);
215 arcDiags.reportDiagnostics(*Diags);
216 printer.EndSourceFile();
217}
218
John McCalld70fb982011-06-15 23:25:17 +0000219//===----------------------------------------------------------------------===//
220// checkForManualIssues.
221//===----------------------------------------------------------------------===//
222
223bool arcmt::checkForManualIssues(CompilerInvocation &origCI,
Douglas Gregor32fbe312012-01-20 16:28:04 +0000224 const FrontendInputFile &Input,
David Blaikiee2eefae2011-09-25 23:39:51 +0000225 DiagnosticConsumer *DiagClient,
Argyrios Kyrtzidisd5713632011-07-19 17:20:03 +0000226 bool emitPremigrationARCErrors,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000227 StringRef plistOut) {
Ted Kremenek8cf47df2011-11-17 23:01:24 +0000228 if (!origCI.getLangOpts()->ObjC1)
John McCalld70fb982011-06-15 23:25:17 +0000229 return false;
230
Ted Kremenek8cf47df2011-11-17 23:01:24 +0000231 LangOptions::GCMode OrigGCMode = origCI.getLangOpts()->getGC();
Fariborz Jahanianaa7b9aa2012-01-25 00:20:29 +0000232 bool NoNSAllocReallocError = origCI.getMigratorOpts().NoNSAllocReallocError;
Argyrios Kyrtzidisd208ef92011-11-04 15:58:08 +0000233
234 std::vector<TransformFn> transforms = arcmt::getAllTransformations(OrigGCMode);
John McCalld70fb982011-06-15 23:25:17 +0000235 assert(!transforms.empty());
236
237 llvm::OwningPtr<CompilerInvocation> CInvok;
238 CInvok.reset(createInvocationForMigration(origCI));
239 CInvok->getFrontendOpts().Inputs.clear();
Douglas Gregor32fbe312012-01-20 16:28:04 +0000240 CInvok->getFrontendOpts().Inputs.push_back(Input);
John McCalld70fb982011-06-15 23:25:17 +0000241
242 CapturedDiagList capturedDiags;
243
244 assert(DiagClient);
245 llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
David Blaikie9c902b52011-09-25 23:23:43 +0000246 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
247 new DiagnosticsEngine(DiagID, DiagClient, /*ShouldOwnClient=*/false));
John McCalld70fb982011-06-15 23:25:17 +0000248
249 // Filter of all diagnostics.
David Blaikiea24a0bc2011-09-25 23:54:33 +0000250 CaptureDiagnosticConsumer errRec(*Diags, capturedDiags);
John McCalld70fb982011-06-15 23:25:17 +0000251 Diags->setClient(&errRec, /*ShouldOwnClient=*/false);
252
253 llvm::OwningPtr<ASTUnit> Unit(
254 ASTUnit::LoadFromCompilerInvocationAction(CInvok.take(), Diags));
255 if (!Unit)
256 return true;
257
258 // Don't filter diagnostics anymore.
259 Diags->setClient(DiagClient, /*ShouldOwnClient=*/false);
260
261 ASTContext &Ctx = Unit->getASTContext();
262
263 if (Diags->hasFatalErrorOccurred()) {
264 Diags->Reset();
265 DiagClient->BeginSourceFile(Ctx.getLangOptions(), &Unit->getPreprocessor());
266 capturedDiags.reportDiagnostics(*Diags);
267 DiagClient->EndSourceFile();
268 return true;
269 }
270
Argyrios Kyrtzidisd5713632011-07-19 17:20:03 +0000271 if (emitPremigrationARCErrors)
272 emitPremigrationErrors(capturedDiags, origCI.getDiagnosticOpts(),
273 Unit->getPreprocessor());
274 if (!plistOut.empty()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000275 SmallVector<StoredDiagnostic, 8> arcDiags;
Argyrios Kyrtzidisd5713632011-07-19 17:20:03 +0000276 for (CapturedDiagList::iterator
277 I = capturedDiags.begin(), E = capturedDiags.end(); I != E; ++I)
278 arcDiags.push_back(*I);
279 writeARCDiagsToPlist(plistOut, arcDiags,
280 Ctx.getSourceManager(), Ctx.getLangOptions());
281 }
282
John McCalld70fb982011-06-15 23:25:17 +0000283 // After parsing of source files ended, we want to reuse the
284 // diagnostics objects to emit further diagnostics.
David Blaikiee2eefae2011-09-25 23:39:51 +0000285 // We call BeginSourceFile because DiagnosticConsumer requires that
John McCalld70fb982011-06-15 23:25:17 +0000286 // diagnostics with source range information are emitted only in between
287 // BeginSourceFile() and EndSourceFile().
288 DiagClient->BeginSourceFile(Ctx.getLangOptions(), &Unit->getPreprocessor());
289
290 // No macros will be added since we are just checking and we won't modify
291 // source code.
292 std::vector<SourceLocation> ARCMTMacroLocs;
293
294 TransformActions testAct(*Diags, capturedDiags, Ctx, Unit->getPreprocessor());
Argyrios Kyrtzidisd208ef92011-11-04 15:58:08 +0000295 MigrationPass pass(Ctx, OrigGCMode, Unit->getSema(), testAct, ARCMTMacroLocs);
Fariborz Jahanianaa7b9aa2012-01-25 00:20:29 +0000296 pass.setNSAllocReallocError(NoNSAllocReallocError);
John McCalld70fb982011-06-15 23:25:17 +0000297
298 for (unsigned i=0, e = transforms.size(); i != e; ++i)
299 transforms[i](pass);
300
301 capturedDiags.reportDiagnostics(*Diags);
302
303 DiagClient->EndSourceFile();
304
Argyrios Kyrtzidise2e40b42011-07-14 00:17:54 +0000305 // If we are migrating code that gets the '-fobjc-arc' flag, make sure
306 // to remove it so that we don't get errors from normal compilation.
Ted Kremenek8cf47df2011-11-17 23:01:24 +0000307 origCI.getLangOpts()->ObjCAutoRefCount = false;
Argyrios Kyrtzidise2e40b42011-07-14 00:17:54 +0000308
Argyrios Kyrtzidis73a0d322011-07-18 07:44:45 +0000309 return capturedDiags.hasErrors() || testAct.hasReportedErrors();
John McCalld70fb982011-06-15 23:25:17 +0000310}
311
312//===----------------------------------------------------------------------===//
313// applyTransformations.
314//===----------------------------------------------------------------------===//
315
Argyrios Kyrtzidis7fbd97f2011-07-09 20:00:58 +0000316static bool applyTransforms(CompilerInvocation &origCI,
Douglas Gregor32fbe312012-01-20 16:28:04 +0000317 const FrontendInputFile &Input,
David Blaikiee2eefae2011-09-25 23:39:51 +0000318 DiagnosticConsumer *DiagClient,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000319 StringRef outputDir,
Argyrios Kyrtzidisd5713632011-07-19 17:20:03 +0000320 bool emitPremigrationARCErrors,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000321 StringRef plistOut) {
Ted Kremenek8cf47df2011-11-17 23:01:24 +0000322 if (!origCI.getLangOpts()->ObjC1)
John McCalld70fb982011-06-15 23:25:17 +0000323 return false;
324
Ted Kremenek8cf47df2011-11-17 23:01:24 +0000325 LangOptions::GCMode OrigGCMode = origCI.getLangOpts()->getGC();
Argyrios Kyrtzidisd208ef92011-11-04 15:58:08 +0000326
John McCalld70fb982011-06-15 23:25:17 +0000327 // Make sure checking is successful first.
328 CompilerInvocation CInvokForCheck(origCI);
Douglas Gregor32fbe312012-01-20 16:28:04 +0000329 if (arcmt::checkForManualIssues(CInvokForCheck, Input, DiagClient,
Argyrios Kyrtzidisd5713632011-07-19 17:20:03 +0000330 emitPremigrationARCErrors, plistOut))
John McCalld70fb982011-06-15 23:25:17 +0000331 return true;
332
333 CompilerInvocation CInvok(origCI);
334 CInvok.getFrontendOpts().Inputs.clear();
Douglas Gregor32fbe312012-01-20 16:28:04 +0000335 CInvok.getFrontendOpts().Inputs.push_back(Input);
John McCalld70fb982011-06-15 23:25:17 +0000336
Argyrios Kyrtzidis7fbd97f2011-07-09 20:00:58 +0000337 MigrationProcess migration(CInvok, DiagClient, outputDir);
John McCalld70fb982011-06-15 23:25:17 +0000338
Argyrios Kyrtzidisd208ef92011-11-04 15:58:08 +0000339 std::vector<TransformFn> transforms = arcmt::getAllTransformations(OrigGCMode);
John McCalld70fb982011-06-15 23:25:17 +0000340 assert(!transforms.empty());
341
342 for (unsigned i=0, e = transforms.size(); i != e; ++i) {
343 bool err = migration.applyTransform(transforms[i]);
344 if (err) return true;
345 }
346
Argyrios Kyrtzidis7fbd97f2011-07-09 20:00:58 +0000347 llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
David Blaikie9c902b52011-09-25 23:23:43 +0000348 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
349 new DiagnosticsEngine(DiagID, DiagClient, /*ShouldOwnClient=*/false));
Argyrios Kyrtzidis7fbd97f2011-07-09 20:00:58 +0000350
351 if (outputDir.empty()) {
Ted Kremenek8cf47df2011-11-17 23:01:24 +0000352 origCI.getLangOpts()->ObjCAutoRefCount = true;
Argyrios Kyrtzidis7fbd97f2011-07-09 20:00:58 +0000353 return migration.getRemapper().overwriteOriginal(*Diags);
Argyrios Kyrtzidise2e40b42011-07-14 00:17:54 +0000354 } else {
355 // If we are migrating code that gets the '-fobjc-arc' flag, make sure
356 // to remove it so that we don't get errors from normal compilation.
Ted Kremenek8cf47df2011-11-17 23:01:24 +0000357 origCI.getLangOpts()->ObjCAutoRefCount = false;
Argyrios Kyrtzidis7fbd97f2011-07-09 20:00:58 +0000358 return migration.getRemapper().flushToDisk(outputDir, *Diags);
Argyrios Kyrtzidise2e40b42011-07-14 00:17:54 +0000359 }
Argyrios Kyrtzidis7fbd97f2011-07-09 20:00:58 +0000360}
361
362bool arcmt::applyTransformations(CompilerInvocation &origCI,
Douglas Gregor32fbe312012-01-20 16:28:04 +0000363 const FrontendInputFile &Input,
David Blaikiee2eefae2011-09-25 23:39:51 +0000364 DiagnosticConsumer *DiagClient) {
Douglas Gregor32fbe312012-01-20 16:28:04 +0000365 return applyTransforms(origCI, Input, DiagClient,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000366 StringRef(), false, StringRef());
Argyrios Kyrtzidis7fbd97f2011-07-09 20:00:58 +0000367}
368
369bool arcmt::migrateWithTemporaryFiles(CompilerInvocation &origCI,
Douglas Gregor32fbe312012-01-20 16:28:04 +0000370 const FrontendInputFile &Input,
David Blaikiee2eefae2011-09-25 23:39:51 +0000371 DiagnosticConsumer *DiagClient,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000372 StringRef outputDir,
Argyrios Kyrtzidisd5713632011-07-19 17:20:03 +0000373 bool emitPremigrationARCErrors,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000374 StringRef plistOut) {
Argyrios Kyrtzidis7fbd97f2011-07-09 20:00:58 +0000375 assert(!outputDir.empty() && "Expected output directory path");
Douglas Gregor32fbe312012-01-20 16:28:04 +0000376 return applyTransforms(origCI, Input, DiagClient,
Argyrios Kyrtzidisd5713632011-07-19 17:20:03 +0000377 outputDir, emitPremigrationARCErrors, plistOut);
Argyrios Kyrtzidis7fbd97f2011-07-09 20:00:58 +0000378}
379
380bool arcmt::getFileRemappings(std::vector<std::pair<std::string,std::string> > &
381 remap,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000382 StringRef outputDir,
David Blaikiee2eefae2011-09-25 23:39:51 +0000383 DiagnosticConsumer *DiagClient) {
Argyrios Kyrtzidis7fbd97f2011-07-09 20:00:58 +0000384 assert(!outputDir.empty());
John McCalld70fb982011-06-15 23:25:17 +0000385
386 llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
David Blaikie9c902b52011-09-25 23:23:43 +0000387 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
388 new DiagnosticsEngine(DiagID, DiagClient, /*ShouldOwnClient=*/false));
Argyrios Kyrtzidis7fbd97f2011-07-09 20:00:58 +0000389
390 FileRemapper remapper;
391 bool err = remapper.initFromDisk(outputDir, *Diags,
392 /*ignoreIfFilesChanged=*/true);
393 if (err)
394 return true;
395
396 CompilerInvocation CI;
397 remapper.applyMappings(CI);
398 remap = CI.getPreprocessorOpts().RemappedFiles;
399
400 return false;
John McCalld70fb982011-06-15 23:25:17 +0000401}
402
403//===----------------------------------------------------------------------===//
John McCalld70fb982011-06-15 23:25:17 +0000404// CollectTransformActions.
405//===----------------------------------------------------------------------===//
406
407namespace {
408
409class ARCMTMacroTrackerPPCallbacks : public PPCallbacks {
410 std::vector<SourceLocation> &ARCMTMacroLocs;
411
412public:
413 ARCMTMacroTrackerPPCallbacks(std::vector<SourceLocation> &ARCMTMacroLocs)
414 : ARCMTMacroLocs(ARCMTMacroLocs) { }
415
Argyrios Kyrtzidis85a14bb2011-08-18 01:05:45 +0000416 virtual void MacroExpands(const Token &MacroNameTok, const MacroInfo *MI,
417 SourceRange Range) {
John McCalld70fb982011-06-15 23:25:17 +0000418 if (MacroNameTok.getIdentifierInfo()->getName() == getARCMTMacroName())
419 ARCMTMacroLocs.push_back(MacroNameTok.getLocation());
420 }
421};
422
423class ARCMTMacroTrackerAction : public ASTFrontendAction {
424 std::vector<SourceLocation> &ARCMTMacroLocs;
425
426public:
427 ARCMTMacroTrackerAction(std::vector<SourceLocation> &ARCMTMacroLocs)
428 : ARCMTMacroLocs(ARCMTMacroLocs) { }
429
430 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000431 StringRef InFile) {
John McCalld70fb982011-06-15 23:25:17 +0000432 CI.getPreprocessor().addPPCallbacks(
433 new ARCMTMacroTrackerPPCallbacks(ARCMTMacroLocs));
434 return new ASTConsumer();
435 }
436};
437
438class RewritesApplicator : public TransformActions::RewriteReceiver {
439 Rewriter &rewriter;
440 ASTContext &Ctx;
441 MigrationProcess::RewriteListener *Listener;
442
443public:
444 RewritesApplicator(Rewriter &rewriter, ASTContext &ctx,
445 MigrationProcess::RewriteListener *listener)
446 : rewriter(rewriter), Ctx(ctx), Listener(listener) {
447 if (Listener)
448 Listener->start(ctx);
449 }
450 ~RewritesApplicator() {
451 if (Listener)
452 Listener->finish();
453 }
454
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000455 virtual void insert(SourceLocation loc, StringRef text) {
John McCalld70fb982011-06-15 23:25:17 +0000456 bool err = rewriter.InsertText(loc, text, /*InsertAfter=*/true,
457 /*indentNewLines=*/true);
458 if (!err && Listener)
459 Listener->insert(loc, text);
460 }
461
462 virtual void remove(CharSourceRange range) {
463 Rewriter::RewriteOptions removeOpts;
464 removeOpts.IncludeInsertsAtBeginOfRange = false;
465 removeOpts.IncludeInsertsAtEndOfRange = false;
466 removeOpts.RemoveLineIfEmpty = true;
467
468 bool err = rewriter.RemoveText(range, removeOpts);
469 if (!err && Listener)
470 Listener->remove(range);
471 }
472
473 virtual void increaseIndentation(CharSourceRange range,
474 SourceLocation parentIndent) {
475 rewriter.IncreaseIndentation(range, parentIndent);
476 }
477};
478
479} // end anonymous namespace.
480
481/// \brief Anchor for VTable.
482MigrationProcess::RewriteListener::~RewriteListener() { }
483
Argyrios Kyrtzidis7fbd97f2011-07-09 20:00:58 +0000484MigrationProcess::MigrationProcess(const CompilerInvocation &CI,
David Blaikiee2eefae2011-09-25 23:39:51 +0000485 DiagnosticConsumer *diagClient,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000486 StringRef outputDir)
Argyrios Kyrtzidis7fbd97f2011-07-09 20:00:58 +0000487 : OrigCI(CI), DiagClient(diagClient) {
488 if (!outputDir.empty()) {
489 llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
David Blaikie9c902b52011-09-25 23:23:43 +0000490 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
491 new DiagnosticsEngine(DiagID, DiagClient, /*ShouldOwnClient=*/false));
Argyrios Kyrtzidis7fbd97f2011-07-09 20:00:58 +0000492 Remapper.initFromDisk(outputDir, *Diags, /*ignoreIfFilesChanges=*/true);
493 }
494}
495
John McCalld70fb982011-06-15 23:25:17 +0000496bool MigrationProcess::applyTransform(TransformFn trans,
497 RewriteListener *listener) {
498 llvm::OwningPtr<CompilerInvocation> CInvok;
499 CInvok.reset(createInvocationForMigration(OrigCI));
500 CInvok->getDiagnosticOpts().IgnoreWarnings = true;
501
502 Remapper.applyMappings(*CInvok);
503
504 CapturedDiagList capturedDiags;
505 std::vector<SourceLocation> ARCMTMacroLocs;
506
507 assert(DiagClient);
508 llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
David Blaikie9c902b52011-09-25 23:23:43 +0000509 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
510 new DiagnosticsEngine(DiagID, DiagClient, /*ShouldOwnClient=*/false));
John McCalld70fb982011-06-15 23:25:17 +0000511
512 // Filter of all diagnostics.
David Blaikiea24a0bc2011-09-25 23:54:33 +0000513 CaptureDiagnosticConsumer errRec(*Diags, capturedDiags);
John McCalld70fb982011-06-15 23:25:17 +0000514 Diags->setClient(&errRec, /*ShouldOwnClient=*/false);
515
516 llvm::OwningPtr<ARCMTMacroTrackerAction> ASTAction;
517 ASTAction.reset(new ARCMTMacroTrackerAction(ARCMTMacroLocs));
518
519 llvm::OwningPtr<ASTUnit> Unit(
520 ASTUnit::LoadFromCompilerInvocationAction(CInvok.take(), Diags,
521 ASTAction.get()));
522 if (!Unit)
523 return true;
524 Unit->setOwnsRemappedFileBuffers(false); // FileRemapper manages that.
525
526 // Don't filter diagnostics anymore.
527 Diags->setClient(DiagClient, /*ShouldOwnClient=*/false);
528
529 ASTContext &Ctx = Unit->getASTContext();
530
531 if (Diags->hasFatalErrorOccurred()) {
532 Diags->Reset();
533 DiagClient->BeginSourceFile(Ctx.getLangOptions(), &Unit->getPreprocessor());
534 capturedDiags.reportDiagnostics(*Diags);
535 DiagClient->EndSourceFile();
536 return true;
537 }
538
539 // After parsing of source files ended, we want to reuse the
540 // diagnostics objects to emit further diagnostics.
David Blaikiee2eefae2011-09-25 23:39:51 +0000541 // We call BeginSourceFile because DiagnosticConsumer requires that
John McCalld70fb982011-06-15 23:25:17 +0000542 // diagnostics with source range information are emitted only in between
543 // BeginSourceFile() and EndSourceFile().
544 DiagClient->BeginSourceFile(Ctx.getLangOptions(), &Unit->getPreprocessor());
545
546 Rewriter rewriter(Ctx.getSourceManager(), Ctx.getLangOptions());
547 TransformActions TA(*Diags, capturedDiags, Ctx, Unit->getPreprocessor());
Ted Kremenek8cf47df2011-11-17 23:01:24 +0000548 MigrationPass pass(Ctx, OrigCI.getLangOpts()->getGC(),
Argyrios Kyrtzidisd208ef92011-11-04 15:58:08 +0000549 Unit->getSema(), TA, ARCMTMacroLocs);
John McCalld70fb982011-06-15 23:25:17 +0000550
551 trans(pass);
552
553 {
554 RewritesApplicator applicator(rewriter, Ctx, listener);
555 TA.applyRewrites(applicator);
556 }
557
558 DiagClient->EndSourceFile();
559
560 if (DiagClient->getNumErrors())
561 return true;
562
563 for (Rewriter::buffer_iterator
564 I = rewriter.buffer_begin(), E = rewriter.buffer_end(); I != E; ++I) {
565 FileID FID = I->first;
566 RewriteBuffer &buf = I->second;
567 const FileEntry *file = Ctx.getSourceManager().getFileEntryForID(FID);
568 assert(file);
569 std::string newFname = file->getName();
570 newFname += "-trans";
571 llvm::SmallString<512> newText;
572 llvm::raw_svector_ostream vecOS(newText);
573 buf.write(vecOS);
574 vecOS.flush();
575 llvm::MemoryBuffer *memBuf = llvm::MemoryBuffer::getMemBufferCopy(
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000576 StringRef(newText.data(), newText.size()), newFname);
John McCalld70fb982011-06-15 23:25:17 +0000577 llvm::SmallString<64> filePath(file->getName());
578 Unit->getFileManager().FixupRelativePath(filePath);
579 Remapper.remap(filePath.str(), memBuf);
580 }
581
582 return false;
583}