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