inlinesimplememberfunctions.cxx 10.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include <string>

#include "plugin.hxx"
13
#include "compat.hxx"
14 15 16 17 18 19 20

// Methods that purely return a local field should be declared in the header and be declared inline.
// So that the compiler can elide the function call and turn it into a simple fixed-offset-load instruction.

namespace {

class InlineSimpleMemberFunctions:
21
    public loplugin::FilteringRewritePlugin<InlineSimpleMemberFunctions>
22 23
{
public:
24
    explicit InlineSimpleMemberFunctions(loplugin::InstantiationData const & data): FilteringRewritePlugin(data) {}
25 26 27 28 29 30 31 32 33

    virtual void run() override { TraverseDecl(compiler.getASTContext().getTranslationUnitDecl()); }

    bool VisitCXXMethodDecl(const CXXMethodDecl * decl);
private:
    bool rewrite(const CXXMethodDecl * functionDecl);
};

static bool oneAndOnlyOne(clang::Stmt::const_child_range range) {
34
    if (range.begin() == range.end()) {
35 36
        return false;
    }
37
    if (++range.begin() != range.end()) {
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
        return false;
    }
    return true;
}


bool InlineSimpleMemberFunctions::VisitCXXMethodDecl(const CXXMethodDecl * functionDecl) {
    if (ignoreLocation(functionDecl)) {
        return true;
    }
    // no point in doing virtual methods, the compiler always has to generate a vtable entry and a method
    if (functionDecl->isVirtual()) {
        return true;
    }
    if (functionDecl->getTemplatedKind() != FunctionDecl::TK_NonTemplate) {
        return true;
    }
    if (!functionDecl->isInstance()) {
        return true;
    }
    if (!functionDecl->isOutOfLine()) {
        return true;
    }
    if( !functionDecl->hasBody()) {
        return true;
    }
    if( functionDecl->isInlineSpecified()) {
        return true;
    }
67 68 69 70 71 72
    if( functionDecl->getCanonicalDecl()->isInlineSpecified()) {
        return true;
    }
    if( functionDecl->getNameAsString().find("Impl") != std::string::npos) {
        return true;
    }
73
    // ignore stuff that forms part of the stable URE interface
74
    if (isInUnoIncludeFile(functionDecl)) {
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
        return true;
    }
    // ignore stuff like:
    //   template<class E> E * Sequence<E>::begin() { return getArray(); }
    if( functionDecl->getParent()->getDescribedClassTemplate() != nullptr ) {
        return true;
    }

    /*
      The chain here looks like
        CompoundStmt
          ReturnStmt
            other stuff
              CXXThisExpr
    */

    const CompoundStmt* compoundStmt = dyn_cast< CompoundStmt >( functionDecl->getBody() );
    if (compoundStmt == nullptr) {
        return true;
    }
    if (compoundStmt->body_begin() == compoundStmt->body_end()) {
        return true;
    }


    const Stmt* childStmt = *compoundStmt->child_begin();

    if (dyn_cast<ReturnStmt>( childStmt ) == nullptr) {
        return true;
    }
    if (!oneAndOnlyOne(childStmt->children())) {
        return true;
    }


    /* Don't warn if we see a method definition like
         X X::a() {
             return *this;
         }
      which translates to:
        CompoundStmt
          ReturnStmt
            ImplicitCastExpr
              UnaryOperator
                CXXThisExpr
      or:
        CompoundStmt
          ReturnStmt
            UnaryOperator
              CXXThisExpr
    */
    childStmt = *childStmt->child_begin();
    if (dyn_cast<ImplicitCastExpr>( childStmt ) != nullptr
        && oneAndOnlyOne( childStmt->children() ))
    {
        const Stmt* childStmt2 = *childStmt->child_begin();
        if (dyn_cast<UnaryOperator>( childStmt2 ) != nullptr
            && oneAndOnlyOne(childStmt2->children()))
        {
            childStmt2 = *childStmt2->child_begin();
            if (dyn_cast<CXXThisExpr>( childStmt2 ) != nullptr
136
                && childStmt2->children().begin() == childStmt2->children().end())
137 138 139 140 141 142 143 144 145 146
            {
                return true;
            }
        }
    }
    if (dyn_cast<UnaryOperator>( childStmt ) != nullptr
        && oneAndOnlyOne( childStmt->children() ))
    {
        const Stmt* childStmt2 = *childStmt->child_begin();
        if (dyn_cast<CXXThisExpr>( childStmt2 ) != nullptr
147
            && childStmt2->children().begin() == childStmt2->children().end())
148 149 150 151 152
        {
            return true;
        }
    }

153
    /* look for a chains like:
154 155
       CompoundStmt
         ReturnStmt
156 157
           stuff
             CXXThisExpr
158
    */
Noel Grandin's avatar
Noel Grandin committed
159 160
    childStmt = *(*compoundStmt->child_begin())->child_begin();
    while (1) {
161 162 163 164 165 166 167 168 169
        if (dyn_cast<CallExpr>( childStmt ) != nullptr)
            return true;
        if (dyn_cast<CXXNewExpr>( childStmt ) != nullptr)
            return true;
        if (dyn_cast<CXXConstructExpr>( childStmt ) != nullptr)
            return true;
        if (dyn_cast<ConditionalOperator>( childStmt ) != nullptr)
            return true;
        if (dyn_cast<BinaryOperator>( childStmt ) != nullptr)
Noel Grandin's avatar
Noel Grandin committed
170
            return true;
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
        // exclude methods that return fields on incomplete types .e.g the pImpl pattern
        const MemberExpr* memberExpr = dyn_cast<MemberExpr>( childStmt );
        if (memberExpr != nullptr && memberExpr->getMemberDecl()) {
            const FieldDecl* fieldDecl = dyn_cast<FieldDecl>(memberExpr->getMemberDecl());
            if (fieldDecl != nullptr)
            {
                // yes, a little bit of a hack. However, it is quite hard to determine if the method
                // in question is accessing a field via a pImpl pattern.
                if (fieldDecl->getType()->isIncompleteType())
                    return true;
                if (fieldDecl->getNameAsString().find("Impl") != std::string::npos)
                    return true;
                if (fieldDecl->getNameAsString().find("pImp") != std::string::npos)
                    return true;
                // somewhere in VCL
                if (fieldDecl->getNameAsString().find("mpGlobalSyncData") != std::string::npos)
                    return true;
                std::string s = fieldDecl->getType().getAsString();
                if (s.find("Impl") != std::string::npos || s.find("pImp") != std::string::npos || s.find("Internal") != std::string::npos)
                    return true;
            }
        }
Noel Grandin's avatar
Noel Grandin committed
193
        if (dyn_cast<CXXThisExpr>( childStmt ) != nullptr) {
194 195 196 197 198 199 200 201 202 203 204 205 206
            if (!rewrite(functionDecl))
            {
                report(
                    DiagnosticsEngine::Warning,
                    "inlinesimpleaccessmethods",
                    functionDecl->getSourceRange().getBegin())
                  << functionDecl->getSourceRange();
                // display the location of the class member declaration so I don't have to search for it by hand
                report(
                    DiagnosticsEngine::Note,
                    "inlinesimpleaccessmethods",
                    functionDecl->getCanonicalDecl()->getSourceRange().getBegin())
                  << functionDecl->getCanonicalDecl()->getSourceRange();
Noel Grandin's avatar
Noel Grandin committed
207 208 209
                }
             return true;
        }
210
        if ( childStmt->children().begin() == childStmt->children().end() )
211
            return true;
Noel Grandin's avatar
Noel Grandin committed
212 213
        childStmt = *childStmt->child_begin();
    }
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
    return true;
}

static std::string ReplaceString(std::string subject, const std::string& search,
                          const std::string& replace) {
    size_t pos = 0;
    while ((pos = subject.find(search, pos)) != std::string::npos) {
         subject.replace(pos, search.length(), replace);
         pos += replace.length();
    }
    return subject;
}

bool InlineSimpleMemberFunctions::rewrite(const CXXMethodDecl * functionDecl) {
    if (rewriter == nullptr) {
        return false;
    }
    // Only rewrite declarations in include files if a
    // definition is also seen, to avoid compilation of a
    // definition (in a main file only processed later) to fail
    // with a "mismatch" error before the rewriter had a chance
    // to act upon the definition.
236 237 238 239
    if (!compiler.getSourceManager().isInMainFile(
            compiler.getSourceManager().getSpellingLoc(
                functionDecl->getNameInfo().getLoc())))
    {
240 241 242 243 244 245
        return false;
    }

    const char *p1, *p2;

    // get the function body contents
246 247
    p1 = compiler.getSourceManager().getCharacterData( compat::getBeginLoc(functionDecl->getBody()) );
    p2 = compiler.getSourceManager().getCharacterData( compat::getEndLoc(functionDecl->getBody()) );
248
    std::string s1( p1, p2 - p1 + 1);
249 250 251 252 253 254

    /* we can't safely move around stuff containing comments, we mess up the resulting code */
    if ( s1.find("/*") != std::string::npos || s1.find("//") != std::string::npos ) {
        return false;
    }

255 256 257 258 259 260 261 262 263
    // strip linefeeds and any double-spaces, so we have a max of one space between tokens
    s1 = ReplaceString(s1, "\r", "");
    s1 = ReplaceString(s1, "\n", "");
    s1 = ReplaceString(s1, "\t", " ");
    s1 = ReplaceString(s1, "  ", " ");
    s1 = ReplaceString(s1, "  ", " ");
    s1 = ReplaceString(s1, "  ", " ");
    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 266 267 268 269 270 271 272 273 274 275 276
// commented out because for some reason it will sometimes chomp an extra token
//    SourceLocation endOfRemoveLoc = functionDecl->getBody()->getLocEnd();
//    for (;;) {
//        endOfRemoveLoc = endOfRemoveLoc.getLocWithOffset(1);
//        p1 = compiler.getSourceManager().getCharacterData( endOfRemoveLoc );
//        if (*p1 != ' ' && *p1 != '\r' && *p1 != '\n' && *p1 != '\t')
//            break;
//    }

    // remove the function's out of line body and declaration
    RewriteOptions opts;
    opts.RemoveLineIfEmpty = true;
277
    if (!removeText(SourceRange(compat::getBeginLoc(functionDecl), compat::getEndLoc(functionDecl->getBody())), opts)) {
278 279 280 281 282
        return false;
    }

    // scan forward until we find the semicolon
    const FunctionDecl * canonicalDecl = functionDecl->getCanonicalDecl();
283
    p1 = compiler.getSourceManager().getCharacterData( compat::getEndLoc(canonicalDecl) );
284 285 286 287
    p2 = ++p1;
    while (*p2 != 0 && *p2 != ';') p2++;

    // insert the function body into the inline function definition (i.e. the one inside the class definition)
288
    return replaceText(compat::getEndLoc(canonicalDecl).getLocWithOffset(p2 - p1 + 1), 1, s1);
289 290
}

291
loplugin::Plugin::Registration< InlineSimpleMemberFunctions > X("inlinesimplememberfunctions");
292 293 294 295

}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */