summaryrefslogtreecommitdiffstats
path: root/compilerplugins/clang/reducevarscope.cxx
blob: c293fd432e6a26a7076478590dccc14bd26a2961 (plain)
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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
/* -*- 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 <map>
#include <set>
#include <vector>
#include <unordered_map>
#include <unordered_set>

#include "plugin.hxx"
#include "check.hxx"
#include "clang/AST/CXXInheritance.h"
#include "clang/AST/StmtVisitor.h"

// Original idea from mike kaganski.
// Look for variables that can have their scoped reduced, which makes the code easier to read.

// TODO when dealing with vars that are referenced in multiple child blocks, the check is very primitive
// and could be greatly improved.

namespace
{
class ReduceVarScope : public loplugin::FilteringPlugin<ReduceVarScope>
{
public:
    explicit ReduceVarScope(loplugin::InstantiationData const& data)
        : FilteringPlugin(data)
    {
    }

    bool preRun() override
    {
        if (!compiler.getLangOpts().CPlusPlus)
            return false;
        // ignore some files with problematic macros
        std::string fn(handler.getMainFileName());
        loplugin::normalizeDotDotInFilePath(fn);
        // some declarations look better all together
        if (fn == SRCDIR "/package/source/manifest/ManifestExport.cxx")
            return false;
        // storing pointer to OUString internal data
        if (fn == SRCDIR "/connectivity/source/drivers/odbc/ODatabaseMetaDataResultSet.cxx"
            || fn == SRCDIR "/sc/source/filter/excel/xestyle.cxx"
            || fn == SRCDIR "/sw/source/filter/html/htmlflywriter.cxx"
            || fn == SRCDIR "/unoxml/source/dom/element.cxx"
            || fn == SRCDIR "/unoxml/source/dom/document.cxx"
            || fn == SRCDIR "/sd/source/filter/eppt/pptx-animations.cxx")
            return false;
        if (fn == SRCDIR "/sal/qa/rtl/strings/nonconstarray.cxx")
            return false;
        return true;
    }

    virtual void run() override
    {
        if (!preRun())
            return;

        TraverseDecl(compiler.getASTContext().getTranslationUnitDecl());
        postRun();
    }

    virtual void postRun() override
    {
        for (auto const& pair : maVarDeclMap)
        {
            auto varDecl = pair.first;
            auto const& depthInfo = pair.second;
            if (depthInfo.maDeclBlockPath.size() == depthInfo.maCommonBlockPath.size())
                continue;
            if (maVarDeclToIgnoreSet.find(varDecl) != maVarDeclToIgnoreSet.end())
                continue;
            auto it = maVarUseSourceRangeMap.find(varDecl);
            if (it == maVarUseSourceRangeMap.end())
                continue;
            report(DiagnosticsEngine::Warning, "can reduce scope of var", varDecl->getLocation())
                << varDecl->getSourceRange();
            for (SourceRange const& useRange : it->second)
                report(DiagnosticsEngine::Note, "used here", useRange.getBegin()) << useRange;
        }
    }

    bool VisitUnaryOperator(UnaryOperator const* expr)
    {
        // if we take the address of it
        UnaryOperator::Opcode op = expr->getOpcode();
        if (op == UO_AddrOf)
            recordIgnore(expr->getSubExpr());
        return true;
    }

    bool VisitDeclRefExpr(const DeclRefExpr*);
    bool VisitVarDecl(const VarDecl*);
    bool VisitLambdaExpr(const LambdaExpr*);

    bool PreTraverseFunctionDecl(FunctionDecl*);
    bool PostTraverseFunctionDecl(FunctionDecl*, bool);
    bool TraverseFunctionDecl(FunctionDecl*);

    bool PreTraverseCompoundStmt(CompoundStmt*);
    bool PostTraverseCompoundStmt(CompoundStmt*, bool);
    bool TraverseCompoundStmt(CompoundStmt*);

    bool PreTraverseWhileStmt(WhileStmt*);
    bool PostTraverseWhileStmt(WhileStmt*, bool);
    bool TraverseWhileStmt(WhileStmt*);

    bool PreTraverseDoStmt(DoStmt*);
    bool PostTraverseDoStmt(DoStmt*, bool);
    bool TraverseDoStmt(DoStmt*);

    bool PreTraverseCXXForRangeStmt(CXXForRangeStmt*);
    bool PostTraverseCXXForRangeStmt(CXXForRangeStmt*, bool);
    bool TraverseCXXForRangeStmt(CXXForRangeStmt*);

    bool PreTraverseForStmt(ForStmt*);
    bool PostTraverseForStmt(ForStmt*, bool);
    bool TraverseForStmt(ForStmt*);

    bool PreTraverseSwitchStmt(SwitchStmt*);
    bool PostTraverseSwitchStmt(SwitchStmt*, bool);
    bool TraverseSwitchStmt(SwitchStmt*);

private:
    struct DepthInfo
    {
        unsigned int mnFirstDepth = 0;
        unsigned int mnFirstLoopDepth = 0;
        std::vector<unsigned int> maDeclBlockPath = {};
        std::vector<unsigned int> maCommonBlockPath = {};
    };
    std::unordered_map<VarDecl const*, DepthInfo> maVarDeclMap; // varDecl->depth
    std::unordered_set<VarDecl const*> maVarDeclToIgnoreSet;
    std::map<VarDecl const*, std::vector<SourceRange>> maVarUseSourceRangeMap;
    std::vector<unsigned int> maCurrentBlockPath;
    unsigned int mnCurrentDepth = 0;
    unsigned int mnCurrentLoopDepth = 0;
    static unsigned int gnBlockId;

    bool isTypeOK(QualType qt);
    bool isInitConstant(const VarDecl* varDecl);

    void recordIgnore(Expr const* expr)
    {
        for (;;)
        {
            expr = expr->IgnoreParenImpCasts();
            if (auto const e = dyn_cast<MemberExpr>(expr))
            {
                if (isa<FieldDecl>(e->getMemberDecl()))
                {
                    expr = e->getBase();
                    continue;
                }
            }
            if (auto const e = dyn_cast<ArraySubscriptExpr>(expr))
            {
                expr = e->getBase();
                continue;
            }
            if (auto const e = dyn_cast<BinaryOperator>(expr))
            {
                if (e->getOpcode() == BO_PtrMemD)
                {
                    expr = e->getLHS();
                    continue;
                }
            }
            break;
        }
        auto const dre = dyn_cast<DeclRefExpr>(expr);
        if (dre == nullptr)
            return;
        auto const var = dyn_cast<VarDecl>(dre->getDecl());
        if (var == nullptr)
            return;
        maVarDeclToIgnoreSet.insert(var);
    }
};

unsigned int ReduceVarScope::gnBlockId = 0;

bool ReduceVarScope::PreTraverseFunctionDecl(FunctionDecl* functionDecl)
{
    // Ignore functions that contains #ifdef-ery, can be quite tricky
    // to make useful changes when this plugin fires in such functions
    if (containsPreprocessingConditionalInclusion(functionDecl->getSourceRange()))
        return false;
    return true;
}

bool ReduceVarScope::PostTraverseFunctionDecl(FunctionDecl*, bool) { return true; }

bool ReduceVarScope::TraverseFunctionDecl(FunctionDecl* functionDecl)
{
    bool ret = true;
    if (PreTraverseFunctionDecl(functionDecl))
    {
        ret = FilteringPlugin::TraverseFunctionDecl(functionDecl);
        PostTraverseFunctionDecl(functionDecl, ret);
    }
    return ret;
}

bool ReduceVarScope::PreTraverseCompoundStmt(CompoundStmt*)
{
    assert(mnCurrentDepth != std::numeric_limits<unsigned int>::max());
    ++mnCurrentDepth;
    ++gnBlockId;
    maCurrentBlockPath.push_back(gnBlockId);
    return true;
}

bool ReduceVarScope::PostTraverseCompoundStmt(CompoundStmt*, bool)
{
    assert(mnCurrentDepth != 0);
    --mnCurrentDepth;
    maCurrentBlockPath.pop_back();
    return true;
}

bool ReduceVarScope::TraverseCompoundStmt(CompoundStmt* decl)
{
    bool ret = true;
    if (PreTraverseCompoundStmt(decl))
    {
        ret = FilteringPlugin::TraverseCompoundStmt(decl);
        PostTraverseCompoundStmt(decl, ret);
    }
    return ret;
}

bool ReduceVarScope::PreTraverseWhileStmt(WhileStmt*)
{
    assert(mnCurrentLoopDepth != std::numeric_limits<unsigned int>::max());
    ++mnCurrentLoopDepth;
    return true;
}

bool ReduceVarScope::PostTraverseWhileStmt(WhileStmt*, bool)
{
    assert(mnCurrentLoopDepth != 0);
    --mnCurrentLoopDepth;
    return true;
}

bool ReduceVarScope::TraverseWhileStmt(WhileStmt* decl)
{
    bool ret = true;
    if (PreTraverseWhileStmt(decl))
    {
        ret = FilteringPlugin::TraverseWhileStmt(decl);
        PostTraverseWhileStmt(decl, ret);
    }
    return ret;
}

bool ReduceVarScope::PreTraverseDoStmt(DoStmt*)
{
    assert(mnCurrentLoopDepth != std::numeric_limits<unsigned int>::max());
    ++mnCurrentLoopDepth;
    return true;
}

bool ReduceVarScope::PostTraverseDoStmt(DoStmt*, bool)
{
    assert(mnCurrentLoopDepth != 0);
    --mnCurrentLoopDepth;
    return true;
}

bool ReduceVarScope::TraverseDoStmt(DoStmt* decl)
{
    bool ret = true;
    if (PreTraverseDoStmt(decl))
    {
        ret = FilteringPlugin::TraverseDoStmt(decl);
        PostTraverseDoStmt(decl, ret);
    }
    return ret;
}

bool ReduceVarScope::PreTraverseSwitchStmt(SwitchStmt*)
{
    assert(mnCurrentLoopDepth != std::numeric_limits<unsigned int>::max());
    ++mnCurrentLoopDepth;
    return true;
}

bool ReduceVarScope::PostTraverseSwitchStmt(SwitchStmt*, bool)
{
    assert(mnCurrentLoopDepth != 0);
    --mnCurrentLoopDepth;
    return true;
}

// Consider a switch to be a loop, because weird things happen inside it
bool ReduceVarScope::TraverseSwitchStmt(SwitchStmt* decl)
{
    bool ret = true;
    if (PreTraverseSwitchStmt(decl))
    {
        ret = FilteringPlugin::TraverseSwitchStmt(decl);
        PostTraverseSwitchStmt(decl, ret);
    }
    return ret;
}

bool ReduceVarScope::PreTraverseCXXForRangeStmt(CXXForRangeStmt*)
{
    assert(mnCurrentLoopDepth != std::numeric_limits<unsigned int>::max());
    ++mnCurrentLoopDepth;
    return true;
}

bool ReduceVarScope::PostTraverseCXXForRangeStmt(CXXForRangeStmt*, bool)
{
    assert(mnCurrentLoopDepth != 0);
    --mnCurrentLoopDepth;
    return true;
}

bool ReduceVarScope::TraverseCXXForRangeStmt(CXXForRangeStmt* decl)
{
    bool ret = true;
    if (PreTraverseCXXForRangeStmt(decl))
    {
        ret = FilteringPlugin::TraverseCXXForRangeStmt(decl);
        PostTraverseCXXForRangeStmt(decl, ret);
    }
    return ret;
}

bool ReduceVarScope::PreTraverseForStmt(ForStmt* forStmt)
{
    assert(mnCurrentLoopDepth != std::numeric_limits<unsigned int>::max());
    ++mnCurrentLoopDepth;

    auto declStmt = dyn_cast_or_null<DeclStmt>(forStmt->getInit());
    if (declStmt)
    {
        if (declStmt->isSingleDecl())
        {
            if (auto varDecl = dyn_cast_or_null<VarDecl>(declStmt->getSingleDecl()))
                maVarDeclToIgnoreSet.insert(varDecl);
        }
        else
        {
            for (auto const& decl : declStmt->getDeclGroup())
                if (auto varDecl = dyn_cast_or_null<VarDecl>(decl))
                    maVarDeclToIgnoreSet.insert(varDecl);
        }
    }

    return true;
}

bool ReduceVarScope::PostTraverseForStmt(ForStmt*, bool)
{
    assert(mnCurrentLoopDepth != 0);
    --mnCurrentLoopDepth;
    return true;
}

bool ReduceVarScope::TraverseForStmt(ForStmt* decl)
{
    bool ret = true;
    if (PreTraverseForStmt(decl))
    {
        ret = FilteringPlugin::TraverseForStmt(decl);
        PostTraverseForStmt(decl, ret);
    }
    return ret;
}

bool ReduceVarScope::VisitVarDecl(const VarDecl* varDecl)
{
    if (ignoreLocation(varDecl))
        return true;
    if (varDecl->isExceptionVariable() || isa<ParmVarDecl>(varDecl))
        return true;
    // ignore stuff in header files (which should really not be there, but anyhow)
    if (!compiler.getSourceManager().isInMainFile(varDecl->getLocation()))
        return true;
    // Ignore macros like FD_ZERO
    if (compiler.getSourceManager().isMacroBodyExpansion(compat::getBeginLoc(varDecl)))
        return true;
    if (varDecl->hasGlobalStorage())
        return true;
    if (varDecl->isConstexpr())
        return true;
    if (varDecl->isInitCapture())
        return true;
    if (varDecl->isCXXForRangeDecl())
        return true;
    if (!isTypeOK(varDecl->getType()))
        return true;

    if (varDecl->hasInit() && !isInitConstant(varDecl))
        return true;

    maVarDeclMap[varDecl].mnFirstDepth = mnCurrentDepth;
    maVarDeclMap[varDecl].mnFirstLoopDepth = mnCurrentLoopDepth;
    maVarDeclMap[varDecl].maDeclBlockPath = maCurrentBlockPath;

    return true;
}

bool ReduceVarScope::isInitConstant(const VarDecl* varDecl)
{
    // check for string or scalar literals
    const Expr* initExpr = varDecl->getInit();
    if (auto e = dyn_cast<ExprWithCleanups>(initExpr))
        initExpr = e->getSubExpr();
    if (isa<clang::StringLiteral>(initExpr))
        return true;
    if (auto constructExpr = dyn_cast<CXXConstructExpr>(initExpr))
    {
        if (constructExpr->getNumArgs() == 0)
        {
            return true; // i.e., empty string
        }
        else
        {
            auto stringLit2 = dyn_cast<clang::StringLiteral>(constructExpr->getArg(0));
            if (stringLit2)
                return true;
        }
    }

    auto const init = varDecl->getInit();
    if (init->isValueDependent())
        return false;
    return init->isConstantInitializer(compiler.getASTContext(), false /*ForRef*/);
}

bool ReduceVarScope::isTypeOK(QualType varType)
{
    // TODO improve this - requires more analysis because it's really easy to
    // take a pointer to an array
    if (varType->isArrayType())
        return false;

    if (varType.isCXX11PODType(compiler.getASTContext()))
        return true;
    if (!varType->isRecordType())
        return false;
    auto recordDecl = dyn_cast_or_null<CXXRecordDecl>(varType->getAs<RecordType>()->getDecl());
    if (recordDecl && recordDecl->hasTrivialDestructor())
        return true;
    auto const tc = loplugin::TypeCheck(varType);
    // Safe types with destructors that don't do anything interesting
    if (tc.Class("OString").Namespace("rtl").GlobalNamespace()
        || tc.Class("OUString").Namespace("rtl").GlobalNamespace()
        || tc.Class("OStringBuffer").Namespace("rtl").GlobalNamespace()
        || tc.Class("OUStringBuffer").Namespace("rtl").GlobalNamespace()
        || tc.Class("Color").GlobalNamespace() || tc.Class("Pair").GlobalNamespace()
        || tc.Class("Point").GlobalNamespace() || tc.Class("Size").GlobalNamespace()
        || tc.Class("Range").GlobalNamespace() || tc.Class("Selection").GlobalNamespace()
        || tc.Class("Rectangle").Namespace("tools").GlobalNamespace())
        return true;
    return false;
}

