unusedmethods.cxx 14.9 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 <cassert>
#include <string>
#include <iostream>
13
#include <fstream>
14
#include <set>
15 16
#include <unordered_map>

17 18 19

#include "clang/AST/Attr.h"

20 21 22
#include "plugin.hxx"

/**
23 24 25 26 27 28 29 30
This plugin performs 3 different analyses:

(1) Find unused methods
(2) Find methods whose return types are never evaluated
(3) Find methods which are public, but are never called from outside the class i.e. they can be private

It does so, by dumping various call/definition/use info to a log file.
Then we will post-process the various lists and find the set of unused methods.
31

32
Be warned that it produces around 15G of log file.
33 34 35

The process goes something like this:
  $ make check
36
  $ make FORCE_COMPILE_ALL=1 COMPILER_PLUGIN_TOOL='unusedmethods' check
37
  $ ./compilerplugins/clang/unusedmethods.py
38 39 40 41 42 43 44 45 46 47 48 49

and then
  $ for dir in *; do make FORCE_COMPILE_ALL=1 UPDATE_FILES=$dir COMPILER_PLUGIN_TOOL='unusedmethodsremove' $dir; done
to auto-remove the method declarations

Note that the actual process may involve a fair amount of undoing, hand editing, and general messing around
to get it to work :-)

*/

namespace {

Noel Grandin's avatar
Noel Grandin committed
50 51
struct MyFuncInfo
{
52
    std::string access;
Noel Grandin's avatar
Noel Grandin committed
53 54 55
    std::string returnType;
    std::string nameAndParams;
    std::string sourceLocation;
56
    std::string virtualness;
Noel Grandin's avatar
Noel Grandin committed
57 58

};
59 60
bool operator < (const MyFuncInfo &lhs, const MyFuncInfo &rhs)
{
61 62
    return std::tie(lhs.returnType, lhs.nameAndParams)
         < std::tie(rhs.returnType, rhs.nameAndParams);
63
}
Noel Grandin's avatar
Noel Grandin committed
64

65
// try to limit the voluminous output a little
66 67

// for the "unused method" analysis
Noel Grandin's avatar
Noel Grandin committed
68 69
static std::set<MyFuncInfo> callSet;
static std::set<MyFuncInfo> definitionSet;
70 71
// for the "unused return type" analysis
static std::set<MyFuncInfo> usedReturnSet;
72
// for the "can be private" analysis
73
static std::set<MyFuncInfo> calledFromOutsideSet;
74 75


76
class UnusedMethods:
77
    public RecursiveASTVisitor<UnusedMethods>, public loplugin::Plugin
78 79
{
public:
80
    explicit UnusedMethods(loplugin::InstantiationData const & data):
81
        Plugin(data) {}
82

83 84 85 86 87 88
    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
89

90
        std::string output;
91
        for (const MyFuncInfo & s : definitionSet)
92 93
            output += "definition:\t" + s.access + "\t" + s.returnType + "\t" + s.nameAndParams
                      + "\t" + s.sourceLocation + "\t" + s.virtualness + "\n";
94
        // for the "unused method" analysis
Noel Grandin's avatar
Noel Grandin committed
95 96
        for (const MyFuncInfo & s : callSet)
            output += "call:\t" + s.returnType + "\t" + s.nameAndParams + "\n";
97
        // for the "unused return type" analysis
98 99
        for (const MyFuncInfo & s : usedReturnSet)
            output += "usedReturn:\t" + s.returnType + "\t" + s.nameAndParams + "\n";
100
        // for the "method can be private" analysis
101 102
        for (const MyFuncInfo & s : calledFromOutsideSet)
            output += "outside:\t" + s.returnType + "\t" + s.nameAndParams + "\n";
103
        std::ofstream myfile;
104
        myfile.open( WORKDIR "/loplugin.unusedmethods.log", std::ios::app | std::ios::out);
105 106 107
        myfile << output;
        myfile.close();
    }
108

Noel Grandin's avatar
Noel Grandin committed
109
    bool shouldVisitTemplateInstantiations () const { return true; }
110
    bool shouldVisitImplicitCode() const { return true; }
Noel Grandin's avatar
Noel Grandin committed
111

112
    bool VisitCallExpr(CallExpr* );
113
    bool VisitFunctionDecl( const FunctionDecl* decl );
114
    bool VisitDeclRefExpr( const DeclRefExpr* );
115
    bool VisitCXXConstructExpr( const CXXConstructExpr* );
116
    bool TraverseCXXRecordDecl( CXXRecordDecl* );
117 118 119
    bool TraverseFunctionDecl( FunctionDecl* );
    bool TraverseCXXMethodDecl( CXXMethodDecl* );
    bool TraverseCXXConversionDecl( CXXConversionDecl* );
120
    bool TraverseCXXDeductionGuideDecl( CXXDeductionGuideDecl* );
121

Noel Grandin's avatar
Noel Grandin committed
122
private:
123
    void logCallToRootMethods(const FunctionDecl* functionDecl, std::set<MyFuncInfo>& funcSet);
Noel Grandin's avatar
Noel Grandin committed
124
    MyFuncInfo niceName(const FunctionDecl* functionDecl);
125 126
    std::string toString(SourceLocation loc);
    void functionTouchedFromExpr( const FunctionDecl* calleeFunctionDecl, const Expr* expr );
127
    CXXRecordDecl const * currentCxxRecordDecl = nullptr;
128
    FunctionDecl const * currentFunctionDecl = nullptr;
129 130
};

