Index: tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h =================================================================== --- tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h +++ tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h @@ -187,6 +187,14 @@ template const RegionTy* getAs() const; virtual bool isBoundable() const { return false; } + + /// Get variable name for memory region. The name is obtained from + /// the variable/field declaration retrieved from the memory region. + /// Regions that point to an element of an array are returned as: "arr[0]". + /// Regions that point to a struct are returned as: "st.var". + /// + /// \returns variable name for memory region + std::string getVariableName() const; }; /// MemSpaceRegion - A memory region that represents a "memory space"; Index: tools/clang/lib/StaticAnalyzer/Core/MemRegion.cpp =================================================================== --- tools/clang/lib/StaticAnalyzer/Core/MemRegion.cpp +++ tools/clang/lib/StaticAnalyzer/Core/MemRegion.cpp @@ -635,6 +635,45 @@ superRegion->printPrettyAsExpr(os); } +std::string MemRegion::getVariableName() const { + std::string VariableName{""}; + std::string ArrayIndices{""}; + + const clang::ento::MemRegion *R = this; + llvm::SmallString<50> buf; + llvm::raw_svector_ostream os(buf); + + // Obtain array indices to add them to the variable name. + const clang::ento::ElementRegion *ER = nullptr; + while ((ER = R->getAs())) { + llvm::APSInt IndexInArray = + ER->getIndex().getAs()->getValue(); + + llvm::SmallString<2> intValAsString; + IndexInArray.toString(intValAsString); + std::string idx{intValAsString.begin(), intValAsString.end()}; + + ArrayIndices = "[" + idx + "]" + ArrayIndices; + + R = ER->getSuperRegion(); + } + + // Get variable name. + if (R && R->canPrintPretty()) { + R->printPretty(os); + VariableName += os.str(); + } + + // Combine variable name with indices. + if (VariableName.size() && VariableName.back() == '\'') { + VariableName.insert(VariableName.size() - 1, ArrayIndices); + } else { + VariableName += ArrayIndices; + } + + return VariableName; +} + //===----------------------------------------------------------------------===// // MemRegionManager methods. //===----------------------------------------------------------------------===//