bool ReduceVarScope::VisitDeclRefExpr(const DeclRefExpr* declRefExpr)
{
    if (ignoreLocation(declRefExpr))
        return true;
    const Decl* decl = declRefExpr->getDecl();
    if (!isa<VarDecl>(decl) || isa<ParmVarDecl>(decl))
        return true;
    const VarDecl* varDecl = dyn_cast<VarDecl>(decl)->getCanonicalDecl();
    // ignore stuff in header files (which should really not be there, but anyhow)
    if (!compiler.getSourceManager().isInMainFile(varDecl->getLocation()))
        return true;

    auto varIt = maVarDeclMap.find(varDecl);
    if (varIt == maVarDeclMap.end())
        return true;

    auto& depthInfo = varIt->second;

    // merge block paths to get common ancestor path
    if (depthInfo.maCommonBlockPath.empty())
        depthInfo.maCommonBlockPath = maCurrentBlockPath;
    else
    {
        auto len = std::min(depthInfo.maCommonBlockPath.size(), maCurrentBlockPath.size());
        unsigned int i = 0;
        while (i < len && depthInfo.maCommonBlockPath[i] == maCurrentBlockPath[i])
            ++i;
        depthInfo.maCommonBlockPath.resize(i);
        if (depthInfo.maCommonBlockPath == depthInfo.maDeclBlockPath)
        {
            maVarDeclMap.erase(varIt);
            maVarUseSourceRangeMap.erase(varDecl);
            return true;
        }
    }

    // seen in a loop below initial decl
    if (mnCurrentLoopDepth > depthInfo.mnFirstLoopDepth)
    {
        // TODO, we could additionally check if we are reading or writing to the var inside a loop
        // We only need to exclude vars that are written to, or passed taken-addr-of, or have non-const method called,
        // or passed as arg to non-const-ref parameter.
        maVarDeclMap.erase(varIt);
        maVarUseSourceRangeMap.erase(varDecl);
        return true;
    }

    auto it = maVarUseSourceRangeMap.find(varDecl);
    if (it == maVarUseSourceRangeMap.end())
        it = maVarUseSourceRangeMap.emplace(varDecl, std::vector<SourceRange>()).first;
    it->second.push_back(declRefExpr->getSourceRange());

    return true;
}

bool ReduceVarScope::VisitLambdaExpr(const LambdaExpr* lambdaExpr)
{
    if (ignoreLocation(lambdaExpr))
        return true;
    for (auto captureIt = lambdaExpr->capture_begin(); captureIt != lambdaExpr->capture_end();
         ++captureIt)
    {
        const LambdaCapture& capture = *captureIt;
        if (capture.capturesVariable())
        {
            auto varDecl = capture.getCapturedVar();
            maVarDeclMap.erase(varDecl);
            maVarUseSourceRangeMap.erase(varDecl);
        }
    }
    return true;
}

loplugin::Plugin::Registration<ReduceVarScope> reducevarscope("reducevarscope", false);
}

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