blob: 3381ab5c82ead7ac52d507b9de2165c3d85200f9 [file] [log] [blame]
Haojian Wu357ef992016-09-21 13:18:19 +00001//===-- ClangMove.cpp - Implement ClangMove functationalities ---*- C++ -*-===//
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 "ClangMove.h"
Haojian Wu36265162017-01-03 09:00:51 +000011#include "HelperDeclRefGraph.h"
Haojian Wu357ef992016-09-21 13:18:19 +000012#include "clang/ASTMatchers/ASTMatchers.h"
13#include "clang/Basic/SourceManager.h"
14#include "clang/Format/Format.h"
15#include "clang/Frontend/CompilerInstance.h"
16#include "clang/Lex/Lexer.h"
17#include "clang/Lex/Preprocessor.h"
18#include "clang/Rewrite/Core/Rewriter.h"
19#include "clang/Tooling/Core/Replacement.h"
Haojian Wu36265162017-01-03 09:00:51 +000020#include "llvm/Support/Debug.h"
Haojian Wud2a6d7b2016-10-04 09:05:31 +000021#include "llvm/Support/Path.h"
Haojian Wu357ef992016-09-21 13:18:19 +000022
Haojian Wu36265162017-01-03 09:00:51 +000023#define DEBUG_TYPE "clang-move"
24
Haojian Wu357ef992016-09-21 13:18:19 +000025using namespace clang::ast_matchers;
26
27namespace clang {
28namespace move {
29namespace {
30
Haojian Wu7bd492c2016-10-14 10:07:58 +000031// FIXME: Move to ASTMatchers.
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +000032AST_MATCHER(VarDecl, isStaticDataMember) { return Node.isStaticDataMember(); }
Haojian Wu7bd492c2016-10-14 10:07:58 +000033
Haojian Wub3d98882017-01-17 10:08:11 +000034AST_MATCHER(NamedDecl, notInMacro) { return !Node.getLocation().isMacroID(); }
35
Haojian Wue77bcc72016-10-13 10:31:00 +000036AST_MATCHER_P(Decl, hasOutermostEnclosingClass,
37 ast_matchers::internal::Matcher<Decl>, InnerMatcher) {
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +000038 const auto *Context = Node.getDeclContext();
39 if (!Context)
40 return false;
Haojian Wue77bcc72016-10-13 10:31:00 +000041 while (const auto *NextContext = Context->getParent()) {
42 if (isa<NamespaceDecl>(NextContext) ||
43 isa<TranslationUnitDecl>(NextContext))
44 break;
45 Context = NextContext;
46 }
47 return InnerMatcher.matches(*Decl::castFromDeclContext(Context), Finder,
48 Builder);
49}
50
51AST_MATCHER_P(CXXMethodDecl, ofOutermostEnclosingClass,
52 ast_matchers::internal::Matcher<CXXRecordDecl>, InnerMatcher) {
53 const CXXRecordDecl *Parent = Node.getParent();
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +000054 if (!Parent)
55 return false;
Haojian Wue77bcc72016-10-13 10:31:00 +000056 while (const auto *NextParent =
57 dyn_cast<CXXRecordDecl>(Parent->getParent())) {
58 Parent = NextParent;
59 }
60
61 return InnerMatcher.matches(*Parent, Finder, Builder);
62}
63
Eric Liu5e721372018-05-17 12:40:50 +000064std::string CleanPath(StringRef PathRef) {
65 llvm::SmallString<128> Path(PathRef);
66 llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
67 return Path.str();
68}
69
Haojian Wud2a6d7b2016-10-04 09:05:31 +000070// Make the Path absolute using the CurrentDir if the Path is not an absolute
71// path. An empty Path will result in an empty string.
72std::string MakeAbsolutePath(StringRef CurrentDir, StringRef Path) {
73 if (Path.empty())
74 return "";
75 llvm::SmallString<128> InitialDirectory(CurrentDir);
76 llvm::SmallString<128> AbsolutePath(Path);
77 if (std::error_code EC =
78 llvm::sys::fs::make_absolute(InitialDirectory, AbsolutePath))
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +000079 llvm::errs() << "Warning: could not make absolute file: '" << EC.message()
Haojian Wud2a6d7b2016-10-04 09:05:31 +000080 << '\n';
Eric Liu5e721372018-05-17 12:40:50 +000081 return CleanPath(std::move(AbsolutePath));
Haojian Wud2a6d7b2016-10-04 09:05:31 +000082}
83
84// Make the Path absolute using the current working directory of the given
85// SourceManager if the Path is not an absolute path.
86//
87// The Path can be a path relative to the build directory, or retrieved from
88// the SourceManager.
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +000089std::string MakeAbsolutePath(const SourceManager &SM, StringRef Path) {
Haojian Wud2a6d7b2016-10-04 09:05:31 +000090 llvm::SmallString<128> AbsolutePath(Path);
91 if (std::error_code EC =
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +000092 SM.getFileManager().getVirtualFileSystem()->makeAbsolute(
93 AbsolutePath))
94 llvm::errs() << "Warning: could not make absolute file: '" << EC.message()
Haojian Wud2a6d7b2016-10-04 09:05:31 +000095 << '\n';
Haojian Wudb726572016-10-12 15:50:30 +000096 // Handle symbolic link path cases.
97 // We are trying to get the real file path of the symlink.
98 const DirectoryEntry *Dir = SM.getFileManager().getDirectory(
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +000099 llvm::sys::path::parent_path(AbsolutePath.str()));
Haojian Wudb726572016-10-12 15:50:30 +0000100 if (Dir) {
101 StringRef DirName = SM.getFileManager().getCanonicalName(Dir);
Eric Liuad3fed62018-05-16 20:10:10 +0000102 // FIXME: getCanonicalName might fail to get real path on VFS.
103 if (llvm::sys::path::is_absolute(DirName)) {
Eric Liu5e721372018-05-17 12:40:50 +0000104 SmallString<128> AbsoluteFilename;
Eric Liuad3fed62018-05-16 20:10:10 +0000105 llvm::sys::path::append(AbsoluteFilename, DirName,
106 llvm::sys::path::filename(AbsolutePath.str()));
Eric Liu5e721372018-05-17 12:40:50 +0000107 return CleanPath(AbsoluteFilename);
Eric Liuad3fed62018-05-16 20:10:10 +0000108 }
Haojian Wudb726572016-10-12 15:50:30 +0000109 }
Eric Liu5e721372018-05-17 12:40:50 +0000110 return CleanPath(AbsolutePath);
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000111}
112
113// Matches AST nodes that are expanded within the given AbsoluteFilePath.
114AST_POLYMORPHIC_MATCHER_P(isExpansionInFile,
115 AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc),
116 std::string, AbsoluteFilePath) {
117 auto &SourceManager = Finder->getASTContext().getSourceManager();
118 auto ExpansionLoc = SourceManager.getExpansionLoc(Node.getLocStart());
119 if (ExpansionLoc.isInvalid())
120 return false;
121 auto FileEntry =
122 SourceManager.getFileEntryForID(SourceManager.getFileID(ExpansionLoc));
123 if (!FileEntry)
124 return false;
125 return MakeAbsolutePath(SourceManager, FileEntry->getName()) ==
126 AbsoluteFilePath;
127}
128
Haojian Wu357ef992016-09-21 13:18:19 +0000129class FindAllIncludes : public clang::PPCallbacks {
130public:
131 explicit FindAllIncludes(SourceManager *SM, ClangMoveTool *const MoveTool)
132 : SM(*SM), MoveTool(MoveTool) {}
133
134 void InclusionDirective(clang::SourceLocation HashLoc,
135 const clang::Token & /*IncludeTok*/,
136 StringRef FileName, bool IsAngled,
Haojian Wu2930be12016-11-08 19:55:13 +0000137 clang::CharSourceRange FilenameRange,
Haojian Wu357ef992016-09-21 13:18:19 +0000138 const clang::FileEntry * /*File*/,
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000139 StringRef SearchPath, StringRef /*RelativePath*/,
Julie Hockett546943f2018-05-10 19:13:14 +0000140 const clang::Module * /*Imported*/,
141 SrcMgr::CharacteristicKind /*FileType*/) override {
Haojian Wudaf4cb82016-09-23 13:28:38 +0000142 if (const auto *FileEntry = SM.getFileEntryForID(SM.getFileID(HashLoc)))
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000143 MoveTool->addIncludes(FileName, IsAngled, SearchPath,
Haojian Wu2930be12016-11-08 19:55:13 +0000144 FileEntry->getName(), FilenameRange, SM);
Haojian Wu357ef992016-09-21 13:18:19 +0000145 }
146
147private:
148 const SourceManager &SM;
149 ClangMoveTool *const MoveTool;
150};
151
Haojian Wu32a552f2017-01-03 14:22:25 +0000152/// Add a declatration being moved to new.h/cc. Note that the declaration will
153/// also be deleted in old.h/cc.
154void MoveDeclFromOldFileToNewFile(ClangMoveTool *MoveTool, const NamedDecl *D) {
155 MoveTool->getMovedDecls().push_back(D);
156 MoveTool->addRemovedDecl(D);
157 MoveTool->getUnremovedDeclsInOldHeader().erase(D);
158}
159
Haojian Wu4543fec2016-11-16 13:05:19 +0000160class FunctionDeclarationMatch : public MatchFinder::MatchCallback {
161public:
162 explicit FunctionDeclarationMatch(ClangMoveTool *MoveTool)
163 : MoveTool(MoveTool) {}
164
165 void run(const MatchFinder::MatchResult &Result) override {
166 const auto *FD = Result.Nodes.getNodeAs<clang::FunctionDecl>("function");
167 assert(FD);
168 const clang::NamedDecl *D = FD;
169 if (const auto *FTD = FD->getDescribedFunctionTemplate())
170 D = FTD;
Haojian Wu32a552f2017-01-03 14:22:25 +0000171 MoveDeclFromOldFileToNewFile(MoveTool, D);
172 }
173
174private:
175 ClangMoveTool *MoveTool;
176};
177
Haojian Wu4a920502017-02-27 13:19:13 +0000178class VarDeclarationMatch : public MatchFinder::MatchCallback {
179public:
180 explicit VarDeclarationMatch(ClangMoveTool *MoveTool)
181 : MoveTool(MoveTool) {}
182
183 void run(const MatchFinder::MatchResult &Result) override {
184 const auto *VD = Result.Nodes.getNodeAs<clang::VarDecl>("var");
185 assert(VD);
186 MoveDeclFromOldFileToNewFile(MoveTool, VD);
187 }
188
189private:
190 ClangMoveTool *MoveTool;
191};
192
Haojian Wud69d9072017-01-04 14:50:49 +0000193class TypeAliasMatch : public MatchFinder::MatchCallback {
194public:
195 explicit TypeAliasMatch(ClangMoveTool *MoveTool)
196 : MoveTool(MoveTool) {}
197
198 void run(const MatchFinder::MatchResult &Result) override {
199 if (const auto *TD = Result.Nodes.getNodeAs<clang::TypedefDecl>("typedef"))
200 MoveDeclFromOldFileToNewFile(MoveTool, TD);
201 else if (const auto *TAD =
202 Result.Nodes.getNodeAs<clang::TypeAliasDecl>("type_alias")) {
203 const NamedDecl * D = TAD;
204 if (const auto * TD = TAD->getDescribedAliasTemplate())
205 D = TD;
206 MoveDeclFromOldFileToNewFile(MoveTool, D);
207 }
208 }
209
210private:
211 ClangMoveTool *MoveTool;
212};
213
Haojian Wu32a552f2017-01-03 14:22:25 +0000214class EnumDeclarationMatch : public MatchFinder::MatchCallback {
215public:
216 explicit EnumDeclarationMatch(ClangMoveTool *MoveTool)
217 : MoveTool(MoveTool) {}
218
219 void run(const MatchFinder::MatchResult &Result) override {
220 const auto *ED = Result.Nodes.getNodeAs<clang::EnumDecl>("enum");
221 assert(ED);
222 MoveDeclFromOldFileToNewFile(MoveTool, ED);
Haojian Wu4543fec2016-11-16 13:05:19 +0000223 }
224
225private:
226 ClangMoveTool *MoveTool;
227};
228
Haojian Wu35ca9462016-11-14 14:15:44 +0000229class ClassDeclarationMatch : public MatchFinder::MatchCallback {
230public:
231 explicit ClassDeclarationMatch(ClangMoveTool *MoveTool)
232 : MoveTool(MoveTool) {}
233 void run(const MatchFinder::MatchResult &Result) override {
234 clang::SourceManager* SM = &Result.Context->getSourceManager();
235 if (const auto *CMD =
236 Result.Nodes.getNodeAs<clang::CXXMethodDecl>("class_method"))
237 MatchClassMethod(CMD, SM);
238 else if (const auto *VD = Result.Nodes.getNodeAs<clang::VarDecl>(
239 "class_static_var_decl"))
240 MatchClassStaticVariable(VD, SM);
241 else if (const auto *CD = Result.Nodes.getNodeAs<clang::CXXRecordDecl>(
242 "moved_class"))
243 MatchClassDeclaration(CD, SM);
244 }
245
246private:
247 void MatchClassMethod(const clang::CXXMethodDecl* CMD,
248 clang::SourceManager* SM) {
249 // Skip inline class methods. isInline() ast matcher doesn't ignore this
250 // case.
251 if (!CMD->isInlined()) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000252 MoveTool->getMovedDecls().push_back(CMD);
253 MoveTool->addRemovedDecl(CMD);
Haojian Wu35ca9462016-11-14 14:15:44 +0000254 // Get template class method from its method declaration as
255 // UnremovedDecls stores template class method.
256 if (const auto *FTD = CMD->getDescribedFunctionTemplate())
257 MoveTool->getUnremovedDeclsInOldHeader().erase(FTD);
258 else
259 MoveTool->getUnremovedDeclsInOldHeader().erase(CMD);
260 }
261 }
262
263 void MatchClassStaticVariable(const clang::NamedDecl *VD,
264 clang::SourceManager* SM) {
Haojian Wu32a552f2017-01-03 14:22:25 +0000265 MoveDeclFromOldFileToNewFile(MoveTool, VD);
Haojian Wu35ca9462016-11-14 14:15:44 +0000266 }
267
268 void MatchClassDeclaration(const clang::CXXRecordDecl *CD,
269 clang::SourceManager* SM) {
270 // Get class template from its class declaration as UnremovedDecls stores
271 // class template.
272 if (const auto *TC = CD->getDescribedClassTemplate())
Haojian Wu08e402a2016-12-02 12:39:39 +0000273 MoveTool->getMovedDecls().push_back(TC);
Haojian Wu35ca9462016-11-14 14:15:44 +0000274 else
Haojian Wu08e402a2016-12-02 12:39:39 +0000275 MoveTool->getMovedDecls().push_back(CD);
Haojian Wu48ac3042016-11-23 10:04:19 +0000276 MoveTool->addRemovedDecl(MoveTool->getMovedDecls().back());
Haojian Wu35ca9462016-11-14 14:15:44 +0000277 MoveTool->getUnremovedDeclsInOldHeader().erase(
Haojian Wu08e402a2016-12-02 12:39:39 +0000278 MoveTool->getMovedDecls().back());
Haojian Wu35ca9462016-11-14 14:15:44 +0000279 }
280
281 ClangMoveTool *MoveTool;
282};
283
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000284// Expand to get the end location of the line where the EndLoc of the given
285// Decl.
286SourceLocation
Haojian Wu08e402a2016-12-02 12:39:39 +0000287getLocForEndOfDecl(const clang::Decl *D,
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000288 const LangOptions &LangOpts = clang::LangOptions()) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000289 const auto &SM = D->getASTContext().getSourceManager();
Richard Smith4bb15ab2018-04-30 05:26:07 +0000290 // If the expansion range is a character range, this is the location of
291 // the first character past the end. Otherwise it's the location of the
292 // first character in the final token in the range.
293 auto EndExpansionLoc = SM.getExpansionRange(D->getLocEnd()).getEnd();
Haojian Wudc4edba2016-12-13 15:35:47 +0000294 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(EndExpansionLoc);
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000295 // Try to load the file buffer.
296 bool InvalidTemp = false;
Haojian Wu08e402a2016-12-02 12:39:39 +0000297 llvm::StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000298 if (InvalidTemp)
299 return SourceLocation();
300
301 const char *TokBegin = File.data() + LocInfo.second;
302 // Lex from the start of the given location.
Haojian Wu08e402a2016-12-02 12:39:39 +0000303 Lexer Lex(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000304 TokBegin, File.end());
305
306 llvm::SmallVector<char, 16> Line;
307 // FIXME: this is a bit hacky to get ReadToEndOfLine work.
308 Lex.setParsingPreprocessorDirective(true);
309 Lex.ReadToEndOfLine(&Line);
Haojian Wudc4edba2016-12-13 15:35:47 +0000310 SourceLocation EndLoc = EndExpansionLoc.getLocWithOffset(Line.size());
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000311 // If we already reach EOF, just return the EOF SourceLocation;
312 // otherwise, move 1 offset ahead to include the trailing newline character
313 // '\n'.
Haojian Wu08e402a2016-12-02 12:39:39 +0000314 return SM.getLocForEndOfFile(LocInfo.first) == EndLoc
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000315 ? EndLoc
316 : EndLoc.getLocWithOffset(1);
317}
318
319// Get full range of a Decl including the comments associated with it.
320clang::CharSourceRange
Haojian Wu08e402a2016-12-02 12:39:39 +0000321getFullRange(const clang::Decl *D,
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000322 const clang::LangOptions &options = clang::LangOptions()) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000323 const auto &SM = D->getASTContext().getSourceManager();
324 clang::SourceRange Full(SM.getExpansionLoc(D->getLocStart()),
325 getLocForEndOfDecl(D));
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000326 // Expand to comments that are associated with the Decl.
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000327 if (const auto *Comment = D->getASTContext().getRawCommentForDeclNoCache(D)) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000328 if (SM.isBeforeInTranslationUnit(Full.getEnd(), Comment->getLocEnd()))
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000329 Full.setEnd(Comment->getLocEnd());
330 // FIXME: Don't delete a preceding comment, if there are no other entities
331 // it could refer to.
Haojian Wu08e402a2016-12-02 12:39:39 +0000332 if (SM.isBeforeInTranslationUnit(Comment->getLocStart(), Full.getBegin()))
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000333 Full.setBegin(Comment->getLocStart());
334 }
335
336 return clang::CharSourceRange::getCharRange(Full);
337}
338
Haojian Wu08e402a2016-12-02 12:39:39 +0000339std::string getDeclarationSourceText(const clang::Decl *D) {
340 const auto &SM = D->getASTContext().getSourceManager();
341 llvm::StringRef SourceText =
342 clang::Lexer::getSourceText(getFullRange(D), SM, clang::LangOptions());
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000343 return SourceText.str();
344}
345
Haojian Wu08e402a2016-12-02 12:39:39 +0000346bool isInHeaderFile(const clang::Decl *D,
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000347 llvm::StringRef OriginalRunningDirectory,
348 llvm::StringRef OldHeader) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000349 const auto &SM = D->getASTContext().getSourceManager();
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000350 if (OldHeader.empty())
Haojian Wu357ef992016-09-21 13:18:19 +0000351 return false;
352 auto ExpansionLoc = SM.getExpansionLoc(D->getLocStart());
353 if (ExpansionLoc.isInvalid())
354 return false;
355
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000356 if (const auto *FE = SM.getFileEntryForID(SM.getFileID(ExpansionLoc))) {
357 return MakeAbsolutePath(SM, FE->getName()) ==
358 MakeAbsolutePath(OriginalRunningDirectory, OldHeader);
359 }
Haojian Wu357ef992016-09-21 13:18:19 +0000360
361 return false;
362}
363
Haojian Wu08e402a2016-12-02 12:39:39 +0000364std::vector<std::string> getNamespaces(const clang::Decl *D) {
Haojian Wu357ef992016-09-21 13:18:19 +0000365 std::vector<std::string> Namespaces;
366 for (const auto *Context = D->getDeclContext(); Context;
367 Context = Context->getParent()) {
368 if (llvm::isa<clang::TranslationUnitDecl>(Context) ||
369 llvm::isa<clang::LinkageSpecDecl>(Context))
370 break;
371
372 if (const auto *ND = llvm::dyn_cast<clang::NamespaceDecl>(Context))
373 Namespaces.push_back(ND->getName().str());
374 }
375 std::reverse(Namespaces.begin(), Namespaces.end());
376 return Namespaces;
377}
378
Haojian Wu357ef992016-09-21 13:18:19 +0000379clang::tooling::Replacements
380createInsertedReplacements(const std::vector<std::string> &Includes,
Haojian Wu08e402a2016-12-02 12:39:39 +0000381 const std::vector<const NamedDecl *> &Decls,
Haojian Wu48ac3042016-11-23 10:04:19 +0000382 llvm::StringRef FileName, bool IsHeader = false,
383 StringRef OldHeaderInclude = "") {
Haojian Wu53eab1e2016-10-14 13:43:49 +0000384 std::string NewCode;
Haojian Wu220c7552016-10-14 13:01:36 +0000385 std::string GuardName(FileName);
386 if (IsHeader) {
Haojian Wuac97fc32016-10-17 15:26:34 +0000387 for (size_t i = 0; i < GuardName.size(); ++i) {
388 if (!isAlphanumeric(GuardName[i]))
389 GuardName[i] = '_';
390 }
Haojian Wu220c7552016-10-14 13:01:36 +0000391 GuardName = StringRef(GuardName).upper();
Haojian Wu53eab1e2016-10-14 13:43:49 +0000392 NewCode += "#ifndef " + GuardName + "\n";
Haojian Wu53315a72016-11-15 09:06:59 +0000393 NewCode += "#define " + GuardName + "\n\n";
Haojian Wu220c7552016-10-14 13:01:36 +0000394 }
Haojian Wu357ef992016-09-21 13:18:19 +0000395
Haojian Wu48ac3042016-11-23 10:04:19 +0000396 NewCode += OldHeaderInclude;
Haojian Wu357ef992016-09-21 13:18:19 +0000397 // Add #Includes.
Haojian Wu357ef992016-09-21 13:18:19 +0000398 for (const auto &Include : Includes)
Haojian Wu53eab1e2016-10-14 13:43:49 +0000399 NewCode += Include;
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000400
Haojian Wu53eab1e2016-10-14 13:43:49 +0000401 if (!Includes.empty())
402 NewCode += "\n";
Haojian Wu357ef992016-09-21 13:18:19 +0000403
404 // Add moved class definition and its related declarations. All declarations
405 // in same namespace are grouped together.
Haojian Wu53315a72016-11-15 09:06:59 +0000406 //
407 // Record namespaces where the current position is in.
Haojian Wu357ef992016-09-21 13:18:19 +0000408 std::vector<std::string> CurrentNamespaces;
Haojian Wu08e402a2016-12-02 12:39:39 +0000409 for (const auto *MovedDecl : Decls) {
Haojian Wu53315a72016-11-15 09:06:59 +0000410 // The namespaces of the declaration being moved.
Haojian Wu08e402a2016-12-02 12:39:39 +0000411 std::vector<std::string> DeclNamespaces = getNamespaces(MovedDecl);
Haojian Wu357ef992016-09-21 13:18:19 +0000412 auto CurrentIt = CurrentNamespaces.begin();
413 auto DeclIt = DeclNamespaces.begin();
Haojian Wu53315a72016-11-15 09:06:59 +0000414 // Skip the common prefix.
Haojian Wu357ef992016-09-21 13:18:19 +0000415 while (CurrentIt != CurrentNamespaces.end() &&
416 DeclIt != DeclNamespaces.end()) {
417 if (*CurrentIt != *DeclIt)
418 break;
419 ++CurrentIt;
420 ++DeclIt;
421 }
Haojian Wu53315a72016-11-15 09:06:59 +0000422 // Calculate the new namespaces after adding MovedDecl in CurrentNamespace,
423 // which is used for next iteration of this loop.
Haojian Wu357ef992016-09-21 13:18:19 +0000424 std::vector<std::string> NextNamespaces(CurrentNamespaces.begin(),
425 CurrentIt);
426 NextNamespaces.insert(NextNamespaces.end(), DeclIt, DeclNamespaces.end());
Haojian Wu53315a72016-11-15 09:06:59 +0000427
428
429 // End with CurrentNamespace.
430 bool HasEndCurrentNamespace = false;
Haojian Wu357ef992016-09-21 13:18:19 +0000431 auto RemainingSize = CurrentNamespaces.end() - CurrentIt;
432 for (auto It = CurrentNamespaces.rbegin(); RemainingSize > 0;
433 --RemainingSize, ++It) {
434 assert(It < CurrentNamespaces.rend());
Haojian Wu53eab1e2016-10-14 13:43:49 +0000435 NewCode += "} // namespace " + *It + "\n";
Haojian Wu53315a72016-11-15 09:06:59 +0000436 HasEndCurrentNamespace = true;
Haojian Wu357ef992016-09-21 13:18:19 +0000437 }
Haojian Wu53315a72016-11-15 09:06:59 +0000438 // Add trailing '\n' after the nested namespace definition.
439 if (HasEndCurrentNamespace)
440 NewCode += "\n";
441
442 // If the moved declaration is not in CurrentNamespace, add extra namespace
443 // definitions.
444 bool IsInNewNamespace = false;
Haojian Wu357ef992016-09-21 13:18:19 +0000445 while (DeclIt != DeclNamespaces.end()) {
Haojian Wu53eab1e2016-10-14 13:43:49 +0000446 NewCode += "namespace " + *DeclIt + " {\n";
Haojian Wu53315a72016-11-15 09:06:59 +0000447 IsInNewNamespace = true;
Haojian Wu357ef992016-09-21 13:18:19 +0000448 ++DeclIt;
449 }
Haojian Wu53315a72016-11-15 09:06:59 +0000450 // If the moved declaration is in same namespace CurrentNamespace, add
451 // a preceeding `\n' before the moved declaration.
Haojian Wu50a45d92016-11-18 10:51:16 +0000452 // FIXME: Don't add empty lines between using declarations.
Haojian Wu53315a72016-11-15 09:06:59 +0000453 if (!IsInNewNamespace)
454 NewCode += "\n";
Haojian Wu08e402a2016-12-02 12:39:39 +0000455 NewCode += getDeclarationSourceText(MovedDecl);
Haojian Wu357ef992016-09-21 13:18:19 +0000456 CurrentNamespaces = std::move(NextNamespaces);
457 }
458 std::reverse(CurrentNamespaces.begin(), CurrentNamespaces.end());
Haojian Wu53eab1e2016-10-14 13:43:49 +0000459 for (const auto &NS : CurrentNamespaces)
460 NewCode += "} // namespace " + NS + "\n";
Haojian Wu220c7552016-10-14 13:01:36 +0000461
Haojian Wu53eab1e2016-10-14 13:43:49 +0000462 if (IsHeader)
Haojian Wu53315a72016-11-15 09:06:59 +0000463 NewCode += "\n#endif // " + GuardName + "\n";
Haojian Wu53eab1e2016-10-14 13:43:49 +0000464 return clang::tooling::Replacements(
465 clang::tooling::Replacement(FileName, 0, 0, NewCode));
Haojian Wu357ef992016-09-21 13:18:19 +0000466}
467
Haojian Wu36265162017-01-03 09:00:51 +0000468// Return a set of all decls which are used/referenced by the given Decls.
469// Specically, given a class member declaration, this method will return all
470// decls which are used by the whole class.
471llvm::DenseSet<const Decl *>
472getUsedDecls(const HelperDeclRefGraph *RG,
473 const std::vector<const NamedDecl *> &Decls) {
474 assert(RG);
475 llvm::DenseSet<const CallGraphNode *> Nodes;
476 for (const auto *D : Decls) {
477 auto Result = RG->getReachableNodes(
478 HelperDeclRGBuilder::getOutmostClassOrFunDecl(D));
479 Nodes.insert(Result.begin(), Result.end());
480 }
481 llvm::DenseSet<const Decl *> Results;
482 for (const auto *Node : Nodes)
483 Results.insert(Node->getDecl());
484 return Results;
485}
486
Haojian Wu357ef992016-09-21 13:18:19 +0000487} // namespace
488
489std::unique_ptr<clang::ASTConsumer>
490ClangMoveAction::CreateASTConsumer(clang::CompilerInstance &Compiler,
491 StringRef /*InFile*/) {
492 Compiler.getPreprocessor().addPPCallbacks(llvm::make_unique<FindAllIncludes>(
493 &Compiler.getSourceManager(), &MoveTool));
494 return MatchFinder.newASTConsumer();
495}
496
Haojian Wub15c8da2016-11-24 10:17:17 +0000497ClangMoveTool::ClangMoveTool(ClangMoveContext *const Context,
498 DeclarationReporter *const Reporter)
499 : Context(Context), Reporter(Reporter) {
500 if (!Context->Spec.NewHeader.empty())
501 CCIncludes.push_back("#include \"" + Context->Spec.NewHeader + "\"\n");
Haojian Wu357ef992016-09-21 13:18:19 +0000502}
503
Haojian Wu08e402a2016-12-02 12:39:39 +0000504void ClangMoveTool::addRemovedDecl(const NamedDecl *Decl) {
505 const auto &SM = Decl->getASTContext().getSourceManager();
506 auto Loc = Decl->getLocation();
Haojian Wu48ac3042016-11-23 10:04:19 +0000507 StringRef FilePath = SM.getFilename(Loc);
508 FilePathToFileID[FilePath] = SM.getFileID(Loc);
509 RemovedDecls.push_back(Decl);
510}
511
Haojian Wu357ef992016-09-21 13:18:19 +0000512void ClangMoveTool::registerMatchers(ast_matchers::MatchFinder *Finder) {
Haojian Wub15c8da2016-11-24 10:17:17 +0000513 auto InOldHeader =
514 isExpansionInFile(makeAbsolutePath(Context->Spec.OldHeader));
515 auto InOldCC = isExpansionInFile(makeAbsolutePath(Context->Spec.OldCC));
Haojian Wu357ef992016-09-21 13:18:19 +0000516 auto InOldFiles = anyOf(InOldHeader, InOldCC);
Haojian Wu03c89632017-05-02 12:15:11 +0000517 auto classTemplateForwardDecls =
518 classTemplateDecl(unless(has(cxxRecordDecl(isDefinition()))));
519 auto ForwardClassDecls = namedDecl(
520 anyOf(cxxRecordDecl(unless(anyOf(isImplicit(), isDefinition()))),
521 classTemplateForwardDecls));
Haojian Wu32a552f2017-01-03 14:22:25 +0000522 auto TopLevelDecl =
523 hasDeclContext(anyOf(namespaceDecl(), translationUnitDecl()));
Haojian Wu2930be12016-11-08 19:55:13 +0000524
525 //============================================================================
526 // Matchers for old header
527 //============================================================================
528 // Match all top-level named declarations (e.g. function, variable, enum) in
529 // old header, exclude forward class declarations and namespace declarations.
530 //
Haojian Wub15c8da2016-11-24 10:17:17 +0000531 // We consider declarations inside a class belongs to the class. So these
532 // declarations will be ignored.
Haojian Wu2930be12016-11-08 19:55:13 +0000533 auto AllDeclsInHeader = namedDecl(
Haojian Wu03c89632017-05-02 12:15:11 +0000534 unless(ForwardClassDecls), unless(namespaceDecl()),
535 unless(usingDirectiveDecl()), // using namespace decl.
Haojian Wud4786342018-02-09 15:57:30 +0000536 notInMacro(),
Haojian Wu2930be12016-11-08 19:55:13 +0000537 InOldHeader,
Haojian Wub15c8da2016-11-24 10:17:17 +0000538 hasParent(decl(anyOf(namespaceDecl(), translationUnitDecl()))),
539 hasDeclContext(decl(anyOf(namespaceDecl(), translationUnitDecl()))));
Haojian Wu2930be12016-11-08 19:55:13 +0000540 Finder->addMatcher(AllDeclsInHeader.bind("decls_in_header"), this);
Haojian Wub15c8da2016-11-24 10:17:17 +0000541
542 // Don't register other matchers when dumping all declarations in header.
543 if (Context->DumpDeclarations)
544 return;
545
Haojian Wu2930be12016-11-08 19:55:13 +0000546 // Match forward declarations in old header.
Haojian Wu03c89632017-05-02 12:15:11 +0000547 Finder->addMatcher(namedDecl(ForwardClassDecls, InOldHeader).bind("fwd_decl"),
Haojian Wu2930be12016-11-08 19:55:13 +0000548 this);
549
550 //============================================================================
Haojian Wu2930be12016-11-08 19:55:13 +0000551 // Matchers for old cc
552 //============================================================================
Haojian Wu36265162017-01-03 09:00:51 +0000553 auto IsOldCCTopLevelDecl = allOf(
554 hasParent(decl(anyOf(namespaceDecl(), translationUnitDecl()))), InOldCC);
555 // Matching using decls/type alias decls which are in named/anonymous/global
556 // namespace, these decls are always copied to new.h/cc. Those in classes,
557 // functions are covered in other matchers.
Haojian Wub3d98882017-01-17 10:08:11 +0000558 Finder->addMatcher(namedDecl(anyOf(usingDecl(IsOldCCTopLevelDecl),
559 usingDirectiveDecl(IsOldCCTopLevelDecl),
560 typeAliasDecl(IsOldCCTopLevelDecl)),
561 notInMacro())
562 .bind("using_decl"),
563 this);
Haojian Wu357ef992016-09-21 13:18:19 +0000564
Haojian Wu67bb6512016-10-19 14:13:21 +0000565 // Match static functions/variable definitions which are defined in named
566 // namespaces.
Haojian Wub15c8da2016-11-24 10:17:17 +0000567 Optional<ast_matchers::internal::Matcher<NamedDecl>> HasAnySymbolNames;
568 for (StringRef SymbolName : Context->Spec.Names) {
569 llvm::StringRef GlobalSymbolName = SymbolName.trim().ltrim(':');
570 const auto HasName = hasName(("::" + GlobalSymbolName).str());
571 HasAnySymbolNames =
572 HasAnySymbolNames ? anyOf(*HasAnySymbolNames, HasName) : HasName;
573 }
574
575 if (!HasAnySymbolNames) {
576 llvm::errs() << "No symbols being moved.\n";
577 return;
578 }
579 auto InMovedClass =
580 hasOutermostEnclosingClass(cxxRecordDecl(*HasAnySymbolNames));
Haojian Wu36265162017-01-03 09:00:51 +0000581
582 // Matchers for helper declarations in old.cc.
583 auto InAnonymousNS = hasParent(namespaceDecl(isAnonymous()));
Haojian Wu4775ce52017-01-17 13:22:37 +0000584 auto NotInMovedClass= allOf(unless(InMovedClass), InOldCC);
585 auto IsOldCCHelper =
586 allOf(NotInMovedClass, anyOf(isStaticStorageClass(), InAnonymousNS));
Haojian Wu36265162017-01-03 09:00:51 +0000587 // Match helper classes separately with helper functions/variables since we
588 // want to reuse these matchers in finding helpers usage below.
Haojian Wu4775ce52017-01-17 13:22:37 +0000589 //
590 // There could be forward declarations usage for helpers, especially for
591 // classes and functions. We need include these forward declarations.
592 //
593 // Forward declarations for variable helpers will be excluded as these
594 // declarations (with "extern") are not supposed in cpp file.
595 auto HelperFuncOrVar =
596 namedDecl(notInMacro(), anyOf(functionDecl(IsOldCCHelper),
597 varDecl(isDefinition(), IsOldCCHelper)));
Haojian Wub3d98882017-01-17 10:08:11 +0000598 auto HelperClasses =
Haojian Wu4775ce52017-01-17 13:22:37 +0000599 cxxRecordDecl(notInMacro(), NotInMovedClass, InAnonymousNS);
Haojian Wu36265162017-01-03 09:00:51 +0000600 // Save all helper declarations in old.cc.
601 Finder->addMatcher(
602 namedDecl(anyOf(HelperFuncOrVar, HelperClasses)).bind("helper_decls"),
603 this);
604
605 // Construct an AST-based call graph of helper declarations in old.cc.
606 // In the following matcheres, "dc" is a caller while "helper_decls" and
607 // "used_class" is a callee, so a new edge starting from caller to callee will
608 // be add in the graph.
609 //
610 // Find helper function/variable usages.
611 Finder->addMatcher(
612 declRefExpr(to(HelperFuncOrVar), hasAncestor(decl().bind("dc")))
613 .bind("func_ref"),
614 &RGBuilder);
615 // Find helper class usages.
616 Finder->addMatcher(
617 typeLoc(loc(recordType(hasDeclaration(HelperClasses.bind("used_class")))),
618 hasAncestor(decl().bind("dc"))),
619 &RGBuilder);
Haojian Wu35ca9462016-11-14 14:15:44 +0000620
621 //============================================================================
622 // Matchers for old files, including old.h/old.cc
623 //============================================================================
624 // Create a MatchCallback for class declarations.
625 MatchCallbacks.push_back(llvm::make_unique<ClassDeclarationMatch>(this));
626 // Match moved class declarations.
Haojian Wu32a552f2017-01-03 14:22:25 +0000627 auto MovedClass = cxxRecordDecl(InOldFiles, *HasAnySymbolNames,
628 isDefinition(), TopLevelDecl)
629 .bind("moved_class");
Haojian Wu35ca9462016-11-14 14:15:44 +0000630 Finder->addMatcher(MovedClass, MatchCallbacks.back().get());
631 // Match moved class methods (static methods included) which are defined
632 // outside moved class declaration.
633 Finder->addMatcher(
Haojian Wu4543fec2016-11-16 13:05:19 +0000634 cxxMethodDecl(InOldFiles, ofOutermostEnclosingClass(*HasAnySymbolNames),
Haojian Wu35ca9462016-11-14 14:15:44 +0000635 isDefinition())
636 .bind("class_method"),
637 MatchCallbacks.back().get());
638 // Match static member variable definition of the moved class.
639 Finder->addMatcher(
640 varDecl(InMovedClass, InOldFiles, isDefinition(), isStaticDataMember())
641 .bind("class_static_var_decl"),
642 MatchCallbacks.back().get());
643
Haojian Wu4543fec2016-11-16 13:05:19 +0000644 MatchCallbacks.push_back(llvm::make_unique<FunctionDeclarationMatch>(this));
Haojian Wu32a552f2017-01-03 14:22:25 +0000645 Finder->addMatcher(functionDecl(InOldFiles, *HasAnySymbolNames, TopLevelDecl)
Haojian Wu4543fec2016-11-16 13:05:19 +0000646 .bind("function"),
647 MatchCallbacks.back().get());
Haojian Wu32a552f2017-01-03 14:22:25 +0000648
Haojian Wu4a920502017-02-27 13:19:13 +0000649 MatchCallbacks.push_back(llvm::make_unique<VarDeclarationMatch>(this));
650 Finder->addMatcher(
651 varDecl(InOldFiles, *HasAnySymbolNames, TopLevelDecl).bind("var"),
652 MatchCallbacks.back().get());
653
Haojian Wud69d9072017-01-04 14:50:49 +0000654 // Match enum definition in old.h. Enum helpers (which are defined in old.cc)
Haojian Wu32a552f2017-01-03 14:22:25 +0000655 // will not be moved for now no matter whether they are used or not.
656 MatchCallbacks.push_back(llvm::make_unique<EnumDeclarationMatch>(this));
657 Finder->addMatcher(
658 enumDecl(InOldHeader, *HasAnySymbolNames, isDefinition(), TopLevelDecl)
659 .bind("enum"),
660 MatchCallbacks.back().get());
Haojian Wud69d9072017-01-04 14:50:49 +0000661
662 // Match type alias in old.h, this includes "typedef" and "using" type alias
663 // declarations. Type alias helpers (which are defined in old.cc) will not be
664 // moved for now no matter whether they are used or not.
665 MatchCallbacks.push_back(llvm::make_unique<TypeAliasMatch>(this));
666 Finder->addMatcher(namedDecl(anyOf(typedefDecl().bind("typedef"),
667 typeAliasDecl().bind("type_alias")),
668 InOldHeader, *HasAnySymbolNames, TopLevelDecl),
669 MatchCallbacks.back().get());
Haojian Wu357ef992016-09-21 13:18:19 +0000670}
671
672void ClangMoveTool::run(const ast_matchers::MatchFinder::MatchResult &Result) {
Haojian Wu2930be12016-11-08 19:55:13 +0000673 if (const auto *D =
674 Result.Nodes.getNodeAs<clang::NamedDecl>("decls_in_header")) {
675 UnremovedDeclsInOldHeader.insert(D);
Haojian Wu357ef992016-09-21 13:18:19 +0000676 } else if (const auto *FWD =
677 Result.Nodes.getNodeAs<clang::CXXRecordDecl>("fwd_decl")) {
Haojian Wub15c8da2016-11-24 10:17:17 +0000678 // Skip all forward declarations which appear after moved class declaration.
Haojian Wu29c38f72016-10-21 19:26:43 +0000679 if (RemovedDecls.empty()) {
Haojian Wub53ec462016-11-10 05:33:26 +0000680 if (const auto *DCT = FWD->getDescribedClassTemplate())
Haojian Wu08e402a2016-12-02 12:39:39 +0000681 MovedDecls.push_back(DCT);
Haojian Wub53ec462016-11-10 05:33:26 +0000682 else
Haojian Wu08e402a2016-12-02 12:39:39 +0000683 MovedDecls.push_back(FWD);
Haojian Wu29c38f72016-10-21 19:26:43 +0000684 }
Haojian Wu357ef992016-09-21 13:18:19 +0000685 } else if (const auto *ND =
Haojian Wu36265162017-01-03 09:00:51 +0000686 Result.Nodes.getNodeAs<clang::NamedDecl>("helper_decls")) {
687 MovedDecls.push_back(ND);
688 HelperDeclarations.push_back(ND);
Nicola Zaghen0efd5242018-05-15 16:37:45 +0000689 LLVM_DEBUG(llvm::dbgs() << "Add helper : " << ND->getNameAsString() << " ("
690 << ND << ")\n");
Haojian Wu67bb6512016-10-19 14:13:21 +0000691 } else if (const auto *UD =
692 Result.Nodes.getNodeAs<clang::NamedDecl>("using_decl")) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000693 MovedDecls.push_back(UD);
Haojian Wu357ef992016-09-21 13:18:19 +0000694 }
695}
696
Haojian Wu2930be12016-11-08 19:55:13 +0000697std::string ClangMoveTool::makeAbsolutePath(StringRef Path) {
Haojian Wub15c8da2016-11-24 10:17:17 +0000698 return MakeAbsolutePath(Context->OriginalRunningDirectory, Path);
Haojian Wu2930be12016-11-08 19:55:13 +0000699}
700
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000701void ClangMoveTool::addIncludes(llvm::StringRef IncludeHeader, bool IsAngled,
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000702 llvm::StringRef SearchPath,
703 llvm::StringRef FileName,
Haojian Wu2930be12016-11-08 19:55:13 +0000704 clang::CharSourceRange IncludeFilenameRange,
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000705 const SourceManager &SM) {
Haojian Wudb726572016-10-12 15:50:30 +0000706 SmallVector<char, 128> HeaderWithSearchPath;
707 llvm::sys::path::append(HeaderWithSearchPath, SearchPath, IncludeHeader);
Haojian Wufb68ca12018-01-31 12:12:29 +0000708 std::string AbsoluteIncludeHeader =
Haojian Wudb726572016-10-12 15:50:30 +0000709 MakeAbsolutePath(SM, llvm::StringRef(HeaderWithSearchPath.data(),
Haojian Wufb68ca12018-01-31 12:12:29 +0000710 HeaderWithSearchPath.size()));
Haojian Wudaf4cb82016-09-23 13:28:38 +0000711 std::string IncludeLine =
712 IsAngled ? ("#include <" + IncludeHeader + ">\n").str()
713 : ("#include \"" + IncludeHeader + "\"\n").str();
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000714
Haojian Wufb68ca12018-01-31 12:12:29 +0000715 std::string AbsoluteOldHeader = makeAbsolutePath(Context->Spec.OldHeader);
Haojian Wudb726572016-10-12 15:50:30 +0000716 std::string AbsoluteCurrentFile = MakeAbsolutePath(SM, FileName);
717 if (AbsoluteOldHeader == AbsoluteCurrentFile) {
Haojian Wufb68ca12018-01-31 12:12:29 +0000718 // Find old.h includes "old.h".
719 if (AbsoluteOldHeader == AbsoluteIncludeHeader) {
720 OldHeaderIncludeRangeInHeader = IncludeFilenameRange;
721 return;
722 }
Haojian Wudaf4cb82016-09-23 13:28:38 +0000723 HeaderIncludes.push_back(IncludeLine);
Haojian Wub15c8da2016-11-24 10:17:17 +0000724 } else if (makeAbsolutePath(Context->Spec.OldCC) == AbsoluteCurrentFile) {
Haojian Wufb68ca12018-01-31 12:12:29 +0000725 // Find old.cc includes "old.h".
726 if (AbsoluteOldHeader == AbsoluteIncludeHeader) {
727 OldHeaderIncludeRangeInCC = IncludeFilenameRange;
728 return;
729 }
Haojian Wudaf4cb82016-09-23 13:28:38 +0000730 CCIncludes.push_back(IncludeLine);
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000731 }
Haojian Wu357ef992016-09-21 13:18:19 +0000732}
733
Haojian Wu08e402a2016-12-02 12:39:39 +0000734void ClangMoveTool::removeDeclsInOldFiles() {
Haojian Wu48ac3042016-11-23 10:04:19 +0000735 if (RemovedDecls.empty()) return;
Haojian Wu36265162017-01-03 09:00:51 +0000736
737 // If old_header is not specified (only move declarations from old.cc), remain
738 // all the helper function declarations in old.cc as UnremovedDeclsInOldHeader
739 // is empty in this case, there is no way to verify unused/used helpers.
740 if (!Context->Spec.OldHeader.empty()) {
741 std::vector<const NamedDecl *> UnremovedDecls;
742 for (const auto *D : UnremovedDeclsInOldHeader)
743 UnremovedDecls.push_back(D);
744
745 auto UsedDecls = getUsedDecls(RGBuilder.getGraph(), UnremovedDecls);
746
747 // We remove the helper declarations which are not used in the old.cc after
748 // moving the given declarations.
749 for (const auto *D : HelperDeclarations) {
Nicola Zaghen0efd5242018-05-15 16:37:45 +0000750 LLVM_DEBUG(llvm::dbgs() << "Check helper is used: "
751 << D->getNameAsString() << " (" << D << ")\n");
Haojian Wu4775ce52017-01-17 13:22:37 +0000752 if (!UsedDecls.count(HelperDeclRGBuilder::getOutmostClassOrFunDecl(
753 D->getCanonicalDecl()))) {
Nicola Zaghen0efd5242018-05-15 16:37:45 +0000754 LLVM_DEBUG(llvm::dbgs() << "Helper removed in old.cc: "
755 << D->getNameAsString() << " (" << D << ")\n");
Haojian Wu36265162017-01-03 09:00:51 +0000756 RemovedDecls.push_back(D);
757 }
758 }
759 }
760
Haojian Wu08e402a2016-12-02 12:39:39 +0000761 for (const auto *RemovedDecl : RemovedDecls) {
762 const auto &SM = RemovedDecl->getASTContext().getSourceManager();
763 auto Range = getFullRange(RemovedDecl);
Haojian Wu357ef992016-09-21 13:18:19 +0000764 clang::tooling::Replacement RemoveReplacement(
Haojian Wu48ac3042016-11-23 10:04:19 +0000765 SM,
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000766 clang::CharSourceRange::getCharRange(Range.getBegin(), Range.getEnd()),
Haojian Wu357ef992016-09-21 13:18:19 +0000767 "");
768 std::string FilePath = RemoveReplacement.getFilePath().str();
Haojian Wub15c8da2016-11-24 10:17:17 +0000769 auto Err = Context->FileToReplacements[FilePath].add(RemoveReplacement);
Haojian Wu48ac3042016-11-23 10:04:19 +0000770 if (Err)
Haojian Wu53eab1e2016-10-14 13:43:49 +0000771 llvm::errs() << llvm::toString(std::move(Err)) << "\n";
Haojian Wu48ac3042016-11-23 10:04:19 +0000772 }
Haojian Wu08e402a2016-12-02 12:39:39 +0000773 const auto &SM = RemovedDecls[0]->getASTContext().getSourceManager();
Haojian Wu48ac3042016-11-23 10:04:19 +0000774
775 // Post process of cleanup around all the replacements.
Haojian Wub15c8da2016-11-24 10:17:17 +0000776 for (auto &FileAndReplacements : Context->FileToReplacements) {
Haojian Wu48ac3042016-11-23 10:04:19 +0000777 StringRef FilePath = FileAndReplacements.first;
778 // Add #include of new header to old header.
Haojian Wub15c8da2016-11-24 10:17:17 +0000779 if (Context->Spec.OldDependOnNew &&
Haojian Wu08e402a2016-12-02 12:39:39 +0000780 MakeAbsolutePath(SM, FilePath) ==
Haojian Wub15c8da2016-11-24 10:17:17 +0000781 makeAbsolutePath(Context->Spec.OldHeader)) {
Haojian Wu48ac3042016-11-23 10:04:19 +0000782 // FIXME: Minimize the include path like include-fixer.
Haojian Wub15c8da2016-11-24 10:17:17 +0000783 std::string IncludeNewH =
784 "#include \"" + Context->Spec.NewHeader + "\"\n";
Haojian Wu48ac3042016-11-23 10:04:19 +0000785 // This replacment for inserting header will be cleaned up at the end.
786 auto Err = FileAndReplacements.second.add(
787 tooling::Replacement(FilePath, UINT_MAX, 0, IncludeNewH));
788 if (Err)
789 llvm::errs() << llvm::toString(std::move(Err)) << "\n";
Haojian Wu53eab1e2016-10-14 13:43:49 +0000790 }
Haojian Wu253d5962016-10-06 08:29:32 +0000791
Haojian Wu48ac3042016-11-23 10:04:19 +0000792 auto SI = FilePathToFileID.find(FilePath);
793 // Ignore replacements for new.h/cc.
794 if (SI == FilePathToFileID.end()) continue;
Haojian Wu08e402a2016-12-02 12:39:39 +0000795 llvm::StringRef Code = SM.getBufferData(SI->second);
Antonio Maiorano0d7d9c22017-01-17 00:13:32 +0000796 auto Style = format::getStyle("file", FilePath, Context->FallbackStyle);
797 if (!Style) {
798 llvm::errs() << llvm::toString(Style.takeError()) << "\n";
799 continue;
800 }
Haojian Wu253d5962016-10-06 08:29:32 +0000801 auto CleanReplacements = format::cleanupAroundReplacements(
Antonio Maiorano0d7d9c22017-01-17 00:13:32 +0000802 Code, Context->FileToReplacements[FilePath], *Style);
Haojian Wu253d5962016-10-06 08:29:32 +0000803
804 if (!CleanReplacements) {
805 llvm::errs() << llvm::toString(CleanReplacements.takeError()) << "\n";
806 continue;
807 }
Haojian Wub15c8da2016-11-24 10:17:17 +0000808 Context->FileToReplacements[FilePath] = *CleanReplacements;
Haojian Wu357ef992016-09-21 13:18:19 +0000809 }
810}
811
Haojian Wu08e402a2016-12-02 12:39:39 +0000812void ClangMoveTool::moveDeclsToNewFiles() {
813 std::vector<const NamedDecl *> NewHeaderDecls;
814 std::vector<const NamedDecl *> NewCCDecls;
815 for (const auto *MovedDecl : MovedDecls) {
816 if (isInHeaderFile(MovedDecl, Context->OriginalRunningDirectory,
Haojian Wub15c8da2016-11-24 10:17:17 +0000817 Context->Spec.OldHeader))
Haojian Wu357ef992016-09-21 13:18:19 +0000818 NewHeaderDecls.push_back(MovedDecl);
819 else
820 NewCCDecls.push_back(MovedDecl);
821 }
822
Haojian Wu36265162017-01-03 09:00:51 +0000823 auto UsedDecls = getUsedDecls(RGBuilder.getGraph(), RemovedDecls);
824 std::vector<const NamedDecl *> ActualNewCCDecls;
825
826 // Filter out all unused helpers in NewCCDecls.
827 // We only move the used helpers (including transively used helpers) and the
828 // given symbols being moved.
829 for (const auto *D : NewCCDecls) {
830 if (llvm::is_contained(HelperDeclarations, D) &&
Haojian Wu4775ce52017-01-17 13:22:37 +0000831 !UsedDecls.count(HelperDeclRGBuilder::getOutmostClassOrFunDecl(
832 D->getCanonicalDecl())))
Haojian Wu36265162017-01-03 09:00:51 +0000833 continue;
834
Nicola Zaghen0efd5242018-05-15 16:37:45 +0000835 LLVM_DEBUG(llvm::dbgs() << "Helper used in new.cc: " << D->getNameAsString()
836 << " " << D << "\n");
Haojian Wu36265162017-01-03 09:00:51 +0000837 ActualNewCCDecls.push_back(D);
838 }
839
Haojian Wub15c8da2016-11-24 10:17:17 +0000840 if (!Context->Spec.NewHeader.empty()) {
Haojian Wu48ac3042016-11-23 10:04:19 +0000841 std::string OldHeaderInclude =
Haojian Wub15c8da2016-11-24 10:17:17 +0000842 Context->Spec.NewDependOnOld
843 ? "#include \"" + Context->Spec.OldHeader + "\"\n"
844 : "";
845 Context->FileToReplacements[Context->Spec.NewHeader] =
846 createInsertedReplacements(HeaderIncludes, NewHeaderDecls,
847 Context->Spec.NewHeader, /*IsHeader=*/true,
848 OldHeaderInclude);
Haojian Wu48ac3042016-11-23 10:04:19 +0000849 }
Haojian Wub15c8da2016-11-24 10:17:17 +0000850 if (!Context->Spec.NewCC.empty())
851 Context->FileToReplacements[Context->Spec.NewCC] =
Haojian Wu36265162017-01-03 09:00:51 +0000852 createInsertedReplacements(CCIncludes, ActualNewCCDecls,
853 Context->Spec.NewCC);
Haojian Wu357ef992016-09-21 13:18:19 +0000854}
855
Haojian Wu2930be12016-11-08 19:55:13 +0000856// Move all contents from OldFile to NewFile.
857void ClangMoveTool::moveAll(SourceManager &SM, StringRef OldFile,
858 StringRef NewFile) {
859 const FileEntry *FE = SM.getFileManager().getFile(makeAbsolutePath(OldFile));
860 if (!FE) {
861 llvm::errs() << "Failed to get file: " << OldFile << "\n";
862 return;
863 }
864 FileID ID = SM.getOrCreateFileID(FE, SrcMgr::C_User);
865 auto Begin = SM.getLocForStartOfFile(ID);
866 auto End = SM.getLocForEndOfFile(ID);
867 clang::tooling::Replacement RemoveAll (
868 SM, clang::CharSourceRange::getCharRange(Begin, End), "");
869 std::string FilePath = RemoveAll.getFilePath().str();
Haojian Wub15c8da2016-11-24 10:17:17 +0000870 Context->FileToReplacements[FilePath] =
871 clang::tooling::Replacements(RemoveAll);
Haojian Wu2930be12016-11-08 19:55:13 +0000872
873 StringRef Code = SM.getBufferData(ID);
874 if (!NewFile.empty()) {
875 auto AllCode = clang::tooling::Replacements(
876 clang::tooling::Replacement(NewFile, 0, 0, Code));
Haojian Wufb68ca12018-01-31 12:12:29 +0000877 auto ReplaceOldInclude = [&](clang::CharSourceRange OldHeaderIncludeRange) {
878 AllCode = AllCode.merge(clang::tooling::Replacements(
879 clang::tooling::Replacement(SM, OldHeaderIncludeRange,
880 '"' + Context->Spec.NewHeader + '"')));
881 };
882 // Fix the case where old.h/old.cc includes "old.h", we replace the
883 // `#include "old.h"` with `#include "new.h"`.
884 if (Context->Spec.NewCC == NewFile && OldHeaderIncludeRangeInCC.isValid())
885 ReplaceOldInclude(OldHeaderIncludeRangeInCC);
886 else if (Context->Spec.NewHeader == NewFile &&
887 OldHeaderIncludeRangeInHeader.isValid())
888 ReplaceOldInclude(OldHeaderIncludeRangeInHeader);
Haojian Wub15c8da2016-11-24 10:17:17 +0000889 Context->FileToReplacements[NewFile] = std::move(AllCode);
Haojian Wu2930be12016-11-08 19:55:13 +0000890 }
891}
892
Haojian Wu357ef992016-09-21 13:18:19 +0000893void ClangMoveTool::onEndOfTranslationUnit() {
Haojian Wub15c8da2016-11-24 10:17:17 +0000894 if (Context->DumpDeclarations) {
895 assert(Reporter);
896 for (const auto *Decl : UnremovedDeclsInOldHeader) {
897 auto Kind = Decl->getKind();
898 const std::string QualifiedName = Decl->getQualifiedNameAsString();
Haojian Wu4a920502017-02-27 13:19:13 +0000899 if (Kind == Decl::Kind::Var)
900 Reporter->reportDeclaration(QualifiedName, "Variable");
901 else if (Kind == Decl::Kind::Function ||
902 Kind == Decl::Kind::FunctionTemplate)
Haojian Wub15c8da2016-11-24 10:17:17 +0000903 Reporter->reportDeclaration(QualifiedName, "Function");
904 else if (Kind == Decl::Kind::ClassTemplate ||
905 Kind == Decl::Kind::CXXRecord)
906 Reporter->reportDeclaration(QualifiedName, "Class");
Haojian Wu85867722017-01-16 09:34:07 +0000907 else if (Kind == Decl::Kind::Enum)
908 Reporter->reportDeclaration(QualifiedName, "Enum");
909 else if (Kind == Decl::Kind::Typedef ||
910 Kind == Decl::Kind::TypeAlias ||
911 Kind == Decl::Kind::TypeAliasTemplate)
912 Reporter->reportDeclaration(QualifiedName, "TypeAlias");
Haojian Wub15c8da2016-11-24 10:17:17 +0000913 }
914 return;
915 }
916
Haojian Wu357ef992016-09-21 13:18:19 +0000917 if (RemovedDecls.empty())
918 return;
Haojian Wud4786342018-02-09 15:57:30 +0000919 // Ignore symbols that are not supported when checking if there is unremoved
920 // symbol in old header. This makes sure that we always move old files to new
921 // files when all symbols produced from dump_decls are moved.
Eric Liu47a42d52016-12-06 10:12:23 +0000922 auto IsSupportedKind = [](const clang::NamedDecl *Decl) {
923 switch (Decl->getKind()) {
924 case Decl::Kind::Function:
925 case Decl::Kind::FunctionTemplate:
926 case Decl::Kind::ClassTemplate:
927 case Decl::Kind::CXXRecord:
Haojian Wu32a552f2017-01-03 14:22:25 +0000928 case Decl::Kind::Enum:
Haojian Wud69d9072017-01-04 14:50:49 +0000929 case Decl::Kind::Typedef:
930 case Decl::Kind::TypeAlias:
931 case Decl::Kind::TypeAliasTemplate:
Haojian Wu4a920502017-02-27 13:19:13 +0000932 case Decl::Kind::Var:
Eric Liu47a42d52016-12-06 10:12:23 +0000933 return true;
934 default:
935 return false;
936 }
937 };
938 if (std::none_of(UnremovedDeclsInOldHeader.begin(),
939 UnremovedDeclsInOldHeader.end(), IsSupportedKind) &&
940 !Context->Spec.OldHeader.empty()) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000941 auto &SM = RemovedDecls[0]->getASTContext().getSourceManager();
Haojian Wub15c8da2016-11-24 10:17:17 +0000942 moveAll(SM, Context->Spec.OldHeader, Context->Spec.NewHeader);
943 moveAll(SM, Context->Spec.OldCC, Context->Spec.NewCC);
Haojian Wu2930be12016-11-08 19:55:13 +0000944 return;
945 }
Nicola Zaghen0efd5242018-05-15 16:37:45 +0000946 LLVM_DEBUG(RGBuilder.getGraph()->dump());
Haojian Wu08e402a2016-12-02 12:39:39 +0000947 moveDeclsToNewFiles();
Haojian Wu36265162017-01-03 09:00:51 +0000948 removeDeclsInOldFiles();
Haojian Wu357ef992016-09-21 13:18:19 +0000949}
950
951} // namespace move
952} // namespace clang