1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 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
 67
 68
 69
 70
 71
 72
 73
 74
 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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
/* -*- 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 <cassert>
#include <string>
#include <iostream>
#include <fstream>
#include <set>
#include <unordered_map>


#include "clang/AST/Attr.h"

#include "plugin.hxx"
#include "compat.hxx"

/**
 Find methods that are only called from inside their own class, and are only called from one spot.
 They are candidates to be removed and have their code inlined into the call site.


 TODO if a method has only one call-site, and that call site is inside a constructor
     then it's probably worth inlining, since it's probably an old method that was intended to be shared amongst
     multiple constructors
*/

namespace {

struct MyFuncInfo
{
    std::string access;
    std::string returnType;
    std::string nameAndParams;
    std::string sourceLocation;

};
bool operator < (const MyFuncInfo &lhs, const MyFuncInfo &rhs)
{
    return std::tie(lhs.returnType, lhs.nameAndParams)
         < std::tie(rhs.returnType, rhs.nameAndParams);
}

// try to limit the voluminous output a little

static std::set<std::pair<std::string, MyFuncInfo>> calledFromSet;
static std::set<MyFuncInfo> definitionSet;
static std::set<MyFuncInfo> calledFromOutsideSet;
static std::set<MyFuncInfo> largeFunctionSet;
static std::set<MyFuncInfo> addressOfSet;


class ExpandableMethods:
    public RecursiveASTVisitor<ExpandableMethods>, public loplugin::Plugin
{
public:
    explicit ExpandableMethods(loplugin::InstantiationData const & data):
        Plugin(data) {}

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

        // dump all our output in one write call - this is to try and limit IO "crosstalk" between multiple processes
        // writing to the same logfile

        std::string output;
        for (const MyFuncInfo & s : definitionSet)
            output += "definition:\t" + s.access + "\t" + s.returnType + "\t" + s.nameAndParams + "\t" + s.sourceLocation + "\n";<--- Consider using std::accumulate algorithm instead of a raw loop.
        for (const MyFuncInfo & s : calledFromOutsideSet)
            output += "outside:\t" + s.returnType + "\t" + s.nameAndParams + "\n";<--- Consider using std::accumulate algorithm instead of a raw loop.
        for (const std::pair<std::string,MyFuncInfo> & s : calledFromSet)
            output += "calledFrom:\t" + s.first<--- Consider using std::accumulate algorithm instead of a raw loop.
                       + "\t" + s.second.returnType + "\t" + s.second.nameAndParams + "\n";
        for (const MyFuncInfo & s : largeFunctionSet)
            output += "large:\t" + s.returnType + "\t" + s.nameAndParams + "\n";<--- Consider using std::accumulate algorithm instead of a raw loop.
        for (const MyFuncInfo & s : addressOfSet)
            output += "addrof:\t" + s.returnType + "\t" + s.nameAndParams + "\n";<--- Consider using std::accumulate algorithm instead of a raw loop.
        std::ofstream myfile;
        myfile.open( WORKDIR "/loplugin.expandablemethods.log", std::ios::app | std::ios::out);
        myfile << output;
        myfile.close();
    }

    bool shouldVisitTemplateInstantiations () const { return true; }
    bool shouldVisitImplicitCode() const { return true; }

    bool VisitFunctionDecl( const FunctionDecl* );
    bool VisitDeclRefExpr( const DeclRefExpr* );
    bool VisitMemberExpr( const MemberExpr* );
    // interception methods for FunctionDecl and all its subclasses
    bool TraverseFunctionDecl( FunctionDecl* );
    bool TraverseCXXMethodDecl( CXXMethodDecl* );
    bool TraverseCXXConstructorDecl( CXXConstructorDecl* );
    bool TraverseCXXConversionDecl( CXXConversionDecl* );
    bool TraverseCXXDestructorDecl( CXXDestructorDecl* );

private:
    MyFuncInfo niceName(const FunctionDecl* functionDecl);
    std::string toString(SourceLocation loc);
    void functionTouchedFromExpr( const FunctionDecl* calleeFunctionDecl, const Expr* expr );
    bool isCalleeFunctionInteresting( const FunctionDecl* );

    // I use traverse and a member variable because I cannot find a reliable way of walking back up the AST tree using the parentStmt() stuff
    std::vector<const FunctionDecl*> maTraversingFunctions;
};

MyFuncInfo ExpandableMethods::niceName(const FunctionDecl* functionDecl)
{
    if (functionDecl->getInstantiatedFromMemberFunction())
        functionDecl = functionDecl->getInstantiatedFromMemberFunction();
#if CLANG_VERSION < 90000
    else if (functionDecl->getClassScopeSpecializationPattern())
        functionDecl = functionDecl->getClassScopeSpecializationPattern();
#endif
    else if (functionDecl->getTemplateInstantiationPattern())
        functionDecl = functionDecl->getTemplateInstantiationPattern();

    MyFuncInfo aInfo;
    switch (functionDecl->getAccess())
    {
    case AS_public: aInfo.access = "public"; break;
    case AS_private: aInfo.access = "private"; break;
    case AS_protected: aInfo.access = "protected"; break;
    default: aInfo.access = "unknown"; break;
    }
    if (!isa<CXXConstructorDecl>(functionDecl)) {
        aInfo.returnType = functionDecl->getReturnType().getCanonicalType().getAsString();
    } else {
        aInfo.returnType = "";
    }

    if (isa<CXXMethodDecl>(functionDecl)) {
        const CXXRecordDecl* recordDecl = dyn_cast<CXXMethodDecl>(functionDecl)->getParent();
        aInfo.nameAndParams += recordDecl->getQualifiedNameAsString();
        aInfo.nameAndParams += "::";
    }
    aInfo.nameAndParams += functionDecl->getNameAsString() + "(";
    bool bFirst = true;
    for (const ParmVarDecl *pParmVarDecl : functionDecl->parameters()) {
        if (bFirst)
            bFirst = false;
        else
            aInfo.nameAndParams += ",";
        aInfo.nameAndParams += pParmVarDecl->getType().getCanonicalType().getAsString();
    }
    aInfo.nameAndParams += ")";
    if (isa<CXXMethodDecl>(functionDecl) && dyn_cast<CXXMethodDecl>(functionDecl)->isConst()) {
        aInfo.nameAndParams += " const";
    }

    aInfo.sourceLocation = toString( functionDecl->getLocation() );

    return aInfo;
}

std::string ExpandableMethods::toString(SourceLocation loc)
{
    SourceLocation expansionLoc = compiler.getSourceManager().getExpansionLoc( loc );
    StringRef name = getFilenameOfLocation(expansionLoc);
    std::string sourceLocation = std::string(name.substr(strlen(SRCDIR)+1)) + ":" + std::to_string(compiler.getSourceManager().getSpellingLineNumber(expansionLoc));
    loplugin::normalizeDotDotInFilePath(sourceLocation);
    return sourceLocation;
}

bool ExpandableMethods::VisitFunctionDecl( const FunctionDecl* functionDecl )
{
    const FunctionDecl* canonicalFunctionDecl = functionDecl->getCanonicalDecl();
    if (!isCalleeFunctionInteresting(canonicalFunctionDecl)) {
        return true;
    }
    definitionSet.insert(niceName(canonicalFunctionDecl));

    if (functionDecl->doesThisDeclarationHaveABody()) {
        bool bLargeFunction = false;
        if (const CompoundStmt* compoundStmt = dyn_cast<CompoundStmt>(functionDecl->getBody())) {
            if (compoundStmt->size() > 1) {
                bLargeFunction = true;
            }
            if (!bLargeFunction) {
                 auto s1 = compiler.getSourceManager().getCharacterData(compoundStmt->getLBracLoc());
                 auto s2 = compiler.getSourceManager().getCharacterData(compoundStmt->getRBracLoc());
                 bLargeFunction = (s2 - s1) > 40;
                 // any function that uses a parameter more than once
                 if (!bLargeFunction) {
                     StringRef bodyText(s1, s2-s1);
                     for (const ParmVarDecl* param : functionDecl->parameters()) {
                         StringRef name = param->getName();
                         if (name.empty())
                             continue;
                         size_t idx = bodyText.find(name);
                         if (idx != StringRef::npos && bodyText.find(name, idx+1) != StringRef::npos) {
                             bLargeFunction = true;
                             break;
                         }
                     }
                 }
            }
        }
        if (bLargeFunction) {
            largeFunctionSet.insert(niceName(canonicalFunctionDecl));
        }
    }
    return true;
}