Noel Grandin's avatar
Noel Grandin committed
131
MyFuncInfo UnusedMethods::niceName(const FunctionDecl* functionDecl)
132
{
Noel Grandin's avatar
Noel Grandin committed
133 134
    if (functionDecl->getInstantiatedFromMemberFunction())
        functionDecl = functionDecl->getInstantiatedFromMemberFunction();
135
#if CLANG_VERSION < 90000
Noel Grandin's avatar
Noel Grandin committed
136 137
    else if (functionDecl->getClassScopeSpecializationPattern())
        functionDecl = functionDecl->getClassScopeSpecializationPattern();
138
#endif
Noel Grandin's avatar
Noel Grandin committed
139 140 141
    else if (functionDecl->getTemplateInstantiationPattern())
        functionDecl = functionDecl->getTemplateInstantiationPattern();

Noel Grandin's avatar
Noel Grandin committed
142
    MyFuncInfo aInfo;
143 144 145 146 147 148 149
    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;
    }
150
    if (!isa<CXXConstructorDecl>(functionDecl)) {
151
        aInfo.returnType = functionDecl->getReturnType().getCanonicalType().getAsString();
152 153 154
    } else {
        aInfo.returnType = "";
    }
Noel Grandin's avatar
Noel Grandin committed
155

Noel Grandin's avatar
Noel Grandin committed
156
    if (auto methodDecl = dyn_cast<CXXMethodDecl>(functionDecl)) {
157
        const CXXRecordDecl* recordDecl = methodDecl->getParent();
Noel Grandin's avatar
Noel Grandin committed
158 159 160 161
        aInfo.nameAndParams = recordDecl->getQualifiedNameAsString()
                + "::"
                + functionDecl->getNameAsString()
                + "(";
162 163
        if (methodDecl->isVirtual())
            aInfo.virtualness = "virtual";
164
    }
Noel Grandin's avatar
Noel Grandin committed
165 166 167 168
    else
    {
        aInfo.nameAndParams = functionDecl->getQualifiedNameAsString() + "(";
    }
169
    bool bFirst = true;
170
    for (const ParmVarDecl *pParmVarDecl : functionDecl->parameters()) {
171 172 173
        if (bFirst)
            bFirst = false;
        else
Noel Grandin's avatar
Noel Grandin committed
174 175
            aInfo.nameAndParams += ",";
        aInfo.nameAndParams += pParmVarDecl->getType().getCanonicalType().getAsString();
176
    }
Noel Grandin's avatar
Noel Grandin committed
177
    aInfo.nameAndParams += ")";
178
    if (isa<CXXMethodDecl>(functionDecl) && dyn_cast<CXXMethodDecl>(functionDecl)->isConst()) {
Noel Grandin's avatar
Noel Grandin committed
179
        aInfo.nameAndParams += " const";
180
    }
Noel Grandin's avatar
Noel Grandin committed
181

182
    aInfo.sourceLocation = toString( functionDecl->getLocation() );
Noel Grandin's avatar
Noel Grandin committed
183 184

    return aInfo;
185 186
}

187 188 189 190 191
std::string UnusedMethods::toString(SourceLocation loc)
{
    SourceLocation expansionLoc = compiler.getSourceManager().getExpansionLoc( loc );
    StringRef name = compiler.getSourceManager().getFilename(expansionLoc);
    std::string sourceLocation = std::string(name.substr(strlen(SRCDIR)+1)) + ":" + std::to_string(compiler.getSourceManager().getSpellingLineNumber(expansionLoc));
192
    loplugin::normalizeDotDotInFilePath(sourceLocation);
193 194 195 196 197
    return sourceLocation;
}

// For virtual/overriding methods, we need to pretend we called the root method(s),
// so that they get marked as used.
198
void UnusedMethods::logCallToRootMethods(const FunctionDecl* functionDecl, std::set<MyFuncInfo>& funcSet)
199
{
200
    functionDecl = functionDecl->getCanonicalDecl();
Noel Grandin's avatar
Noel Grandin committed
201
    bool bCalledSuperMethod = false;
202 203 204 205 206
    if (isa<CXXMethodDecl>(functionDecl)) {
        const CXXMethodDecl* methodDecl = dyn_cast<CXXMethodDecl>(functionDecl);
        for(CXXMethodDecl::method_iterator it = methodDecl->begin_overridden_methods();
            it != methodDecl->end_overridden_methods(); ++it)
        {
207
            logCallToRootMethods(*it, funcSet);
Noel Grandin's avatar
Noel Grandin committed
208
            bCalledSuperMethod = true;
209
        }
210
    }
Noel Grandin's avatar
Noel Grandin committed
211
    if (!bCalledSuperMethod)
212
    {
Noel Grandin's avatar
Noel Grandin committed
213 214
        while (functionDecl->getTemplateInstantiationPattern())
            functionDecl = functionDecl->getTemplateInstantiationPattern();
215 216 217
        if (functionDecl->getLocation().isValid() && !ignoreLocation( functionDecl )
             && !functionDecl->isExternC())
            funcSet.insert(niceName(functionDecl));
218 219 220 221 222
    }
}

bool UnusedMethods::VisitCallExpr(CallExpr* expr)
{
Noel Grandin's avatar
Noel Grandin committed
223 224
    // Note that I don't ignore ANYTHING here, because I want to get calls to my code that result
    // from template instantiation deep inside the STL and other external code
225

226
    FunctionDecl* calleeFunctionDecl = expr->getDirectCallee();
227
    if (calleeFunctionDecl == nullptr) {
Noel Grandin's avatar
Noel Grandin committed
228 229 230 231 232 233 234
        Expr* callee = expr->getCallee()->IgnoreParenImpCasts();
        DeclRefExpr* dr = dyn_cast<DeclRefExpr>(callee);
        if (dr) {
            calleeFunctionDecl = dyn_cast<FunctionDecl>(dr->getDecl());
            if (calleeFunctionDecl)
                goto gotfunc;
        }
235 236
        return true;
    }
Noel Grandin's avatar
Noel Grandin committed
237 238

gotfunc:
239

240 241 242 243 244 245 246 247 248 249

    if (currentFunctionDecl == calleeFunctionDecl)
        ; // for "unused method" analysis, ignore recursive calls
    else if (currentFunctionDecl
            && currentFunctionDecl->getIdentifier()
            && currentFunctionDecl->getName() == "Clone"
            && currentFunctionDecl->getParent() == calleeFunctionDecl->getParent()
            && isa<CXXConstructorDecl>(calleeFunctionDecl))
        ; // if we are inside Clone(), ignore calls to the same class's constructor
    else
250
        logCallToRootMethods(calleeFunctionDecl, callSet);
251

252
    const Stmt* parent = getParentStmt(expr);
253

254
    // Now do the checks necessary for the "can be private" analysis
255
    CXXMethodDecl* calleeMethodDecl = dyn_cast<CXXMethodDecl>(calleeFunctionDecl);
256
    if (calleeMethodDecl && calleeMethodDecl->getAccess() != AS_private)
257
    {
258
        const FunctionDecl* parentFunctionOfCallSite = getParentFunctionDecl(expr);
259 260 261
        if (parentFunctionOfCallSite != calleeFunctionDecl) {
            if (!parentFunctionOfCallSite || !ignoreLocation(parentFunctionOfCallSite)) {
                calledFromOutsideSet.insert(niceName(calleeFunctionDecl));
262
            }
263 264 265 266
        }
    }

    // Now do the checks necessary for the "unused return value" analysis
267
    if (calleeFunctionDecl->getReturnType()->isVoidType()) {
268 269 270
        return true;
    }
    if (!parent) {
271 272
        // we will get null parent if it's under a CXXConstructExpr node
        logCallToRootMethods(calleeFunctionDecl, usedReturnSet);
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
        return true;
    }
    if (isa<Expr>(parent) || isa<ReturnStmt>(parent) || isa<DeclStmt>(parent)
        || isa<IfStmt>(parent) || isa<SwitchStmt>(parent) || isa<ForStmt>(parent)
        || isa<WhileStmt>(parent) || isa<DoStmt>(parent)
        || isa<CXXForRangeStmt>(parent))
    {
        logCallToRootMethods(calleeFunctionDecl, usedReturnSet);
        return true;
    }
    if (isa<CompoundStmt>(parent) || isa<DefaultStmt>(parent) || isa<CaseStmt>(parent)
        || isa<LabelStmt>(parent))
    {
        return true;
    }
    parent->dump();
289 290 291
    return true;
}

292 293 294 295 296 297 298 299
bool UnusedMethods::VisitCXXConstructExpr( const CXXConstructExpr* constructExpr )
{
    // Note that I don't ignore ANYTHING here, because I want to get calls to my code that result
    // from template instantiation deep inside the STL and other external code

    const CXXConstructorDecl* constructorDecl = constructExpr->getConstructor();
    constructorDecl = constructorDecl->getCanonicalDecl();

300 301 302 303
    if (!constructorDecl->getLocation().isValid() || ignoreLocation(constructorDecl)) {
        return true;
    }

304 305
    logCallToRootMethods(constructorDecl, callSet);

306 307 308 309
    // Now do the checks necessary for the "can be private" analysis
    if (constructorDecl->getParent() != currentCxxRecordDecl)
        calledFromOutsideSet.insert(niceName(constructorDecl));

310 311 312
    return true;
}

313
bool UnusedMethods::VisitFunctionDecl( const FunctionDecl* functionDecl )
314 315
{
    // ignore stuff that forms part of the stable URE interface
316
    if (isInUnoIncludeFile(functionDecl)) {
317 318
        return true;
    }
319
    const FunctionDecl* canonicalFunctionDecl = functionDecl->getCanonicalDecl();
320 321 322
    if (isa<CXXDestructorDecl>(functionDecl)) {
        return true;
    }
323
    if (functionDecl->isDeleted() || functionDecl->isDefaulted()) {
324 325
        return true;
    }
326 327 328
    if (isa<CXXConstructorDecl>(functionDecl)
        && dyn_cast<CXXConstructorDecl>(functionDecl)->isCopyOrMoveConstructor())
    {
329 330
        return true;
    }
331 332 333 334 335 336 337 338 339 340
    if (!canonicalFunctionDecl->getLocation().isValid() || ignoreLocation(canonicalFunctionDecl)) {
        return true;
    }
    // ignore method overrides, since the call will show up as being directed to the root method
    const CXXMethodDecl* methodDecl = dyn_cast<CXXMethodDecl>(functionDecl);
    if (methodDecl && (methodDecl->size_overridden_methods() != 0 || methodDecl->hasAttr<OverrideAttr>())) {
        return true;
    }
    if (!functionDecl->isExternC()) {
        MyFuncInfo funcInfo = niceName(canonicalFunctionDecl);
341 342
        definitionSet.insert(funcInfo);
    }
343 344 345 346 347
    return true;
}

bool UnusedMethods::VisitDeclRefExpr( const DeclRefExpr* declRefExpr )
{
348 349
    const FunctionDecl* functionDecl = dyn_cast<FunctionDecl>(declRefExpr->getDecl());
    if (!functionDecl) {
350 351
        return true;
    }
352 353
    logCallToRootMethods(functionDecl->getCanonicalDecl(), callSet);
    logCallToRootMethods(functionDecl->getCanonicalDecl(), usedReturnSet);
354 355 356 357 358

    // Now do the checks necessary for the "can be private" analysis
    const CXXMethodDecl* methodDecl = dyn_cast<CXXMethodDecl>(functionDecl);
    if (methodDecl && methodDecl->getAccess() != AS_private)
    {
359
        const FunctionDecl* parentFunctionOfCallSite = getParentFunctionDecl(declRefExpr);
360 361 362 363 364 365 366
        if (parentFunctionOfCallSite != functionDecl) {
            if (!parentFunctionOfCallSite || !ignoreLocation(parentFunctionOfCallSite)) {
                calledFromOutsideSet.insert(niceName(functionDecl));
            }
        }
    }

367 368 369
    return true;
}

370 371 372 373 374 375 376 377 378
bool UnusedMethods::TraverseCXXRecordDecl(CXXRecordDecl* cxxRecordDecl)
{
    auto copy = currentCxxRecordDecl;
    currentCxxRecordDecl = cxxRecordDecl;
    bool ret = RecursiveASTVisitor::TraverseCXXRecordDecl(cxxRecordDecl);
    currentCxxRecordDecl = copy;
    return ret;
}

379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
bool UnusedMethods::TraverseFunctionDecl(FunctionDecl* f)
{
    auto copy = currentFunctionDecl;
    currentFunctionDecl = f;
    bool ret = RecursiveASTVisitor::TraverseFunctionDecl(f);
    currentFunctionDecl = copy;
    return ret;
}
bool UnusedMethods::TraverseCXXMethodDecl(CXXMethodDecl* f)
{
    auto copy = currentFunctionDecl;
    currentFunctionDecl = f;
    bool ret = RecursiveASTVisitor::TraverseCXXMethodDecl(f);
    currentFunctionDecl = copy;
    return ret;
}
bool UnusedMethods::TraverseCXXConversionDecl(CXXConversionDecl* f)
{
    auto copy = currentFunctionDecl;
    currentFunctionDecl = f;
    bool ret = RecursiveASTVisitor::TraverseCXXConversionDecl(f);
    currentFunctionDecl = copy;
    return ret;
}
403 404 405 406 407 408 409 410
bool UnusedMethods::TraverseCXXDeductionGuideDecl(CXXDeductionGuideDecl* f)
{
    auto copy = currentFunctionDecl;
    currentFunctionDecl = f;
    bool ret = RecursiveASTVisitor::TraverseCXXDeductionGuideDecl(f);
    currentFunctionDecl = copy;
    return ret;
}
411

412
loplugin::Plugin::Registration< UnusedMethods > X("unusedmethods", false);
413 414 415 416

}

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