bump product version to 5.0.4.1
[LibreOffice.git] / compilerplugins / clang / inlinesimplememberfunctions.cxx
blob42dd2569df723884fdcead6bb213824af0dfd606
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3 * This file is part of the LibreOffice project.
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
8 */
10 #include <string>
12 #include "plugin.hxx"
13 #include "compat.hxx"
15 // Methods that purely return a local field should be declared in the header and be declared inline.
16 // So that the compiler can elide the function call and turn it into a simple fixed-offset-load instruction.
18 namespace {
20 class InlineSimpleMemberFunctions:
21 public RecursiveASTVisitor<InlineSimpleMemberFunctions>, public loplugin::RewritePlugin
23 public:
24 explicit InlineSimpleMemberFunctions(InstantiationData const & data): RewritePlugin(data) {}
26 virtual void run() override { TraverseDecl(compiler.getASTContext().getTranslationUnitDecl()); }
28 bool VisitCXXMethodDecl(const CXXMethodDecl * decl);
29 private:
30 bool rewrite(const CXXMethodDecl * functionDecl);
33 static bool oneAndOnlyOne(clang::Stmt::const_child_range range) {
34 if (range.empty()) {
35 return false;
37 if ((++range.first) != range.second) {
38 return false;
40 return true;
44 bool InlineSimpleMemberFunctions::VisitCXXMethodDecl(const CXXMethodDecl * functionDecl) {
45 if (ignoreLocation(functionDecl)) {
46 return true;
48 // no point in doing virtual methods, the compiler always has to generate a vtable entry and a method
49 if (functionDecl->isVirtual()) {
50 return true;
52 if (functionDecl->getTemplatedKind() != FunctionDecl::TK_NonTemplate) {
53 return true;
55 if (!functionDecl->isInstance()) {
56 return true;
58 if (!functionDecl->isOutOfLine()) {
59 return true;
61 if( !functionDecl->hasBody()) {
62 return true;
64 if( functionDecl->isInlineSpecified()) {
65 return true;
67 if( functionDecl->getCanonicalDecl()->isInlineSpecified()) {
68 return true;
70 if( functionDecl->getNameAsString().find("Impl") != std::string::npos) {
71 return true;
73 // ignore stuff that forms part of the stable URE interface
74 if (isInUnoIncludeFile(compiler.getSourceManager().getSpellingLoc(
75 functionDecl->getCanonicalDecl()->getNameInfo().getLoc()))) {
76 return true;
78 // ignore stuff like:
79 // template<class E> E * Sequence<E>::begin() { return getArray(); }
80 if( functionDecl->getParent()->getDescribedClassTemplate() != nullptr ) {
81 return true;
85 The chain here looks like
86 CompoundStmt
87 ReturnStmt
88 other stuff
89 CXXThisExpr
92 const CompoundStmt* compoundStmt = dyn_cast< CompoundStmt >( functionDecl->getBody() );
93 if (compoundStmt == nullptr) {
94 return true;
96 if (compoundStmt->body_begin() == compoundStmt->body_end()) {
97 return true;
101 const Stmt* childStmt = *compoundStmt->child_begin();
103 if (dyn_cast<ReturnStmt>( childStmt ) == nullptr) {
104 return true;
106 if (!oneAndOnlyOne(childStmt->children())) {
107 return true;
111 /* Don't warn if we see a method definition like
112 X X::a() {
113 return *this;
115 which translates to:
116 CompoundStmt
117 ReturnStmt
118 ImplicitCastExpr
119 UnaryOperator
120 CXXThisExpr
122 CompoundStmt
123 ReturnStmt
124 UnaryOperator
125 CXXThisExpr
127 childStmt = *childStmt->child_begin();
128 if (dyn_cast<ImplicitCastExpr>( childStmt ) != nullptr
129 && oneAndOnlyOne( childStmt->children() ))
131 const Stmt* childStmt2 = *childStmt->child_begin();
132 if (dyn_cast<UnaryOperator>( childStmt2 ) != nullptr
133 && oneAndOnlyOne(childStmt2->children()))
135 childStmt2 = *childStmt2->child_begin();
136 if (dyn_cast<CXXThisExpr>( childStmt2 ) != nullptr
137 && childStmt2->children().empty())
139 return true;
143 if (dyn_cast<UnaryOperator>( childStmt ) != nullptr
144 && oneAndOnlyOne( childStmt->children() ))
146 const Stmt* childStmt2 = *childStmt->child_begin();
147 if (dyn_cast<CXXThisExpr>( childStmt2 ) != nullptr
148 && childStmt2->children().empty())
150 return true;
154 /* look for a chains like:
155 CompoundStmt
156 ReturnStmt
157 stuff
158 CXXThisExpr
160 childStmt = *(*compoundStmt->child_begin())->child_begin();
161 while (1) {
162 if (dyn_cast<CallExpr>( childStmt ) != nullptr)
163 return true;
164 if (dyn_cast<CXXNewExpr>( childStmt ) != nullptr)
165 return true;
166 if (dyn_cast<CXXConstructExpr>( childStmt ) != nullptr)
167 return true;
168 if (dyn_cast<ConditionalOperator>( childStmt ) != nullptr)
169 return true;
170 if (dyn_cast<BinaryOperator>( childStmt ) != nullptr)
171 return true;
172 // exclude methods that return fields on incomplete types .e.g the pImpl pattern
173 const MemberExpr* memberExpr = dyn_cast<MemberExpr>( childStmt );
174 if (memberExpr != nullptr && memberExpr->getMemberDecl()) {
175 const FieldDecl* fieldDecl = dyn_cast<FieldDecl>(memberExpr->getMemberDecl());
176 if (fieldDecl != nullptr)
178 // yes, a little bit of a hack. However, it is quite hard to determine if the method
179 // in question is accessing a field via a pImpl pattern.
180 if (fieldDecl->getType()->isIncompleteType())
181 return true;
182 if (fieldDecl->getNameAsString().find("Impl") != std::string::npos)
183 return true;
184 if (fieldDecl->getNameAsString().find("pImp") != std::string::npos)
185 return true;
186 // somewhere in VCL
187 if (fieldDecl->getNameAsString().find("mpGlobalSyncData") != std::string::npos)
188 return true;
189 std::string s = fieldDecl->getType().getAsString();
190 if (s.find("Impl") != std::string::npos || s.find("pImp") != std::string::npos || s.find("Internal") != std::string::npos)
191 return true;
194 if (dyn_cast<CXXThisExpr>( childStmt ) != nullptr) {
195 if (!rewrite(functionDecl))
197 report(
198 DiagnosticsEngine::Warning,
199 "inlinesimpleaccessmethods",
200 functionDecl->getSourceRange().getBegin())
201 << functionDecl->getSourceRange();
202 // display the location of the class member declaration so I don't have to search for it by hand
203 report(
204 DiagnosticsEngine::Note,
205 "inlinesimpleaccessmethods",
206 functionDecl->getCanonicalDecl()->getSourceRange().getBegin())
207 << functionDecl->getCanonicalDecl()->getSourceRange();
209 return true;
211 if ( childStmt->children().empty() )
212 return true;
213 childStmt = *childStmt->child_begin();
215 return true;
218 static std::string ReplaceString(std::string subject, const std::string& search,
219 const std::string& replace) {
220 size_t pos = 0;
221 while ((pos = subject.find(search, pos)) != std::string::npos) {
222 subject.replace(pos, search.length(), replace);
223 pos += replace.length();
225 return subject;
228 bool InlineSimpleMemberFunctions::rewrite(const CXXMethodDecl * functionDecl) {
229 if (rewriter == nullptr) {
230 return false;
232 // Only rewrite declarations in include files if a
233 // definition is also seen, to avoid compilation of a
234 // definition (in a main file only processed later) to fail
235 // with a "mismatch" error before the rewriter had a chance
236 // to act upon the definition.
237 if (!compat::isInMainFile( compiler.getSourceManager(),
238 compiler.getSourceManager().getSpellingLoc(
239 functionDecl->getNameInfo().getLoc()))) {
240 return false;
243 const char *p1, *p2;
245 // get the function body contents
246 p1 = compiler.getSourceManager().getCharacterData( functionDecl->getBody()->getLocStart() );
247 p2 = compiler.getSourceManager().getCharacterData( functionDecl->getBody()->getLocEnd() );
248 std::string s1( p1, p2 - p1 + 1);
250 /* we can't safely move around stuff containing comments, we mess up the resulting code */
251 if ( s1.find("/*") != std::string::npos || s1.find("//") != std::string::npos ) {
252 return false;
255 // strip linefeeds and any double-spaces, so we have a max of one space between tokens
256 s1 = ReplaceString(s1, "\r", "");
257 s1 = ReplaceString(s1, "\n", "");
258 s1 = ReplaceString(s1, "\t", " ");
259 s1 = ReplaceString(s1, " ", " ");
260 s1 = ReplaceString(s1, " ", " ");
261 s1 = ReplaceString(s1, " ", " ");
262 s1 = " " + s1;
264 // scan from the end of the function's body through the trailing whitespace, so we can do a nice clean remove
265 // commented out because for some reason it will sometimes chomp an extra token
266 // SourceLocation endOfRemoveLoc = functionDecl->getBody()->getLocEnd();
267 // for (;;) {
268 // endOfRemoveLoc = endOfRemoveLoc.getLocWithOffset(1);
269 // p1 = compiler.getSourceManager().getCharacterData( endOfRemoveLoc );
270 // if (*p1 != ' ' && *p1 != '\r' && *p1 != '\n' && *p1 != '\t')
271 // break;
272 // }
274 // remove the function's out of line body and declaration
275 RewriteOptions opts;
276 opts.RemoveLineIfEmpty = true;
277 if (!removeText(SourceRange(functionDecl->getLocStart(), functionDecl->getBody()->getLocEnd()), opts)) {
278 return false;
281 // scan forward until we find the semicolon
282 const FunctionDecl * canonicalDecl = functionDecl->getCanonicalDecl();
283 p1 = compiler.getSourceManager().getCharacterData( canonicalDecl->getLocEnd() );
284 p2 = ++p1;
285 while (*p2 != 0 && *p2 != ';') p2++;
287 // insert the function body into the inline function definition (i.e. the one inside the class definition)
288 return replaceText(canonicalDecl->getLocEnd().getLocWithOffset(p2 - p1 + 1), 1, s1);
291 loplugin::Plugin::Registration< InlineSimpleMemberFunctions > X("inlinesimplememberfunctions");
295 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */