├── .github └── workflows │ └── ci.yml ├── .gitignore ├── CMakeLists.txt ├── LICENSE ├── README.md ├── main.cpp └── tests ├── 01 ├── CMakeLists.txt └── test01.cpp └── 02 ├── CMakeLists.txt └── test02.cpp /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | pull_request: 8 | schedule: 9 | # run CI every day even if no PRs/merges occur 10 | - cron: '0 12 * * *' 11 | 12 | jobs: 13 | lint: 14 | runs-on: ubuntu-latest 15 | steps: 16 | - uses: actions/checkout@v2 17 | 18 | - name: deps 19 | run: sudo apt install clang-format-9 20 | 21 | - name: lint 22 | run: clang-format-9 -i main.cpp && git diff --exit-code 23 | build: 24 | runs-on: ubuntu-20.04 25 | strategy: 26 | matrix: 27 | llvm-toolchain: [9, 10, 11] 28 | steps: 29 | - uses: actions/checkout@v2 30 | 31 | - name: deps 32 | run: | 33 | wget -O - https://apt.llvm.org/llvm-snapshot.gpg.key | sudo apt-key add - 34 | sudo add-apt-repository "deb http://apt.llvm.org/focal/ llvm-toolchain-focal-${{ matrix.llvm-toolchain }} main" 35 | sudo apt update 36 | sudo apt install \ 37 | llvm-${{ matrix.llvm-toolchain }} \ 38 | llvm-${{ matrix.llvm-toolchain }}-dev \ 39 | clang-${{ matrix.llvm-toolchain }} \ 40 | libclang-${{ matrix.llvm-toolchain }}-dev 41 | 42 | - name: build 43 | run: | 44 | export LLVM_DIR=/usr/lib/llvm-${{ matrix.llvm-toolchain }}/lib/cmake/llvm 45 | export Clang_DIR=/usr/lib/llvm-${{ matrix.llvm-toolchain }}/lib/cmake/clang 46 | mkdir build && cd build 47 | cmake -DCMAKE_BUILD_TYPE=Debug .. 48 | cmake --build . 49 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | # Created by https://www.gitignore.io/api/vim,c++,cmake,clion 3 | # Edit at https://www.gitignore.io/?templates=vim,c++,cmake,clion 4 | 5 | ### C++ ### 6 | # Prerequisites 7 | *.d 8 | 9 | # Compiled Object files 10 | *.slo 11 | *.lo 12 | *.o 13 | *.obj 14 | 15 | # Precompiled Headers 16 | *.gch 17 | *.pch 18 | 19 | # Compiled Dynamic libraries 20 | *.so 21 | *.dylib 22 | *.dll 23 | 24 | # Fortran module files 25 | *.mod 26 | *.smod 27 | 28 | # Compiled Static libraries 29 | *.lai 30 | *.la 31 | *.a 32 | *.lib 33 | 34 | # Executables 35 | *.exe 36 | *.out 37 | *.app 38 | 39 | ### CLion ### 40 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm 41 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 42 | 43 | # User-specific stuff 44 | .idea/**/workspace.xml 45 | .idea/**/tasks.xml 46 | .idea/**/usage.statistics.xml 47 | .idea/**/dictionaries 48 | .idea/**/shelf 49 | 50 | # Generated files 51 | .idea/**/contentModel.xml 52 | 53 | # Sensitive or high-churn files 54 | .idea/**/dataSources/ 55 | .idea/**/dataSources.ids 56 | .idea/**/dataSources.local.xml 57 | .idea/**/sqlDataSources.xml 58 | .idea/**/dynamic.xml 59 | .idea/**/uiDesigner.xml 60 | .idea/**/dbnavigator.xml 61 | 62 | # Gradle 63 | .idea/**/gradle.xml 64 | .idea/**/libraries 65 | 66 | # Gradle and Maven with auto-import 67 | # When using Gradle or Maven with auto-import, you should exclude module files, 68 | # since they will be recreated, and may cause churn. Uncomment if using 69 | # auto-import. 70 | # .idea/modules.xml 71 | # .idea/*.iml 72 | # .idea/modules 73 | 74 | # CMake 75 | cmake-build-*/ 76 | 77 | # Mongo Explorer plugin 78 | .idea/**/mongoSettings.xml 79 | 80 | # File-based project format 81 | *.iws 82 | 83 | # IntelliJ 84 | out/ 85 | 86 | # mpeltonen/sbt-idea plugin 87 | .idea_modules/ 88 | 89 | # JIRA plugin 90 | atlassian-ide-plugin.xml 91 | 92 | # Cursive Clojure plugin 93 | .idea/replstate.xml 94 | 95 | # Crashlytics plugin (for Android Studio and IntelliJ) 96 | com_crashlytics_export_strings.xml 97 | crashlytics.properties 98 | crashlytics-build.properties 99 | fabric.properties 100 | 101 | # Editor-based Rest Client 102 | .idea/httpRequests 103 | 104 | # Android studio 3.1+ serialized cache file 105 | .idea/caches/build_file_checksums.ser 106 | 107 | # JetBrains templates 108 | **___jb_tmp___ 109 | 110 | ### CLion Patch ### 111 | # Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721 112 | 113 | # *.iml 114 | # modules.xml 115 | # .idea/misc.xml 116 | # *.ipr 117 | 118 | # Sonarlint plugin 119 | .idea/sonarlint 120 | 121 | ### CMake ### 122 | CMakeLists.txt.user 123 | CMakeCache.txt 124 | CMakeFiles 125 | CMakeScripts 126 | Testing 127 | Makefile 128 | cmake_install.cmake 129 | install_manifest.txt 130 | compile_commands.json 131 | CTestTestfile.cmake 132 | _deps 133 | 134 | ### CMake Patch ### 135 | # External projects 136 | *-prefix/ 137 | 138 | ### Vim ### 139 | # Swap 140 | [._]*.s[a-v][a-z] 141 | [._]*.sw[a-p] 142 | [._]s[a-rt-v][a-z] 143 | [._]ss[a-gi-z] 144 | [._]sw[a-p] 145 | 146 | # Session 147 | Session.vim 148 | 149 | # Temporary 150 | .netrwhist 151 | *~ 152 | # Auto-generated tag files 153 | tags 154 | # Persistent undo 155 | [._]*.un~ 156 | 157 | # End of https://www.gitignore.io/api/vim,c++,cmake,clion -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.8) 2 | project(constexpr-everything CXX) 3 | 4 | set(CMAKE_CXX_STANDARD 14) 5 | set(CMAKE_CXX_STANDARD_REQUIRED ON) 6 | 7 | set(CMAKE_EXPORT_COMPILE_COMMANDS ON) 8 | 9 | set(CMAKE_CXX_FLAGS 10 | "${CMAKE_CXX_FLAGS} -Wno-unused-parameter -Wall -fno-strict-aliasing -fno-exceptions -fno-rtti" 11 | ) 12 | 13 | # NOTE(ww): When multiple versions of libclang are installed, CMake gets 14 | # confused and picks the wrong (usually old) one. These settings tell it to 15 | # assume a natural decreasing search order, which should fix *some* cases. See: 16 | # https://github.com/CastXML/CastXML/issues/148 and 17 | # https://github.com/mesonbuild/meson/issues/5636 18 | set(CMAKE_FIND_PACKAGE_SORT_ORDER NATURAL) 19 | set(CMAKE_FIND_PACKAGE_SORT_DIRECTION DEC) 20 | 21 | set(LIBRARY_LIST 22 | clangASTMatchers 23 | clangTooling 24 | clangDriver 25 | clangAST 26 | clangLex 27 | clangParse 28 | clangBasic 29 | clangFrontend 30 | clangEdit 31 | clangSerialization 32 | clangSema 33 | clangAnalysis 34 | clangFrontendTool 35 | clangDynamicASTMatchers 36 | clangRewrite 37 | clangRewriteFrontend 38 | clangToolingCore) 39 | 40 | find_package(LLVM REQUIRED CONFIG) 41 | message(STATUS "Found LLVM ${LLVM_PACKAGE_VERSION}") 42 | message(STATUS "Using LLVMConfig.cmake in: ${LLVM_DIR}") 43 | 44 | if((${LLVM_PACKAGE_VERSION} VERSION_LESS "9.0.0") 45 | OR (${LLVM_PACKAGE_VERSION} VERSION_GREATER_EQUAL "12")) 46 | message(FATAL_ERROR "Only LLVM 9 through 11 are supported.") 47 | endif() 48 | 49 | # The clang package doesn't appear to provide a version 50 | find_package(Clang REQUIRED CONFIG) 51 | message(STATUS "Using ClangConfig.cmake in: ${CLANG_CMAKE_DIR}") 52 | 53 | include_directories(${LLVM_INCLUDE_DIRS} ${CLANG_INCLUDE_DIRS}) 54 | if(LLVM_BUILD_MAIN_SRC_DIR) 55 | include_directories(${LLVM_BUILD_MAIN_SRC_DIR}/tools/clang/include) 56 | include_directories(${LLVM_BUILD_BINARY_DIR}/tools/clang/include) 57 | endif() 58 | link_directories(${LLVM_LIBRARY_DIRS}) 59 | add_definitions(${LLVM_DEFINITIONS}) 60 | 61 | add_definitions(-D__STDC_LIMIT_MACROS -D__STDC_CONSTANT_MACROS) 62 | 63 | add_executable(${PROJECT_NAME} main.cpp) 64 | target_link_libraries(${PROJECT_NAME} ${LIBRARY_LIST}) 65 | 66 | target_link_libraries( 67 | ${PROJECT_NAME} 68 | LLVMTransformUtils 69 | LLVMAnalysis 70 | LLVMTarget 71 | LLVMOption # Support 72 | LLVMObject # BitReader, Core, Support 73 | LLVMBitReader # Core, Support 74 | LLVMCore # Support 75 | LLVMSupport) 76 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # constexpr-everything 2 | 3 | [![Build Status](https://img.shields.io/github/workflow/status/trailofbits/constexpr-everything/CI/master)](https://github.com/trailofbits/constexpr-everything/actions?query=workflow%3ACI) 4 | 5 | A libclang based project to automatically rewrite as much code as possible to be 6 | evaluated in `constexpr` contexts. 7 | 8 | Requires LLVM (and Clang) 9, 10, or 11. 9 | 10 | ## Building 11 | 12 | ```bash 13 | mkdir build 14 | cd build 15 | cmake -DCMAKE_BUILD_TYPE=Debug .. 16 | cmake --build . 17 | ``` 18 | 19 | ## Usage 20 | 21 | Build a project with a 22 | [compilation database](https://clang.llvm.org/docs/JSONCompilationDatabase.html), 23 | run `constexpr-everything` on the source files. 24 | 25 | Read more about the tool at 26 | https://blog.trailofbits.com/2019/06/27/use-constexpr-for-faster-smaller-and-safer-code/. 27 | 28 | ## License 29 | 30 | constexpr-everything is licensed and distributed under the Apache 2.0 license. 31 | [Contact us](mailto:opensource@trailofbits.com) if you're looking for an exception to the terms. 32 | -------------------------------------------------------------------------------- /main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include "clang/AST/RecursiveASTVisitor.h" 4 | #include "clang/Basic/DiagnosticSema.h" 5 | #include "clang/Basic/PartialDiagnostic.h" 6 | #include "clang/Basic/Specifiers.h" 7 | #include "clang/Frontend/CompilerInstance.h" 8 | #include "clang/Frontend/FrontendActions.h" 9 | #include "clang/Frontend/TextDiagnosticPrinter.h" 10 | #include "clang/Rewrite/Core/Rewriter.h" 11 | #include "clang/Rewrite/Frontend/FixItRewriter.h" 12 | #include "clang/Sema/Sema.h" 13 | #include "clang/Tooling/CommonOptionsParser.h" 14 | #include "clang/Tooling/Tooling.h" 15 | #include "llvm/Support/CommandLine.h" 16 | 17 | using namespace clang; 18 | using namespace clang::tooling; 19 | 20 | namespace { 21 | llvm::cl::OptionCategory ConstexprCategory("constexpr-everything [-fix]"); 22 | 23 | llvm::cl::extrahelp ConstexprCategoryHelp(R"( 24 | Use clang's existing constexpr validation code to automatically apply constexpr where appropriate 25 | )"); 26 | 27 | llvm::cl::opt 28 | ConstExprFixItOption("fix", llvm::cl::init(false), 29 | llvm::cl::desc("apply fix-its to existing code"), 30 | llvm::cl::cat(ConstexprCategory)); 31 | 32 | llvm::cl::extrahelp 33 | CommonHelp(clang::tooling::CommonOptionsParser::HelpMessage); 34 | } // namespace 35 | 36 | namespace { 37 | 38 | // These functions are stolen from clang::Sema, where they're private. 39 | // From lib/Sema/SemaDeclCXX.cpp 40 | bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 41 | DeclStmt *DS, SourceLocation &Cxx1yLoc) { 42 | // C++11 [dcl.constexpr]p3 and p4: 43 | // The definition of a constexpr function(p3) or constructor(p4) [...] shall 44 | // contain only 45 | for (const auto *DclIt : DS->decls()) { 46 | switch (DclIt->getKind()) { 47 | case Decl::StaticAssert: 48 | case Decl::Using: 49 | case Decl::UsingShadow: 50 | case Decl::UsingDirective: 51 | case Decl::UnresolvedUsingTypename: 52 | case Decl::UnresolvedUsingValue: 53 | // - static_assert-declarations 54 | // - using-declarations, 55 | // - using-directives, 56 | continue; 57 | 58 | case Decl::Typedef: 59 | case Decl::TypeAlias: { 60 | // - typedef declarations and alias-declarations that do not define 61 | // classes or enumerations, 62 | const auto *TN = cast(DclIt); 63 | if (TN->getUnderlyingType()->isVariablyModifiedType()) { 64 | // Don't allow variably-modified types in constexpr functions. 65 | TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 66 | SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 67 | << TL.getSourceRange() << TL.getType() 68 | << isa(Dcl); 69 | return false; 70 | } 71 | continue; 72 | } 73 | 74 | case Decl::Enum: 75 | case Decl::CXXRecord: 76 | // C++1y allows types to be defined, not just declared. 77 | if (cast(DclIt)->isThisDeclarationADefinition()) 78 | SemaRef.Diag(DS->getBeginLoc(), 79 | SemaRef.getLangOpts().CPlusPlus14 80 | ? diag::warn_cxx11_compat_constexpr_type_definition 81 | : diag::ext_constexpr_type_definition) 82 | << isa(Dcl); 83 | continue; 84 | 85 | case Decl::EnumConstant: 86 | case Decl::IndirectField: 87 | case Decl::ParmVar: 88 | // These can only appear with other declarations which are banned in 89 | // C++11 and permitted in C++1y, so ignore them. 90 | continue; 91 | 92 | case Decl::Var: 93 | case Decl::Decomposition: { 94 | // C++1y [dcl.constexpr]p3 allows anything except: 95 | // a definition of a variable of non-literal type or of static or 96 | // thread storage duration or for which no initialization is performed. 97 | const auto *VD = cast(DclIt); 98 | if (VD->isThisDeclarationADefinition()) { 99 | if (VD->isStaticLocal()) { 100 | SemaRef.Diag(VD->getLocation(), diag::err_constexpr_local_var_static) 101 | << isa(Dcl) 102 | << (VD->getTLSKind() == VarDecl::TLS_Dynamic); 103 | return false; 104 | } 105 | if (!VD->getType()->isDependentType() && 106 | SemaRef.RequireLiteralType( 107 | VD->getLocation(), VD->getType(), 108 | diag::err_constexpr_local_var_non_literal_type, 109 | isa(Dcl))) 110 | return false; 111 | if (!VD->getType()->isDependentType() && !VD->hasInit() && 112 | !VD->isCXXForRangeDecl()) { 113 | #if (LLVM_VERSION_MAJOR >= 10) 114 | SemaRef.Diag(VD->getLocation(), diag::ext_constexpr_local_var_no_init) 115 | << isa(Dcl); 116 | #else 117 | SemaRef.Diag(VD->getLocation(), diag::err_constexpr_local_var_no_init) 118 | << isa(Dcl); 119 | #endif 120 | return false; 121 | } 122 | } 123 | SemaRef.Diag(VD->getLocation(), 124 | SemaRef.getLangOpts().CPlusPlus14 125 | ? diag::warn_cxx11_compat_constexpr_local_var 126 | : diag::ext_constexpr_local_var) 127 | << isa(Dcl); 128 | continue; 129 | } 130 | 131 | case Decl::NamespaceAlias: 132 | case Decl::Function: 133 | // These are disallowed in C++11 and permitted in C++1y. Allow them 134 | // everywhere as an extension. 135 | if (!Cxx1yLoc.isValid()) 136 | Cxx1yLoc = DS->getBeginLoc(); 137 | continue; 138 | 139 | default: 140 | SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) 141 | << isa(Dcl); 142 | return false; 143 | } 144 | } 145 | 146 | return true; 147 | } 148 | 149 | // CheckConstexprParameterTypes - Check whether a function's parameter types 150 | // are all literal types. If so, return true. If not, produce a suitable 151 | // diagnostic and return false. 152 | 153 | // from lib/Sema/SemaDeclCXX.cpp 154 | static bool CheckConstexprParameterTypes(Sema &SemaRef, 155 | const FunctionDecl *FD) { 156 | unsigned ArgIndex = 0; 157 | const FunctionProtoType *FT = FD->getType()->getAs(); 158 | for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(), 159 | e = FT->param_type_end(); 160 | i != e; ++i, ++ArgIndex) { 161 | const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 162 | SourceLocation ParamLoc = PD->getLocation(); 163 | if (!(*i)->isDependentType() && 164 | SemaRef.RequireLiteralType( 165 | ParamLoc, *i, diag::err_constexpr_non_literal_param, ArgIndex + 1, 166 | PD->getSourceRange(), isa(FD))) 167 | return false; 168 | } 169 | return true; 170 | } 171 | } // namespace 172 | 173 | /* 174 | * ConstexprFunctionASTVisitor 175 | * 176 | * Find all functions that can be constexpr but arent. Create diagnostics for 177 | * them and mark them constexpr for the next pass. 178 | */ 179 | class ConstexprFunctionASTVisitor 180 | : public clang::RecursiveASTVisitor { 181 | clang::SourceManager &sourceManager_; 182 | clang::CompilerInstance &CI_; 183 | clang::DiagnosticsEngine &DE; 184 | 185 | public: 186 | explicit ConstexprFunctionASTVisitor(clang::SourceManager &sm, 187 | clang::CompilerInstance &ci) 188 | : sourceManager_(sm), CI_(ci), DE(ci.getASTContext().getDiagnostics()) {} 189 | 190 | bool VisitFunctionDecl(clang::FunctionDecl *func) { 191 | 192 | // Only functions in our TU 193 | SourceLocation loc = func->getSourceRange().getBegin(); 194 | if (!sourceManager_.isWrittenInMainFile(loc)) 195 | return true; 196 | 197 | // Skip existing constExpr functions 198 | if (func->isConstexpr()) 199 | return true; 200 | 201 | // Don't mark main as constexpr 202 | if (func->isMain()) 203 | return true; 204 | 205 | // Destructors can't be constexpr 206 | if (isa(func)) 207 | return true; 208 | 209 | auto &sema = CI_.getSema(); 210 | 211 | // Temporarily disable diagnostics for these next functions, use a 212 | // unique_ptr deleter to handle restoring it 213 | sema.getDiagnostics().setSuppressAllDiagnostics(true); 214 | { 215 | auto returnDiagnostics = [&sema](int *) { 216 | sema.getDiagnostics().setSuppressAllDiagnostics(false); 217 | }; 218 | int lol = 0; 219 | std::unique_ptr scope( 220 | &lol, returnDiagnostics); 221 | 222 | #if LLVM_VERSION_MAJOR >= 10 223 | if (!sema.CheckConstexprFunctionDefinition( 224 | func, Sema::CheckConstexprKind::CheckValid)) 225 | return true; 226 | #else 227 | if (!sema.CheckConstexprFunctionDecl(func)) 228 | return true; 229 | #endif 230 | 231 | // We can't check this if we don't have a function body. 232 | if (!func->getBody()) 233 | return true; 234 | 235 | #if LLVM_VERSION_MAJOR <= 9 236 | if (!sema.CheckConstexprFunctionBody(func, func->getBody())) 237 | return true; 238 | #endif 239 | 240 | if (!CheckConstexprParameterTypes(sema, func)) 241 | return true; 242 | } 243 | 244 | SmallVector Diags; 245 | if (!Expr::isPotentialConstantExpr(func, Diags)) 246 | return true; 247 | 248 | // Mark function as constexpr, the next ast visitor will use this 249 | // information to find constexpr vardecls 250 | func->setConstexprKind(CSK_constexpr); 251 | 252 | // Create diagnostic 253 | const auto FixIt = clang::FixItHint::CreateInsertion(loc, "constexpr "); 254 | const auto ID = DE.getCustomDiagID(clang::DiagnosticsEngine::Warning, 255 | "function can be constexpr"); 256 | 257 | DE.Report(loc, ID).AddFixItHint(FixIt); 258 | 259 | return true; 260 | } 261 | }; 262 | 263 | class ConstexprVarDeclFunctionASTVisitor 264 | : public clang::RecursiveASTVisitor { 265 | clang::SourceManager &sourceManager_; 266 | clang::CompilerInstance &CI_; 267 | clang::DiagnosticsEngine &DE; 268 | 269 | class ConstexprVarDeclVisitor 270 | : public clang::RecursiveASTVisitor { 271 | clang::CompilerInstance &CI_; 272 | clang::DiagnosticsEngine &DE; 273 | 274 | public: 275 | explicit ConstexprVarDeclVisitor(clang::CompilerInstance &ci) 276 | : CI_(ci), DE(ci.getASTContext().getDiagnostics()) {} 277 | 278 | bool VisitDeclStmt(clang::DeclStmt *stmt) { 279 | if (!stmt->isSingleDecl()) 280 | return true; 281 | 282 | clang::VarDecl *var = 283 | clang::dyn_cast(*stmt->decl_begin()); 284 | if (!var) 285 | return true; 286 | 287 | // Skip variables that are already constexpr 288 | if (var->isConstexpr()) 289 | return true; 290 | 291 | // Only do locals for right now 292 | if (!var->hasLocalStorage()) 293 | return true; 294 | 295 | clang::SourceLocation loc = stmt->getSourceRange().getBegin(); 296 | auto &sema = CI_.getSema(); 297 | 298 | // var needs an initializer 299 | Expr *Init = var->getInit(); 300 | if (!Init) 301 | return true; 302 | 303 | // If the var is const we can mark it constexpr 304 | QualType ty = var->getType(); 305 | if (!ty.isConstQualified()) 306 | return true; 307 | 308 | // Is init an integral constant expression 309 | if (!var->checkInitIsICE()) 310 | return true; 311 | 312 | // Does the init function use dependent values 313 | if (Init->isValueDependent()) 314 | return true; 315 | 316 | // Can we evaluate the value 317 | if (!var->evaluateValue()) 318 | return true; 319 | 320 | // Is init an ice 321 | if (!var->isInitICE()) 322 | return true; 323 | 324 | // Create Diagnostic/FixIt 325 | const auto FixIt = clang::FixItHint::CreateInsertion(loc, "constexpr "); 326 | const auto ID = DE.getCustomDiagID(clang::DiagnosticsEngine::Warning, 327 | "variable can be constexpr"); 328 | 329 | DE.Report(loc, ID).AddFixItHint(FixIt); 330 | 331 | return true; 332 | } 333 | }; 334 | 335 | public: 336 | explicit ConstexprVarDeclFunctionASTVisitor(clang::SourceManager &sm, 337 | clang::CompilerInstance &ci) 338 | : sourceManager_(sm), CI_(ci), DE(ci.getASTContext().getDiagnostics()) {} 339 | 340 | bool VisitFunctionDecl(clang::FunctionDecl *func) { 341 | // Only functions in our TU 342 | SourceLocation loc = func->getSourceRange().getBegin(); 343 | if (!sourceManager_.isWrittenInMainFile(loc)) 344 | return true; 345 | 346 | // Don't go through functions that are already constexpr 347 | if (func->isConstexpr()) 348 | return true; 349 | 350 | ConstexprVarDeclVisitor vd(CI_); 351 | vd.TraverseFunctionDecl(func); 352 | 353 | return true; 354 | } 355 | }; 356 | 357 | class ConstexprEverythingASTConsumer : public clang::ASTConsumer { 358 | ConstexprFunctionASTVisitor functionVisitor; 359 | ConstexprVarDeclFunctionASTVisitor varDeclVisitor; 360 | 361 | public: 362 | // override the constructor in order to pass CI 363 | explicit ConstexprEverythingASTConsumer(clang::CompilerInstance &ci) 364 | : functionVisitor(ci.getSourceManager(), ci), 365 | varDeclVisitor(ci.getSourceManager(), ci) {} 366 | 367 | void HandleTranslationUnit(clang::ASTContext &astContext) override { 368 | functionVisitor.TraverseDecl(astContext.getTranslationUnitDecl()); 369 | varDeclVisitor.TraverseDecl(astContext.getTranslationUnitDecl()); 370 | } 371 | }; 372 | 373 | class FunctionDeclFrontendAction : public clang::ASTFrontendAction { 374 | 375 | class ConstexprFixItOptions : public clang::FixItOptions { 376 | std::string RewriteFilename(const std::string &Filename, int &fd) override { 377 | return Filename; 378 | } 379 | }; 380 | 381 | std::unique_ptr rewriter = nullptr; 382 | bool inPlaceRewrite; 383 | 384 | public: 385 | FunctionDeclFrontendAction() : inPlaceRewrite(ConstExprFixItOption) {} 386 | 387 | std::unique_ptr 388 | CreateASTConsumer(clang::CompilerInstance &CI, 389 | clang::StringRef file) override { 390 | 391 | if (inPlaceRewrite) { 392 | ConstexprFixItOptions fixItOptions; 393 | fixItOptions.InPlace = inPlaceRewrite; 394 | 395 | rewriter = std::make_unique( 396 | CI.getDiagnostics(), CI.getASTContext().getSourceManager(), 397 | CI.getASTContext().getLangOpts(), &fixItOptions); 398 | 399 | CI.getDiagnostics().setClient(rewriter.get(), false); 400 | } 401 | 402 | return std::make_unique( 403 | CI); // pass CI pointer to ASTConsumer 404 | } 405 | 406 | void EndSourceFileAction() override { 407 | if (inPlaceRewrite) 408 | rewriter->WriteFixedFiles(); 409 | } 410 | }; 411 | 412 | int main(int argc, const char **argv) { 413 | CommonOptionsParser OptionsParser(argc, argv, ConstexprCategory); 414 | 415 | ClangTool Tool(OptionsParser.getCompilations(), 416 | OptionsParser.getSourcePathList()); 417 | Tool.run(newFrontendActionFactory().get()); 418 | } 419 | -------------------------------------------------------------------------------- /tests/01/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | project(test01 CXX) 2 | 3 | set(CMAKE_CXX_STANDARD 14) 4 | set(CMAKE_EXPORT_COMPILE_COMMANDS On) 5 | 6 | add_executable(${PROJECT_NAME} test01.cpp) 7 | -------------------------------------------------------------------------------- /tests/01/test01.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int my_strlen(const char *in) 5 | { 6 | int rv = 0; 7 | while (*in++) 8 | rv++; 9 | 10 | return rv; 11 | } 12 | 13 | std::string get_input() 14 | { 15 | std::string in; 16 | std::getline(std::cin, in); 17 | 18 | return in; 19 | } 20 | 21 | int main(int argc, char **argv) 22 | { 23 | int first = my_strlen(argv[0]); 24 | int second = my_strlen(get_input().c_str()); 25 | int third = my_strlen("aaaaaaaaaaaaaaaaaaaaaa"); 26 | 27 | std::cout << "first: " << first << "\n"; 28 | std::cout << "second: " << second << "\n"; 29 | std::cout << "third: " << third << "\n"; 30 | 31 | return 0; 32 | } 33 | -------------------------------------------------------------------------------- /tests/02/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | project(test02 CXX) 2 | 3 | set(CMAKE_CXX_STANDARD 14) 4 | set(CMAKE_EXPORT_COMPILE_COMMANDS On) 5 | 6 | add_executable(${PROJECT_NAME} test02.cpp) 7 | -------------------------------------------------------------------------------- /tests/02/test02.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | class X { 4 | private: 5 | int num; 6 | public: 7 | //Default constructor 8 | X() : num(0) { 9 | std::cout << "\tDefault Constructor\n"; 10 | } 11 | 12 | //Overloaded constructor 13 | X(const int& val) : num(val) { 14 | } 15 | 16 | //Copy constructor 17 | X(const X& lVal) 18 | : num(lVal.num) { 19 | std::cout << "\tCopy constructor\n"; 20 | } 21 | 22 | //Copy assignment constructor 23 | X& operator=(const X& lVal) { 24 | this->num = lVal.num; 25 | std::cout << "\tCopy Assignment Operator\n"; 26 | return *this; 27 | } 28 | 29 | int getNum() const { return num; } 30 | 31 | }; 32 | 33 | X doSomething() { 34 | X x(100); 35 | 36 | return x; 37 | } 38 | 39 | int main() { 40 | std::cout << "x1:\n"; 41 | const X x1 = doSomething(); 42 | 43 | std::cout << "x2:\n"; 44 | X x2; 45 | x2 = doSomething(); 46 | 47 | const X x3(400); 48 | 49 | std::cout << x3.getNum() << "\n"; 50 | 51 | const X x4(x3); 52 | const X x5(x3); 53 | 54 | std::cout << x4.getNum() << "\n"; 55 | } 56 | --------------------------------------------------------------------------------