├── .clang-format ├── .devcontainer ├── Dockerfile └── devcontainer.json ├── .github └── workflows │ └── ccpp.yml ├── .gitignore ├── CMakeLists.txt ├── COPYING ├── README.md └── main.cpp /.clang-format: -------------------------------------------------------------------------------- 1 | --- 2 | Language: Cpp 3 | # BasedOnStyle: LLVM 4 | AccessModifierOffset: -2 5 | AlignAfterOpenBracket: Align 6 | AlignConsecutiveAssignments: false 7 | AlignConsecutiveDeclarations: false 8 | AlignEscapedNewlines: Right 9 | AlignOperands: true 10 | AlignTrailingComments: true 11 | AllowAllParametersOfDeclarationOnNextLine: true 12 | AllowShortBlocksOnASingleLine: false 13 | AllowShortCaseLabelsOnASingleLine: false 14 | AllowShortFunctionsOnASingleLine: All 15 | AllowShortIfStatementsOnASingleLine: false 16 | AllowShortLoopsOnASingleLine: false 17 | AlwaysBreakAfterDefinitionReturnType: None 18 | AlwaysBreakAfterReturnType: None 19 | AlwaysBreakBeforeMultilineStrings: false 20 | AlwaysBreakTemplateDeclarations: MultiLine 21 | BinPackArguments: true 22 | BinPackParameters: true 23 | BraceWrapping: 24 | AfterClass: false 25 | AfterControlStatement: false 26 | AfterEnum: false 27 | AfterFunction: false 28 | AfterNamespace: false 29 | AfterObjCDeclaration: false 30 | AfterStruct: false 31 | AfterUnion: false 32 | AfterExternBlock: false 33 | BeforeCatch: false 34 | BeforeElse: false 35 | IndentBraces: false 36 | SplitEmptyFunction: true 37 | SplitEmptyRecord: true 38 | SplitEmptyNamespace: true 39 | BreakBeforeBinaryOperators: None 40 | BreakBeforeBraces: Attach 41 | BreakBeforeInheritanceComma: false 42 | BreakInheritanceList: BeforeColon 43 | BreakBeforeTernaryOperators: true 44 | BreakConstructorInitializersBeforeComma: false 45 | BreakConstructorInitializers: BeforeColon 46 | BreakAfterJavaFieldAnnotations: false 47 | BreakStringLiterals: true 48 | ColumnLimit: 80 49 | CommentPragmas: '^ IWYU pragma:' 50 | CompactNamespaces: false 51 | ConstructorInitializerAllOnOneLineOrOnePerLine: false 52 | ConstructorInitializerIndentWidth: 4 53 | ContinuationIndentWidth: 4 54 | Cpp11BracedListStyle: true 55 | DerivePointerAlignment: false 56 | DisableFormat: false 57 | ExperimentalAutoDetectBinPacking: false 58 | FixNamespaceComments: true 59 | ForEachMacros: 60 | - foreach 61 | - Q_FOREACH 62 | - BOOST_FOREACH 63 | IncludeBlocks: Preserve 64 | IncludeCategories: 65 | - Regex: '^"(llvm|llvm-c|clang|clang-c)/' 66 | Priority: 2 67 | - Regex: '^(<|"(gtest|gmock|isl|json)/)' 68 | Priority: 3 69 | - Regex: '.*' 70 | Priority: 1 71 | IncludeIsMainRegex: '(Test)?$' 72 | IndentCaseLabels: false 73 | IndentPPDirectives: None 74 | IndentWidth: 2 75 | IndentWrappedFunctionNames: false 76 | JavaScriptQuotes: Leave 77 | JavaScriptWrapImports: true 78 | KeepEmptyLinesAtTheStartOfBlocks: true 79 | MacroBlockBegin: '' 80 | MacroBlockEnd: '' 81 | MaxEmptyLinesToKeep: 1 82 | NamespaceIndentation: None 83 | ObjCBinPackProtocolList: Auto 84 | ObjCBlockIndentWidth: 2 85 | ObjCSpaceAfterProperty: false 86 | ObjCSpaceBeforeProtocolList: true 87 | PenaltyBreakAssignment: 2 88 | PenaltyBreakBeforeFirstCallParameter: 19 89 | PenaltyBreakComment: 300 90 | PenaltyBreakFirstLessLess: 120 91 | PenaltyBreakString: 1000 92 | PenaltyBreakTemplateDeclaration: 10 93 | PenaltyExcessCharacter: 1000000 94 | PenaltyReturnTypeOnItsOwnLine: 60 95 | PointerAlignment: Right 96 | ReflowComments: true 97 | SortIncludes: true 98 | SortUsingDeclarations: true 99 | SpaceAfterCStyleCast: false 100 | SpaceAfterTemplateKeyword: true 101 | SpaceBeforeAssignmentOperators: true 102 | SpaceBeforeCpp11BracedList: false 103 | SpaceBeforeCtorInitializerColon: true 104 | SpaceBeforeInheritanceColon: true 105 | SpaceBeforeParens: ControlStatements 106 | SpaceBeforeRangeBasedForLoopColon: true 107 | SpaceInEmptyParentheses: false 108 | SpacesBeforeTrailingComments: 1 109 | SpacesInAngles: false 110 | SpacesInContainerLiterals: true 111 | SpacesInCStyleCastParentheses: false 112 | SpacesInParentheses: false 113 | SpacesInSquareBrackets: false 114 | Standard: Cpp11 115 | TabWidth: 8 116 | UseTab: Never 117 | ... 118 | 119 | -------------------------------------------------------------------------------- /.devcontainer/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM mcr.microsoft.com/devcontainers/cpp:1-ubuntu-22.04 2 | 3 | ARG REINSTALL_CMAKE_VERSION_FROM_SOURCE="none" 4 | 5 | # [Optional] Uncomment this section to install additional vcpkg ports. 6 | # RUN su vscode -c "${VCPKG_ROOT}/vcpkg install " 7 | 8 | # [Optional] Uncomment this section to install additional packages. 9 | RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \ 10 | && apt-get -y install --no-install-recommends \ 11 | build-essential cmake lsb-release wget software-properties-common gnupg 12 | 13 | RUN sudo bash -c "$(wget -O - https://apt.llvm.org/llvm.sh)" 14 | RUN sudo apt-get -y install llvm-18-dev libclang-18-dev -------------------------------------------------------------------------------- /.devcontainer/devcontainer.json: -------------------------------------------------------------------------------- 1 | // For format details, see https://aka.ms/devcontainer.json. For config options, see the 2 | // README at: https://github.com/devcontainers/templates/tree/main/src/cpp 3 | { 4 | "name": "C++", 5 | "build": { 6 | "dockerfile": "Dockerfile" 7 | }, 8 | 9 | // Features to add to the dev container. More info: https://containers.dev/features. 10 | // "features": {}, 11 | 12 | // Configure tool-specific properties. 13 | "customizations": { 14 | // Configure properties specific to VS Code. 15 | "vscode": { 16 | "settings": {}, 17 | "extensions": [ 18 | "streetsidesoftware.code-spell-checker", 19 | "llvm-vs-code-extensions.vscode-clangd", 20 | "GitHub.vscode-github-actions" 21 | ] 22 | } 23 | } 24 | 25 | // Use 'forwardPorts' to make a list of ports inside the container available locally. 26 | // "forwardPorts": [], 27 | 28 | // Use 'postCreateCommand' to run commands after the container is created. 29 | // "postCreateCommand": "gcc -v", 30 | 31 | // Uncomment to connect as root instead. More info: https://aka.ms/dev-containers-non-root. 32 | // "remoteUser": "root" 33 | } -------------------------------------------------------------------------------- /.github/workflows/ccpp.yml: -------------------------------------------------------------------------------- 1 | name: C/C++ CI 2 | 3 | on: 4 | push: 5 | branches: main 6 | pull_request: 7 | 8 | jobs: 9 | llvm: 10 | runs-on: ${{ matrix.os }} 11 | timeout-minutes: 10 12 | strategy: 13 | fail-fast: false 14 | matrix: 15 | version: [13, 14, 15, 16, 17, 18] 16 | os: [ubuntu-22.04] 17 | 18 | steps: 19 | - uses: actions/checkout@v4 20 | 21 | - name: Install package repository for Clang/LLVM ${{ matrix.version }} 22 | run: | 23 | wget https://apt.llvm.org/llvm.sh 24 | chmod +x llvm.sh 25 | sudo ./llvm.sh ${{ matrix.version }} 26 | 27 | - name: Install build prerequisites and Clang/LLVM ${{ matrix.version }} 28 | run: | 29 | sudo apt-get -y remove llvm-14-dev llvm-15-dev 30 | sudo apt-get -y install build-essential \ 31 | cmake \ 32 | libcurl4-openssl-dev \ 33 | libedit-dev \ 34 | llvm-${{ matrix.version }}-dev \ 35 | libclang-${{ matrix.version }}-dev 36 | 37 | - name: Build xunused for Clang/LLVM ${{ matrix.version }} 38 | run: | 39 | mkdir build 40 | cmake -B build 41 | make -C build 42 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | build/** 2 | .vscode/ 3 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.7) 2 | project(xunused) 3 | 4 | # Let find_package(...) search for the latest version when multiple versions of 5 | # the same library are available. Therefore ... 6 | # 7 | # 1) set natural sort order to compare contiguous digits as whole numbers, and 8 | # 2) do ordering in descending mode to test latest found folder first. 9 | # 10 | set(CMAKE_FIND_PACKAGE_SORT_ORDER NATURAL) 11 | set(CMAKE_FIND_PACKAGE_SORT_DIRECTION DEC) 12 | 13 | find_package(LLVM ${LLVM_VERSION_REQUIRED} CONFIG REQUIRED) 14 | message(STATUS "Found LLVM ${LLVM_PACKAGE_VERSION}") 15 | message(STATUS "Using LLVMConfig.cmake in: ${LLVM_DIR}") 16 | 17 | if (LLVM_VERSION_MAJOR GREATER_EQUAL 16) 18 | if (LLVM_VERSION_MAJOR GREATER_EQUAL 18) 19 | find_package(Clang ${LLVM_VERSION_MAJOR}.${LLVM_VERSION_MINOR} CONFIG REQUIRED) 20 | else() 21 | find_package(Clang ${LLVM_VERSION_MAJOR} CONFIG REQUIRED) 22 | endif() 23 | message(STATUS "Using ClangConfig.cmake in: ${Clang_DIR}") 24 | endif (LLVM_VERSION_MAJOR GREATER_EQUAL 16) 25 | 26 | option(XUNUSED_LINK_LLVM_DYLIB 27 | "Link against the LLVM dynamic library" 28 | ${LLVM_LINK_LLVM_DYLIB}) 29 | 30 | option(XUNUSED_LINK_CLANG_DYLIB 31 | "Link against the clang dynamic library" 32 | ${CLANG_LINK_CLANG_DYLIB}) 33 | 34 | message(STATUS "Link against the LLVM dynamic library: ${XUNUSED_LINK_LLVM_DYLIB}") 35 | message(STATUS "Link against the Clang dynamic library: ${XUNUSED_LINK_CLANG_DYLIB}") 36 | 37 | include_directories(${LLVM_INCLUDE_DIRS}) 38 | include_directories(${CLANG_INCLUDE_DIRS}) 39 | 40 | add_definitions(${LLVM_DEFINITIONS}) 41 | add_definitions(${CLANG_DEFINITIONS}) 42 | 43 | link_directories(${LLVM_LIBRARY_DIRS}) 44 | link_directories(${CLANG_LIBRARY_DIRS}) 45 | 46 | set(CMAKE_CXX_STANDARD 17) 47 | set(CMAKE_EXPORT_COMPILE_COMMANDS ON) 48 | 49 | add_executable(xunused main.cpp) 50 | 51 | if (XUNUSED_LINK_CLANG_DYLIB) 52 | set(XUNUSED_CLANG_LIBS "clang-cpp") 53 | else (XUNUSED_LINK_CLANG_DYLIB) 54 | set(XUNUSED_CLANG_LIBS "clangIndex" 55 | "clangTooling" 56 | "clangFrontend" 57 | "clangDriver" 58 | "clangSerialization" 59 | "clangParse" 60 | "clangSema" 61 | "clangAnalysis" 62 | "clangASTMatchers" 63 | "clangAST" 64 | "clangEdit" 65 | "clangLex" 66 | "clangBasic") 67 | if (LLVM_VERSION_MAJOR GREATER_EQUAL 15) 68 | list(APPEND XUNUSED_CLANG_LIBS "clangSupport") 69 | endif (LLVM_VERSION_MAJOR GREATER_EQUAL 15) 70 | endif (XUNUSED_LINK_CLANG_DYLIB) 71 | 72 | if (XUNUSED_LINK_LLVM_DYLIB) 73 | set(XUNUSED_LLVM_LIBS "LLVM") 74 | else (XUNUSED_LINK_LLVM_DYLIB) 75 | set(XUNUSED_LLVM_LIBS "LLVMX86AsmParser" 76 | "LLVMSupport" 77 | "LLVMOption" 78 | "LLVMProfileData" 79 | "LLVMFrontendOpenMP") 80 | if (LLVM_VERSION_MAJOR EQUAL 15) 81 | list(APPEND XUNUSED_LLVM_LIBS "LLVMWindowsDriver") 82 | endif (LLVM_VERSION_MAJOR EQUAL 15) 83 | endif (XUNUSED_LINK_LLVM_DYLIB) 84 | 85 | target_link_libraries(xunused PRIVATE ${XUNUSED_CLANG_LIBS} ${XUNUSED_LLVM_LIBS}) 86 | 87 | install(TARGETS xunused DESTINATION bin) 88 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # xunused 2 | `xunused` is a tool to find unused C/C++ functions and methods across source files in the whole project. 3 | It is built upon clang to parse the source code (in parallel). It then shows all functions that had 4 | a definition but no use. Templates, virtual functions, constructors, functions with `static` linkage are 5 | all taken into account. If you find an issue, please open a issue on https://github.com/mgehre/xunused or file a pull request. 6 | 7 | xunused is compatible with LLVM and Clang versions 13 to 18. 8 | 9 | ## Building and Installation 10 | First download or build the necessary versions of LLVM and Clang with development headers. 11 | On Debian and Ubuntu, this can easily be done via [http://apt.llvm.org](http://apt.llvm.org) and `apt install llvm-18-dev libclang-18-dev`. 12 | Then build via 13 | ``` 14 | mkdir build 15 | cd build 16 | cmake .. 17 | make 18 | ``` 19 | 20 | ## Run it 21 | To run the tool, provide a [compilation database](https://clang.llvm.org/docs/JSONCompilationDatabase.html). 22 | By default, it will analyze all files that are mentioned in it. 23 | ``` 24 | cd build 25 | ./xunused /path/to/your/project/compile_commands.json 26 | ``` 27 | You can specify the option `-filter` together with a regular expressions. Only files who's path is matching the regular 28 | expression will be analyzed. You might want to exclude your test's source code to find functions that are only used by tests but not any other code. 29 | 30 | If `xunused` complains about missing include files such as `stddef.h`, try adding `-extra-arg=-I/usr/include/clang/17/include` (or similar) to the arguments. 31 | -------------------------------------------------------------------------------- /main.cpp: -------------------------------------------------------------------------------- 1 | #include "clang/AST/AST.h" 2 | #include "clang/AST/ASTContext.h" 3 | #include "clang/ASTMatchers/ASTMatchFinder.h" 4 | #include "clang/ASTMatchers/ASTMatchers.h" 5 | #include "clang/Basic/Version.h" 6 | #include "clang/Driver/Options.h" 7 | #include "clang/Frontend/ASTConsumers.h" 8 | #include "clang/Frontend/FrontendActions.h" 9 | #include "clang/Index/USRGeneration.h" 10 | #include "clang/Tooling/AllTUsExecution.h" 11 | #include "clang/Tooling/Tooling.h" 12 | #include "llvm/Support/Signals.h" 13 | #include 14 | #include 15 | #include 16 | 17 | 18 | using namespace clang; 19 | using namespace clang::ast_matchers; 20 | 21 | template 22 | void discard_if(std::set &c, Predicate pred) { 23 | for (auto it{c.begin()}, end{c.end()}; it != end;) { 24 | if (pred(*it)) { 25 | it = c.erase(it); 26 | } else { 27 | ++it; 28 | } 29 | } 30 | } 31 | 32 | struct DeclLoc { 33 | DeclLoc() = default; 34 | DeclLoc(std::string Filename, unsigned Line) 35 | : Filename(std::move(Filename)), Line(Line) {} 36 | SmallString<128> Filename; 37 | unsigned Line; 38 | }; 39 | 40 | struct DefInfo { 41 | const FunctionDecl *Definition; 42 | size_t Uses; 43 | std::string Name; 44 | std::string Filename; 45 | unsigned Line; 46 | std::vector Declarations; 47 | }; 48 | 49 | std::mutex Mutex; 50 | std::map AllDecls; 51 | 52 | bool getUSRForDecl(const Decl *Decl, std::string &USR) { 53 | llvm::SmallVector Buff; 54 | 55 | if (index::generateUSRForDecl(Decl, Buff)) 56 | return false; 57 | 58 | USR = std::string(Buff.data(), Buff.size()); 59 | return true; 60 | } 61 | 62 | /// Returns all declarations that are not the definition of F 63 | std::vector getDeclarations(const FunctionDecl *F, 64 | const SourceManager &SM) { 65 | std::vector Decls; 66 | for (const FunctionDecl *R : F->redecls()) { 67 | if (R->doesThisDeclarationHaveABody()) 68 | continue; 69 | auto Begin = R->getSourceRange().getBegin(); 70 | Decls.emplace_back(SM.getFilename(Begin).str(), SM.getSpellingLineNumber(Begin)); 71 | SM.getFileManager().makeAbsolutePath(Decls.back().Filename); 72 | } 73 | return Decls; 74 | } 75 | 76 | class FunctionDeclMatchHandler : public MatchFinder::MatchCallback { 77 | public: 78 | void finalize(const SourceManager &SM) { 79 | std::unique_lock LockGuard(Mutex); 80 | 81 | std::vector UnusedDefs; 82 | 83 | std::set_difference(Defs.begin(), Defs.end(), Uses.begin(), Uses.end(), 84 | std::back_inserter(UnusedDefs)); 85 | 86 | for (auto *F : UnusedDefs) { 87 | F = F->getDefinition(); 88 | assert(F); 89 | std::string USR; 90 | if (!getUSRForDecl(F, USR)) 91 | continue; 92 | // llvm::errs() << "UnusedDefs: " << USR << "\n"; 93 | auto it_inserted = AllDecls.emplace(std::move(USR), DefInfo{F, 0}); 94 | if (!it_inserted.second) { 95 | it_inserted.first->second.Definition = F; 96 | } 97 | it_inserted.first->second.Name = F->getQualifiedNameAsString(); 98 | 99 | auto Begin = F->getSourceRange().getBegin(); 100 | it_inserted.first->second.Filename = SM.getFilename(Begin); 101 | it_inserted.first->second.Line = SM.getSpellingLineNumber(Begin); 102 | 103 | it_inserted.first->second.Declarations = getDeclarations(F, SM); 104 | } 105 | 106 | // Weak functions are not the definitive definition. Remove it from 107 | // Defs before checking which uses we need to consider in other TUs, 108 | // so the functions overwritting the weak definition here are marked 109 | // as used. 110 | discard_if(Defs, [](const FunctionDecl *FD) { return FD->isWeak(); }); 111 | 112 | std::vector ExternalUses; 113 | 114 | std::set_difference(Uses.begin(), Uses.end(), Defs.begin(), Defs.end(), 115 | std::back_inserter(ExternalUses)); 116 | 117 | for (auto *F : ExternalUses) { 118 | // llvm::errs() << "ExternalUses: " << F->getNameAsString() << "\n"; 119 | std::string USR; 120 | if (!getUSRForDecl(F, USR)) 121 | continue; 122 | // llvm::errs() << "ExternalUses: " << USR << "\n"; 123 | auto it_inserted = AllDecls.emplace(std::move(USR), DefInfo{nullptr, 1}); 124 | if (!it_inserted.second) { 125 | it_inserted.first->second.Uses++; 126 | } 127 | } 128 | } 129 | 130 | void handleUse(const ValueDecl *D, const SourceManager *SM) { 131 | auto *FD = dyn_cast(D); 132 | if (!FD) 133 | return; 134 | 135 | if (SM->isInSystemHeader(FD->getSourceRange().getBegin())) 136 | return; 137 | if (FD->isTemplateInstantiation()) { 138 | FD = FD->getTemplateInstantiationPattern(); 139 | assert(FD); 140 | } 141 | 142 | #if 0 143 | llvm::errs() << "Use "; 144 | FD->printName(llvm::errs()); 145 | //llvm::errs() << " USR:" << USR; 146 | llvm::errs() << "\n"; 147 | #endif 148 | Uses.insert(FD->getCanonicalDecl()); 149 | } 150 | void run(const MatchFinder::MatchResult &Result) override { 151 | if (const auto *F = Result.Nodes.getNodeAs("fnDecl")) { 152 | if (!F->hasBody()) 153 | return; // Ignore '= delete' and '= default' definitions. 154 | 155 | if (auto *Templ = F->getInstantiatedFromMemberFunction()) 156 | F = Templ; 157 | 158 | if (F->isTemplateInstantiation()) { 159 | F = F->getTemplateInstantiationPattern(); 160 | assert(F); 161 | } 162 | 163 | auto Begin = F->getSourceRange().getBegin(); 164 | if (Result.SourceManager->isInSystemHeader(Begin)) 165 | return; 166 | 167 | if (!Result.SourceManager->isWrittenInMainFile(Begin)) 168 | return; 169 | 170 | auto *MD = dyn_cast(F); 171 | if (MD) { 172 | if (MD->isVirtual() 173 | #if CLANG_VERSION_MAJOR >= 18 174 | && !MD->isPureVirtual() 175 | #else 176 | && !MD->isPure() 177 | #endif 178 | && MD->size_overridden_methods()) 179 | return; // overriding method 180 | if (isa(MD)) 181 | return; // We don't see uses of destructors. 182 | } 183 | 184 | if (F->isMain()) 185 | return; 186 | #if 0 187 | llvm::errs() << "FunctionDecl "; 188 | F->printName(llvm::errs()); 189 | llvm::errs() << " USR:" << USR << "\n"; 190 | #endif 191 | Defs.insert(F->getCanonicalDecl()); 192 | 193 | // __attribute__((constructor())) are always used 194 | if (F->hasAttr()) 195 | handleUse(F, Result.SourceManager); 196 | 197 | } else if (const auto *R = Result.Nodes.getNodeAs("declRef")) { 198 | handleUse(R->getDecl(), Result.SourceManager); 199 | } else if (const auto *R = 200 | Result.Nodes.getNodeAs("memberRef")) { 201 | handleUse(R->getMemberDecl(), Result.SourceManager); 202 | } else if (const auto *R = Result.Nodes.getNodeAs( 203 | "cxxConstructExpr")) { 204 | handleUse(R->getConstructor(), Result.SourceManager); 205 | } 206 | } 207 | 208 | std::set Defs; 209 | std::set Uses; 210 | }; 211 | 212 | class XUnusedASTConsumer : public ASTConsumer { 213 | public: 214 | XUnusedASTConsumer() { 215 | Matcher.addMatcher( 216 | functionDecl(isDefinition(), unless(isImplicit())).bind("fnDecl"), 217 | &Handler); 218 | Matcher.addMatcher(declRefExpr().bind("declRef"), &Handler); 219 | Matcher.addMatcher(memberExpr().bind("memberRef"), &Handler); 220 | Matcher.addMatcher(cxxConstructExpr().bind("cxxConstructExpr"), &Handler); 221 | } 222 | 223 | void HandleTranslationUnit(ASTContext &Context) override { 224 | Matcher.matchAST(Context); 225 | Handler.finalize(Context.getSourceManager()); 226 | } 227 | 228 | private: 229 | FunctionDeclMatchHandler Handler; 230 | MatchFinder Matcher; 231 | }; 232 | 233 | // For each source file provided to the tool, a new FrontendAction is created. 234 | class XUnusedFrontendAction : public ASTFrontendAction { 235 | public: 236 | std::unique_ptr CreateASTConsumer(CompilerInstance & /*CI*/, 237 | StringRef /*File*/) override { 238 | return std::make_unique(); 239 | } 240 | }; 241 | 242 | class XUnusedFrontendActionFactory : public tooling::FrontendActionFactory { 243 | public: 244 | std::unique_ptr create() override { return std::make_unique(); } 245 | }; 246 | 247 | int main(int argc, const char **argv) { 248 | llvm::sys::PrintStackTraceOnErrorSignal(argv[0]); 249 | 250 | const char *Overview = R"( 251 | xunused is tool to find unused functions and methods across a whole C/C++ project. 252 | )"; 253 | 254 | tooling::ExecutorName.setInitialValue("all-TUs"); 255 | #if 1 256 | auto Executor = clang::tooling::createExecutorFromCommandLineArgs( 257 | argc, argv, llvm::cl::getGeneralCategory(), Overview); 258 | if (!Executor) { 259 | llvm::errs() << llvm::toString(Executor.takeError()) << "\n"; 260 | return 1; 261 | } 262 | auto Err = 263 | Executor->get()->execute(std::unique_ptr( 264 | new XUnusedFrontendActionFactory())); 265 | #else 266 | static llvm::cl::OptionCategory XUnusedCategory("xunused options"); 267 | CommonOptionsParser op(argc, argv, XUnusedCategory); 268 | AllTUsToolExecutor > Executor(op.getCompilations(), /*ThreadCount=*/0); 269 | auto Err = Executor.execute(std::unique_ptr( 270 | new XUnusedFrontendActionFactory())); 271 | #endif 272 | 273 | if (Err) { 274 | llvm::errs() << llvm::toString(std::move(Err)) << "\n"; 275 | } 276 | 277 | for (auto &KV : AllDecls) { 278 | DefInfo &I = KV.second; 279 | if (I.Definition && I.Uses == 0) { 280 | llvm::errs() << I.Filename << ":" << I.Line << ": warning:" 281 | << " Function '" << I.Name << "' is unused\n"; 282 | for (auto &D : I.Declarations) { 283 | llvm::errs() << D.Filename << ":" << D.Line << ": note:" 284 | << " declared here\n"; 285 | } 286 | } 287 | } 288 | } 289 | --------------------------------------------------------------------------------