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
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * Based on LLVM/Clang.
 *
 * This file is distributed under the University of Illinois Open Source
 * License. See LICENSE.TXT for details.
 *
*/

#ifndef LO_CLANG_SHARED_PLUGINS

#include <algorithm>
#include <cassert>
#include <list>
#include <map>

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

// Idea from bubli. Check that the index variable in a for loop is able to cover the range
// revealed by the terminating condition.
// If not, we might end up in an endless loop, or just not process certain parts.

namespace
{

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

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

    bool VisitForStmt( const ForStmt* stmt ) {<--- The function 'VisitForStmt' is never used.
        checkExpr(stmt->getCond());
        return true;
    }

    bool VisitWhileStmt(WhileStmt const * stmt) {<--- The function 'VisitWhileStmt' is never used.
        checkExpr(stmt->getCond());
        return true;
    }

    bool VisitDoStmt(DoStmt const * stmt) {<--- The function 'VisitDoStmt' is never used.
        checkExpr(stmt->getCond());
        return true;
    }

private:
    unsigned getIntValueWidth(QualType type) const;

    void checkSubExpr(Expr const * expr, bool positive);

    void checkExpr(Expr const * expr);

    struct Comparison {
        BinaryOperator const * op;
        unsigned rhsWidth;
    };

    struct Comparisons {
        std::list<Comparison> comparisons;
        unsigned lhsWidth;
    };

    std::map<Decl const *, Comparisons> comparisons_;
};

unsigned LoopVarTooSmall::getIntValueWidth(QualType type) const {
    if (auto const et = type->getAs<EnumType>()) {
        auto const ed = et->getDecl();
        if (!ed->isFixed()) {
            unsigned pos = ed->getNumPositiveBits();
            unsigned neg = ed->getNumNegativeBits();
            return neg == 0 ? std::max(pos, 1U) : std::max(pos + 1, neg);
        }
    }
    return compiler.getASTContext().getIntWidth(type);
}

void LoopVarTooSmall::checkSubExpr(Expr const * expr, bool positive) {
    auto const e = expr->IgnoreImplicit()->IgnoreParenImpCasts();
    if (auto const uo = dyn_cast<UnaryOperator>(e)) {
        if (uo->getOpcode() == UO_LNot) {
            checkSubExpr(uo->getSubExpr(), !positive);
        }
        return;
    }
    const BinaryOperator* binOp = dyn_cast<BinaryOperator>(e);
    if (!binOp)
        return;
    bool less;
    if (positive) {
        switch (binOp->getOpcode()) {
        case BO_LAnd:
            checkSubExpr(binOp->getLHS(), true);
            checkSubExpr(binOp->getRHS(), true);
            return;
        case BO_LT:
        case BO_NE:
            less = true;
            break;
        case BO_LE:
            less = false;
            break;
        default:
            return;
        }
    } else {
        switch (binOp->getOpcode()) {
        case BO_LOr:
            checkSubExpr(binOp->getLHS(), false);
            checkSubExpr(binOp->getRHS(), false);
            return;
        case BO_GE:
        case BO_EQ:
            less = true;
            break;
        case BO_GT:
            less = false;
            break;
        default:
            return;
        }
    }
    auto lhs = dyn_cast<DeclRefExpr>(binOp->getLHS()->IgnoreParenImpCasts());
    if (!lhs)
        return;
    QualType qt = lhs->getType();
    if (!qt->isIntegralOrEnumerationType())
        return;
    unsigned qt1BitWidth = getIntValueWidth(qt);
    auto lhsDecl = lhs->getDecl();
    if (!isa<VarDecl>(lhsDecl)) {
        if (auto fd = dyn_cast<FieldDecl>(lhsDecl)) {
            if (fd->isBitField()) {
                qt1BitWidth = std::max(
                    qt1BitWidth,
                    fd->getBitWidthValue(compiler.getASTContext()));
            }
        } else {
            return;
        }
    }
    const Expr* binOpRHS = binOp->getRHS()->IgnoreParenImpCasts();
    QualType qt2 = binOpRHS->getType();
    if (!qt2->isIntegralType(compiler.getASTContext()))
        return;
    unsigned qt2BitWidth;
    llvm::APSInt aIntResult;
    // Work around missing Clang 3.9 fix <https://reviews.llvm.org/rL271762>
    // "Sema: do not attempt to sizeof a dependent type", causing Clang 3.8 to
    // crash during EvaluateAsInt() on expressions of the form
    //
    //   sizeof (T)
    //
    // with dependent type T:
    if (!binOpRHS->isValueDependent()
        && compat::EvaluateAsInt(binOpRHS, aIntResult, compiler.getASTContext()))
    {
        if (less && aIntResult.isStrictlyPositive()) {
            --aIntResult;
        }
        qt2BitWidth = aIntResult.isUnsigned() || !aIntResult.isNegative()
            ? std::max(aIntResult.getActiveBits(), 1U)
            : aIntResult.getBitWidth() - aIntResult.countLeadingOnes() + 1;
    } else {
        // Ignore complex expressions for now, promotion rules on conditions
        // like "i < (size()+1)" make it hard to guess at a correct type:
        if (isa<BinaryOperator>(binOpRHS) || isa<ConditionalOperator>(binOpRHS))
        {
            return;
        }
        qt2BitWidth = getIntValueWidth(qt2);
        if (auto dre = dyn_cast<DeclRefExpr>(binOpRHS)) {
            if (auto fd = dyn_cast<FieldDecl>(dre->getDecl())) {
                if (fd->isBitField()) {
                    qt2BitWidth = std::max(
                        qt2BitWidth,
                        fd->getBitWidthValue(compiler.getASTContext()));
                }
            }
        }
    }

    auto i = comparisons_.find(lhsDecl);
    if (i == comparisons_.end()) {
        i = (comparisons_.insert(
                 decltype(comparisons_)::value_type(lhsDecl, {{}, qt1BitWidth}))
             .first);
    } else {
        assert(i->second.lhsWidth == qt1BitWidth);
    }
    bool ins = true;
    for (auto j = i->second.comparisons.begin();
         j != i->second.comparisons.end();)
    {
        if (qt2BitWidth > j->rhsWidth) {
            ins = false;
            break;
        } else if (qt2BitWidth < j->rhsWidth) {
            j = i->second.comparisons.erase(j);
        } else {
            ++j;
        }
    }
    if (ins) {
        i->second.comparisons.push_back({binOp, qt2BitWidth});
    }
}

void LoopVarTooSmall::checkExpr(Expr const * expr) {
    if (expr != nullptr && !ignoreLocation(expr)) {
        assert(comparisons_.empty());
        checkSubExpr(expr, true);
        for (auto const & i: comparisons_) {
            for (auto const & j: i.second.comparisons) {
                if (i.second.lhsWidth < j.rhsWidth) {
                    report(
                        DiagnosticsEngine::Warning,
                        "loop index type %0 is narrower than length type %1",
                        j.op->getExprLoc())
                        << j.op->getLHS()->IgnoreImpCasts()->getType()
                        << j.op->getRHS()->IgnoreImpCasts()->getType()
                        << j.op->getSourceRange();
                }
            }
        }
        comparisons_.clear();
    }
}

loplugin::Plugin::Registration< LoopVarTooSmall > loopvartoosmall("loopvartoosmall");

}

#endif // LO_CLANG_SHARED_PLUGINS

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