bool ExpandableMethods::TraverseFunctionDecl( FunctionDecl* p )
{
    maTraversingFunctions.push_back(p);
    bool ret = RecursiveASTVisitor::TraverseFunctionDecl(p);
    maTraversingFunctions.pop_back();
    return ret;
}
bool ExpandableMethods::TraverseCXXMethodDecl( CXXMethodDecl* p )
{
    maTraversingFunctions.push_back(p);
    bool ret = RecursiveASTVisitor::TraverseCXXMethodDecl(p);
    maTraversingFunctions.pop_back();
    return ret;
}
bool ExpandableMethods::TraverseCXXConstructorDecl( CXXConstructorDecl* p )
{
    maTraversingFunctions.push_back(p);
    bool ret = RecursiveASTVisitor::TraverseCXXConstructorDecl(p);
    maTraversingFunctions.pop_back();
    return ret;
}
bool ExpandableMethods::TraverseCXXConversionDecl( CXXConversionDecl* p )
{
    maTraversingFunctions.push_back(p);
    bool ret = RecursiveASTVisitor::TraverseCXXConversionDecl(p);
    maTraversingFunctions.pop_back();
    return ret;
}
bool ExpandableMethods::TraverseCXXDestructorDecl( CXXDestructorDecl* p )
{
    maTraversingFunctions.push_back(p);
    bool ret = RecursiveASTVisitor::TraverseCXXDestructorDecl(p);
    maTraversingFunctions.pop_back();
    return ret;
}

bool ExpandableMethods::VisitMemberExpr( const MemberExpr* memberExpr )
{
    const FunctionDecl* functionDecl = dyn_cast<FunctionDecl>(memberExpr->getMemberDecl());
    if (functionDecl) {
        functionTouchedFromExpr(functionDecl, memberExpr);
    }
    return true;
}

bool ExpandableMethods::VisitDeclRefExpr( const DeclRefExpr* declRefExpr )
{
    const FunctionDecl* functionDecl = dyn_cast<FunctionDecl>(declRefExpr->getDecl());
    if (functionDecl) {
        functionTouchedFromExpr(functionDecl, declRefExpr);
    }
    return true;
}

void ExpandableMethods::functionTouchedFromExpr( const FunctionDecl* calleeFunctionDecl, const Expr* expr )
{
    const FunctionDecl* canonicalFunctionDecl = calleeFunctionDecl->getCanonicalDecl();
    if (!isCalleeFunctionInteresting(canonicalFunctionDecl)) {
        return;
    }

    calledFromSet.emplace(toString(compat::getBeginLoc(expr)), niceName(canonicalFunctionDecl));

    if (const UnaryOperator* unaryOp = dyn_cast_or_null<UnaryOperator>(getParentStmt(expr))) {
        if (unaryOp->getOpcode() == UO_AddrOf) {
            addressOfSet.insert(niceName(canonicalFunctionDecl));
        }
    }

    const CXXMethodDecl* calleeMethodDecl = dyn_cast<CXXMethodDecl>(calleeFunctionDecl);
    if (maTraversingFunctions.empty())
    {
        calledFromOutsideSet.insert(niceName(canonicalFunctionDecl));
    }
    else
    {
        const CXXMethodDecl* callsiteParentMethodDecl = dyn_cast<CXXMethodDecl>(maTraversingFunctions.back());
        if (!callsiteParentMethodDecl
            || calleeMethodDecl->getParent() != callsiteParentMethodDecl->getParent())
        {
            calledFromOutsideSet.insert(niceName(canonicalFunctionDecl));
        }
    }
}

bool ExpandableMethods::isCalleeFunctionInteresting(const FunctionDecl* functionDecl)
{
    // ignore stuff that forms part of the stable URE interface
    if (isInUnoIncludeFile(functionDecl)) {
        return false;
    }
    if (isa<CXXDestructorDecl>(functionDecl)) {
        return false;
    }
    if (functionDecl->isDeleted() || functionDecl->isDefaulted()) {
        return false;
    }
    if (isa<CXXConstructorDecl>(functionDecl)
        && dyn_cast<CXXConstructorDecl>(functionDecl)->isCopyOrMoveConstructor())
    {
        return false;
    }
    if (!functionDecl->getLocation().isValid() || ignoreLocation(functionDecl)) {
        return false;
    }
    const CXXMethodDecl* methodDecl = dyn_cast<CXXMethodDecl>(functionDecl);
    if (!methodDecl || methodDecl->isVirtual()) {
        return false;
    }
    return true;
}

loplugin::Plugin::Registration< ExpandableMethods > X("expandablemethods", false);

}

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