[PATCH] D53397: [MinGW] Link to correct openmp library
SquallATF updated this revision to Diff 170330. SquallATF added a comment. - add test Repository: rC Clang https://reviews.llvm.org/D53397 Files: lib/Driver/ToolChains/MinGW.cpp test/Driver/fopenmp.c Index: test/Driver/fopenmp.c === --- test/Driver/fopenmp.c +++ test/Driver/fopenmp.c @@ -10,6 +10,9 @@ // RUN: %clang -target x86_64-netbsd -fopenmp=libomp -c %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-CC1-OPENMP // RUN: %clang -target x86_64-netbsd -fopenmp=libgomp -c %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-CC1-NO-OPENMP // RUN: %clang -target x86_64-netbsd -fopenmp=libiomp5 -c %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-CC1-OPENMP +// RUN: %clang -target x86_64-windows-gnu -fopenmp=libomp -c %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-CC1-OPENMP +// RUN: %clang -target x86_64-windows-gnu -fopenmp=libgomp -c %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-CC1-NO-OPENMP +// RUN: %clang -target x86_64-windows-gnu -fopenmp=libiomp5 -c %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-CC1-OPENMP // // CHECK-CC1-OPENMP: "-cc1" // CHECK-CC1-OPENMP: "-fopenmp" @@ -49,6 +52,14 @@ // RUN: %clang -nostdlib -target x86_64-netbsd -fopenmp=libgomp %s -o %t -### 2>&1 | FileCheck %s --check-prefix=CHECK-NO-GOMP // RUN: %clang -nostdlib -target x86_64-netbsd -fopenmp=libiomp5 %s -o %t -### 2>&1 | FileCheck %s --check-prefix=CHECK-NO-IOMP5 // +// RUN: %clang -target x86_64-windows-gnu -fopenmp=libomp %s -o %t -### 2>&1 | FileCheck %s --check-prefix=CHECK-LD-OMP +// RUN: %clang -target x86_64-windows-gnu -fopenmp=libgomp %s -o %t -### 2>&1 | FileCheck %s --check-prefix=CHECK-LD-GOMP --check-prefix=CHECK-LD-GOMP-NO-RT +// RUN: %clang -target x86_64-windows-gnu -fopenmp=libiomp5 %s -o %t -### 2>&1 | FileCheck %s --check-prefix=CHECK-LD-IOMP5MD +// +// RUN: %clang -nostdlib -target x86_64-windows-gnu -fopenmp=libomp %s -o %t -### 2>&1 | FileCheck %s --check-prefix=CHECK-NO-OMP +// RUN: %clang -nostdlib -target x86_64-windows-gnu -fopenmp=libgomp %s -o %t -### 2>&1 | FileCheck %s --check-prefix=CHECK-NO-GOMP +// RUN: %clang -nostdlib -target x86_64-windows-gnu -fopenmp=libiomp5 %s -o %t -### 2>&1 | FileCheck %s --check-prefix=CHECK-NO-IOMP5MD +// // CHECK-LD-OMP: "{{.*}}ld{{(.exe)?}}" // CHECK-LD-OMP: "-lomp" // @@ -60,6 +71,9 @@ // CHECK-LD-IOMP5: "{{.*}}ld{{(.exe)?}}" // CHECK-LD-IOMP5: "-liomp5" // +// CHECK-LD-IOMP5MD: "{{.*}}ld{{(.exe)?}}" +// CHECK-LD-IOMP5MD: "-liomp5md" +// // CHECK-NO-OMP: "{{.*}}ld{{(.exe)?}}" // CHECK-NO-OMP-NOT: "-lomp" // @@ -69,6 +83,9 @@ // CHECK-NO-IOMP5: "{{.*}}ld{{(.exe)?}}" // CHECK-NO-IOMP5-NOT: "-liomp5" // +// CHECK-NO-IOMP5MD: "{{.*}}ld{{(.exe)?}}" +// CHECK-NO-IOMP5MD-NOT: "-liomp5md" +// // We'd like to check that the default is sane, but until we have the ability // to *always* semantically analyze OpenMP without always generating runtime // calls (in the event of an unsupported runtime), we don't have a good way to @@ -79,6 +96,10 @@ // RUN: %clang -target x86_64-darwin -fopenmp %s -o %t -### 2>&1 | FileCheck %s --check-prefix=CHECK-LD-ANY // RUN: %clang -target x86_64-freebsd -fopenmp %s -o %t -### 2>&1 | FileCheck %s --check-prefix=CHECK-LD-ANY // RUN: %clang -target x86_64-netbsd -fopenmp %s -o %t -### 2>&1 | FileCheck %s --check-prefix=CHECK-LD-ANY +// RUN: %clang -target x86_64-windows-gnu -fopenmp %s -o %t -### 2>&1 | FileCheck %s --check-prefix=CHECK-LD-ANYMD // // CHECK-LD-ANY: "{{.*}}ld{{(.exe)?}}" // CHECK-LD-ANY: "-l{{(omp|gomp|iomp5)}}" +// +// CHECK-LD-ANYMD: "{{.*}}ld{{(.exe)?}}" +// CHECK-LD-ANYMD: "-l{{(omp|gomp|iomp5md)}}" Index: lib/Driver/ToolChains/MinGW.cpp === --- lib/Driver/ToolChains/MinGW.cpp +++ lib/Driver/ToolChains/MinGW.cpp @@ -220,8 +220,24 @@ CmdArgs.push_back("-lssp_nonshared"); CmdArgs.push_back("-lssp"); } - if (Args.hasArg(options::OPT_fopenmp)) -CmdArgs.push_back("-lgomp"); + + if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ, + options::OPT_fno_openmp, false)) { +switch (TC.getDriver().getOpenMPRuntime(Args)) { +case Driver::OMPRT_OMP: + CmdArgs.push_back("-lomp"); + break; +case Driver::OMPRT_IOMP5: + CmdArgs.push_back("-liomp5md"); + break; +case Driver::OMPRT_GOMP: + CmdArgs.push_back("-lgomp"); + break; +case Driver::OMPRT_Unknown: + // Already diagnosed. + break; +} + } AddLibGCC(Args, CmdArgs); Index: test/Driver/fopenmp.c === --- test/Driver/fopenmp.c +++ test/Driver/fopenmp.c @@ -10,6 +10,9 @@ // RUN: %clang -target x86_64-netbsd -fopenmp=libomp -c %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-CC1-OPENMP // RUN: %clang -target x86_64-netbsd -fopenmp=lib
[PATCH] D53476: [clang-cl] Allowed -fopenmp work and link openmp library from per-runtime library directory
SquallATF created this revision. Herald added subscribers: cfe-commits, guansong. clang-cl driver has -fopenmp related code, but -fopenmp not alloewd press to clang-cl driver, this patch fixed it and allowed link to multiarch openmp library. Repository: rC Clang https://reviews.llvm.org/D53476 Files: include/clang/Driver/Options.td lib/Driver/ToolChains/MSVC.cpp test/OpenMP/Inputs/resource_dir/x86_64-msvc-win32/lib/.keep test/OpenMP/linking.c Index: test/OpenMP/linking.c === --- test/OpenMP/linking.c +++ test/OpenMP/linking.c @@ -83,11 +83,12 @@ // // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \ // RUN: -fopenmp=libomp -target x86_64-msvc-win32 -rtlib=platform \ +// RUN: -resource-dir=%S/Inputs/resource_dir \ // RUN: | FileCheck --check-prefix=CHECK-MSVC-LINK-64 %s // CHECK-MSVC-LINK-64: link.exe // CHECK-MSVC-LINK-64-SAME: -nodefaultlib:vcomp.lib // CHECK-MSVC-LINK-64-SAME: -nodefaultlib:vcompd.lib -// CHECK-MSVC-LINK-64-SAME: -libpath:{{.+}}/../lib +// CHECK-MSVC-LINK-64-SAME: -libpath:{{.+[/\\]}}x86_64-msvc-win32{{/|}}lib // CHECK-MSVC-LINK-64-SAME: -defaultlib:libomp.lib // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 -fopenmp-simd -target x86_64-msvc-win32 -rtlib=platform | FileCheck --check-prefix SIMD-ONLY11 %s @@ -97,6 +98,7 @@ // // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \ // RUN: -fopenmp=libiomp5 -target x86_64-msvc-win32 -rtlib=platform \ +// RUN: -resource-dir=%S/Inputs/resource_dir \ // RUN: | FileCheck --check-prefix=CHECK-MSVC-ILINK-64 %s // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 -fopenmp-simd -target x86_64-msvc-win32 -rtlib=platform | FileCheck --check-prefix SIMD-ONLY11 %s @@ -106,6 +108,6 @@ // CHECK-MSVC-ILINK-64: link.exe // CHECK-MSVC-ILINK-64-SAME: -nodefaultlib:vcomp.lib // CHECK-MSVC-ILINK-64-SAME: -nodefaultlib:vcompd.lib -// CHECK-MSVC-ILINK-64-SAME: -libpath:{{.+}}/../lib +// CHECK-MSVC-ILINK-64-SAME: -libpath:{{.+[/\\]}}x86_64-msvc-win32{{/|}}lib // CHECK-MSVC-ILINK-64-SAME: -defaultlib:libiomp5md.lib // Index: lib/Driver/ToolChains/MSVC.cpp === --- lib/Driver/ToolChains/MSVC.cpp +++ lib/Driver/ToolChains/MSVC.cpp @@ -422,8 +422,9 @@ options::OPT_fno_openmp, false)) { CmdArgs.push_back("-nodefaultlib:vcomp.lib"); CmdArgs.push_back("-nodefaultlib:vcompd.lib"); -CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") + - TC.getDriver().Dir + "/../lib")); +for (const auto &LibPath : TC.getLibraryPaths()) { + CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") + LibPath)); +} switch (TC.getDriver().getOpenMPRuntime(Args)) { case Driver::OMPRT_OMP: CmdArgs.push_back("-defaultlib:libomp.lib"); Index: include/clang/Driver/Options.td === --- include/clang/Driver/Options.td +++ include/clang/Driver/Options.td @@ -1516,11 +1516,11 @@ def fobjc_sender_dependent_dispatch : Flag<["-"], "fobjc-sender-dependent-dispatch">, Group; def fomit_frame_pointer : Flag<["-"], "fomit-frame-pointer">, Group; -def fopenmp : Flag<["-"], "fopenmp">, Group, Flags<[CC1Option, NoArgumentUnused]>, +def fopenmp : Flag<["-"], "fopenmp">, Group, Flags<[CC1Option, CoreOption, NoArgumentUnused]>, HelpText<"Parse OpenMP pragmas and generate parallel code.">; def fno_openmp : Flag<["-"], "fno-openmp">, Group, Flags<[NoArgumentUnused]>; def fopenmp_version_EQ : Joined<["-"], "fopenmp-version=">, Group, Flags<[CC1Option, NoArgumentUnused]>; -def fopenmp_EQ : Joined<["-"], "fopenmp=">, Group; +def fopenmp_EQ : Joined<["-"], "fopenmp=">, Group, Flags<[CoreOption]>; def fopenmp_use_tls : Flag<["-"], "fopenmp-use-tls">, Group, Flags<[NoArgumentUnused, HelpHidden]>; def fnoopenmp_use_tls : Flag<["-"], "fnoopenmp-use-tls">, Group, Index: test/OpenMP/linking.c === --- test/OpenMP/linking.c +++ test/OpenMP/linking.c @@ -83,11 +83,12 @@ // // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \ // RUN: -fopenmp=libomp -target x86_64-msvc-win32 -rtlib=platform \ +// RUN: -resource-dir=%S/Inputs/resource_dir \ // RUN: | FileCheck --check-prefix=CHECK-MSVC-LINK-64 %s // CHECK-MSVC-LINK-64: link.exe // CHECK-MSVC-LINK-64-SAME: -nodefaultlib:vcomp.lib // CHECK-MSVC-LINK-64-SAME: -nodefaultlib:vcompd.lib -// CHECK-MSVC-LINK-64-SAME: -libpath:{{.+}}/../lib +// CHECK-MSVC-LINK-64-SAME: -libpath:{{.+[/\\]}}x86_64-msvc-win32{{/|}}lib // CHECK-MSVC-LINK-64-SAME: -defaultlib:libomp.lib // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 -fopenmp-simd -target x86_64-msvc-win32 -rtlib=platform | FileCheck --check-prefix SIMD-ONLY11 %s @@ -97,6 +98,7 @@ // // RUN: %clang -no-canonic
[PATCH] D53397: [MinGW] Link to correct openmp library
mstorsjo accepted this revision. mstorsjo added a comment. This revision is now accepted and ready to land. LGTM, I can commit it for you on Monday, after giving others a chance to comment. Repository: rC Clang https://reviews.llvm.org/D53397 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D53277: [analyzer][NFC] Collect all -analyzer-config options in a .def file
Szelethus updated this revision to Diff 170333. Szelethus added a comment. Split `ANALYZER_OPTION_WITH_FN` up to - `ANALYZER_OPTION_GEN_FN` - `ANALYZER_OPTION_GEN_FN_DEPENDS_ON_USER_MODE` and added some `#error` directives to make it harder to misuse the .def file. https://reviews.llvm.org/D53277 Files: include/clang/StaticAnalyzer/Core/AnalyzerOptions.def include/clang/StaticAnalyzer/Core/AnalyzerOptions.h lib/StaticAnalyzer/Core/AnalyzerOptions.cpp lib/StaticAnalyzer/Core/CoreEngine.cpp Index: lib/StaticAnalyzer/Core/CoreEngine.cpp === --- lib/StaticAnalyzer/Core/CoreEngine.cpp +++ lib/StaticAnalyzer/Core/CoreEngine.cpp @@ -56,17 +56,17 @@ static std::unique_ptr generateWorkList(AnalyzerOptions &Opts, SubEngine &subengine) { switch (Opts.getExplorationStrategy()) { -case AnalyzerOptions::ExplorationStrategyKind::DFS: +case ExplorationStrategyKind::DFS: return WorkList::makeDFS(); -case AnalyzerOptions::ExplorationStrategyKind::BFS: +case ExplorationStrategyKind::BFS: return WorkList::makeBFS(); -case AnalyzerOptions::ExplorationStrategyKind::BFSBlockDFSContents: +case ExplorationStrategyKind::BFSBlockDFSContents: return WorkList::makeBFSBlockDFSContents(); -case AnalyzerOptions::ExplorationStrategyKind::UnexploredFirst: +case ExplorationStrategyKind::UnexploredFirst: return WorkList::makeUnexploredFirst(); -case AnalyzerOptions::ExplorationStrategyKind::UnexploredFirstQueue: +case ExplorationStrategyKind::UnexploredFirstQueue: return WorkList::makeUnexploredFirstPriorityQueue(); -case AnalyzerOptions::ExplorationStrategyKind::UnexploredFirstLocationQueue: +case ExplorationStrategyKind::UnexploredFirstLocationQueue: return WorkList::makeUnexploredFirstPriorityLocationQueue(); } } Index: lib/StaticAnalyzer/Core/AnalyzerOptions.cpp === --- lib/StaticAnalyzer/Core/AnalyzerOptions.cpp +++ lib/StaticAnalyzer/Core/AnalyzerOptions.cpp @@ -49,7 +49,7 @@ return Result; } -AnalyzerOptions::UserModeKind AnalyzerOptions::getUserMode() { +UserModeKind AnalyzerOptions::getUserMode() { if (!UserMode.hasValue()) { StringRef ModeStr = getOptionAsString("mode", "deep"); UserMode = llvm::StringSwitch>(ModeStr) @@ -61,7 +61,7 @@ return UserMode.getValue(); } -AnalyzerOptions::ExplorationStrategyKind +ExplorationStrategyKind AnalyzerOptions::getExplorationStrategy() { if (!ExplorationStrategy.hasValue()) { StringRef StratStr = getOptionAsString("exploration_strategy", @@ -183,137 +183,6 @@ return V.getValue(); } -bool AnalyzerOptions::includeTemporaryDtorsInCFG() { - return getBooleanOption(IncludeTemporaryDtorsInCFG, - "cfg-temporary-dtors", - /* Default = */ true); -} - -bool AnalyzerOptions::includeImplicitDtorsInCFG() { - return getBooleanOption(IncludeImplicitDtorsInCFG, - "cfg-implicit-dtors", - /* Default = */ true); -} - -bool AnalyzerOptions::includeLifetimeInCFG() { - return getBooleanOption(IncludeLifetimeInCFG, "cfg-lifetime", - /* Default = */ false); -} - -bool AnalyzerOptions::includeLoopExitInCFG() { - return getBooleanOption(IncludeLoopExitInCFG, "cfg-loopexit", - /* Default = */ false); -} - -bool AnalyzerOptions::includeRichConstructorsInCFG() { - return getBooleanOption(IncludeRichConstructorsInCFG, - "cfg-rich-constructors", - /* Default = */ true); -} - -bool AnalyzerOptions::includeScopesInCFG() { - return getBooleanOption(IncludeScopesInCFG, - "cfg-scopes", - /* Default = */ false); -} - -bool AnalyzerOptions::mayInlineCXXStandardLibrary() { - return getBooleanOption(InlineCXXStandardLibrary, - "c++-stdlib-inlining", - /*Default=*/true); -} - -bool AnalyzerOptions::mayInlineTemplateFunctions() { - return getBooleanOption(InlineTemplateFunctions, - "c++-template-inlining", - /*Default=*/true); -} - -bool AnalyzerOptions::mayInlineCXXAllocator() { - return getBooleanOption(InlineCXXAllocator, - "c++-allocator-inlining", - /*Default=*/true); -} - -bool AnalyzerOptions::mayInlineCXXContainerMethods() { - return getBooleanOption(InlineCXXContainerMethods, - "c++-container-inlining", - /*Default=*/false); -} - -bool AnalyzerOptions::mayInlineCXXSharedPtrDtor() { - return getBooleanOption(InlineCXXSharedPtrDtor, - "c++-shared_ptr-inlining", - /*Default=*/false); -} - -bool AnalyzerO
[PATCH] D53277: [analyzer][NFC] Collect all -analyzer-config options in a .def file
Szelethus added inline comments. Comment at: include/clang/StaticAnalyzer/Core/AnalyzerOptions.def:386 + +ANALYZER_OPTION_WITH_FN(StringRef, ModelPath, "model-path", "", "", +getModelPath) Szelethus wrote: > Found the use for this here: > https://github.com/llvm-mirror/clang/blob/master/lib/StaticAnalyzer/Frontend/ModelInjector.cpp#L51 > > Which was added by this commit: > https://github.com/llvm-mirror/clang/commit/fdf0d3513240fd8e4da6942e9cd26d2d730eb37b#diff-6e67e63f578935f02bd1d5b20488ea8c > >This patch was contributed by Gábor Horváth as part of his Google Summer of > >Code project. > > @xazax.hun, what would be a good description for this flag? This inline was meant for: `ANALYZER_OPTION_GEN_FN(StringRef, ModelPath, "model-path", "", "", getModelPath)` https://reviews.llvm.org/D53277 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D53481: [clangd] Support passing a relative path to -compile-commands-dir
DaanDeMeyer created this revision. DaanDeMeyer added reviewers: clang-tools-extra, sammccall. DaanDeMeyer added a project: clang-tools-extra. Herald added subscribers: cfe-commits, kadircet, arphaman, jkorous, MaskRay, ioeric, ilya-biryukov. This is useful when using clangd with CMake based projects in Visual Studio Code since when using CMake the `compile_commands.json` file is usually located in a `build` subdirectory which isn't a parent directory of the source files. Allowing passing relative paths to -compile-commands-dir allows specifying `clangd.arguments = ["-compile-commands-dir=build"]` in VSCode's settings file and having it work for each CMake based project that uses the `build` subdirectory as the build directory (instead of having to specify the absolute path to the compile commands directory for each separate project in VSCode's settings). Repository: rCTE Clang Tools Extra https://reviews.llvm.org/D53481 Files: clangd/tool/ClangdMain.cpp Index: clangd/tool/ClangdMain.cpp === --- clangd/tool/ClangdMain.cpp +++ clangd/tool/ClangdMain.cpp @@ -253,14 +253,27 @@ Optional CompileCommandsDirPath; if (CompileCommandsDir.empty()) { CompileCommandsDirPath = None; - } else if (!sys::path::is_absolute(CompileCommandsDir) || - !sys::fs::exists(CompileCommandsDir)) { -errs() << "Path specified by --compile-commands-dir either does not " - "exist or is not an absolute " - "path. The argument will be ignored.\n"; + } else if (!sys::fs::exists(CompileCommandsDir)) { +errs() << "Path specified by --compile-commands-dir does not exist. The " + "argument will be ignored.\n"; CompileCommandsDirPath = None; } else { -CompileCommandsDirPath = CompileCommandsDir; +// If the compile-commands-dir arg path is absolute, use it directly. If +// the path is relative, try to convert it to an absolute path first. +if (sys::path::is_absolute(CompileCommandsDir)) { + CompileCommandsDirPath = CompileCommandsDir; +} else { + SmallString<128> Path(CompileCommandsDir); + std::error_code EC = sys::fs::make_absolute(Path); + if (EC) { +errs() << "Error while converting the relative path specified by " + "--compile-commands-dir to an absolute path: " + << EC.message() << ". The argument will be ignored.\n"; +CompileCommandsDirPath = None; + } else { +CompileCommandsDirPath = Path.str(); + } +} } ClangdServer::Options Opts; Index: clangd/tool/ClangdMain.cpp === --- clangd/tool/ClangdMain.cpp +++ clangd/tool/ClangdMain.cpp @@ -253,14 +253,27 @@ Optional CompileCommandsDirPath; if (CompileCommandsDir.empty()) { CompileCommandsDirPath = None; - } else if (!sys::path::is_absolute(CompileCommandsDir) || - !sys::fs::exists(CompileCommandsDir)) { -errs() << "Path specified by --compile-commands-dir either does not " - "exist or is not an absolute " - "path. The argument will be ignored.\n"; + } else if (!sys::fs::exists(CompileCommandsDir)) { +errs() << "Path specified by --compile-commands-dir does not exist. The " + "argument will be ignored.\n"; CompileCommandsDirPath = None; } else { -CompileCommandsDirPath = CompileCommandsDir; +// If the compile-commands-dir arg path is absolute, use it directly. If +// the path is relative, try to convert it to an absolute path first. +if (sys::path::is_absolute(CompileCommandsDir)) { + CompileCommandsDirPath = CompileCommandsDir; +} else { + SmallString<128> Path(CompileCommandsDir); + std::error_code EC = sys::fs::make_absolute(Path); + if (EC) { +errs() << "Error while converting the relative path specified by " + "--compile-commands-dir to an absolute path: " + << EC.message() << ". The argument will be ignored.\n"; +CompileCommandsDirPath = None; + } else { +CompileCommandsDirPath = Path.str(); + } +} } ClangdServer::Options Opts; ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D53277: [analyzer][NFC] Collect all -analyzer-config options in a .def file
Szelethus updated this revision to Diff 170343. Szelethus added a comment. Added default value to `ANALYZER_OPTION` and split it upto - `ANALYZER_OPTION` and - `ANALYZER_OPTION_DEPENDS_ON_USER_MODE`. The `TYPE` entry only holds `bool`, `unsigned` and `StringRef now. These things will make followup patches significantly more pleasant to implement. https://reviews.llvm.org/D53277 Files: include/clang/StaticAnalyzer/Core/AnalyzerOptions.def include/clang/StaticAnalyzer/Core/AnalyzerOptions.h lib/StaticAnalyzer/Core/AnalyzerOptions.cpp lib/StaticAnalyzer/Core/CoreEngine.cpp Index: lib/StaticAnalyzer/Core/CoreEngine.cpp === --- lib/StaticAnalyzer/Core/CoreEngine.cpp +++ lib/StaticAnalyzer/Core/CoreEngine.cpp @@ -56,17 +56,17 @@ static std::unique_ptr generateWorkList(AnalyzerOptions &Opts, SubEngine &subengine) { switch (Opts.getExplorationStrategy()) { -case AnalyzerOptions::ExplorationStrategyKind::DFS: +case ExplorationStrategyKind::DFS: return WorkList::makeDFS(); -case AnalyzerOptions::ExplorationStrategyKind::BFS: +case ExplorationStrategyKind::BFS: return WorkList::makeBFS(); -case AnalyzerOptions::ExplorationStrategyKind::BFSBlockDFSContents: +case ExplorationStrategyKind::BFSBlockDFSContents: return WorkList::makeBFSBlockDFSContents(); -case AnalyzerOptions::ExplorationStrategyKind::UnexploredFirst: +case ExplorationStrategyKind::UnexploredFirst: return WorkList::makeUnexploredFirst(); -case AnalyzerOptions::ExplorationStrategyKind::UnexploredFirstQueue: +case ExplorationStrategyKind::UnexploredFirstQueue: return WorkList::makeUnexploredFirstPriorityQueue(); -case AnalyzerOptions::ExplorationStrategyKind::UnexploredFirstLocationQueue: +case ExplorationStrategyKind::UnexploredFirstLocationQueue: return WorkList::makeUnexploredFirstPriorityLocationQueue(); } } Index: lib/StaticAnalyzer/Core/AnalyzerOptions.cpp === --- lib/StaticAnalyzer/Core/AnalyzerOptions.cpp +++ lib/StaticAnalyzer/Core/AnalyzerOptions.cpp @@ -49,91 +49,87 @@ return Result; } -AnalyzerOptions::UserModeKind AnalyzerOptions::getUserMode() { +UserModeKind AnalyzerOptions::getUserMode() { if (!UserMode.hasValue()) { -StringRef ModeStr = getOptionAsString("mode", "deep"); -UserMode = llvm::StringSwitch>(ModeStr) - .Case("shallow", UMK_Shallow) - .Case("deep", UMK_Deep) - .Default(None); -assert(UserMode.getValue() && "User mode is invalid."); +UserMode = getOptionAsString("mode", "deep"); } - return UserMode.getValue(); + + auto K = llvm::StringSwitch>(*UserMode) +.Case("shallow", UMK_Shallow) +.Case("deep", UMK_Deep) +.Default(None); + assert(UserMode.hasValue() && "User mode is invalid."); + return K.getValue(); } -AnalyzerOptions::ExplorationStrategyKind +ExplorationStrategyKind AnalyzerOptions::getExplorationStrategy() { if (!ExplorationStrategy.hasValue()) { -StringRef StratStr = getOptionAsString("exploration_strategy", - "unexplored_first_queue"); -ExplorationStrategy = -llvm::StringSwitch>(StratStr) -.Case("dfs", ExplorationStrategyKind::DFS) -.Case("bfs", ExplorationStrategyKind::BFS) -.Case("unexplored_first", - ExplorationStrategyKind::UnexploredFirst) -.Case("unexplored_first_queue", - ExplorationStrategyKind::UnexploredFirstQueue) -.Case("unexplored_first_location_queue", - ExplorationStrategyKind::UnexploredFirstLocationQueue) -.Case("bfs_block_dfs_contents", - ExplorationStrategyKind::BFSBlockDFSContents) -.Default(None); -assert(ExplorationStrategy.hasValue() && - "User mode is invalid."); +ExplorationStrategy = getOptionAsString("exploration_strategy", +"unexplored_first_queue"); } - return ExplorationStrategy.getValue(); + auto K = +llvm::StringSwitch>( + *ExplorationStrategy) + .Case("dfs", ExplorationStrategyKind::DFS) + .Case("bfs", ExplorationStrategyKind::BFS) + .Case("unexplored_first", +ExplorationStrategyKind::UnexploredFirst) + .Case("unexplored_first_queue", +ExplorationStrategyKind::UnexploredFirstQueue) + .Case("unexplored_first_location_queue", +ExplorationStrategyKind::UnexploredFirstLocationQueue) + .Case("bfs_block_dfs_contents", +ExplorationStrategyKind::BFSBlockDFSContents) + .Default(None); + assert(K.hasValue() && "User mode is invalid."); + return K.getValue(); } IPAKind AnalyzerOptions:
[PATCH] D53482: Add clang-format stability check with FormatTests
vglavnyy created this revision. vglavnyy added reviewers: djasper, krasimir. Herald added a subscriber: cfe-commits. Twice running clang-format may give unstable result for some code samples, for example: https://bugs.llvm.org/show_bug.cgi?id=23728 This commit adds stability check to clang-format unit-tests. After apply this patch 10 tests from the FormatTests will fail. > [==] 647 tests from 19 test cases ran. (31449 ms total) > [ PASSED ] 637 tests. > [ FAILED ] 10 tests, listed below: > [ FAILED ] FormatTest.OnlyGeneratesNecessaryReplacements > [ FAILED ] FormatTest.BreaksStringLiterals > [ FAILED ] FormatTest.BreaksStringLiteralsWithTabs > [ FAILED ] FormatTest.BreaksWideAndNSStringLiterals > [ FAILED ] FormatTest.BreaksStringLiteralsWithin_TMacro > [ FAILED ] FormatTest.DoNotBreakStringLiteralsInEscapeSequence > [ FAILED ] FormatTest.OptimizeBreakPenaltyVsExcess > [ FAILED ] FormatTest.WorksFor8bitEncodings > [ FAILED ] FormatTest.SplitsUTF8Strings > [ FAILED ] FormatTest.SupportsCRLF Repository: rC Clang https://reviews.llvm.org/D53482 Files: unittests/Format/FormatTest.cpp Index: unittests/Format/FormatTest.cpp === --- unittests/Format/FormatTest.cpp +++ unittests/Format/FormatTest.cpp @@ -38,7 +38,8 @@ std::string format(llvm::StringRef Code, const FormatStyle &Style = getLLVMStyle(), - StatusCheck CheckComplete = SC_ExpectComplete) { + StatusCheck CheckComplete = SC_ExpectComplete, + bool check = true) { LLVM_DEBUG(llvm::errs() << "---\n"); LLVM_DEBUG(llvm::errs() << Code << "\n\n"); std::vector Ranges(1, tooling::Range(0, Code.size())); @@ -54,6 +55,12 @@ auto Result = applyAllReplacements(Code, Replaces); EXPECT_TRUE(static_cast(Result)); LLVM_DEBUG(llvm::errs() << "\n" << *Result << "\n\n"); +if (check && Status.FormatComplete) { + // Do recursive call and check that format of format is valid. + LLVM_DEBUG(llvm::errs() << "\ncheck\n\n"); + auto FormatedResult = format(*Result, Style, SC_ExpectComplete, false); + EXPECT_EQ(*Result, FormatedResult); +} return *Result; } Index: unittests/Format/FormatTest.cpp === --- unittests/Format/FormatTest.cpp +++ unittests/Format/FormatTest.cpp @@ -38,7 +38,8 @@ std::string format(llvm::StringRef Code, const FormatStyle &Style = getLLVMStyle(), - StatusCheck CheckComplete = SC_ExpectComplete) { + StatusCheck CheckComplete = SC_ExpectComplete, + bool check = true) { LLVM_DEBUG(llvm::errs() << "---\n"); LLVM_DEBUG(llvm::errs() << Code << "\n\n"); std::vector Ranges(1, tooling::Range(0, Code.size())); @@ -54,6 +55,12 @@ auto Result = applyAllReplacements(Code, Replaces); EXPECT_TRUE(static_cast(Result)); LLVM_DEBUG(llvm::errs() << "\n" << *Result << "\n\n"); +if (check && Status.FormatComplete) { + // Do recursive call and check that format of format is valid. + LLVM_DEBUG(llvm::errs() << "\ncheck\n\n"); + auto FormatedResult = format(*Result, Style, SC_ExpectComplete, false); + EXPECT_EQ(*Result, FormatedResult); +} return *Result; } ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r344870 - [analyzer][NFC] Fix inconsistencies in AnalyzerOptions
Author: szelethus Date: Sun Oct 21 11:19:32 2018 New Revision: 344870 URL: http://llvm.org/viewvc/llvm-project?rev=344870&view=rev Log: [analyzer][NFC] Fix inconsistencies in AnalyzerOptions I'm in the process of refactoring AnalyzerOptions. The main motivation behind here is to emit warnings if an invalid -analyzer-config option is given from the command line, and be able to list them all. This first NFC patch contains small modifications to make AnalyzerOptions.cpp a little more consistent. Differential Revision: https://reviews.llvm.org/D53274 Modified: cfe/trunk/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h cfe/trunk/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp cfe/trunk/lib/StaticAnalyzer/Core/CoreEngine.cpp Modified: cfe/trunk/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h?rev=344870&r1=344869&r2=344870&view=diff == --- cfe/trunk/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h (original) +++ cfe/trunk/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h Sun Oct 21 11:19:32 2018 @@ -85,7 +85,7 @@ enum CXXInlineableMemberKind { // Uninitialized = 0, /// A dummy mode in which no C++ inlining is enabled. - CIMK_None = 1, + CIMK_None, /// Refers to regular member function and operator calls. CIMK_MemberFunctions, @@ -102,8 +102,6 @@ enum CXXInlineableMemberKind { /// Describes the different modes of inter-procedural analysis. enum IPAKind { - IPAK_NotSet = 0, - /// Perform only intra-procedural analysis. IPAK_None = 1, @@ -188,16 +186,11 @@ public: UnexploredFirstQueue, UnexploredFirstLocationQueue, BFSBlockDFSContents, -NotSet }; private: - ExplorationStrategyKind ExplorationStrategy = ExplorationStrategyKind::NotSet; - /// Describes the kinds for high-level analyzer mode. enum UserModeKind { -UMK_NotSet = 0, - /// Perform shallow but fast analyzes. UMK_Shallow = 1, @@ -205,16 +198,18 @@ private: UMK_Deep = 2 }; + llvm::Optional ExplorationStrategy; + /// Controls the high-level analyzer mode, which influences the default /// settings for some of the lower-level config options (such as IPAMode). /// \sa getUserMode - UserModeKind UserMode = UMK_NotSet; + llvm::Optional UserMode; /// Controls the mode of inter-procedural analysis. - IPAKind IPAMode = IPAK_NotSet; + llvm::Optional IPAMode; /// Controls which C++ member functions will be considered for inlining. - CXXInlineableMemberKind CXXMemberInliningMode; + llvm::Optional CXXMemberInliningMode; /// \sa includeImplicitDtorsInCFG Optional IncludeImplicitDtorsInCFG; @@ -420,6 +415,12 @@ public: const ento::CheckerBase *C = nullptr, bool SearchInParents = false); + + unsigned getOptionAsUInt(Optional &V, StringRef Name, + unsigned DefaultVal, + const ento::CheckerBase *C = nullptr, + bool SearchInParents = false); + /// Query an option's string value. /// /// If an option value is not provided, returns the given \p DefaultVal. @@ -437,6 +438,11 @@ public: const ento::CheckerBase *C = nullptr, bool SearchInParents = false); + StringRef getOptionAsString(Optional &V, StringRef Name, + StringRef DefaultVal, + const ento::CheckerBase *C = nullptr, + bool SearchInParents = false); + /// Retrieves and sets the UserMode. This is a high-level option, /// which is used to set other low-level options. It is not accessible /// outside of AnalyzerOptions. Modified: cfe/trunk/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp?rev=344870&r1=344869&r2=344870&view=diff == --- cfe/trunk/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp (original) +++ cfe/trunk/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp Sun Oct 21 11:19:32 2018 @@ -50,27 +50,24 @@ AnalyzerOptions::getRegisteredCheckers(b } AnalyzerOptions::UserModeKind AnalyzerOptions::getUserMode() { - if (UserMode == UMK_NotSet) { -StringRef ModeStr = -Config.insert(std::make_pair("mode", "deep")).first->second; -UserMode = llvm::StringSwitch(ModeStr) + if (!UserMode.hasValue()) { +StringRef ModeStr = getOptionAsString("mode", "deep"); +UserMode = llvm::StringSwitch>(ModeStr) .Case("shallow", UMK_Shallow) .Case("deep", UMK_Deep) - .Default(UMK_NotSet); -assert(UserMode != UMK_NotSet && "User mode is invalid."); + .Default(None); +assert(UserMode.getValue() && "User mode is in
[PATCH] D53274: [analyzer][NFC] Fix inconsistencies in AnalyzerOptions
This revision was automatically updated to reflect the committed changes. Szelethus marked 3 inline comments as done. Closed by commit rL344870: [analyzer][NFC] Fix inconsistencies in AnalyzerOptions (authored by Szelethus, committed by ). Herald added a subscriber: llvm-commits. Changed prior to commit: https://reviews.llvm.org/D53274?vs=169703&id=170346#toc Repository: rL LLVM https://reviews.llvm.org/D53274 Files: cfe/trunk/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h cfe/trunk/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp cfe/trunk/lib/StaticAnalyzer/Core/CoreEngine.cpp Index: cfe/trunk/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h === --- cfe/trunk/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h +++ cfe/trunk/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h @@ -85,7 +85,7 @@ // Uninitialized = 0, /// A dummy mode in which no C++ inlining is enabled. - CIMK_None = 1, + CIMK_None, /// Refers to regular member function and operator calls. CIMK_MemberFunctions, @@ -102,8 +102,6 @@ /// Describes the different modes of inter-procedural analysis. enum IPAKind { - IPAK_NotSet = 0, - /// Perform only intra-procedural analysis. IPAK_None = 1, @@ -188,33 +186,30 @@ UnexploredFirstQueue, UnexploredFirstLocationQueue, BFSBlockDFSContents, -NotSet }; private: - ExplorationStrategyKind ExplorationStrategy = ExplorationStrategyKind::NotSet; - /// Describes the kinds for high-level analyzer mode. enum UserModeKind { -UMK_NotSet = 0, - /// Perform shallow but fast analyzes. UMK_Shallow = 1, /// Perform deep analyzes. UMK_Deep = 2 }; + llvm::Optional ExplorationStrategy; + /// Controls the high-level analyzer mode, which influences the default /// settings for some of the lower-level config options (such as IPAMode). /// \sa getUserMode - UserModeKind UserMode = UMK_NotSet; + llvm::Optional UserMode; /// Controls the mode of inter-procedural analysis. - IPAKind IPAMode = IPAK_NotSet; + llvm::Optional IPAMode; /// Controls which C++ member functions will be considered for inlining. - CXXInlineableMemberKind CXXMemberInliningMode; + llvm::Optional CXXMemberInliningMode; /// \sa includeImplicitDtorsInCFG Optional IncludeImplicitDtorsInCFG; @@ -420,6 +415,12 @@ const ento::CheckerBase *C = nullptr, bool SearchInParents = false); + + unsigned getOptionAsUInt(Optional &V, StringRef Name, + unsigned DefaultVal, + const ento::CheckerBase *C = nullptr, + bool SearchInParents = false); + /// Query an option's string value. /// /// If an option value is not provided, returns the given \p DefaultVal. @@ -437,6 +438,11 @@ const ento::CheckerBase *C = nullptr, bool SearchInParents = false); + StringRef getOptionAsString(Optional &V, StringRef Name, + StringRef DefaultVal, + const ento::CheckerBase *C = nullptr, + bool SearchInParents = false); + /// Retrieves and sets the UserMode. This is a high-level option, /// which is used to set other low-level options. It is not accessible /// outside of AnalyzerOptions. Index: cfe/trunk/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp === --- cfe/trunk/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp +++ cfe/trunk/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp @@ -50,27 +50,24 @@ } AnalyzerOptions::UserModeKind AnalyzerOptions::getUserMode() { - if (UserMode == UMK_NotSet) { -StringRef ModeStr = -Config.insert(std::make_pair("mode", "deep")).first->second; -UserMode = llvm::StringSwitch(ModeStr) + if (!UserMode.hasValue()) { +StringRef ModeStr = getOptionAsString("mode", "deep"); +UserMode = llvm::StringSwitch>(ModeStr) .Case("shallow", UMK_Shallow) .Case("deep", UMK_Deep) - .Default(UMK_NotSet); -assert(UserMode != UMK_NotSet && "User mode is invalid."); + .Default(None); +assert(UserMode.getValue() && "User mode is invalid."); } - return UserMode; + return UserMode.getValue(); } AnalyzerOptions::ExplorationStrategyKind AnalyzerOptions::getExplorationStrategy() { - if (ExplorationStrategy == ExplorationStrategyKind::NotSet) { -StringRef StratStr = -Config -.insert(std::make_pair("exploration_strategy", "unexplored_first_queue")) -.first->second; + if (!ExplorationStrategy.hasValue()) { +StringRef StratStr = getOptionAsString("exploration_strategy", + "unexplored_first_queue"); ExplorationStrategy = -llvm::StringSwitch(StratStr) +llvm::StringSwitch>(
[PATCH] D53339: [clang-tidy] Add the abseil-duration-factory-float check
JonasToth added a comment. In https://reviews.llvm.org/D53339#1269998, @hwright wrote: > Ping. > > What are the next steps here? Please mark all comments you consider resolved as 'Done', i think alex already kinda accepted it, but given there were more comments he should take another look. https://reviews.llvm.org/D53339 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D53454: [clang-tidy] add IgnoreMacros option to eadability-redundant-smartptr-get
JonasToth accepted this revision. JonasToth added a comment. This revision is now accepted and ready to land. LGTM, but could you please add a short notice in the release notes? Repository: rCTE Clang Tools Extra https://reviews.llvm.org/D53454 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D53454: [clang-tidy] add IgnoreMacros option to eadability-redundant-smartptr-get
vmiklos added a comment. In https://reviews.llvm.org/D53454#1270298, @JonasToth wrote: > LGTM, but could you please add a short notice in the release notes? Sure, I will do that. Repository: rCTE Clang Tools Extra https://reviews.llvm.org/D53454 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D53454: [clang-tidy] add IgnoreMacros option to eadability-redundant-smartptr-get
This revision was automatically updated to reflect the committed changes. Closed by commit rL344871: [clang-tidy] add IgnoreMacros option to readability-redundant-smartptr-get (authored by vmiklos, committed by ). Herald added a subscriber: llvm-commits. Changed prior to commit: https://reviews.llvm.org/D53454?vs=170256&id=170347#toc Repository: rL LLVM https://reviews.llvm.org/D53454 Files: clang-tools-extra/trunk/clang-tidy/readability/RedundantSmartptrGetCheck.cpp clang-tools-extra/trunk/clang-tidy/readability/RedundantSmartptrGetCheck.h clang-tools-extra/trunk/docs/ReleaseNotes.rst clang-tools-extra/trunk/docs/clang-tidy/checks/readability-redundant-smartptr-get.rst clang-tools-extra/trunk/test/clang-tidy/readability-redundant-smartptr-get-macros.cpp clang-tools-extra/trunk/test/clang-tidy/readability-redundant-smartptr-get.cpp Index: clang-tools-extra/trunk/clang-tidy/readability/RedundantSmartptrGetCheck.cpp === --- clang-tools-extra/trunk/clang-tidy/readability/RedundantSmartptrGetCheck.cpp +++ clang-tools-extra/trunk/clang-tidy/readability/RedundantSmartptrGetCheck.cpp @@ -91,6 +91,11 @@ } // namespace +void RedundantSmartptrGetCheck::storeOptions( +ClangTidyOptions::OptionMap &Opts) { + Options.store(Opts, "IgnoreMacros", IgnoreMacros); +} + void RedundantSmartptrGetCheck::registerMatchers(MatchFinder *Finder) { // Only register the matchers for C++; the functionality currently does not // provide any benefit to other languages, despite being benign. @@ -126,6 +131,9 @@ bool IsPtrToPtr = Result.Nodes.getNodeAs("ptr_to_ptr") != nullptr; bool IsMemberExpr = Result.Nodes.getNodeAs("memberExpr") != nullptr; const auto *GetCall = Result.Nodes.getNodeAs("redundant_get"); + if (GetCall->getBeginLoc().isMacroID() && IgnoreMacros) +return; + const auto *Smartptr = Result.Nodes.getNodeAs("smart_pointer"); if (IsPtrToPtr && IsMemberExpr) { Index: clang-tools-extra/trunk/clang-tidy/readability/RedundantSmartptrGetCheck.h === --- clang-tools-extra/trunk/clang-tidy/readability/RedundantSmartptrGetCheck.h +++ clang-tools-extra/trunk/clang-tidy/readability/RedundantSmartptrGetCheck.h @@ -28,9 +28,14 @@ class RedundantSmartptrGetCheck : public ClangTidyCheck { public: RedundantSmartptrGetCheck(StringRef Name, ClangTidyContext *Context) - : ClangTidyCheck(Name, Context) {} + : ClangTidyCheck(Name, Context), +IgnoreMacros(Options.getLocalOrGlobal("IgnoreMacros", 1) != 0) {} + void storeOptions(ClangTidyOptions::OptionMap &Opts) override; void registerMatchers(ast_matchers::MatchFinder *Finder) override; void check(const ast_matchers::MatchFinder::MatchResult &Result) override; + +private: + const bool IgnoreMacros; }; } // namespace readability Index: clang-tools-extra/trunk/docs/clang-tidy/checks/readability-redundant-smartptr-get.rst === --- clang-tools-extra/trunk/docs/clang-tidy/checks/readability-redundant-smartptr-get.rst +++ clang-tools-extra/trunk/docs/clang-tidy/checks/readability-redundant-smartptr-get.rst @@ -14,3 +14,8 @@ *ptr->get() ==> **ptr if (ptr.get() == nullptr) ... => if (ptr == nullptr) ... + +.. option:: IgnoreMacros + + If this option is set to non-zero (default is `1`), the check will not warn + about calls inside macros. Index: clang-tools-extra/trunk/docs/ReleaseNotes.rst === --- clang-tools-extra/trunk/docs/ReleaseNotes.rst +++ clang-tools-extra/trunk/docs/ReleaseNotes.rst @@ -67,6 +67,10 @@ Improvements to clang-tidy -- +- The :doc:`readability-redundant-smartptr-get + ` check does not warn + about calls inside macros anymore by default. + - New :doc:`abseil-duration-division ` check. Index: clang-tools-extra/trunk/test/clang-tidy/readability-redundant-smartptr-get-macros.cpp === --- clang-tools-extra/trunk/test/clang-tidy/readability-redundant-smartptr-get-macros.cpp +++ clang-tools-extra/trunk/test/clang-tidy/readability-redundant-smartptr-get-macros.cpp @@ -0,0 +1,24 @@ +// RUN: %check_clang_tidy %s readability-redundant-smartptr-get %t -- \ +// RUN: -config="{CheckOptions: [{key: readability-redundant-smartptr-get.IgnoreMacros, value: 0}]}" \ +// RUN: -- -std=c++11 + +namespace std { + +template +struct shared_ptr { + T &operator*() const; + T *operator->() const; + T *get() const; + explicit operator bool() const noexcept; +}; + +} // namespace std + +#define MACRO(p) p.get() + +void Positive() { + std::shared_ptr x; + if (MACRO(x) == nullptr) +; + // CHECK-MESSAGES: :[[@LINE-2]]:13: warning: redundant get() call on smart pointer +}; Index: clang-tools-extra/trunk/test/clang-tidy/readability-redundant-smartpt
[clang-tools-extra] r344871 - [clang-tidy] add IgnoreMacros option to readability-redundant-smartptr-get
Author: vmiklos Date: Sun Oct 21 12:16:25 2018 New Revision: 344871 URL: http://llvm.org/viewvc/llvm-project?rev=344871&view=rev Log: [clang-tidy] add IgnoreMacros option to readability-redundant-smartptr-get And also enable it by default to be consistent with e.g. modernize-use-using. This helps e.g. when running this check on client code where the macro is provided by the system, so there is no easy way to modify it. Reviewed By: JonasToth Differential Revision: https://reviews.llvm.org/D53454 Added: clang-tools-extra/trunk/test/clang-tidy/readability-redundant-smartptr-get-macros.cpp Modified: clang-tools-extra/trunk/clang-tidy/readability/RedundantSmartptrGetCheck.cpp clang-tools-extra/trunk/clang-tidy/readability/RedundantSmartptrGetCheck.h clang-tools-extra/trunk/docs/ReleaseNotes.rst clang-tools-extra/trunk/docs/clang-tidy/checks/readability-redundant-smartptr-get.rst clang-tools-extra/trunk/test/clang-tidy/readability-redundant-smartptr-get.cpp Modified: clang-tools-extra/trunk/clang-tidy/readability/RedundantSmartptrGetCheck.cpp URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/readability/RedundantSmartptrGetCheck.cpp?rev=344871&r1=344870&r2=344871&view=diff == --- clang-tools-extra/trunk/clang-tidy/readability/RedundantSmartptrGetCheck.cpp (original) +++ clang-tools-extra/trunk/clang-tidy/readability/RedundantSmartptrGetCheck.cpp Sun Oct 21 12:16:25 2018 @@ -91,6 +91,11 @@ void registerMatchersForGetEquals(MatchF } // namespace +void RedundantSmartptrGetCheck::storeOptions( +ClangTidyOptions::OptionMap &Opts) { + Options.store(Opts, "IgnoreMacros", IgnoreMacros); +} + void RedundantSmartptrGetCheck::registerMatchers(MatchFinder *Finder) { // Only register the matchers for C++; the functionality currently does not // provide any benefit to other languages, despite being benign. @@ -126,6 +131,9 @@ void RedundantSmartptrGetCheck::check(co bool IsPtrToPtr = Result.Nodes.getNodeAs("ptr_to_ptr") != nullptr; bool IsMemberExpr = Result.Nodes.getNodeAs("memberExpr") != nullptr; const auto *GetCall = Result.Nodes.getNodeAs("redundant_get"); + if (GetCall->getBeginLoc().isMacroID() && IgnoreMacros) +return; + const auto *Smartptr = Result.Nodes.getNodeAs("smart_pointer"); if (IsPtrToPtr && IsMemberExpr) { Modified: clang-tools-extra/trunk/clang-tidy/readability/RedundantSmartptrGetCheck.h URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/readability/RedundantSmartptrGetCheck.h?rev=344871&r1=344870&r2=344871&view=diff == --- clang-tools-extra/trunk/clang-tidy/readability/RedundantSmartptrGetCheck.h (original) +++ clang-tools-extra/trunk/clang-tidy/readability/RedundantSmartptrGetCheck.h Sun Oct 21 12:16:25 2018 @@ -28,9 +28,14 @@ namespace readability { class RedundantSmartptrGetCheck : public ClangTidyCheck { public: RedundantSmartptrGetCheck(StringRef Name, ClangTidyContext *Context) - : ClangTidyCheck(Name, Context) {} + : ClangTidyCheck(Name, Context), +IgnoreMacros(Options.getLocalOrGlobal("IgnoreMacros", 1) != 0) {} + void storeOptions(ClangTidyOptions::OptionMap &Opts) override; void registerMatchers(ast_matchers::MatchFinder *Finder) override; void check(const ast_matchers::MatchFinder::MatchResult &Result) override; + +private: + const bool IgnoreMacros; }; } // namespace readability Modified: clang-tools-extra/trunk/docs/ReleaseNotes.rst URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/docs/ReleaseNotes.rst?rev=344871&r1=344870&r2=344871&view=diff == --- clang-tools-extra/trunk/docs/ReleaseNotes.rst (original) +++ clang-tools-extra/trunk/docs/ReleaseNotes.rst Sun Oct 21 12:16:25 2018 @@ -67,6 +67,10 @@ The improvements are... Improvements to clang-tidy -- +- The :doc:`readability-redundant-smartptr-get + ` check does not warn + about calls inside macros anymore by default. + - New :doc:`abseil-duration-division ` check. Modified: clang-tools-extra/trunk/docs/clang-tidy/checks/readability-redundant-smartptr-get.rst URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/docs/clang-tidy/checks/readability-redundant-smartptr-get.rst?rev=344871&r1=344870&r2=344871&view=diff == --- clang-tools-extra/trunk/docs/clang-tidy/checks/readability-redundant-smartptr-get.rst (original) +++ clang-tools-extra/trunk/docs/clang-tidy/checks/readability-redundant-smartptr-get.rst Sun Oct 21 12:16:25 2018 @@ -14,3 +14,8 @@ Examples: *ptr->get() ==> **ptr if (ptr.get() == nullptr) ... => if (ptr == nullptr) ... + +.. option:: IgnoreMacros + + If this option is set to non-
[PATCH] D53483: [analyzer] Restrict AnalyzerOptions' interface so that non-checker objects have to be registered
Szelethus created this revision. Szelethus added reviewers: NoQ, george.karpenkov, rnkovacs, xazax.hun, MTC. Herald added subscribers: cfe-commits, dkrupp, donat.nagy, mikhail.ramalho, a.sidorin, szepet, whisperity. Herald added a reviewer: teemperor. One of the reasons why `AnalyzerOptions` is so chaotic is that options can be retrieved from the command line whenever and wherever. This allowed for some options to be forgotten for a looong time. Have you ever heard of `"region-store-small-struct-limit"`? In order to prevent this in the future, I'm proposing to restrict `AnalyzerOptions`' interface so that only checker options can be retrieved without special getters. I would like to make every option be accessible only through a getter, but checkers from plugins are a thing, so I'll have to figure something out for that. This also forces developers who'd like to add a new option to register it properly in the .def file. Repository: rC Clang https://reviews.llvm.org/D53483 Files: include/clang/StaticAnalyzer/Core/AnalyzerOptions.h lib/StaticAnalyzer/Checkers/AnalysisOrderChecker.cpp lib/StaticAnalyzer/Checkers/CloneChecker.cpp lib/StaticAnalyzer/Checkers/LocalizationChecker.cpp lib/StaticAnalyzer/Checkers/MallocChecker.cpp lib/StaticAnalyzer/Checkers/MmapWriteExecChecker.cpp lib/StaticAnalyzer/Checkers/NullabilityChecker.cpp lib/StaticAnalyzer/Checkers/NumberObjectConversionChecker.cpp lib/StaticAnalyzer/Checkers/PaddingChecker.cpp lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.h lib/StaticAnalyzer/Checkers/UninitializedObject/UninitializedObjectChecker.cpp lib/StaticAnalyzer/Checkers/VirtualCallChecker.cpp lib/StaticAnalyzer/Core/AnalyzerOptions.cpp unittests/StaticAnalyzer/AnalyzerOptionsTest.cpp Index: unittests/StaticAnalyzer/AnalyzerOptionsTest.cpp === --- unittests/StaticAnalyzer/AnalyzerOptionsTest.cpp +++ unittests/StaticAnalyzer/AnalyzerOptionsTest.cpp @@ -52,23 +52,25 @@ // Checker one has Option specified as true. It should read true regardless of // search mode. CheckerOneMock CheckerOne; - EXPECT_TRUE(Opts.getBooleanOption("Option", false, &CheckerOne)); + EXPECT_TRUE(Opts.getCheckerBooleanOption("Option", false, &CheckerOne)); // The package option is overridden with a checker option. - EXPECT_TRUE(Opts.getBooleanOption("Option", false, &CheckerOne, true)); + EXPECT_TRUE(Opts.getCheckerBooleanOption("Option", false, &CheckerOne, + true)); // The Outer package option is overridden by the Inner package option. No // package option is specified. - EXPECT_TRUE(Opts.getBooleanOption("Option2", false, &CheckerOne, true)); + EXPECT_TRUE(Opts.getCheckerBooleanOption("Option2", false, &CheckerOne, + true)); // No package option is specified and search in packages is turned off. The // default value should be returned. - EXPECT_FALSE(Opts.getBooleanOption("Option2", false, &CheckerOne)); - EXPECT_TRUE(Opts.getBooleanOption("Option2", true, &CheckerOne)); + EXPECT_FALSE(Opts.getCheckerBooleanOption("Option2", false, &CheckerOne)); + EXPECT_TRUE(Opts.getCheckerBooleanOption("Option2", true, &CheckerOne)); // Checker true has no option specified. It should get the default value when // search in parents turned off and false when search in parents turned on. CheckerTwoMock CheckerTwo; - EXPECT_FALSE(Opts.getBooleanOption("Option", false, &CheckerTwo)); - EXPECT_TRUE(Opts.getBooleanOption("Option", true, &CheckerTwo)); - EXPECT_FALSE(Opts.getBooleanOption("Option", true, &CheckerTwo, true)); + EXPECT_FALSE(Opts.getCheckerBooleanOption("Option", false, &CheckerTwo)); + EXPECT_TRUE(Opts.getCheckerBooleanOption("Option", true, &CheckerTwo)); + EXPECT_FALSE(Opts.getCheckerBooleanOption("Option", true, &CheckerTwo, true)); } TEST(StaticAnalyzerOptions, StringOptions) { @@ -83,9 +85,9 @@ CheckerOneMock CheckerOne; EXPECT_TRUE("StringValue" == - Opts.getOptionAsString("Option", "DefaultValue", &CheckerOne)); +Opts.getCheckerStringOption("Option", "DefaultValue", &CheckerOne)); EXPECT_TRUE("DefaultValue" == - Opts.getOptionAsString("Option2", "DefaultValue", &CheckerOne)); + Opts.getCheckerStringOption("Option2", "DefaultValue", &CheckerOne)); } } // end namespace ento } // end namespace clang Index: lib/StaticAnalyzer/Core/AnalyzerOptions.cpp === --- lib/StaticAnalyzer/Core/AnalyzerOptions.cpp +++ lib/StaticAnalyzer/Core/AnalyzerOptions.cpp @@ -51,7 +51,7 @@ UserModeKind AnalyzerOptions::getUserMode() { if (!UserMode.hasValue()) { -UserMode = getOptionAsString("mode", "deep"); +UserMode = getStringOption("mode", "deep"); } auto K = llvm::StringSwitch>(*UserMode) @@ -65,7 +65,7 @@ ExplorationStrategyKin
r344878 - [analyzer][www] Update alpha_checks.html
Author: szelethus Date: Sun Oct 21 15:10:15 2018 New Revision: 344878 URL: http://llvm.org/viewvc/llvm-project?rev=344878&view=rev Log: [analyzer][www] Update alpha_checks.html I added some missing doc. I have not developed any of these checkers, it might worth really inspecting whether I wrote something terribly incorrect. Differential Revision: https://reviews.llvm.org/D52969 Modified: cfe/trunk/www/analyzer/alpha_checks.html cfe/trunk/www/analyzer/available_checks.html Modified: cfe/trunk/www/analyzer/alpha_checks.html URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/www/analyzer/alpha_checks.html?rev=344878&r1=344877&r2=344878&view=diff == --- cfe/trunk/www/analyzer/alpha_checks.html (original) +++ cfe/trunk/www/analyzer/alpha_checks.html Sun Oct 21 15:10:15 2018 @@ -107,6 +107,7 @@ void test(void) { } + alpha.core.CastSize (C) @@ -276,6 +277,33 @@ int test(struct s *p) { +alpha.core.StackAddressAsyncEscape +(C) +Check that addresses to stack memory do not escape the function that involves +dispatch_after or dispatch_async. This checker is +a part of core.StackAddressEscape, but is +https://reviews.llvm.org/D41042>temporarily disabled until some +false positives are fixed. + + +dispatch_block_t test_block_inside_block_async_leak() { + int x = 123; + void (^inner)(void) = ^void(void) { +int y = x; +++y; + }; + void (^outer)(void) = ^void(void) { +int z = x; +++z; +inner(); + }; + return outer; // warn: address of stack-allocated block is captured by a +// returned block +} + + + + alpha.core.TestAfterDivZero (C, C++, ObjC) Check for division by variable that is later compared against 0. @@ -289,6 +317,7 @@ void test(int x) { } + @@ -296,72 +325,142 @@ void test(int x) { Name, DescriptionExample - + + -alpha.cplusplus.VirtualCall +alpha.cplusplus.DeleteWithNonVirtualDtor (C++) -Check virtual member function calls during construction or -destruction. +Reports destructions of polymorphic objects with a non-virtual destructor in +their base class + -class A { -public: - A() { -f(); // warn - } - virtual void f(); -}; - +NonVirtual *create() { + NonVirtual *x = new NVDerived(); // note: conversion from derived to base + // happened here + return x; +} + +void sink(NonVirtual *x) { + delete x; // warn: destruction of a polymorphic object with no virtual +// destructor +} + + + + +alpha.cplusplus.InvalidatedIterator +(C++) +Check for use of invalidated iterators. + + -class A { -public: - ~A() { -this->f(); // warn - } - virtual void f(); +void bad_copy_assign_operator_list1(std::list &L1, +const std::list &L2) { + auto i0 = L1.cbegin(); + L1 = L2; + *i0; // warn: invalidated iterator accessed +} + + + + +alpha.cplusplus.IteratorRange +(C++) +Check for iterators used outside their valid ranges. + + + +void simple_bad_end(const std::vector &v) { + auto i = v.end(); + *i; // warn: iterator accessed outside of its range +} + + + + +alpha.cplusplus.MismatchedIterator +(C++) +Check for use of iterators of different containers where iterators of the same +container are expected. + + + +void bad_insert3(std::vector &v1, std::vector &v2) { + v2.insert(v1.cbegin(), v2.cbegin(), v2.cend()); // warn: container accessed + // using foreign + // iterator argument + v1.insert(v1.cbegin(), v1.cbegin(), v2.cend()); // warn: iterators of + // different containers + // used where the same + // container is + // expected + v1.insert(v1.cbegin(), v2.cbegin(), v1.cend()); // warn: iterators of + // different containers + // used where the same + // container is + // expected +} + + + + +alpha.cplusplus.MisusedMovedObject +(C++) +Method calls on a moved-from object and copying a moved-from object will be +reported. + + + +struct A { + void foo() {} }; + +void f() { + A a; + A b = std::move(a); // note: 'a' became 'moved-from' here + a.foo();// warn: method call on a 'moved-from' object 'a' +} - + alpha.cplusplus.UninitializedObject (C++) -This checker reports uninitialized fields in objects created -after a constructor call. It doesn't only find direct uninitialized -fields, but rather makes a deep inspection of the object, -analyzing all of it's fields subfields.
[PATCH] D52969: [analyzer][www] Update alpha_checks.html
This revision was automatically updated to reflect the committed changes. Closed by commit rL344878: [analyzer][www] Update alpha_checks.html (authored by Szelethus, committed by ). Herald added subscribers: llvm-commits, dkrupp, donat.nagy. Changed prior to commit: https://reviews.llvm.org/D52969?vs=168597&id=170359#toc Repository: rL LLVM https://reviews.llvm.org/D52969 Files: cfe/trunk/www/analyzer/alpha_checks.html cfe/trunk/www/analyzer/available_checks.html Index: cfe/trunk/www/analyzer/available_checks.html === --- cfe/trunk/www/analyzer/available_checks.html +++ cfe/trunk/www/analyzer/available_checks.html @@ -543,8 +543,35 @@ Name, DescriptionExample + +optin.cplusplus.VirtualCall +(C++) +Check virtual member function calls during construction or +destruction. + + +class A { +public: + A() { +f(); // warn + } + virtual void f(); +}; + + +class A { +public: + ~A() { +this->f(); // warn + } + virtual void f(); +}; + + + + optin.mpi.MPI-Checker (C) Checks MPI code Index: cfe/trunk/www/analyzer/alpha_checks.html === --- cfe/trunk/www/analyzer/alpha_checks.html +++ cfe/trunk/www/analyzer/alpha_checks.html @@ -107,6 +107,7 @@ } + alpha.core.CastSize (C) @@ -276,6 +277,33 @@ +alpha.core.StackAddressAsyncEscape +(C) +Check that addresses to stack memory do not escape the function that involves +dispatch_after or dispatch_async. This checker is +a part of core.StackAddressEscape, but is +https://reviews.llvm.org/D41042>temporarily disabled until some +false positives are fixed. + + +dispatch_block_t test_block_inside_block_async_leak() { + int x = 123; + void (^inner)(void) = ^void(void) { +int y = x; +++y; + }; + void (^outer)(void) = ^void(void) { +int z = x; +++z; +inner(); + }; + return outer; // warn: address of stack-allocated block is captured by a +// returned block +} + + + + alpha.core.TestAfterDivZero (C, C++, ObjC) Check for division by variable that is later compared against 0. @@ -289,79 +317,150 @@ } + C++ Alpha Checkers Name, DescriptionExample - + + -alpha.cplusplus.VirtualCall +alpha.cplusplus.DeleteWithNonVirtualDtor (C++) -Check virtual member function calls during construction or -destruction. +Reports destructions of polymorphic objects with a non-virtual destructor in +their base class + -class A { -public: - A() { -f(); // warn - } - virtual void f(); -}; - +NonVirtual *create() { + NonVirtual *x = new NVDerived(); // note: conversion from derived to base + // happened here + return x; +} + +void sink(NonVirtual *x) { + delete x; // warn: destruction of a polymorphic object with no virtual +// destructor +} + + + + +alpha.cplusplus.InvalidatedIterator +(C++) +Check for use of invalidated iterators. + + -class A { -public: - ~A() { -this->f(); // warn - } - virtual void f(); +void bad_copy_assign_operator_list1(std::list &L1, +const std::list &L2) { + auto i0 = L1.cbegin(); + L1 = L2; + *i0; // warn: invalidated iterator accessed +} + + + + +alpha.cplusplus.IteratorRange +(C++) +Check for iterators used outside their valid ranges. + + + +void simple_bad_end(const std::vector &v) { + auto i = v.end(); + *i; // warn: iterator accessed outside of its range +} + + + + +alpha.cplusplus.MismatchedIterator +(C++) +Check for use of iterators of different containers where iterators of the same +container are expected. + + + +void bad_insert3(std::vector &v1, std::vector &v2) { + v2.insert(v1.cbegin(), v2.cbegin(), v2.cend()); // warn: container accessed + // using foreign + // iterator argument + v1.insert(v1.cbegin(), v1.cbegin(), v2.cend()); // warn: iterators of + // different containers + // used where the same + // container is + // expected + v1.insert(v1.cbegin(), v2.cbegin(), v1.cend()); // warn: iterators of + // different containers + // used where the same + // container is + // expected +} + + + + +alpha.cplusplus.MisusedMovedObject +(C++) +Method calls on a moved-from object and copying a moved-from object will be +reported. + + + +struct A { + void foo() {} }; + +void f() { + A a; + A b = std::move(a); // note: 'a' became 'moved-from' here + a.foo();
[PATCH] D51531: [analyzer][UninitializedObjectChecker] Uninit regions are only reported once
Szelethus added a comment. Herald added a subscriber: dkrupp. Ping^5 :) https://reviews.llvm.org/D51531 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D51531: [analyzer][UninitializedObjectChecker] Uninit regions are only reported once
NoQ added a comment. Ugh, i was sure i scanned through all of them, sorry! Pls let me recall what's going on>< https://reviews.llvm.org/D51531 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D48866: [clang-tidy] Add incorrect-pointer-cast checker
hgabii updated this revision to Diff 170360. hgabii added a comment. Warning messages changed. Tests updated. Comments changed based on the recommendations. Documentation refactored and reformatted. Repository: rCTE Clang Tools Extra https://reviews.llvm.org/D48866 Files: clang-tidy/misc/CMakeLists.txt clang-tidy/misc/IncorrectPointerCastCheck.cpp clang-tidy/misc/IncorrectPointerCastCheck.h clang-tidy/misc/MiscTidyModule.cpp docs/ReleaseNotes.rst docs/clang-tidy/checks/list.rst docs/clang-tidy/checks/misc-incorrect-pointer-cast.rst test/clang-tidy/misc-incorrect-pointer-cast.cpp Index: test/clang-tidy/misc-incorrect-pointer-cast.cpp === --- /dev/null +++ test/clang-tidy/misc-incorrect-pointer-cast.cpp @@ -0,0 +1,108 @@ +// RUN: %check_clang_tidy %s misc-incorrect-pointer-cast %t -- \ +// RUN: -config="{CheckOptions: [{key: misc-incorrect-pointer-cast.WarnForDifferentSignedness, value: 1}]}" -- + +struct S1 { + int a; + int b; +}; + +struct S2 { + int a; +}; + +struct S3 { + int a; + double b; +}; + +struct S4 { + int x; + double y; +}; + +struct S5 { + double y; + int x; +}; + +void initDouble(double *d) { + *d = 0.5; +} + +void castCharToSort() { + char c; + short *i = (short *)&c; + // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: cast from 'short' to 'char' may lead to access memory based on invalid memory layout; pointed to type is wider than the allocated type [misc-incorrect-pointer-cast] +} + +void castShortToInt() { + short s; + int *i = (int *)&s; + // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: cast from 'int' to 'short' may lead to access memory based on invalid memory layout; pointed to type is wider than the allocated type [misc-incorrect-pointer-cast] +} + +void castWideCharToLong() { + wchar_t wc; + long *f = (long *)&wc; + // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: cast from 'long' to 'wchar_t' may lead to access memory based on invalid memory layout; pointed to type is wider than the allocated type [misc-incorrect-pointer-cast] +} + +void castFloatToDouble() { + float f; + initDouble((double *)&f); + // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: cast from 'double' to 'float' may lead to access memory based on invalid memory layout; pointed to type is wider than the allocated type [misc-incorrect-pointer-cast] +} + +void castS3ToS1() { + struct S3 s3; + struct S1 *s1 = (struct S1 *)&s3; + // CHECK-MESSAGES: :[[@LINE-1]]:19: warning: cast from 'struct S3' to 'struct S1' may lead to access memory based on invalid memory layout; struct members are incompatible [misc-incorrect-pointer-cast] +} + +void castS4ToS5() { + struct S4 s4; + struct S5 *s5 = (struct S5 *)&s4; + // CHECK-MESSAGES: :[[@LINE-1]]:19: warning: cast from 'struct S4' to 'struct S5' may lead to access memory based on invalid memory layout; struct members are incompatible [misc-incorrect-pointer-cast] +} + +void castULongToLong() { + unsigned long ul; + long *l = (long *)&ul; + // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: cast from 'unsigned long' to 'long' may lead to access memory based on invalid memory layout; different signedness types [misc-incorrect-pointer-cast] +} + +void castIntToUInt() { + int i; + unsigned int *ui = (unsigned int *)&i; + // CHECK-MESSAGES: :[[@LINE-1]]:22: warning: cast from 'int' to 'unsigned int' may lead to access memory based on invalid memory layout; different signedness types [misc-incorrect-pointer-cast] +} + +// negatives +void castIntToFloat() { + int i; + float *f = (float *)&i; +} + +void castShortToChar() { + short s; + char *c = (char *)&s; +} + +void initInt(int *i) { + *i = 1; +} + +void castIntToInt() { + int i; + initInt(&i); +} + +void castS1ToS2() { + struct S1 s1; + struct S2 *s2 = (struct S2 *)&s1; +} + +void castS4ToS3() { + struct S4 s4; + struct S3 *s3 = (struct S3 *)&s4; +} Index: docs/clang-tidy/checks/misc-incorrect-pointer-cast.rst === --- /dev/null +++ docs/clang-tidy/checks/misc-incorrect-pointer-cast.rst @@ -0,0 +1,70 @@ +.. title:: clang-tidy - misc-incorrect-pointer-cast + +misc-incorrect-pointer-cast +=== + +Warns for cases when pointer is cast and the pointed to type is wider than the +allocated type. +For example char vs integer, long vs char etc. +Also warns for cases when the pointed to type layout is different from the +allocated type layout, like different structs, integer vs float/double, +different signedness. + +Allows pointer casts if the pointed to struct type is "part" of the allocated +type. +Which means the allocated type contains the pointed to type member by member. + +Options +--- + +.. option:: WarnForDifferentSignedness + + This option can be configured to warn when the pointed to type signedness + is different from the allocated type. + Disabled by default because this option might be noisy on some code bases. + +Examles
[PATCH] D51531: [analyzer][UninitializedObjectChecker] Uninit regions are only reported once
Szelethus added a comment. As I understood it, your objection was that we could collect already reported regions in a global set stored in the checker objects, but I suspect it's impossible to implement (very difficult to see when a pointer is dangling etc). https://reviews.llvm.org/D51531 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D51531: [analyzer][UninitializedObjectChecker] Uninit regions are only reported once
NoQ added a comment. `MemRegion`s have lifetime of `ExprEngine`, i.e. a single analysis of top-level function. You'll need to clean them up in `checkEndAnalysis()`. https://reviews.llvm.org/D51531 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r344879 - [analyzer][UninitializedObjectChecker] No longer using nonloc::LazyCompoundVal
Author: szelethus Date: Sun Oct 21 16:30:01 2018 New Revision: 344879 URL: http://llvm.org/viewvc/llvm-project?rev=344879&view=rev Log: [analyzer][UninitializedObjectChecker] No longer using nonloc::LazyCompoundVal As rightly pointed out by @NoQ, nonloc::LazyCompoundVals were only used to acquire a constructed object's region, which isn't what LazyCompoundVal was made for. Differential Revision: https://reviews.llvm.org/D51300 Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/UninitializedObject/UninitializedObjectChecker.cpp Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/UninitializedObject/UninitializedObjectChecker.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/UninitializedObject/UninitializedObjectChecker.cpp?rev=344879&r1=344878&r2=344879&view=diff == --- cfe/trunk/lib/StaticAnalyzer/Checkers/UninitializedObject/UninitializedObjectChecker.cpp (original) +++ cfe/trunk/lib/StaticAnalyzer/Checkers/UninitializedObject/UninitializedObjectChecker.cpp Sun Oct 21 16:30:01 2018 @@ -96,12 +96,11 @@ public: // Utility function declarations. -/// Returns the object that was constructed by CtorDecl, or None if that isn't -/// possible. -// TODO: Refactor this function so that it returns the constructed object's -// region. -static Optional -getObjectVal(const CXXConstructorDecl *CtorDecl, CheckerContext &Context); +/// Returns the region that was constructed by CtorDecl, or nullptr if that +/// isn't possible. +static const TypedValueRegion * +getConstructedRegion(const CXXConstructorDecl *CtorDecl, + CheckerContext &Context); /// Checks whether the object constructed by \p Ctor will be analyzed later /// (e.g. if the object is a field of another object, in which case we'd check @@ -135,11 +134,11 @@ void UninitializedObjectChecker::checkEn if (willObjectBeAnalyzedLater(CtorDecl, Context)) return; - Optional Object = getObjectVal(CtorDecl, Context); - if (!Object) + const TypedValueRegion *R = getConstructedRegion(CtorDecl, Context); + if (!R) return; - FindUninitializedFields F(Context.getState(), Object->getRegion(), Opts); + FindUninitializedFields F(Context.getState(), R, Opts); const UninitFieldMap &UninitFields = F.getUninitFields(); @@ -400,25 +399,27 @@ static void printTail(llvm::raw_ostream // Utility functions. //===--===// -static Optional -getObjectVal(const CXXConstructorDecl *CtorDecl, CheckerContext &Context) { +static const TypedValueRegion * +getConstructedRegion(const CXXConstructorDecl *CtorDecl, + CheckerContext &Context) { - Loc ThisLoc = Context.getSValBuilder().getCXXThis(CtorDecl->getParent(), + Loc ThisLoc = Context.getSValBuilder().getCXXThis(CtorDecl, Context.getStackFrame()); - // Getting the value for 'this'. - SVal This = Context.getState()->getSVal(ThisLoc); - // Getting the value for '*this'. - SVal Object = Context.getState()->getSVal(This.castAs()); + SVal ObjectV = Context.getState()->getSVal(ThisLoc); - return Object.getAs(); + auto *R = ObjectV.getAsRegion()->getAs(); + if (R && !R->getValueType()->getAsCXXRecordDecl()) +return nullptr; + + return R; } static bool willObjectBeAnalyzedLater(const CXXConstructorDecl *Ctor, CheckerContext &Context) { - Optional CurrentObject = getObjectVal(Ctor, Context); - if (!CurrentObject) + const TypedValueRegion *CurrRegion = getConstructedRegion(Ctor, Context); + if (!CurrRegion) return false; const LocationContext *LC = Context.getLocationContext(); @@ -429,14 +430,14 @@ static bool willObjectBeAnalyzedLater(co if (!OtherCtor) continue; -Optional OtherObject = -getObjectVal(OtherCtor, Context); -if (!OtherObject) +const TypedValueRegion *OtherRegion = +getConstructedRegion(OtherCtor, Context); +if (!OtherRegion) continue; -// If the CurrentObject is a subregion of OtherObject, it will be analyzed -// during the analysis of OtherObject. -if (CurrentObject->getRegion()->isSubRegionOf(OtherObject->getRegion())) +// If the CurrRegion is a subregion of OtherRegion, it will be analyzed +// during the analysis of OtherRegion. +if (CurrRegion->isSubRegionOf(OtherRegion)) return true; } ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D51300: [analyzer][UninitializedObjectChecker] No longer using nonloc::LazyCompoundVal
This revision was automatically updated to reflect the committed changes. Closed by commit rL344879: [analyzer][UninitializedObjectChecker] No longer using nonloc::LazyCompoundVal (authored by Szelethus, committed by ). Herald added subscribers: llvm-commits, dkrupp, donat.nagy. Changed prior to commit: https://reviews.llvm.org/D51300?vs=168775&id=170361#toc Repository: rL LLVM https://reviews.llvm.org/D51300 Files: cfe/trunk/lib/StaticAnalyzer/Checkers/UninitializedObject/UninitializedObjectChecker.cpp Index: cfe/trunk/lib/StaticAnalyzer/Checkers/UninitializedObject/UninitializedObjectChecker.cpp === --- cfe/trunk/lib/StaticAnalyzer/Checkers/UninitializedObject/UninitializedObjectChecker.cpp +++ cfe/trunk/lib/StaticAnalyzer/Checkers/UninitializedObject/UninitializedObjectChecker.cpp @@ -96,12 +96,11 @@ // Utility function declarations. -/// Returns the object that was constructed by CtorDecl, or None if that isn't -/// possible. -// TODO: Refactor this function so that it returns the constructed object's -// region. -static Optional -getObjectVal(const CXXConstructorDecl *CtorDecl, CheckerContext &Context); +/// Returns the region that was constructed by CtorDecl, or nullptr if that +/// isn't possible. +static const TypedValueRegion * +getConstructedRegion(const CXXConstructorDecl *CtorDecl, + CheckerContext &Context); /// Checks whether the object constructed by \p Ctor will be analyzed later /// (e.g. if the object is a field of another object, in which case we'd check @@ -135,11 +134,11 @@ if (willObjectBeAnalyzedLater(CtorDecl, Context)) return; - Optional Object = getObjectVal(CtorDecl, Context); - if (!Object) + const TypedValueRegion *R = getConstructedRegion(CtorDecl, Context); + if (!R) return; - FindUninitializedFields F(Context.getState(), Object->getRegion(), Opts); + FindUninitializedFields F(Context.getState(), R, Opts); const UninitFieldMap &UninitFields = F.getUninitFields(); @@ -400,25 +399,27 @@ // Utility functions. //===--===// -static Optional -getObjectVal(const CXXConstructorDecl *CtorDecl, CheckerContext &Context) { +static const TypedValueRegion * +getConstructedRegion(const CXXConstructorDecl *CtorDecl, + CheckerContext &Context) { - Loc ThisLoc = Context.getSValBuilder().getCXXThis(CtorDecl->getParent(), + Loc ThisLoc = Context.getSValBuilder().getCXXThis(CtorDecl, Context.getStackFrame()); - // Getting the value for 'this'. - SVal This = Context.getState()->getSVal(ThisLoc); - // Getting the value for '*this'. - SVal Object = Context.getState()->getSVal(This.castAs()); + SVal ObjectV = Context.getState()->getSVal(ThisLoc); - return Object.getAs(); + auto *R = ObjectV.getAsRegion()->getAs(); + if (R && !R->getValueType()->getAsCXXRecordDecl()) +return nullptr; + + return R; } static bool willObjectBeAnalyzedLater(const CXXConstructorDecl *Ctor, CheckerContext &Context) { - Optional CurrentObject = getObjectVal(Ctor, Context); - if (!CurrentObject) + const TypedValueRegion *CurrRegion = getConstructedRegion(Ctor, Context); + if (!CurrRegion) return false; const LocationContext *LC = Context.getLocationContext(); @@ -429,14 +430,14 @@ if (!OtherCtor) continue; -Optional OtherObject = -getObjectVal(OtherCtor, Context); -if (!OtherObject) +const TypedValueRegion *OtherRegion = +getConstructedRegion(OtherCtor, Context); +if (!OtherRegion) continue; -// If the CurrentObject is a subregion of OtherObject, it will be analyzed -// during the analysis of OtherObject. -if (CurrentObject->getRegion()->isSubRegionOf(OtherObject->getRegion())) +// If the CurrRegion is a subregion of OtherRegion, it will be analyzed +// during the analysis of OtherRegion. +if (CurrRegion->isSubRegionOf(OtherRegion)) return true; } Index: cfe/trunk/lib/StaticAnalyzer/Checkers/UninitializedObject/UninitializedObjectChecker.cpp === --- cfe/trunk/lib/StaticAnalyzer/Checkers/UninitializedObject/UninitializedObjectChecker.cpp +++ cfe/trunk/lib/StaticAnalyzer/Checkers/UninitializedObject/UninitializedObjectChecker.cpp @@ -96,12 +96,11 @@ // Utility function declarations. -/// Returns the object that was constructed by CtorDecl, or None if that isn't -/// possible. -// TODO: Refactor this function so that it returns the constructed object's -// region. -static Optional -getObjectVal(const CXXConstructorDecl *CtorDecl, CheckerContext &Context); +/// Returns the region that was constructed by CtorDecl, or nullptr if that +/// isn't possible. +static const TypedValueRegion *
[PATCH] D50250: [clang][ubsan] Implicit Conversion Sanitizer - integer sign change - clang part
lebedev.ri added a comment. @rsmith ping. Repository: rC Clang https://reviews.llvm.org/D50250 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] r344885 - ReleaseNotes: move readability-redundant-smartptr-get part down below new checks
Author: vmiklos Date: Sun Oct 21 23:36:30 2018 New Revision: 344885 URL: http://llvm.org/viewvc/llvm-project?rev=344885&view=rev Log: ReleaseNotes: move readability-redundant-smartptr-get part down below new checks Modified: clang-tools-extra/trunk/docs/ReleaseNotes.rst Modified: clang-tools-extra/trunk/docs/ReleaseNotes.rst URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/docs/ReleaseNotes.rst?rev=344885&r1=344884&r2=344885&view=diff == --- clang-tools-extra/trunk/docs/ReleaseNotes.rst (original) +++ clang-tools-extra/trunk/docs/ReleaseNotes.rst Sun Oct 21 23:36:30 2018 @@ -67,10 +67,6 @@ The improvements are... Improvements to clang-tidy -- -- The :doc:`readability-redundant-smartptr-get - ` check does not warn - about calls inside macros anymore by default. - - New :doc:`abseil-duration-division ` check. @@ -157,6 +153,10 @@ Improvements to clang-tidy ` added. +- The :doc:`readability-redundant-smartptr-get + ` check does not warn + about calls inside macros anymore by default. + Improvements to include-fixer - ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D53481: [clangd] Support passing a relative path to -compile-commands-dir
sammccall accepted this revision. sammccall added a comment. This revision is now accepted and ready to land. Thanks for the fix! Comment at: clangd/tool/ClangdMain.cpp:261 } else { -CompileCommandsDirPath = CompileCommandsDir; +// If the compile-commands-dir arg path is absolute, use it directly. If +// the path is relative, try to convert it to an absolute path first. This comment echoes the code, but doesn't say *why*. Consider replacing with `// clangd changes working directory a lot, so we need an absolute path`. Comment at: clangd/tool/ClangdMain.cpp:263 +// the path is relative, try to convert it to an absolute path first. +if (sys::path::is_absolute(CompileCommandsDir)) { + CompileCommandsDirPath = CompileCommandsDir; it's fine to call make_absolute on an absolute path, it's a no-op. You can do that here to avoid a special case. Comment at: clangd/tool/ClangdMain.cpp:267 + SmallString<128> Path(CompileCommandsDir); + std::error_code EC = sys::fs::make_absolute(Path); + if (EC) { nit: we tend to inline this as `if (std::error_code EC = sys::fs...)` Comment at: clangd/tool/ClangdMain.cpp:272 + << EC.message() << ". The argument will be ignored.\n"; +CompileCommandsDirPath = None; + } else { This is a no-op (as are the existing ones on 255 and 259...) Repository: rCTE Clang Tools Extra https://reviews.llvm.org/D53481 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits