blob: e126852e3820bfda06b14e136e978670c98737af [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);
Eric Liu07d47302018-05-17 14:59:15 +000067 // FIXME: figure out why this is necessary.
68 llvm::sys::path::native(Path);
Eric Liu5e721372018-05-17 12:40:50 +000069 return Path.str();
70}
71
Haojian Wud2a6d7b2016-10-04 09:05:31 +000072// Make the Path absolute using the CurrentDir if the Path is not an absolute
73// path. An empty Path will result in an empty string.
74std::string MakeAbsolutePath(StringRef CurrentDir, StringRef Path) {
75 if (Path.empty())
76 return "";
77 llvm::SmallString<128> InitialDirectory(CurrentDir);
78 llvm::SmallString<128> AbsolutePath(Path);
79 if (std::error_code EC =
80 llvm::sys::fs::make_absolute(InitialDirectory, AbsolutePath))
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +000081 llvm::errs() << "Warning: could not make absolute file: '" << EC.message()
Haojian Wud2a6d7b2016-10-04 09:05:31 +000082 << '\n';
Eric Liu5e721372018-05-17 12:40:50 +000083 return CleanPath(std::move(AbsolutePath));
Haojian Wud2a6d7b2016-10-04 09:05:31 +000084}
85
86// Make the Path absolute using the current working directory of the given
87// SourceManager if the Path is not an absolute path.
88//
89// The Path can be a path relative to the build directory, or retrieved from
90// the SourceManager.
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +000091std::string MakeAbsolutePath(const SourceManager &SM, StringRef Path) {
Haojian Wud2a6d7b2016-10-04 09:05:31 +000092 llvm::SmallString<128> AbsolutePath(Path);
93 if (std::error_code EC =
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +000094 SM.getFileManager().getVirtualFileSystem()->makeAbsolute(
95 AbsolutePath))
96 llvm::errs() << "Warning: could not make absolute file: '" << EC.message()
Haojian Wud2a6d7b2016-10-04 09:05:31 +000097 << '\n';
Haojian Wudb726572016-10-12 15:50:30 +000098 // Handle symbolic link path cases.
99 // We are trying to get the real file path of the symlink.
100 const DirectoryEntry *Dir = SM.getFileManager().getDirectory(
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000101 llvm::sys::path::parent_path(AbsolutePath.str()));
Haojian Wudb726572016-10-12 15:50:30 +0000102 if (Dir) {
103 StringRef DirName = SM.getFileManager().getCanonicalName(Dir);
Eric Liuad3fed62018-05-16 20:10:10 +0000104 // FIXME: getCanonicalName might fail to get real path on VFS.
105 if (llvm::sys::path::is_absolute(DirName)) {
Eric Liu5e721372018-05-17 12:40:50 +0000106 SmallString<128> AbsoluteFilename;
Eric Liuad3fed62018-05-16 20:10:10 +0000107 llvm::sys::path::append(AbsoluteFilename, DirName,
108 llvm::sys::path::filename(AbsolutePath.str()));
Eric Liu5e721372018-05-17 12:40:50 +0000109 return CleanPath(AbsoluteFilename);
Eric Liuad3fed62018-05-16 20:10:10 +0000110 }
Haojian Wudb726572016-10-12 15:50:30 +0000111 }
Eric Liu5e721372018-05-17 12:40:50 +0000112 return CleanPath(AbsolutePath);
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000113}
114
115// Matches AST nodes that are expanded within the given AbsoluteFilePath.
116AST_POLYMORPHIC_MATCHER_P(isExpansionInFile,
117 AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc),
118 std::string, AbsoluteFilePath) {
119 auto &SourceManager = Finder->getASTContext().getSourceManager();
120 auto ExpansionLoc = SourceManager.getExpansionLoc(Node.getLocStart());
121 if (ExpansionLoc.isInvalid())
122 return false;
123 auto FileEntry =
124 SourceManager.getFileEntryForID(SourceManager.getFileID(ExpansionLoc));
125 if (!FileEntry)
126 return false;
127 return MakeAbsolutePath(SourceManager, FileEntry->getName()) ==
128 AbsoluteFilePath;
129}
130
Haojian Wu357ef992016-09-21 13:18:19 +0000131class FindAllIncludes : public clang::PPCallbacks {
132public:
133 explicit FindAllIncludes(SourceManager *SM, ClangMoveTool *const MoveTool)
134 : SM(*SM), MoveTool(MoveTool) {}
135
136 void InclusionDirective(clang::SourceLocation HashLoc,
137 const clang::Token & /*IncludeTok*/,
138 StringRef FileName, bool IsAngled,
Haojian Wu2930be12016-11-08 19:55:13 +0000139 clang::CharSourceRange FilenameRange,
Haojian Wu357ef992016-09-21 13:18:19 +0000140 const clang::FileEntry * /*File*/,
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000141 StringRef SearchPath, StringRef /*RelativePath*/,
Julie Hockett546943f2018-05-10 19:13:14 +0000142 const clang::Module * /*Imported*/,
143 SrcMgr::CharacteristicKind /*FileType*/) override {
Haojian Wudaf4cb82016-09-23 13:28:38 +0000144 if (const auto *FileEntry = SM.getFileEntryForID(SM.getFileID(HashLoc)))
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000145 MoveTool->addIncludes(FileName, IsAngled, SearchPath,
Haojian Wu2930be12016-11-08 19:55:13 +0000146 FileEntry->getName(), FilenameRange, SM);
Haojian Wu357ef992016-09-21 13:18:19 +0000147 }
148
149private:
150 const SourceManager &SM;
151 ClangMoveTool *const MoveTool;
152};
153
Haojian Wu32a552f2017-01-03 14:22:25 +0000154/// Add a declatration being moved to new.h/cc. Note that the declaration will
155/// also be deleted in old.h/cc.
156void MoveDeclFromOldFileToNewFile(ClangMoveTool *MoveTool, const NamedDecl *D) {
157 MoveTool->getMovedDecls().push_back(D);
158 MoveTool->addRemovedDecl(D);
159 MoveTool->getUnremovedDeclsInOldHeader().erase(D);
160}
161
Haojian Wu4543fec2016-11-16 13:05:19 +0000162class FunctionDeclarationMatch : public MatchFinder::MatchCallback {
163public:
164 explicit FunctionDeclarationMatch(ClangMoveTool *MoveTool)
165 : MoveTool(MoveTool) {}
166
167 void run(const MatchFinder::MatchResult &Result) override {
168 const auto *FD = Result.Nodes.getNodeAs<clang::FunctionDecl>("function");
169 assert(FD);
170 const clang::NamedDecl *D = FD;
171 if (const auto *FTD = FD->getDescribedFunctionTemplate())
172 D = FTD;
Haojian Wu32a552f2017-01-03 14:22:25 +0000173 MoveDeclFromOldFileToNewFile(MoveTool, D);
174 }
175
176private:
177 ClangMoveTool *MoveTool;
178};
179
Haojian Wu4a920502017-02-27 13:19:13 +0000180class VarDeclarationMatch : public MatchFinder::MatchCallback {
181public:
182 explicit VarDeclarationMatch(ClangMoveTool *MoveTool)
183 : MoveTool(MoveTool) {}
184
185 void run(const MatchFinder::MatchResult &Result) override {
186 const auto *VD = Result.Nodes.getNodeAs<clang::VarDecl>("var");
187 assert(VD);
188 MoveDeclFromOldFileToNewFile(MoveTool, VD);
189 }
190
191private:
192 ClangMoveTool *MoveTool;
193};
194
Haojian Wud69d9072017-01-04 14:50:49 +0000195class TypeAliasMatch : public MatchFinder::MatchCallback {
196public:
197 explicit TypeAliasMatch(ClangMoveTool *MoveTool)
198 : MoveTool(MoveTool) {}
199
200 void run(const MatchFinder::MatchResult &Result) override {
201 if (const auto *TD = Result.Nodes.getNodeAs<clang::TypedefDecl>("typedef"))
202 MoveDeclFromOldFileToNewFile(MoveTool, TD);
203 else if (const auto *TAD =
204 Result.Nodes.getNodeAs<clang::TypeAliasDecl>("type_alias")) {
205 const NamedDecl * D = TAD;
206 if (const auto * TD = TAD->getDescribedAliasTemplate())
207 D = TD;
208 MoveDeclFromOldFileToNewFile(MoveTool, D);
209 }
210 }
211
212private:
213 ClangMoveTool *MoveTool;
214};
215
Haojian Wu32a552f2017-01-03 14:22:25 +0000216class EnumDeclarationMatch : public MatchFinder::MatchCallback {
217public:
218 explicit EnumDeclarationMatch(ClangMoveTool *MoveTool)
219 : MoveTool(MoveTool) {}
220
221 void run(const MatchFinder::MatchResult &Result) override {
222 const auto *ED = Result.Nodes.getNodeAs<clang::EnumDecl>("enum");
223 assert(ED);
224 MoveDeclFromOldFileToNewFile(MoveTool, ED);
Haojian Wu4543fec2016-11-16 13:05:19 +0000225 }
226
227private:
228 ClangMoveTool *MoveTool;
229};
230
Haojian Wu35ca9462016-11-14 14:15:44 +0000231class ClassDeclarationMatch : public MatchFinder::MatchCallback {
232public:
233 explicit ClassDeclarationMatch(ClangMoveTool *MoveTool)
234 : MoveTool(MoveTool) {}
235 void run(const MatchFinder::MatchResult &Result) override {
236 clang::SourceManager* SM = &Result.Context->getSourceManager();
237 if (const auto *CMD =
238 Result.Nodes.getNodeAs<clang::CXXMethodDecl>("class_method"))
239 MatchClassMethod(CMD, SM);
240 else if (const auto *VD = Result.Nodes.getNodeAs<clang::VarDecl>(
241 "class_static_var_decl"))
242 MatchClassStaticVariable(VD, SM);
243 else if (const auto *CD = Result.Nodes.getNodeAs<clang::CXXRecordDecl>(
244 "moved_class"))
245 MatchClassDeclaration(CD, SM);
246 }
247
248private:
249 void MatchClassMethod(const clang::CXXMethodDecl* CMD,
250 clang::SourceManager* SM) {
251 // Skip inline class methods. isInline() ast matcher doesn't ignore this
252 // case.
253 if (!CMD->isInlined()) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000254 MoveTool->getMovedDecls().push_back(CMD);
255 MoveTool->addRemovedDecl(CMD);
Haojian Wu35ca9462016-11-14 14:15:44 +0000256 // Get template class method from its method declaration as
257 // UnremovedDecls stores template class method.
258 if (const auto *FTD = CMD->getDescribedFunctionTemplate())
259 MoveTool->getUnremovedDeclsInOldHeader().erase(FTD);
260 else
261 MoveTool->getUnremovedDeclsInOldHeader().erase(CMD);
262 }
263 }
264
265 void MatchClassStaticVariable(const clang::NamedDecl *VD,
266 clang::SourceManager* SM) {
Haojian Wu32a552f2017-01-03 14:22:25 +0000267 MoveDeclFromOldFileToNewFile(MoveTool, VD);
Haojian Wu35ca9462016-11-14 14:15:44 +0000268 }
269
270 void MatchClassDeclaration(const clang::CXXRecordDecl *CD,
271 clang::SourceManager* SM) {
272 // Get class template from its class declaration as UnremovedDecls stores
273 // class template.
274 if (const auto *TC = CD->getDescribedClassTemplate())
Haojian Wu08e402a2016-12-02 12:39:39 +0000275 MoveTool->getMovedDecls().push_back(TC);
Haojian Wu35ca9462016-11-14 14:15:44 +0000276 else
Haojian Wu08e402a2016-12-02 12:39:39 +0000277 MoveTool->getMovedDecls().push_back(CD);
Haojian Wu48ac3042016-11-23 10:04:19 +0000278 MoveTool->addRemovedDecl(MoveTool->getMovedDecls().back());
Haojian Wu35ca9462016-11-14 14:15:44 +0000279 MoveTool->getUnremovedDeclsInOldHeader().erase(
Haojian Wu08e402a2016-12-02 12:39:39 +0000280 MoveTool->getMovedDecls().back());
Haojian Wu35ca9462016-11-14 14:15:44 +0000281 }
282
283 ClangMoveTool *MoveTool;
284};
285
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000286// Expand to get the end location of the line where the EndLoc of the given
287// Decl.
288SourceLocation
Haojian Wu08e402a2016-12-02 12:39:39 +0000289getLocForEndOfDecl(const clang::Decl *D,
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000290 const LangOptions &LangOpts = clang::LangOptions()) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000291 const auto &SM = D->getASTContext().getSourceManager();
Richard Smith4bb15ab2018-04-30 05:26:07 +0000292 // If the expansion range is a character range, this is the location of
293 // the first character past the end. Otherwise it's the location of the
294 // first character in the final token in the range.
295 auto EndExpansionLoc = SM.getExpansionRange(D->getLocEnd()).getEnd();
Haojian Wudc4edba2016-12-13 15:35:47 +0000296 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(EndExpansionLoc);
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000297 // Try to load the file buffer.
298 bool InvalidTemp = false;
Haojian Wu08e402a2016-12-02 12:39:39 +0000299 llvm::StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000300 if (InvalidTemp)
301 return SourceLocation();
302
303 const char *TokBegin = File.data() + LocInfo.second;
304 // Lex from the start of the given location.
Haojian Wu08e402a2016-12-02 12:39:39 +0000305 Lexer Lex(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000306 TokBegin, File.end());
307
308 llvm::SmallVector<char, 16> Line;
309 // FIXME: this is a bit hacky to get ReadToEndOfLine work.
310 Lex.setParsingPreprocessorDirective(true);
311 Lex.ReadToEndOfLine(&Line);
Haojian Wudc4edba2016-12-13 15:35:47 +0000312 SourceLocation EndLoc = EndExpansionLoc.getLocWithOffset(Line.size());
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000313 // If we already reach EOF, just return the EOF SourceLocation;
314 // otherwise, move 1 offset ahead to include the trailing newline character
315 // '\n'.
Haojian Wu08e402a2016-12-02 12:39:39 +0000316 return SM.getLocForEndOfFile(LocInfo.first) == EndLoc
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000317 ? EndLoc
318 : EndLoc.getLocWithOffset(1);
319}
320
321// Get full range of a Decl including the comments associated with it.
322clang::CharSourceRange
Haojian Wu08e402a2016-12-02 12:39:39 +0000323getFullRange(const clang::Decl *D,
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000324 const clang::LangOptions &options = clang::LangOptions()) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000325 const auto &SM = D->getASTContext().getSourceManager();
326 clang::SourceRange Full(SM.getExpansionLoc(D->getLocStart()),
327 getLocForEndOfDecl(D));
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000328 // Expand to comments that are associated with the Decl.
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000329 if (const auto *Comment = D->getASTContext().getRawCommentForDeclNoCache(D)) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000330 if (SM.isBeforeInTranslationUnit(Full.getEnd(), Comment->getLocEnd()))
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000331 Full.setEnd(Comment->getLocEnd());
332 // FIXME: Don't delete a preceding comment, if there are no other entities
333 // it could refer to.
Haojian Wu08e402a2016-12-02 12:39:39 +0000334 if (SM.isBeforeInTranslationUnit(Comment->getLocStart(), Full.getBegin()))
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000335 Full.setBegin(Comment->getLocStart());
336 }
337
338 return clang::CharSourceRange::getCharRange(Full);
339}
340
Haojian Wu08e402a2016-12-02 12:39:39 +0000341std::string getDeclarationSourceText(const clang::Decl *D) {
342 const auto &SM = D->getASTContext().getSourceManager();
343 llvm::StringRef SourceText =
344 clang::Lexer::getSourceText(getFullRange(D), SM, clang::LangOptions());
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000345 return SourceText.str();
346}
347
Haojian Wu08e402a2016-12-02 12:39:39 +0000348bool isInHeaderFile(const clang::Decl *D,
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000349 llvm::StringRef OriginalRunningDirectory,
350 llvm::StringRef OldHeader) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000351 const auto &SM = D->getASTContext().getSourceManager();
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000352 if (OldHeader.empty())
Haojian Wu357ef992016-09-21 13:18:19 +0000353 return false;
354 auto ExpansionLoc = SM.getExpansionLoc(D->getLocStart());
355 if (ExpansionLoc.isInvalid())
356 return false;
357
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000358 if (const auto *FE = SM.getFileEntryForID(SM.getFileID(ExpansionLoc))) {
359 return MakeAbsolutePath(SM, FE->getName()) ==
360 MakeAbsolutePath(OriginalRunningDirectory, OldHeader);
361 }
Haojian Wu357ef992016-09-21 13:18:19 +0000362
363 return false;
364}
365
Haojian Wu08e402a2016-12-02 12:39:39 +0000366std::vector<std::string> getNamespaces(const clang::Decl *D) {
Haojian Wu357ef992016-09-21 13:18:19 +0000367 std::vector<std::string> Namespaces;
368 for (const auto *Context = D->getDeclContext(); Context;
369 Context = Context->getParent()) {
370 if (llvm::isa<clang::TranslationUnitDecl>(Context) ||
371 llvm::isa<clang::LinkageSpecDecl>(Context))
372 break;
373
374 if (const auto *ND = llvm::dyn_cast<clang::NamespaceDecl>(Context))
375 Namespaces.push_back(ND->getName().str());
376 }
377 std::reverse(Namespaces.begin(), Namespaces.end());
378 return Namespaces;
379}
380
Haojian Wu357ef992016-09-21 13:18:19 +0000381clang::tooling::Replacements
382createInsertedReplacements(const std::vector<std::string> &Includes,
Haojian Wu08e402a2016-12-02 12:39:39 +0000383 const std::vector<const NamedDecl *> &Decls,
Haojian Wu48ac3042016-11-23 10:04:19 +0000384 llvm::StringRef FileName, bool IsHeader = false,
385 StringRef OldHeaderInclude = "") {
Haojian Wu53eab1e2016-10-14 13:43:49 +0000386 std::string NewCode;
Haojian Wu220c7552016-10-14 13:01:36 +0000387 std::string GuardName(FileName);
388 if (IsHeader) {
Haojian Wuac97fc32016-10-17 15:26:34 +0000389 for (size_t i = 0; i < GuardName.size(); ++i) {
390 if (!isAlphanumeric(GuardName[i]))
391 GuardName[i] = '_';
392 }
Haojian Wu220c7552016-10-14 13:01:36 +0000393 GuardName = StringRef(GuardName).upper();
Haojian Wu53eab1e2016-10-14 13:43:49 +0000394 NewCode += "#ifndef " + GuardName + "\n";
Haojian Wu53315a72016-11-15 09:06:59 +0000395 NewCode += "#define " + GuardName + "\n\n";
Haojian Wu220c7552016-10-14 13:01:36 +0000396 }
Haojian Wu357ef992016-09-21 13:18:19 +0000397
Haojian Wu48ac3042016-11-23 10:04:19 +0000398 NewCode += OldHeaderInclude;
Haojian Wu357ef992016-09-21 13:18:19 +0000399 // Add #Includes.
Haojian Wu357ef992016-09-21 13:18:19 +0000400 for (const auto &Include : Includes)
Haojian Wu53eab1e2016-10-14 13:43:49 +0000401 NewCode += Include;
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000402
Haojian Wu53eab1e2016-10-14 13:43:49 +0000403 if (!Includes.empty())
404 NewCode += "\n";
Haojian Wu357ef992016-09-21 13:18:19 +0000405
406 // Add moved class definition and its related declarations. All declarations
407 // in same namespace are grouped together.
Haojian Wu53315a72016-11-15 09:06:59 +0000408 //
409 // Record namespaces where the current position is in.
Haojian Wu357ef992016-09-21 13:18:19 +0000410 std::vector<std::string> CurrentNamespaces;
Haojian Wu08e402a2016-12-02 12:39:39 +0000411 for (const auto *MovedDecl : Decls) {
Haojian Wu53315a72016-11-15 09:06:59 +0000412 // The namespaces of the declaration being moved.
Haojian Wu08e402a2016-12-02 12:39:39 +0000413 std::vector<std::string> DeclNamespaces = getNamespaces(MovedDecl);
Haojian Wu357ef992016-09-21 13:18:19 +0000414 auto CurrentIt = CurrentNamespaces.begin();
415 auto DeclIt = DeclNamespaces.begin();
Haojian Wu53315a72016-11-15 09:06:59 +0000416 // Skip the common prefix.
Haojian Wu357ef992016-09-21 13:18:19 +0000417 while (CurrentIt != CurrentNamespaces.end() &&
418 DeclIt != DeclNamespaces.end()) {
419 if (*CurrentIt != *DeclIt)
420 break;
421 ++CurrentIt;
422 ++DeclIt;
423 }
Haojian Wu53315a72016-11-15 09:06:59 +0000424 // Calculate the new namespaces after adding MovedDecl in CurrentNamespace,
425 // which is used for next iteration of this loop.
Haojian Wu357ef992016-09-21 13:18:19 +0000426 std::vector<std::string> NextNamespaces(CurrentNamespaces.begin(),
427 CurrentIt);
428 NextNamespaces.insert(NextNamespaces.end(), DeclIt, DeclNamespaces.end());
Haojian Wu53315a72016-11-15 09:06:59 +0000429
430
431 // End with CurrentNamespace.
432 bool HasEndCurrentNamespace = false;
Haojian Wu357ef992016-09-21 13:18:19 +0000433 auto RemainingSize = CurrentNamespaces.end() - CurrentIt;
434 for (auto It = CurrentNamespaces.rbegin(); RemainingSize > 0;
435 --RemainingSize, ++It) {
436 assert(It < CurrentNamespaces.rend());
Haojian Wu53eab1e2016-10-14 13:43:49 +0000437 NewCode += "} // namespace " + *It + "\n";
Haojian Wu53315a72016-11-15 09:06:59 +0000438 HasEndCurrentNamespace = true;
Haojian Wu357ef992016-09-21 13:18:19 +0000439 }
Haojian Wu53315a72016-11-15 09:06:59 +0000440 // Add trailing '\n' after the nested namespace definition.
441 if (HasEndCurrentNamespace)
442 NewCode += "\n";
443
444 // If the moved declaration is not in CurrentNamespace, add extra namespace
445 // definitions.
446 bool IsInNewNamespace = false;
Haojian Wu357ef992016-09-21 13:18:19 +0000447 while (DeclIt != DeclNamespaces.end()) {
Haojian Wu53eab1e2016-10-14 13:43:49 +0000448 NewCode += "namespace " + *DeclIt + " {\n";
Haojian Wu53315a72016-11-15 09:06:59 +0000449 IsInNewNamespace = true;
Haojian Wu357ef992016-09-21 13:18:19 +0000450 ++DeclIt;
451 }
Haojian Wu53315a72016-11-15 09:06:59 +0000452 // If the moved declaration is in same namespace CurrentNamespace, add
453 // a preceeding `\n' before the moved declaration.
Haojian Wu50a45d92016-11-18 10:51:16 +0000454 // FIXME: Don't add empty lines between using declarations.
Haojian Wu53315a72016-11-15 09:06:59 +0000455 if (!IsInNewNamespace)
456 NewCode += "\n";
Haojian Wu08e402a2016-12-02 12:39:39 +0000457 NewCode += getDeclarationSourceText(MovedDecl);
Haojian Wu357ef992016-09-21 13:18:19 +0000458 CurrentNamespaces = std::move(NextNamespaces);
459 }
460 std::reverse(CurrentNamespaces.begin(), CurrentNamespaces.end());
Haojian Wu53eab1e2016-10-14 13:43:49 +0000461 for (const auto &NS : CurrentNamespaces)
462 NewCode += "} // namespace " + NS + "\n";
Haojian Wu220c7552016-10-14 13:01:36 +0000463
Haojian Wu53eab1e2016-10-14 13:43:49 +0000464 if (IsHeader)
Haojian Wu53315a72016-11-15 09:06:59 +0000465 NewCode += "\n#endif // " + GuardName + "\n";
Haojian Wu53eab1e2016-10-14 13:43:49 +0000466 return clang::tooling::Replacements(
467 clang::tooling::Replacement(FileName, 0, 0, NewCode));
Haojian Wu357ef992016-09-21 13:18:19 +0000468}
469
Haojian Wu36265162017-01-03 09:00:51 +0000470// Return a set of all decls which are used/referenced by the given Decls.
471// Specically, given a class member declaration, this method will return all
472// decls which are used by the whole class.
473llvm::DenseSet<const Decl *>
474getUsedDecls(const HelperDeclRefGraph *RG,
475 const std::vector<const NamedDecl *> &Decls) {
476 assert(RG);
477 llvm::DenseSet<const CallGraphNode *> Nodes;
478 for (const auto *D : Decls) {
479 auto Result = RG->getReachableNodes(
480 HelperDeclRGBuilder::getOutmostClassOrFunDecl(D));
481 Nodes.insert(Result.begin(), Result.end());
482 }
483 llvm::DenseSet<const Decl *> Results;
484 for (const auto *Node : Nodes)
485 Results.insert(Node->getDecl());
486 return Results;
487}
488
Haojian Wu357ef992016-09-21 13:18:19 +0000489} // namespace
490
491std::unique_ptr<clang::ASTConsumer>
492ClangMoveAction::CreateASTConsumer(clang::CompilerInstance &Compiler,
493 StringRef /*InFile*/) {
494 Compiler.getPreprocessor().addPPCallbacks(llvm::make_unique<FindAllIncludes>(
495 &Compiler.getSourceManager(), &MoveTool));
496 return MatchFinder.newASTConsumer();
497}
498
Haojian Wub15c8da2016-11-24 10:17:17 +0000499ClangMoveTool::ClangMoveTool(ClangMoveContext *const Context,
500 DeclarationReporter *const Reporter)
501 : Context(Context), Reporter(Reporter) {
502 if (!Context->Spec.NewHeader.empty())
503 CCIncludes.push_back("#include \"" + Context->Spec.NewHeader + "\"\n");
Haojian Wu357ef992016-09-21 13:18:19 +0000504}
505
Haojian Wu08e402a2016-12-02 12:39:39 +0000506void ClangMoveTool::addRemovedDecl(const NamedDecl *Decl) {
507 const auto &SM = Decl->getASTContext().getSourceManager();
508 auto Loc = Decl->getLocation();
Haojian Wu48ac3042016-11-23 10:04:19 +0000509 StringRef FilePath = SM.getFilename(Loc);
510 FilePathToFileID[FilePath] = SM.getFileID(Loc);
511 RemovedDecls.push_back(Decl);
512}
513
Haojian Wu357ef992016-09-21 13:18:19 +0000514void ClangMoveTool::registerMatchers(ast_matchers::MatchFinder *Finder) {
Haojian Wub15c8da2016-11-24 10:17:17 +0000515 auto InOldHeader =
516 isExpansionInFile(makeAbsolutePath(Context->Spec.OldHeader));
517 auto InOldCC = isExpansionInFile(makeAbsolutePath(Context->Spec.OldCC));
Haojian Wu357ef992016-09-21 13:18:19 +0000518 auto InOldFiles = anyOf(InOldHeader, InOldCC);
Haojian Wu03c89632017-05-02 12:15:11 +0000519 auto classTemplateForwardDecls =
520 classTemplateDecl(unless(has(cxxRecordDecl(isDefinition()))));
521 auto ForwardClassDecls = namedDecl(
522 anyOf(cxxRecordDecl(unless(anyOf(isImplicit(), isDefinition()))),
523 classTemplateForwardDecls));
Haojian Wu32a552f2017-01-03 14:22:25 +0000524 auto TopLevelDecl =
525 hasDeclContext(anyOf(namespaceDecl(), translationUnitDecl()));
Haojian Wu2930be12016-11-08 19:55:13 +0000526
527 //============================================================================
528 // Matchers for old header
529 //============================================================================
530 // Match all top-level named declarations (e.g. function, variable, enum) in
531 // old header, exclude forward class declarations and namespace declarations.
532 //
Haojian Wub15c8da2016-11-24 10:17:17 +0000533 // We consider declarations inside a class belongs to the class. So these
534 // declarations will be ignored.
Haojian Wu2930be12016-11-08 19:55:13 +0000535 auto AllDeclsInHeader = namedDecl(
Haojian Wu03c89632017-05-02 12:15:11 +0000536 unless(ForwardClassDecls), unless(namespaceDecl()),
537 unless(usingDirectiveDecl()), // using namespace decl.
Haojian Wud4786342018-02-09 15:57:30 +0000538 notInMacro(),
Haojian Wu2930be12016-11-08 19:55:13 +0000539 InOldHeader,
Haojian Wub15c8da2016-11-24 10:17:17 +0000540 hasParent(decl(anyOf(namespaceDecl(), translationUnitDecl()))),
541 hasDeclContext(decl(anyOf(namespaceDecl(), translationUnitDecl()))));
Haojian Wu2930be12016-11-08 19:55:13 +0000542 Finder->addMatcher(AllDeclsInHeader.bind("decls_in_header"), this);
Haojian Wub15c8da2016-11-24 10:17:17 +0000543
544 // Don't register other matchers when dumping all declarations in header.
545 if (Context->DumpDeclarations)
546 return;
547
Haojian Wu2930be12016-11-08 19:55:13 +0000548 // Match forward declarations in old header.
Haojian Wu03c89632017-05-02 12:15:11 +0000549 Finder->addMatcher(namedDecl(ForwardClassDecls, InOldHeader).bind("fwd_decl"),
Haojian Wu2930be12016-11-08 19:55:13 +0000550 this);
551
552 //============================================================================
Haojian Wu2930be12016-11-08 19:55:13 +0000553 // Matchers for old cc
554 //============================================================================
Haojian Wu36265162017-01-03 09:00:51 +0000555 auto IsOldCCTopLevelDecl = allOf(
556 hasParent(decl(anyOf(namespaceDecl(), translationUnitDecl()))), InOldCC);
557 // Matching using decls/type alias decls which are in named/anonymous/global
558 // namespace, these decls are always copied to new.h/cc. Those in classes,
559 // functions are covered in other matchers.
Haojian Wub3d98882017-01-17 10:08:11 +0000560 Finder->addMatcher(namedDecl(anyOf(usingDecl(IsOldCCTopLevelDecl),
561 usingDirectiveDecl(IsOldCCTopLevelDecl),
562 typeAliasDecl(IsOldCCTopLevelDecl)),
563 notInMacro())
564 .bind("using_decl"),
565 this);
Haojian Wu357ef992016-09-21 13:18:19 +0000566
Haojian Wu67bb6512016-10-19 14:13:21 +0000567 // Match static functions/variable definitions which are defined in named
568 // namespaces.
Haojian Wub15c8da2016-11-24 10:17:17 +0000569 Optional<ast_matchers::internal::Matcher<NamedDecl>> HasAnySymbolNames;
570 for (StringRef SymbolName : Context->Spec.Names) {
571 llvm::StringRef GlobalSymbolName = SymbolName.trim().ltrim(':');
572 const auto HasName = hasName(("::" + GlobalSymbolName).str());
573 HasAnySymbolNames =
574 HasAnySymbolNames ? anyOf(*HasAnySymbolNames, HasName) : HasName;
575 }
576
577 if (!HasAnySymbolNames) {
578 llvm::errs() << "No symbols being moved.\n";
579 return;
580 }
581 auto InMovedClass =
582 hasOutermostEnclosingClass(cxxRecordDecl(*HasAnySymbolNames));
Haojian Wu36265162017-01-03 09:00:51 +0000583
584 // Matchers for helper declarations in old.cc.
585 auto InAnonymousNS = hasParent(namespaceDecl(isAnonymous()));
Haojian Wu4775ce52017-01-17 13:22:37 +0000586 auto NotInMovedClass= allOf(unless(InMovedClass), InOldCC);
587 auto IsOldCCHelper =
588 allOf(NotInMovedClass, anyOf(isStaticStorageClass(), InAnonymousNS));
Haojian Wu36265162017-01-03 09:00:51 +0000589 // Match helper classes separately with helper functions/variables since we
590 // want to reuse these matchers in finding helpers usage below.
Haojian Wu4775ce52017-01-17 13:22:37 +0000591 //
592 // There could be forward declarations usage for helpers, especially for
593 // classes and functions. We need include these forward declarations.
594 //
595 // Forward declarations for variable helpers will be excluded as these
596 // declarations (with "extern") are not supposed in cpp file.
597 auto HelperFuncOrVar =
598 namedDecl(notInMacro(), anyOf(functionDecl(IsOldCCHelper),
599 varDecl(isDefinition(), IsOldCCHelper)));
Haojian Wub3d98882017-01-17 10:08:11 +0000600 auto HelperClasses =
Haojian Wu4775ce52017-01-17 13:22:37 +0000601 cxxRecordDecl(notInMacro(), NotInMovedClass, InAnonymousNS);
Haojian Wu36265162017-01-03 09:00:51 +0000602 // Save all helper declarations in old.cc.
603 Finder->addMatcher(
604 namedDecl(anyOf(HelperFuncOrVar, HelperClasses)).bind("helper_decls"),
605 this);
606
607 // Construct an AST-based call graph of helper declarations in old.cc.
608 // In the following matcheres, "dc" is a caller while "helper_decls" and
609 // "used_class" is a callee, so a new edge starting from caller to callee will
610 // be add in the graph.
611 //
612 // Find helper function/variable usages.
613 Finder->addMatcher(
614 declRefExpr(to(HelperFuncOrVar), hasAncestor(decl().bind("dc")))
615 .bind("func_ref"),
616 &RGBuilder);
617 // Find helper class usages.
618 Finder->addMatcher(
619 typeLoc(loc(recordType(hasDeclaration(HelperClasses.bind("used_class")))),
620 hasAncestor(decl().bind("dc"))),
621 &RGBuilder);
Haojian Wu35ca9462016-11-14 14:15:44 +0000622
623 //============================================================================
624 // Matchers for old files, including old.h/old.cc
625 //============================================================================
626 // Create a MatchCallback for class declarations.
627 MatchCallbacks.push_back(llvm::make_unique<ClassDeclarationMatch>(this));
628 // Match moved class declarations.
Haojian Wu32a552f2017-01-03 14:22:25 +0000629 auto MovedClass = cxxRecordDecl(InOldFiles, *HasAnySymbolNames,
630 isDefinition(), TopLevelDecl)
631 .bind("moved_class");
Haojian Wu35ca9462016-11-14 14:15:44 +0000632 Finder->addMatcher(MovedClass, MatchCallbacks.back().get());
633 // Match moved class methods (static methods included) which are defined
634 // outside moved class declaration.
635 Finder->addMatcher(
Haojian Wu4543fec2016-11-16 13:05:19 +0000636 cxxMethodDecl(InOldFiles, ofOutermostEnclosingClass(*HasAnySymbolNames),
Haojian Wu35ca9462016-11-14 14:15:44 +0000637 isDefinition())
638 .bind("class_method"),
639 MatchCallbacks.back().get());
640 // Match static member variable definition of the moved class.
641 Finder->addMatcher(
642 varDecl(InMovedClass, InOldFiles, isDefinition(), isStaticDataMember())
643 .bind("class_static_var_decl"),
644 MatchCallbacks.back().get());
645
Haojian Wu4543fec2016-11-16 13:05:19 +0000646 MatchCallbacks.push_back(llvm::make_unique<FunctionDeclarationMatch>(this));
Haojian Wu32a552f2017-01-03 14:22:25 +0000647 Finder->addMatcher(functionDecl(InOldFiles, *HasAnySymbolNames, TopLevelDecl)
Haojian Wu4543fec2016-11-16 13:05:19 +0000648 .bind("function"),
649 MatchCallbacks.back().get());
Haojian Wu32a552f2017-01-03 14:22:25 +0000650
Haojian Wu4a920502017-02-27 13:19:13 +0000651 MatchCallbacks.push_back(llvm::make_unique<VarDeclarationMatch>(this));
652 Finder->addMatcher(
653 varDecl(InOldFiles, *HasAnySymbolNames, TopLevelDecl).bind("var"),
654 MatchCallbacks.back().get());
655
Haojian Wud69d9072017-01-04 14:50:49 +0000656 // Match enum definition in old.h. Enum helpers (which are defined in old.cc)
Haojian Wu32a552f2017-01-03 14:22:25 +0000657 // will not be moved for now no matter whether they are used or not.
658 MatchCallbacks.push_back(llvm::make_unique<EnumDeclarationMatch>(this));
659 Finder->addMatcher(
660 enumDecl(InOldHeader, *HasAnySymbolNames, isDefinition(), TopLevelDecl)
661 .bind("enum"),
662 MatchCallbacks.back().get());
Haojian Wud69d9072017-01-04 14:50:49 +0000663
664 // Match type alias in old.h, this includes "typedef" and "using" type alias
665 // declarations. Type alias helpers (which are defined in old.cc) will not be
666 // moved for now no matter whether they are used or not.
667 MatchCallbacks.push_back(llvm::make_unique<TypeAliasMatch>(this));
668 Finder->addMatcher(namedDecl(anyOf(typedefDecl().bind("typedef"),
669 typeAliasDecl().bind("type_alias")),
670 InOldHeader, *HasAnySymbolNames, TopLevelDecl),
671 MatchCallbacks.back().get());
Haojian Wu357ef992016-09-21 13:18:19 +0000672}
673
674void ClangMoveTool::run(const ast_matchers::MatchFinder::MatchResult &Result) {
Haojian Wu2930be12016-11-08 19:55:13 +0000675 if (const auto *D =
676 Result.Nodes.getNodeAs<clang::NamedDecl>("decls_in_header")) {
677 UnremovedDeclsInOldHeader.insert(D);
Haojian Wu357ef992016-09-21 13:18:19 +0000678 } else if (const auto *FWD =
679 Result.Nodes.getNodeAs<clang::CXXRecordDecl>("fwd_decl")) {
Haojian Wub15c8da2016-11-24 10:17:17 +0000680 // Skip all forward declarations which appear after moved class declaration.
Haojian Wu29c38f72016-10-21 19:26:43 +0000681 if (RemovedDecls.empty()) {
Haojian Wub53ec462016-11-10 05:33:26 +0000682 if (const auto *DCT = FWD->getDescribedClassTemplate())
Haojian Wu08e402a2016-12-02 12:39:39 +0000683 MovedDecls.push_back(DCT);
Haojian Wub53ec462016-11-10 05:33:26 +0000684 else
Haojian Wu08e402a2016-12-02 12:39:39 +0000685 MovedDecls.push_back(FWD);
Haojian Wu29c38f72016-10-21 19:26:43 +0000686 }
Haojian Wu357ef992016-09-21 13:18:19 +0000687 } else if (const auto *ND =
Haojian Wu36265162017-01-03 09:00:51 +0000688 Result.Nodes.getNodeAs<clang::NamedDecl>("helper_decls")) {
689 MovedDecls.push_back(ND);
690 HelperDeclarations.push_back(ND);
Nicola Zaghen0efd5242018-05-15 16:37:45 +0000691 LLVM_DEBUG(llvm::dbgs() << "Add helper : " << ND->getNameAsString() << " ("
692 << ND << ")\n");
Haojian Wu67bb6512016-10-19 14:13:21 +0000693 } else if (const auto *UD =
694 Result.Nodes.getNodeAs<clang::NamedDecl>("using_decl")) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000695 MovedDecls.push_back(UD);
Haojian Wu357ef992016-09-21 13:18:19 +0000696 }
697}
698
Haojian Wu2930be12016-11-08 19:55:13 +0000699std::string ClangMoveTool::makeAbsolutePath(StringRef Path) {
Haojian Wub15c8da2016-11-24 10:17:17 +0000700 return MakeAbsolutePath(Context->OriginalRunningDirectory, Path);
Haojian Wu2930be12016-11-08 19:55:13 +0000701}
702
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000703void ClangMoveTool::addIncludes(llvm::StringRef IncludeHeader, bool IsAngled,
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000704 llvm::StringRef SearchPath,
705 llvm::StringRef FileName,
Haojian Wu2930be12016-11-08 19:55:13 +0000706 clang::CharSourceRange IncludeFilenameRange,
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000707 const SourceManager &SM) {
Haojian Wudb726572016-10-12 15:50:30 +0000708 SmallVector<char, 128> HeaderWithSearchPath;
709 llvm::sys::path::append(HeaderWithSearchPath, SearchPath, IncludeHeader);
Haojian Wufb68ca12018-01-31 12:12:29 +0000710 std::string AbsoluteIncludeHeader =
Haojian Wudb726572016-10-12 15:50:30 +0000711 MakeAbsolutePath(SM, llvm::StringRef(HeaderWithSearchPath.data(),
Haojian Wufb68ca12018-01-31 12:12:29 +0000712 HeaderWithSearchPath.size()));
Haojian Wudaf4cb82016-09-23 13:28:38 +0000713 std::string IncludeLine =
714 IsAngled ? ("#include <" + IncludeHeader + ">\n").str()
715 : ("#include \"" + IncludeHeader + "\"\n").str();
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000716
Haojian Wufb68ca12018-01-31 12:12:29 +0000717 std::string AbsoluteOldHeader = makeAbsolutePath(Context->Spec.OldHeader);
Haojian Wudb726572016-10-12 15:50:30 +0000718 std::string AbsoluteCurrentFile = MakeAbsolutePath(SM, FileName);
719 if (AbsoluteOldHeader == AbsoluteCurrentFile) {
Haojian Wufb68ca12018-01-31 12:12:29 +0000720 // Find old.h includes "old.h".
721 if (AbsoluteOldHeader == AbsoluteIncludeHeader) {
722 OldHeaderIncludeRangeInHeader = IncludeFilenameRange;
723 return;
724 }
Haojian Wudaf4cb82016-09-23 13:28:38 +0000725 HeaderIncludes.push_back(IncludeLine);
Haojian Wub15c8da2016-11-24 10:17:17 +0000726 } else if (makeAbsolutePath(Context->Spec.OldCC) == AbsoluteCurrentFile) {
Haojian Wufb68ca12018-01-31 12:12:29 +0000727 // Find old.cc includes "old.h".
728 if (AbsoluteOldHeader == AbsoluteIncludeHeader) {
729 OldHeaderIncludeRangeInCC = IncludeFilenameRange;
730 return;
731 }
Haojian Wudaf4cb82016-09-23 13:28:38 +0000732 CCIncludes.push_back(IncludeLine);
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000733 }
Haojian Wu357ef992016-09-21 13:18:19 +0000734}
735
Haojian Wu08e402a2016-12-02 12:39:39 +0000736void ClangMoveTool::removeDeclsInOldFiles() {
Haojian Wu48ac3042016-11-23 10:04:19 +0000737 if (RemovedDecls.empty()) return;
Haojian Wu36265162017-01-03 09:00:51 +0000738
739 // If old_header is not specified (only move declarations from old.cc), remain
740 // all the helper function declarations in old.cc as UnremovedDeclsInOldHeader
741 // is empty in this case, there is no way to verify unused/used helpers.
742 if (!Context->Spec.OldHeader.empty()) {
743 std::vector<const NamedDecl *> UnremovedDecls;
744 for (const auto *D : UnremovedDeclsInOldHeader)
745 UnremovedDecls.push_back(D);
746
747 auto UsedDecls = getUsedDecls(RGBuilder.getGraph(), UnremovedDecls);
748
749 // We remove the helper declarations which are not used in the old.cc after
750 // moving the given declarations.
751 for (const auto *D : HelperDeclarations) {
Nicola Zaghen0efd5242018-05-15 16:37:45 +0000752 LLVM_DEBUG(llvm::dbgs() << "Check helper is used: "
753 << D->getNameAsString() << " (" << D << ")\n");
Haojian Wu4775ce52017-01-17 13:22:37 +0000754 if (!UsedDecls.count(HelperDeclRGBuilder::getOutmostClassOrFunDecl(
755 D->getCanonicalDecl()))) {
Nicola Zaghen0efd5242018-05-15 16:37:45 +0000756 LLVM_DEBUG(llvm::dbgs() << "Helper removed in old.cc: "
757 << D->getNameAsString() << " (" << D << ")\n");
Haojian Wu36265162017-01-03 09:00:51 +0000758 RemovedDecls.push_back(D);
759 }
760 }
761 }
762
Haojian Wu08e402a2016-12-02 12:39:39 +0000763 for (const auto *RemovedDecl : RemovedDecls) {
764 const auto &SM = RemovedDecl->getASTContext().getSourceManager();
765 auto Range = getFullRange(RemovedDecl);
Haojian Wu357ef992016-09-21 13:18:19 +0000766 clang::tooling::Replacement RemoveReplacement(
Haojian Wu48ac3042016-11-23 10:04:19 +0000767 SM,
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000768 clang::CharSourceRange::getCharRange(Range.getBegin(), Range.getEnd()),
Haojian Wu357ef992016-09-21 13:18:19 +0000769 "");
770 std::string FilePath = RemoveReplacement.getFilePath().str();
Haojian Wub15c8da2016-11-24 10:17:17 +0000771 auto Err = Context->FileToReplacements[FilePath].add(RemoveReplacement);
Haojian Wu48ac3042016-11-23 10:04:19 +0000772 if (Err)
Haojian Wu53eab1e2016-10-14 13:43:49 +0000773 llvm::errs() << llvm::toString(std::move(Err)) << "\n";
Haojian Wu48ac3042016-11-23 10:04:19 +0000774 }
Haojian Wu08e402a2016-12-02 12:39:39 +0000775 const auto &SM = RemovedDecls[0]->getASTContext().getSourceManager();
Haojian Wu48ac3042016-11-23 10:04:19 +0000776
777 // Post process of cleanup around all the replacements.
Haojian Wub15c8da2016-11-24 10:17:17 +0000778 for (auto &FileAndReplacements : Context->FileToReplacements) {
Haojian Wu48ac3042016-11-23 10:04:19 +0000779 StringRef FilePath = FileAndReplacements.first;
780 // Add #include of new header to old header.
Haojian Wub15c8da2016-11-24 10:17:17 +0000781 if (Context->Spec.OldDependOnNew &&
Haojian Wu08e402a2016-12-02 12:39:39 +0000782 MakeAbsolutePath(SM, FilePath) ==
Haojian Wub15c8da2016-11-24 10:17:17 +0000783 makeAbsolutePath(Context->Spec.OldHeader)) {
Haojian Wu48ac3042016-11-23 10:04:19 +0000784 // FIXME: Minimize the include path like include-fixer.
Haojian Wub15c8da2016-11-24 10:17:17 +0000785 std::string IncludeNewH =
786 "#include \"" + Context->Spec.NewHeader + "\"\n";
Haojian Wu48ac3042016-11-23 10:04:19 +0000787 // This replacment for inserting header will be cleaned up at the end.
788 auto Err = FileAndReplacements.second.add(
789 tooling::Replacement(FilePath, UINT_MAX, 0, IncludeNewH));
790 if (Err)
791 llvm::errs() << llvm::toString(std::move(Err)) << "\n";
Haojian Wu53eab1e2016-10-14 13:43:49 +0000792 }
Haojian Wu253d5962016-10-06 08:29:32 +0000793
Haojian Wu48ac3042016-11-23 10:04:19 +0000794 auto SI = FilePathToFileID.find(FilePath);
795 // Ignore replacements for new.h/cc.
796 if (SI == FilePathToFileID.end()) continue;
Haojian Wu08e402a2016-12-02 12:39:39 +0000797 llvm::StringRef Code = SM.getBufferData(SI->second);
Antonio Maiorano0d7d9c22017-01-17 00:13:32 +0000798 auto Style = format::getStyle("file", FilePath, Context->FallbackStyle);
799 if (!Style) {
800 llvm::errs() << llvm::toString(Style.takeError()) << "\n";
801 continue;
802 }
Haojian Wu253d5962016-10-06 08:29:32 +0000803 auto CleanReplacements = format::cleanupAroundReplacements(
Antonio Maiorano0d7d9c22017-01-17 00:13:32 +0000804 Code, Context->FileToReplacements[FilePath], *Style);
Haojian Wu253d5962016-10-06 08:29:32 +0000805
806 if (!CleanReplacements) {
807 llvm::errs() << llvm::toString(CleanReplacements.takeError()) << "\n";
808 continue;
809 }
Haojian Wub15c8da2016-11-24 10:17:17 +0000810 Context->FileToReplacements[FilePath] = *CleanReplacements;
Haojian Wu357ef992016-09-21 13:18:19 +0000811 }
812}
813
Haojian Wu08e402a2016-12-02 12:39:39 +0000814void ClangMoveTool::moveDeclsToNewFiles() {
815 std::vector<const NamedDecl *> NewHeaderDecls;
816 std::vector<const NamedDecl *> NewCCDecls;
817 for (const auto *MovedDecl : MovedDecls) {
818 if (isInHeaderFile(MovedDecl, Context->OriginalRunningDirectory,
Haojian Wub15c8da2016-11-24 10:17:17 +0000819 Context->Spec.OldHeader))
Haojian Wu357ef992016-09-21 13:18:19 +0000820 NewHeaderDecls.push_back(MovedDecl);
821 else
822 NewCCDecls.push_back(MovedDecl);
823 }
824
Haojian Wu36265162017-01-03 09:00:51 +0000825 auto UsedDecls = getUsedDecls(RGBuilder.getGraph(), RemovedDecls);
826 std::vector<const NamedDecl *> ActualNewCCDecls;
827
828 // Filter out all unused helpers in NewCCDecls.
829 // We only move the used helpers (including transively used helpers) and the
830 // given symbols being moved.
831 for (const auto *D : NewCCDecls) {
832 if (llvm::is_contained(HelperDeclarations, D) &&
Haojian Wu4775ce52017-01-17 13:22:37 +0000833 !UsedDecls.count(HelperDeclRGBuilder::getOutmostClassOrFunDecl(
834 D->getCanonicalDecl())))
Haojian Wu36265162017-01-03 09:00:51 +0000835 continue;
836
Nicola Zaghen0efd5242018-05-15 16:37:45 +0000837 LLVM_DEBUG(llvm::dbgs() << "Helper used in new.cc: " << D->getNameAsString()
838 << " " << D << "\n");
Haojian Wu36265162017-01-03 09:00:51 +0000839 ActualNewCCDecls.push_back(D);
840 }
841
Haojian Wub15c8da2016-11-24 10:17:17 +0000842 if (!Context->Spec.NewHeader.empty()) {
Haojian Wu48ac3042016-11-23 10:04:19 +0000843 std::string OldHeaderInclude =
Haojian Wub15c8da2016-11-24 10:17:17 +0000844 Context->Spec.NewDependOnOld
845 ? "#include \"" + Context->Spec.OldHeader + "\"\n"
846 : "";
847 Context->FileToReplacements[Context->Spec.NewHeader] =
848 createInsertedReplacements(HeaderIncludes, NewHeaderDecls,
849 Context->Spec.NewHeader, /*IsHeader=*/true,
850 OldHeaderInclude);
Haojian Wu48ac3042016-11-23 10:04:19 +0000851 }
Haojian Wub15c8da2016-11-24 10:17:17 +0000852 if (!Context->Spec.NewCC.empty())
853 Context->FileToReplacements[Context->Spec.NewCC] =
Haojian Wu36265162017-01-03 09:00:51 +0000854 createInsertedReplacements(CCIncludes, ActualNewCCDecls,
855 Context->Spec.NewCC);
Haojian Wu357ef992016-09-21 13:18:19 +0000856}
857
Haojian Wu2930be12016-11-08 19:55:13 +0000858// Move all contents from OldFile to NewFile.
859void ClangMoveTool::moveAll(SourceManager &SM, StringRef OldFile,
860 StringRef NewFile) {
861 const FileEntry *FE = SM.getFileManager().getFile(makeAbsolutePath(OldFile));
862 if (!FE) {
863 llvm::errs() << "Failed to get file: " << OldFile << "\n";
864 return;
865 }
866 FileID ID = SM.getOrCreateFileID(FE, SrcMgr::C_User);
867 auto Begin = SM.getLocForStartOfFile(ID);
868 auto End = SM.getLocForEndOfFile(ID);
869 clang::tooling::Replacement RemoveAll (
870 SM, clang::CharSourceRange::getCharRange(Begin, End), "");
871 std::string FilePath = RemoveAll.getFilePath().str();
Haojian Wub15c8da2016-11-24 10:17:17 +0000872 Context->FileToReplacements[FilePath] =
873 clang::tooling::Replacements(RemoveAll);
Haojian Wu2930be12016-11-08 19:55:13 +0000874
875 StringRef Code = SM.getBufferData(ID);
876 if (!NewFile.empty()) {
877 auto AllCode = clang::tooling::Replacements(
878 clang::tooling::Replacement(NewFile, 0, 0, Code));
Haojian Wufb68ca12018-01-31 12:12:29 +0000879 auto ReplaceOldInclude = [&](clang::CharSourceRange OldHeaderIncludeRange) {
880 AllCode = AllCode.merge(clang::tooling::Replacements(
881 clang::tooling::Replacement(SM, OldHeaderIncludeRange,
882 '"' + Context->Spec.NewHeader + '"')));
883 };
884 // Fix the case where old.h/old.cc includes "old.h", we replace the
885 // `#include "old.h"` with `#include "new.h"`.
886 if (Context->Spec.NewCC == NewFile && OldHeaderIncludeRangeInCC.isValid())
887 ReplaceOldInclude(OldHeaderIncludeRangeInCC);
888 else if (Context->Spec.NewHeader == NewFile &&
889 OldHeaderIncludeRangeInHeader.isValid())
890 ReplaceOldInclude(OldHeaderIncludeRangeInHeader);
Haojian Wub15c8da2016-11-24 10:17:17 +0000891 Context->FileToReplacements[NewFile] = std::move(AllCode);
Haojian Wu2930be12016-11-08 19:55:13 +0000892 }
893}
894
Haojian Wu357ef992016-09-21 13:18:19 +0000895void ClangMoveTool::onEndOfTranslationUnit() {
Haojian Wub15c8da2016-11-24 10:17:17 +0000896 if (Context->DumpDeclarations) {
897 assert(Reporter);
898 for (const auto *Decl : UnremovedDeclsInOldHeader) {
899 auto Kind = Decl->getKind();
900 const std::string QualifiedName = Decl->getQualifiedNameAsString();
Haojian Wu4a920502017-02-27 13:19:13 +0000901 if (Kind == Decl::Kind::Var)
902 Reporter->reportDeclaration(QualifiedName, "Variable");
903 else if (Kind == Decl::Kind::Function ||
904 Kind == Decl::Kind::FunctionTemplate)
Haojian Wub15c8da2016-11-24 10:17:17 +0000905 Reporter->reportDeclaration(QualifiedName, "Function");
906 else if (Kind == Decl::Kind::ClassTemplate ||
907 Kind == Decl::Kind::CXXRecord)
908 Reporter->reportDeclaration(QualifiedName, "Class");
Haojian Wu85867722017-01-16 09:34:07 +0000909 else if (Kind == Decl::Kind::Enum)
910 Reporter->reportDeclaration(QualifiedName, "Enum");
911 else if (Kind == Decl::Kind::Typedef ||
912 Kind == Decl::Kind::TypeAlias ||
913 Kind == Decl::Kind::TypeAliasTemplate)
914 Reporter->reportDeclaration(QualifiedName, "TypeAlias");
Haojian Wub15c8da2016-11-24 10:17:17 +0000915 }
916 return;
917 }
918
Haojian Wu357ef992016-09-21 13:18:19 +0000919 if (RemovedDecls.empty())
920 return;
Haojian Wud4786342018-02-09 15:57:30 +0000921 // Ignore symbols that are not supported when checking if there is unremoved
922 // symbol in old header. This makes sure that we always move old files to new
923 // files when all symbols produced from dump_decls are moved.
Eric Liu47a42d52016-12-06 10:12:23 +0000924 auto IsSupportedKind = [](const clang::NamedDecl *Decl) {
925 switch (Decl->getKind()) {
926 case Decl::Kind::Function:
927 case Decl::Kind::FunctionTemplate:
928 case Decl::Kind::ClassTemplate:
929 case Decl::Kind::CXXRecord:
Haojian Wu32a552f2017-01-03 14:22:25 +0000930 case Decl::Kind::Enum:
Haojian Wud69d9072017-01-04 14:50:49 +0000931 case Decl::Kind::Typedef:
932 case Decl::Kind::TypeAlias:
933 case Decl::Kind::TypeAliasTemplate:
Haojian Wu4a920502017-02-27 13:19:13 +0000934 case Decl::Kind::Var:
Eric Liu47a42d52016-12-06 10:12:23 +0000935 return true;
936 default:
937 return false;
938 }
939 };
940 if (std::none_of(UnremovedDeclsInOldHeader.begin(),
941 UnremovedDeclsInOldHeader.end(), IsSupportedKind) &&
942 !Context->Spec.OldHeader.empty()) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000943 auto &SM = RemovedDecls[0]->getASTContext().getSourceManager();
Haojian Wub15c8da2016-11-24 10:17:17 +0000944 moveAll(SM, Context->Spec.OldHeader, Context->Spec.NewHeader);
945 moveAll(SM, Context->Spec.OldCC, Context->Spec.NewCC);
Haojian Wu2930be12016-11-08 19:55:13 +0000946 return;
947 }
Nicola Zaghen0efd5242018-05-15 16:37:45 +0000948 LLVM_DEBUG(RGBuilder.getGraph()->dump());
Haojian Wu08e402a2016-12-02 12:39:39 +0000949 moveDeclsToNewFiles();
Haojian Wu36265162017-01-03 09:00:51 +0000950 removeDeclsInOldFiles();
Haojian Wu357ef992016-09-21 13:18:19 +0000951}
952
953} // namespace move
954} // namespace clang