diff --git a/.ci/generate_test_report.py b/.ci/generate_test_report.py
index ff601a0cde106..6f2137e7803bb 100644
--- a/.ci/generate_test_report.py
+++ b/.ci/generate_test_report.py
@@ -19,12 +19,13 @@ def junit_from_xml(xml):
class TestReports(unittest.TestCase):
def test_title_only(self):
- self.assertEqual(_generate_report("Foo", []), ("", "success"))
+ self.assertEqual(_generate_report("Foo", 0, []), ("", "success"))
def test_no_tests_in_testsuite(self):
self.assertEqual(
_generate_report(
"Foo",
+ 1,
[
junit_from_xml(
dedent(
@@ -45,6 +46,7 @@ def test_no_failures(self):
self.assertEqual(
_generate_report(
"Foo",
+ 0,
[
junit_from_xml(
dedent(
@@ -70,10 +72,51 @@ def test_no_failures(self):
),
)
+ def test_no_failures_build_failed(self):
+ self.assertEqual(
+ _generate_report(
+ "Foo",
+ 1,
+ [
+ junit_from_xml(
+ dedent(
+ """\
+
+
+
+
+
+ """
+ )
+ )
+ ],
+ buildkite_info={
+ "BUILDKITE_ORGANIZATION_SLUG": "organization_slug",
+ "BUILDKITE_PIPELINE_SLUG": "pipeline_slug",
+ "BUILDKITE_BUILD_NUMBER": "build_number",
+ "BUILDKITE_JOB_ID": "job_id",
+ },
+ ),
+ (
+ dedent(
+ """\
+ # Foo
+
+ * 1 test passed
+
+ All tests passed but another part of the build **failed**.
+
+ [Download](https://buildkite.com/organizations/organization_slug/pipelines/pipeline_slug/builds/build_number/jobs/job_id/download.txt) the build's log file to see the details."""
+ ),
+ "error",
+ ),
+ )
+
def test_report_single_file_single_testsuite(self):
self.assertEqual(
_generate_report(
"Foo",
+ 1,
[
junit_from_xml(
dedent(
@@ -166,6 +209,7 @@ def test_report_single_file_multiple_testsuites(self):
self.assertEqual(
_generate_report(
"ABC and DEF",
+ 1,
[
junit_from_xml(
dedent(
@@ -198,6 +242,7 @@ def test_report_multiple_files_multiple_testsuites(self):
self.assertEqual(
_generate_report(
"ABC and DEF",
+ 1,
[
junit_from_xml(
dedent(
@@ -238,6 +283,7 @@ def test_report_dont_list_failures(self):
self.assertEqual(
_generate_report(
"Foo",
+ 1,
[
junit_from_xml(
dedent(
@@ -272,6 +318,7 @@ def test_report_dont_list_failures_link_to_log(self):
self.assertEqual(
_generate_report(
"Foo",
+ 1,
[
junit_from_xml(
dedent(
@@ -312,6 +359,7 @@ def test_report_size_limit(self):
self.assertEqual(
_generate_report(
"Foo",
+ 1,
[
junit_from_xml(
dedent(
@@ -351,12 +399,18 @@ def test_report_size_limit(self):
# and output will not be.
def _generate_report(
title,
+ return_code,
junit_objects,
size_limit=1024 * 1024,
list_failures=True,
buildkite_info=None,
):
if not junit_objects:
+ # Note that we do not post an empty report, therefore we can ignore a
+ # non-zero return code in situations like this.
+ #
+ # If we were going to post a report, then yes, it would be misleading
+ # to say we succeeded when the final return code was non-zero.
return ("", "success")
failures = {}
@@ -385,7 +439,11 @@ def _generate_report(
if not tests_run:
return ("", None)
- style = "error" if tests_failed else "success"
+ style = "success"
+ # Either tests failed, or all tests passed but something failed to build.
+ if tests_failed or return_code != 0:
+ style = "error"
+
report = [f"# {title}", ""]
tests_passed = tests_run - tests_skipped - tests_failed
@@ -400,17 +458,17 @@ def plural(num_tests):
if tests_failed:
report.append(f"* {tests_failed} {plural(tests_failed)} failed")
- if not list_failures:
- if buildkite_info is not None:
- log_url = (
- "https://buildkite.com/organizations/{BUILDKITE_ORGANIZATION_SLUG}/"
- "pipelines/{BUILDKITE_PIPELINE_SLUG}/builds/{BUILDKITE_BUILD_NUMBER}/"
- "jobs/{BUILDKITE_JOB_ID}/download.txt".format(**buildkite_info)
- )
- download_text = f"[Download]({log_url})"
- else:
- download_text = "Download"
+ if buildkite_info is not None:
+ log_url = (
+ "https://buildkite.com/organizations/{BUILDKITE_ORGANIZATION_SLUG}/"
+ "pipelines/{BUILDKITE_PIPELINE_SLUG}/builds/{BUILDKITE_BUILD_NUMBER}/"
+ "jobs/{BUILDKITE_JOB_ID}/download.txt".format(**buildkite_info)
+ )
+ download_text = f"[Download]({log_url})"
+ else:
+ download_text = "Download"
+ if not list_failures:
report.extend(
[
"",
@@ -435,11 +493,23 @@ def plural(num_tests):
"",
]
)
+ elif return_code != 0:
+ # No tests failed but the build was in a failed state. Bring this to the user's
+ # attention.
+ report.extend(
+ [
+ "",
+ "All tests passed but another part of the build **failed**.",
+ "",
+ f"{download_text} the build's log file to see the details.",
+ ]
+ )
report = "\n".join(report)
if len(report.encode("utf-8")) > size_limit:
return _generate_report(
title,
+ return_code,
junit_objects,
size_limit,
list_failures=False,
@@ -449,9 +519,10 @@ def plural(num_tests):
return report, style
-def generate_report(title, junit_files, buildkite_info):
+def generate_report(title, return_code, junit_files, buildkite_info):
return _generate_report(
title,
+ return_code,
[JUnitXml.fromfile(p) for p in junit_files],
buildkite_info=buildkite_info,
)
@@ -463,6 +534,7 @@ def generate_report(title, junit_files, buildkite_info):
"title", help="Title of the test report, without Markdown formatting."
)
parser.add_argument("context", help="Annotation context to write to.")
+ parser.add_argument("return_code", help="The build's return code.", type=int)
parser.add_argument("junit_files", help="Paths to JUnit report files.", nargs="*")
args = parser.parse_args()
@@ -477,7 +549,9 @@ def generate_report(title, junit_files, buildkite_info):
if len(buildkite_info) != len(env_var_names):
buildkite_info = None
- report, style = generate_report(args.title, args.junit_files, buildkite_info)
+ report, style = generate_report(
+ args.title, args.return_code, args.junit_files, buildkite_info
+ )
if report:
p = subprocess.Popen(
diff --git a/.ci/metrics/metrics.py b/.ci/metrics/metrics.py
index 55025e50d1081..8edc00bc6bd37 100644
--- a/.ci/metrics/metrics.py
+++ b/.ci/metrics/metrics.py
@@ -12,7 +12,7 @@
"https://influx-prod-13-prod-us-east-0.grafana.net/api/v1/push/influx/write"
)
GITHUB_PROJECT = "llvm/llvm-project"
-WORKFLOWS_TO_TRACK = ["Check code formatting", "LLVM Premerge Checks"]
+WORKFLOWS_TO_TRACK = ["LLVM Premerge Checks"]
SCRAPE_INTERVAL_SECONDS = 5 * 60
@@ -80,6 +80,18 @@ def get_metrics(github_repo: github.Repository, workflows_to_track: dict[str, in
completed_at = workflow_jobs[0].completed_at
job_result = int(workflow_jobs[0].conclusion == "success")
+ if job_result:
+ # We still might want to mark the job as a failure if one of the steps
+ # failed. This is required due to use setting continue-on-error in
+ # the premerge pipeline to prevent sending emails while we are
+ # testing the infrastructure.
+ # TODO(boomanaiden154): Remove this once the premerge pipeline is no
+ # longer in a testing state and we can directly assert the workflow
+ # result.
+ for step in workflow_jobs[0].steps:
+ if step.conclusion != "success":
+ job_result = 0
+ break
queue_time = started_at - created_at
run_time = completed_at - started_at
diff --git a/.ci/monolithic-linux.sh b/.ci/monolithic-linux.sh
index 4bfebd5f75279..55741bc831046 100755
--- a/.ci/monolithic-linux.sh
+++ b/.ci/monolithic-linux.sh
@@ -29,6 +29,8 @@ if [[ -n "${CLEAR_CACHE:-}" ]]; then
fi
function at-exit {
+ retcode=$?
+
mkdir -p artifacts
ccache --print-stats > artifacts/ccache_stats.txt
@@ -37,7 +39,7 @@ function at-exit {
if command -v buildkite-agent 2>&1 >/dev/null
then
python3 "${MONOREPO_ROOT}"/.ci/generate_test_report.py ":linux: Linux x64 Test Results" \
- "linux-x64-test-results" "${BUILD_DIR}"/test-results.*.xml
+ "linux-x64-test-results" $retcode "${BUILD_DIR}"/test-results.*.xml
fi
}
trap at-exit EXIT
diff --git a/.ci/monolithic-windows.sh b/.ci/monolithic-windows.sh
index 25cdd2f419f47..68303a3ea153a 100755
--- a/.ci/monolithic-windows.sh
+++ b/.ci/monolithic-windows.sh
@@ -28,6 +28,8 @@ fi
sccache --zero-stats
function at-exit {
+ retcode=$?
+
mkdir -p artifacts
sccache --show-stats >> artifacts/sccache_stats.txt
@@ -36,7 +38,7 @@ function at-exit {
if command -v buildkite-agent 2>&1 >/dev/null
then
python "${MONOREPO_ROOT}"/.ci/generate_test_report.py ":windows: Windows x64 Test Results" \
- "windows-x64-test-results" "${BUILD_DIR}"/test-results.*.xml
+ "windows-x64-test-results" $retcode "${BUILD_DIR}"/test-results.*.xml
fi
}
trap at-exit EXIT
diff --git a/.github/workflows/spirv-tests.yml b/.github/workflows/spirv-tests.yml
index 75918e73e8973..34c77a398c150 100644
--- a/.github/workflows/spirv-tests.yml
+++ b/.github/workflows/spirv-tests.yml
@@ -26,4 +26,4 @@ jobs:
build_target: check-llvm-codegen-spirv
projects:
extra_cmake_args: '-DLLVM_TARGETS_TO_BUILD="" -DLLVM_EXPERIMENTAL_TARGETS_TO_BUILD="SPIRV" -DLLVM_INCLUDE_SPIRV_TOOLS_TESTS=ON'
- os_list: '["ubuntu-latest"]'
+ os_list: '["ubuntu-22.04"]'
diff --git a/clang-tools-extra/clang-tidy/ClangTidyCheck.cpp b/clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
index 4aa9fe228ee79..341343e90822b 100644
--- a/clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
+++ b/clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
@@ -163,9 +163,10 @@ void ClangTidyCheck::OptionsView::store(
store(Options, LocalName, Value ? StringRef("true") : StringRef("false"));
}
-std::optional ClangTidyCheck::OptionsView::getEnumInt(
- StringRef LocalName, ArrayRef Mapping, bool CheckGlobal,
- bool IgnoreCase) const {
+std::optional
+ClangTidyCheck::OptionsView::getEnumInt(StringRef LocalName,
+ ArrayRef Mapping,
+ bool CheckGlobal) const {
if (!CheckGlobal && Context->getOptionsCollector())
Context->getOptionsCollector()->insert((NamePrefix + LocalName).str());
auto Iter = CheckGlobal ? findPriorityOption(CheckOptions, NamePrefix,
@@ -178,12 +179,10 @@ std::optional ClangTidyCheck::OptionsView::getEnumInt(
StringRef Closest;
unsigned EditDistance = 3;
for (const auto &NameAndEnum : Mapping) {
- if (IgnoreCase) {
- if (Value.equals_insensitive(NameAndEnum.second))
- return NameAndEnum.first;
- } else if (Value == NameAndEnum.second) {
+ if (Value == NameAndEnum.second) {
return NameAndEnum.first;
- } else if (Value.equals_insensitive(NameAndEnum.second)) {
+ }
+ if (Value.equals_insensitive(NameAndEnum.second)) {
Closest = NameAndEnum.second;
EditDistance = 0;
continue;
diff --git a/clang-tools-extra/clang-tidy/ClangTidyCheck.h b/clang-tools-extra/clang-tidy/ClangTidyCheck.h
index 7427aa9bf48f8..037526a0bd9af 100644
--- a/clang-tools-extra/clang-tidy/ClangTidyCheck.h
+++ b/clang-tools-extra/clang-tidy/ClangTidyCheck.h
@@ -333,9 +333,9 @@ class ClangTidyCheck : public ast_matchers::MatchFinder::MatchCallback {
/// supply the mapping required to convert between ``T`` and a string.
template
std::enable_if_t, std::optional>
- get(StringRef LocalName, bool IgnoreCase = false) const {
+ get(StringRef LocalName) const {
if (std::optional ValueOr =
- getEnumInt(LocalName, typeEraseMapping(), false, IgnoreCase))
+ getEnumInt(LocalName, typeEraseMapping(), false))
return static_cast(*ValueOr);
return std::nullopt;
}
@@ -353,9 +353,9 @@ class ClangTidyCheck : public ast_matchers::MatchFinder::MatchCallback {
/// \ref clang::tidy::OptionEnumMapping must be specialized for ``T`` to
/// supply the mapping required to convert between ``T`` and a string.
template
- std::enable_if_t, T> get(StringRef LocalName, T Default,
- bool IgnoreCase = false) const {
- return get(LocalName, IgnoreCase).value_or(Default);
+ std::enable_if_t, T> get(StringRef LocalName,
+ T Default) const {
+ return get(LocalName).value_or(Default);
}
/// Read a named option from the ``Context`` and parse it as an
@@ -373,9 +373,9 @@ class ClangTidyCheck : public ast_matchers::MatchFinder::MatchCallback {
/// supply the mapping required to convert between ``T`` and a string.
template
std::enable_if_t, std::optional>
- getLocalOrGlobal(StringRef LocalName, bool IgnoreCase = false) const {
+ getLocalOrGlobal(StringRef LocalName) const {
if (std::optional ValueOr =
- getEnumInt(LocalName, typeEraseMapping(), true, IgnoreCase))
+ getEnumInt(LocalName, typeEraseMapping(), true))
return static_cast(*ValueOr);
return std::nullopt;
}
@@ -394,10 +394,9 @@ class ClangTidyCheck : public ast_matchers::MatchFinder::MatchCallback {
/// \ref clang::tidy::OptionEnumMapping must be specialized for ``T`` to
/// supply the mapping required to convert between ``T`` and a string.
template
- std::enable_if_t, T>
- getLocalOrGlobal(StringRef LocalName, T Default,
- bool IgnoreCase = false) const {
- return getLocalOrGlobal(LocalName, IgnoreCase).value_or(Default);
+ std::enable_if_t, T> getLocalOrGlobal(StringRef LocalName,
+ T Default) const {
+ return getLocalOrGlobal(LocalName).value_or(Default);
}
/// Stores an option with the check-local name \p LocalName with
@@ -454,7 +453,7 @@ class ClangTidyCheck : public ast_matchers::MatchFinder::MatchCallback {
std::optional getEnumInt(StringRef LocalName,
ArrayRef Mapping,
- bool CheckGlobal, bool IgnoreCase) const;
+ bool CheckGlobal) const;
template
std::enable_if_t, std::vector>
diff --git a/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp b/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp
index 445c7f85c900c..8bac6f161fa05 100644
--- a/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp
+++ b/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp
@@ -12,6 +12,7 @@
#include "llvm/ADT/SmallString.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Errc.h"
+#include "llvm/Support/ErrorOr.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/MemoryBufferRef.h"
#include "llvm/Support/Path.h"
@@ -298,12 +299,11 @@ ConfigOptionsProvider::getRawOptions(llvm::StringRef FileName) {
if (ConfigOptions.InheritParentConfig.value_or(false)) {
LLVM_DEBUG(llvm::dbgs()
<< "Getting options for file " << FileName << "...\n");
- assert(FS && "FS must be set.");
- llvm::SmallString<128> AbsoluteFilePath(FileName);
-
- if (!FS->makeAbsolute(AbsoluteFilePath)) {
- addRawFileOptions(AbsoluteFilePath, RawOptions);
+ llvm::ErrorOr> AbsoluteFilePath =
+ getNormalizedAbsolutePath(FileName);
+ if (AbsoluteFilePath) {
+ addRawFileOptions(AbsoluteFilePath->str(), RawOptions);
}
}
RawOptions.emplace_back(ConfigOptions,
@@ -334,36 +334,48 @@ FileOptionsBaseProvider::FileOptionsBaseProvider(
OverrideOptions(std::move(OverrideOptions)),
ConfigHandlers(std::move(ConfigHandlers)) {}
+llvm::ErrorOr>
+FileOptionsBaseProvider::getNormalizedAbsolutePath(llvm::StringRef Path) {
+ assert(FS && "FS must be set.");
+ llvm::SmallString<128> NormalizedAbsolutePath = {Path};
+ std::error_code Err = FS->makeAbsolute(NormalizedAbsolutePath);
+ if (Err)
+ return Err;
+ llvm::sys::path::remove_dots(NormalizedAbsolutePath, /*remove_dot_dot=*/true);
+ return NormalizedAbsolutePath;
+}
+
void FileOptionsBaseProvider::addRawFileOptions(
llvm::StringRef AbsolutePath, std::vector &CurOptions) {
auto CurSize = CurOptions.size();
-
// Look for a suitable configuration file in all parent directories of the
// file. Start with the immediate parent directory and move up.
- StringRef Path = llvm::sys::path::parent_path(AbsolutePath);
- for (StringRef CurrentPath = Path; !CurrentPath.empty();
- CurrentPath = llvm::sys::path::parent_path(CurrentPath)) {
- std::optional Result;
-
- auto Iter = CachedOptions.find(CurrentPath);
- if (Iter != CachedOptions.end())
- Result = Iter->second;
-
- if (!Result)
- Result = tryReadConfigFile(CurrentPath);
-
- if (Result) {
- // Store cached value for all intermediate directories.
- while (Path != CurrentPath) {
+ StringRef RootPath = llvm::sys::path::parent_path(AbsolutePath);
+ auto MemorizedConfigFile =
+ [this, &RootPath](StringRef CurrentPath) -> std::optional {
+ const auto Iter = CachedOptions.Memorized.find(CurrentPath);
+ if (Iter != CachedOptions.Memorized.end())
+ return CachedOptions.Storage[Iter->second];
+ std::optional OptionsSource = tryReadConfigFile(CurrentPath);
+ if (OptionsSource) {
+ const size_t Index = CachedOptions.Storage.size();
+ CachedOptions.Storage.emplace_back(OptionsSource.value());
+ while (RootPath != CurrentPath) {
LLVM_DEBUG(llvm::dbgs()
- << "Caching configuration for path " << Path << ".\n");
- if (!CachedOptions.count(Path))
- CachedOptions[Path] = *Result;
- Path = llvm::sys::path::parent_path(Path);
+ << "Caching configuration for path " << RootPath << ".\n");
+ CachedOptions.Memorized[RootPath] = Index;
+ RootPath = llvm::sys::path::parent_path(RootPath);
}
- CachedOptions[Path] = *Result;
-
- CurOptions.push_back(*Result);
+ CachedOptions.Memorized[CurrentPath] = Index;
+ RootPath = llvm::sys::path::parent_path(CurrentPath);
+ }
+ return OptionsSource;
+ };
+ for (StringRef CurrentPath = RootPath; !CurrentPath.empty();
+ CurrentPath = llvm::sys::path::parent_path(CurrentPath)) {
+ if (std::optional Result =
+ MemorizedConfigFile(CurrentPath)) {
+ CurOptions.emplace_back(Result.value());
if (!Result->first.InheritParentConfig.value_or(false))
break;
}
@@ -396,16 +408,15 @@ std::vector
FileOptionsProvider::getRawOptions(StringRef FileName) {
LLVM_DEBUG(llvm::dbgs() << "Getting options for file " << FileName
<< "...\n");
- assert(FS && "FS must be set.");
-
- llvm::SmallString<128> AbsoluteFilePath(FileName);
- if (FS->makeAbsolute(AbsoluteFilePath))
+ llvm::ErrorOr> AbsoluteFilePath =
+ getNormalizedAbsolutePath(FileName);
+ if (!AbsoluteFilePath)
return {};
std::vector RawOptions =
- DefaultOptionsProvider::getRawOptions(AbsoluteFilePath.str());
- addRawFileOptions(AbsoluteFilePath, RawOptions);
+ DefaultOptionsProvider::getRawOptions(AbsoluteFilePath->str());
+ addRawFileOptions(AbsoluteFilePath->str(), RawOptions);
OptionsSource CommandLineOptions(OverrideOptions,
OptionsSourceTypeCheckCommandLineOption);
diff --git a/clang-tools-extra/clang-tidy/ClangTidyOptions.h b/clang-tools-extra/clang-tidy/ClangTidyOptions.h
index 85d5a02ebbc1b..dd78c570d25d9 100644
--- a/clang-tools-extra/clang-tidy/ClangTidyOptions.h
+++ b/clang-tools-extra/clang-tidy/ClangTidyOptions.h
@@ -10,6 +10,7 @@
#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CLANGTIDYOPTIONS_H
#include "llvm/ADT/IntrusiveRefCntPtr.h"
+#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/ErrorOr.h"
@@ -237,11 +238,17 @@ class FileOptionsBaseProvider : public DefaultOptionsProvider {
void addRawFileOptions(llvm::StringRef AbsolutePath,
std::vector &CurOptions);
+ llvm::ErrorOr>
+ getNormalizedAbsolutePath(llvm::StringRef AbsolutePath);
+
/// Try to read configuration files from \p Directory using registered
/// \c ConfigHandlers.
std::optional tryReadConfigFile(llvm::StringRef Directory);
- llvm::StringMap CachedOptions;
+ struct OptionsCache {
+ llvm::StringMap Memorized;
+ llvm::SmallVector Storage;
+ } CachedOptions;
ClangTidyOptions OverrideOptions;
ConfigFileHandlers ConfigHandlers;
llvm::IntrusiveRefCntPtr FS;
diff --git a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
index b27616f3dcc65..c5f0b5b28418f 100644
--- a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
@@ -33,6 +33,7 @@
#include "InaccurateEraseCheck.h"
#include "IncDecInConditionsCheck.h"
#include "IncorrectEnableIfCheck.h"
+#include "IncorrectEnableSharedFromThisCheck.h"
#include "IncorrectRoundingsCheck.h"
#include "InfiniteLoopCheck.h"
#include "IntegerDivisionCheck.h"
@@ -144,6 +145,8 @@ class BugproneModule : public ClangTidyModule {
"bugprone-inaccurate-erase");
CheckFactories.registerCheck(
"bugprone-incorrect-enable-if");
+ CheckFactories.registerCheck(
+ "bugprone-incorrect-enable-shared-from-this");
CheckFactories.registerCheck(
"bugprone-return-const-ref-from-parameter");
CheckFactories.registerCheck(
diff --git a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
index 8bd5646c5fe05..e8309c68b7fca 100644
--- a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
@@ -27,6 +27,11 @@ add_clang_library(clangTidyBugproneModule STATIC
ForwardingReferenceOverloadCheck.cpp
ImplicitWideningOfMultiplicationResultCheck.cpp
InaccurateEraseCheck.cpp
+ IncorrectEnableIfCheck.cpp
+ IncorrectEnableSharedFromThisCheck.cpp
+ ReturnConstRefFromParameterCheck.cpp
+ SuspiciousStringviewDataUsageCheck.cpp
+ SwitchMissingDefaultCaseCheck.cpp
IncDecInConditionsCheck.cpp
IncorrectEnableIfCheck.cpp
IncorrectRoundingsCheck.cpp
diff --git a/clang-tools-extra/clang-tidy/bugprone/IncorrectEnableSharedFromThisCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/IncorrectEnableSharedFromThisCheck.cpp
new file mode 100644
index 0000000000000..425e46cf6c88c
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/bugprone/IncorrectEnableSharedFromThisCheck.cpp
@@ -0,0 +1,65 @@
+//===--- IncorrectEnableSharedFromThisCheck.cpp - clang-tidy --------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "IncorrectEnableSharedFromThisCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/DeclCXX.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::bugprone {
+
+void IncorrectEnableSharedFromThisCheck::registerMatchers(MatchFinder *Finder) {
+ const auto EnableSharedFromThis =
+ cxxRecordDecl(hasName("enable_shared_from_this"), isInStdNamespace());
+ const auto QType = hasCanonicalType(hasDeclaration(
+ cxxRecordDecl(
+ anyOf(EnableSharedFromThis.bind("enable_rec"),
+ cxxRecordDecl(hasAnyBase(cxxBaseSpecifier(
+ isPublic(), hasType(hasCanonicalType(
+ hasDeclaration(EnableSharedFromThis))))))))
+ .bind("base_rec")));
+ Finder->addMatcher(
+ cxxRecordDecl(
+ unless(isExpansionInSystemHeader()),
+ hasDirectBase(cxxBaseSpecifier(unless(isPublic()), hasType(QType))
+ .bind("base")))
+ .bind("derived"),
+ this);
+}
+
+void IncorrectEnableSharedFromThisCheck::check(
+ const MatchFinder::MatchResult &Result) {
+ const auto *BaseSpec = Result.Nodes.getNodeAs("base");
+ const auto *Base = Result.Nodes.getNodeAs("base_rec");
+ const auto *Derived = Result.Nodes.getNodeAs("derived");
+ const bool IsEnableSharedFromThisDirectBase =
+ Result.Nodes.getNodeAs("enable_rec") == Base;
+ const bool HasWrittenAccessSpecifier =
+ BaseSpec->getAccessSpecifierAsWritten() != AS_none;
+ const auto ReplacementRange = CharSourceRange(
+ SourceRange(BaseSpec->getBeginLoc()), HasWrittenAccessSpecifier);
+ const llvm::StringRef Replacement =
+ HasWrittenAccessSpecifier ? "public" : "public ";
+ const FixItHint Hint =
+ IsEnableSharedFromThisDirectBase
+ ? FixItHint::CreateReplacement(ReplacementRange, Replacement)
+ : FixItHint();
+ diag(Derived->getLocation(),
+ "%2 is not publicly inheriting from "
+ "%select{%1 which inherits from |}0'std::enable_shared_"
+ "from_this', "
+ "which will cause unintended behaviour "
+ "when using 'shared_from_this'; make the inheritance "
+ "public",
+ DiagnosticIDs::Warning)
+ << IsEnableSharedFromThisDirectBase << Base << Derived << Hint;
+}
+
+} // namespace clang::tidy::bugprone
diff --git a/clang-tools-extra/clang-tidy/bugprone/IncorrectEnableSharedFromThisCheck.h b/clang-tools-extra/clang-tidy/bugprone/IncorrectEnableSharedFromThisCheck.h
new file mode 100644
index 0000000000000..987c56059259b
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/bugprone/IncorrectEnableSharedFromThisCheck.h
@@ -0,0 +1,35 @@
+//===--- IncorrectEnableSharedFromThisCheck.h - clang-tidy ------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_INCORRECTENABLESHAREDFROMTHISCHECK_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_INCORRECTENABLESHAREDFROMTHISCHECK_H
+
+#include "../ClangTidyCheck.h"
+
+namespace clang::tidy::bugprone {
+
+/// Detect classes or structs that do not publicly inherit from
+/// ``std::enable_shared_from_this``, because unintended behavior will
+/// otherwise occur when calling ``shared_from_this``.
+///
+/// For the user-facing documentation see:
+/// http://clang.llvm.org/extra/clang-tidy/checks/bugprone/incorrect-enable-shared-from-this.html
+class IncorrectEnableSharedFromThisCheck : public ClangTidyCheck {
+public:
+ IncorrectEnableSharedFromThisCheck(StringRef Name, ClangTidyContext *Context)
+ : ClangTidyCheck(Name, Context) {}
+ void registerMatchers(ast_matchers::MatchFinder *Finder) override;
+ void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
+ bool isLanguageVersionSupported(const LangOptions &LangOpts) const override {
+ return LangOpts.CPlusPlus11;
+ }
+};
+
+} // namespace clang::tidy::bugprone
+
+#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_INCORRECTENABLESHAREDFROMTHISCHECK_H
diff --git a/clang-tools-extra/clang-tidy/bugprone/NarrowingConversionsCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/NarrowingConversionsCheck.cpp
index a950704208c73..bafcd402ca851 100644
--- a/clang-tools-extra/clang-tidy/bugprone/NarrowingConversionsCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/NarrowingConversionsCheck.cpp
@@ -38,7 +38,7 @@ AST_MATCHER(FieldDecl, hasIntBitwidth) {
assert(Node.isBitField());
const ASTContext &Ctx = Node.getASTContext();
unsigned IntBitWidth = Ctx.getIntWidth(Ctx.IntTy);
- unsigned CurrentBitWidth = Node.getBitWidthValue(Ctx);
+ unsigned CurrentBitWidth = Node.getBitWidthValue();
return IntBitWidth == CurrentBitWidth;
}
@@ -513,7 +513,9 @@ void NarrowingConversionsCheck::handleFloatingCast(const ASTContext &Context,
return;
}
const BuiltinType *FromType = getBuiltinType(Rhs);
- if (ToType->getKind() < FromType->getKind())
+ if (!llvm::APFloatBase::isRepresentableBy(
+ Context.getFloatTypeSemantics(FromType->desugar()),
+ Context.getFloatTypeSemantics(ToType->desugar())))
diagNarrowType(SourceLoc, Lhs, Rhs);
}
}
diff --git a/clang-tools-extra/clang-tidy/bugprone/TooSmallLoopVariableCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/TooSmallLoopVariableCheck.cpp
index a73d46f01d9b2..4ceeefb78ee82 100644
--- a/clang-tools-extra/clang-tidy/bugprone/TooSmallLoopVariableCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/TooSmallLoopVariableCheck.cpp
@@ -124,7 +124,7 @@ static MagnitudeBits calcMagnitudeBits(const ASTContext &Context,
unsigned SignedBits = IntExprType->isUnsignedIntegerType() ? 0U : 1U;
if (const auto *BitField = IntExpr->getSourceBitField()) {
- unsigned BitFieldWidth = BitField->getBitWidthValue(Context);
+ unsigned BitFieldWidth = BitField->getBitWidthValue();
return {BitFieldWidth - SignedBits, BitFieldWidth};
}
diff --git a/clang-tools-extra/clang-tidy/hicpp/MultiwayPathsCoveredCheck.cpp b/clang-tools-extra/clang-tidy/hicpp/MultiwayPathsCoveredCheck.cpp
index 47dafca2d03ff..7028c3958f103 100644
--- a/clang-tools-extra/clang-tidy/hicpp/MultiwayPathsCoveredCheck.cpp
+++ b/clang-tools-extra/clang-tidy/hicpp/MultiwayPathsCoveredCheck.cpp
@@ -160,7 +160,7 @@ void MultiwayPathsCoveredCheck::handleSwitchWithoutDefault(
}
if (const auto *BitfieldDecl =
Result.Nodes.getNodeAs("bitfield")) {
- return twoPow(BitfieldDecl->getBitWidthValue(*Result.Context));
+ return twoPow(BitfieldDecl->getBitWidthValue());
}
return static_cast(0);
diff --git a/clang-tools-extra/clang-tidy/misc/UseInternalLinkageCheck.cpp b/clang-tools-extra/clang-tidy/misc/UseInternalLinkageCheck.cpp
index 1e0f398a4a560..4778182944abd 100644
--- a/clang-tools-extra/clang-tidy/misc/UseInternalLinkageCheck.cpp
+++ b/clang-tools-extra/clang-tidy/misc/UseInternalLinkageCheck.cpp
@@ -125,7 +125,7 @@ void UseInternalLinkageCheck::registerMatchers(MatchFinder *Finder) {
exportDecl()))))));
Finder->addMatcher(
functionDecl(Common, hasBody(),
- unless(anyOf(cxxMethodDecl(),
+ unless(anyOf(cxxMethodDecl(), isConsteval(),
isAllocationOrDeallocationOverloadedFunction(),
isMain())))
.bind("fn"),
diff --git a/clang-tools-extra/clang-tidy/modernize/UseAutoCheck.cpp b/clang-tools-extra/clang-tidy/modernize/UseAutoCheck.cpp
index aec67808846b1..7a2d804e173ce 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseAutoCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/UseAutoCheck.cpp
@@ -342,7 +342,7 @@ static void ignoreTypeLocClasses(
Loc = Loc.getNextTypeLoc();
}
-static bool isMutliLevelPointerToTypeLocClasses(
+static bool isMultiLevelPointerToTypeLocClasses(
TypeLoc Loc,
std::initializer_list const &LocClasses) {
ignoreTypeLocClasses(Loc, {TypeLoc::Paren, TypeLoc::Qualified});
@@ -424,7 +424,7 @@ void UseAutoCheck::replaceExpr(
auto Diag = diag(Range.getBegin(), Message);
- bool ShouldReplenishVariableName = isMutliLevelPointerToTypeLocClasses(
+ bool ShouldReplenishVariableName = isMultiLevelPointerToTypeLocClasses(
TSI->getTypeLoc(), {TypeLoc::FunctionProto, TypeLoc::ConstantArray});
// Space after 'auto' to handle cases where the '*' in the pointer type is
diff --git a/clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitialization.cpp b/clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitialization.cpp
index 034894c11bf2c..dc2e8a38a3e97 100644
--- a/clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitialization.cpp
+++ b/clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitialization.cpp
@@ -104,15 +104,18 @@ AST_MATCHER_FUNCTION_P(StatementMatcher,
hasArgument(0, hasType(ReceiverType)))));
}
+AST_MATCHER(CXXMethodDecl, isStatic) { return Node.isStatic(); }
+
AST_MATCHER_FUNCTION(StatementMatcher, isConstRefReturningFunctionCall) {
- // Only allow initialization of a const reference from a free function if it
- // has no arguments. Otherwise it could return an alias to one of its
- // arguments and the arguments need to be checked for const use as well.
- return callExpr(callee(functionDecl(returns(hasCanonicalType(
- matchers::isReferenceToConst())))
- .bind(FunctionDeclId)),
- argumentCountIs(0), unless(callee(cxxMethodDecl())))
- .bind(InitFunctionCallId);
+ // Only allow initialization of a const reference from a free function or
+ // static member function if it has no arguments. Otherwise it could return
+ // an alias to one of its arguments and the arguments need to be checked
+ // for const use as well.
+ return callExpr(argumentCountIs(0),
+ callee(functionDecl(returns(hasCanonicalType(matchers::isReferenceToConst())),
+ unless(cxxMethodDecl(unless(isStatic()))))
+ .bind(FunctionDeclId)))
+ .bind(InitFunctionCallId);
}
AST_MATCHER_FUNCTION_P(StatementMatcher, initializerReturnsReferenceToConst,
@@ -232,7 +235,7 @@ UnnecessaryCopyInitialization::UnnecessaryCopyInitialization(
Options.get("ExcludedContainerTypes", ""))) {}
void UnnecessaryCopyInitialization::registerMatchers(MatchFinder *Finder) {
- auto LocalVarCopiedFrom = [this](const internal::Matcher &CopyCtorArg) {
+ auto LocalVarCopiedFrom = [this](const ast_matchers::internal::Matcher &CopyCtorArg) {
return compoundStmt(
forEachDescendant(
declStmt(
diff --git a/clang-tools-extra/clang-tidy/readability/ContainerSizeEmptyCheck.h b/clang-tools-extra/clang-tidy/readability/ContainerSizeEmptyCheck.h
index 3aa4bdc496194..e449686f77566 100644
--- a/clang-tools-extra/clang-tidy/readability/ContainerSizeEmptyCheck.h
+++ b/clang-tools-extra/clang-tidy/readability/ContainerSizeEmptyCheck.h
@@ -19,10 +19,10 @@ namespace clang::tidy::readability {
///
/// The emptiness of a container should be checked using the `empty()` method
/// instead of the `size()`/`length()` method. It shows clearer intent to use
-/// `empty()`. Furthermore some containers may implement the `empty()` method
-/// but not implement the `size()` or `length()` method. Using `empty()`
-/// whenever possible makes it easier to switch to another container in the
-/// future.
+/// `empty()`. Furthermore some containers (for example, a `std::forward_list`)
+/// may implement the `empty()` method but not implement the `size()` or
+/// `length()` method. Using `empty()` whenever possible makes it easier to
+/// switch to another container in the future.
class ContainerSizeEmptyCheck : public ClangTidyCheck {
public:
ContainerSizeEmptyCheck(StringRef Name, ClangTidyContext *Context);
diff --git a/clang-tools-extra/clang-tidy/readability/RedundantCastingCheck.cpp b/clang-tools-extra/clang-tidy/readability/RedundantCastingCheck.cpp
index 4d5adbe02f525..768540e05c759 100644
--- a/clang-tools-extra/clang-tidy/readability/RedundantCastingCheck.cpp
+++ b/clang-tools-extra/clang-tidy/readability/RedundantCastingCheck.cpp
@@ -108,6 +108,10 @@ void RedundantCastingCheck::registerMatchers(MatchFinder *Finder) {
auto BitfieldMemberExpr = memberExpr(member(fieldDecl(isBitField())));
+ const ast_matchers::internal::VariadicDynCastAllOfMatcher<
+ Stmt, CXXParenListInitExpr>
+ cxxParenListInitExpr; // NOLINT(readability-identifier-naming)
+
Finder->addMatcher(
explicitCastExpr(
unless(hasCastKind(CK_ConstructorConversion)),
@@ -117,6 +121,7 @@ void RedundantCastingCheck::registerMatchers(MatchFinder *Finder) {
hasDestinationType(qualType().bind("dstType")),
hasSourceExpression(anyOf(
expr(unless(initListExpr()), unless(BitfieldMemberExpr),
+ unless(cxxParenListInitExpr()),
hasType(qualType().bind("srcType")))
.bind("source"),
initListExpr(unless(hasInit(1, expr())),
diff --git a/clang-tools-extra/clang-tidy/readability/UseStdMinMaxCheck.cpp b/clang-tools-extra/clang-tidy/readability/UseStdMinMaxCheck.cpp
index 179173502a8d0..6f6b8a853a91e 100644
--- a/clang-tools-extra/clang-tidy/readability/UseStdMinMaxCheck.cpp
+++ b/clang-tools-extra/clang-tidy/readability/UseStdMinMaxCheck.cpp
@@ -79,6 +79,27 @@ static QualType getNonTemplateAlias(QualType QT) {
return QT;
}
+static QualType getReplacementCastType(const Expr *CondLhs, const Expr *CondRhs,
+ QualType ComparedType) {
+ QualType LhsType = CondLhs->getType();
+ QualType RhsType = CondRhs->getType();
+ QualType LhsCanonicalType =
+ LhsType.getCanonicalType().getNonReferenceType().getUnqualifiedType();
+ QualType RhsCanonicalType =
+ RhsType.getCanonicalType().getNonReferenceType().getUnqualifiedType();
+ QualType GlobalImplicitCastType;
+ if (LhsCanonicalType != RhsCanonicalType) {
+ if (llvm::isa(CondRhs)) {
+ GlobalImplicitCastType = getNonTemplateAlias(LhsType);
+ } else if (llvm::isa(CondLhs)) {
+ GlobalImplicitCastType = getNonTemplateAlias(RhsType);
+ } else {
+ GlobalImplicitCastType = getNonTemplateAlias(ComparedType);
+ }
+ }
+ return GlobalImplicitCastType;
+}
+
static std::string createReplacement(const Expr *CondLhs, const Expr *CondRhs,
const Expr *AssignLhs,
const SourceManager &Source,
@@ -92,18 +113,8 @@ static std::string createReplacement(const Expr *CondLhs, const Expr *CondRhs,
const llvm::StringRef AssignLhsStr = Lexer::getSourceText(
Source.getExpansionRange(AssignLhs->getSourceRange()), Source, LO);
- QualType GlobalImplicitCastType;
- QualType LhsType = CondLhs->getType()
- .getCanonicalType()
- .getNonReferenceType()
- .getUnqualifiedType();
- QualType RhsType = CondRhs->getType()
- .getCanonicalType()
- .getNonReferenceType()
- .getUnqualifiedType();
- if (LhsType != RhsType) {
- GlobalImplicitCastType = getNonTemplateAlias(BO->getLHS()->getType());
- }
+ QualType GlobalImplicitCastType =
+ getReplacementCastType(CondLhs, CondRhs, BO->getLHS()->getType());
return (AssignLhsStr + " = " + FunctionName +
(!GlobalImplicitCastType.isNull()
diff --git a/clang-tools-extra/clangd/Hover.cpp b/clang-tools-extra/clangd/Hover.cpp
index 298fa79e3fd0b..5e136d0e76ece 100644
--- a/clang-tools-extra/clangd/Hover.cpp
+++ b/clang-tools-extra/clangd/Hover.cpp
@@ -1018,7 +1018,7 @@ void addLayoutInfo(const NamedDecl &ND, HoverInfo &HI) {
const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Record);
HI.Offset = Layout.getFieldOffset(FD->getFieldIndex());
if (FD->isBitField())
- HI.Size = FD->getBitWidthValue(Ctx);
+ HI.Size = FD->getBitWidthValue();
else if (auto Size = Ctx.getTypeSizeInCharsIfKnown(FD->getType()))
HI.Size = FD->isZeroSize(Ctx) ? 0 : Size->getQuantity() * 8;
if (HI.Size) {
diff --git a/clang-tools-extra/docs/ReleaseNotes.rst b/clang-tools-extra/docs/ReleaseNotes.rst
index 19c59f5b32eed..3fe2f0ce01bcc 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -108,19 +108,19 @@ Improvements to clang-query
Improvements to clang-tidy
--------------------------
-- Improved :program:`clang-tidy`'s `--verify-config` flag by adding support for
- the configuration options of the `Clang Static Analyzer Checks
- `_.
-
- Improved :program:`run-clang-tidy.py` script. Fixed minor shutdown noise
happening on certain platforms when interrupting the script.
-- Improved :program:`clang-tidy` by accepting parameters file in command line.
+- Improved :program:`clang-tidy`:
-- Removed :program:`clang-tidy`'s global options for most of checks. All options
- are changed to local options except `IncludeStyle`, `StrictMode` and
- `IgnoreMacros`. Global scoped `StrictMode` and `IgnoreMacros` are deprecated
- and will be removed in further releases.
+ - add support for `--verify-config` flag to check the configuration options of
+ the `Clang Static Analyzer Checks `_.
+ - accept parameters file in command line.
+ - fix incorrect configuration file path resolving when file paths contain ``..``.
+ - remove global options for most of checks. All options are changed to local
+ options except `IncludeStyle`, `StrictMode` and `IgnoreMacros`. Global scoped
+ `StrictMode` and `IgnoreMacros` are deprecated and will be removed in further
+ releases.
.. csv-table::
:header: "Check", "Options removed from global option"
@@ -145,6 +145,13 @@ New checks
Warns about code that tries to cast between pointers by means of
``std::bit_cast`` or ``memcpy``.
+- New :doc:`bugprone-incorrect-enable-shared-from-this
+ ` check.
+
+ Detect classes or structs that do not publicly inherit from
+ ``std::enable_shared_from_this``, because unintended behavior will
+ otherwise occur when calling ``shared_from_this``.
+
- New :doc:`bugprone-nondeterministic-pointer-iteration-order
`
check.
@@ -192,7 +199,7 @@ Changes in existing checks
the offending code with ``reinterpret_cast``, to more clearly express intent.
- Improved :doc:`bugprone-dangling-handle
- ` check to treat `std::span` as a
+ ` check to treat ``std::span`` as a
handle class.
- Improved :doc:`bugprone-exception-escape
@@ -203,6 +210,11 @@ Changes in existing checks
` check by fixing
a crash when determining if an ``enable_if[_t]`` was found.
+- Improve :doc:`bugprone-narrowing-conversions
+ ` to avoid incorrect check
+ results when floating point type is not ``float``, ``double`` and
+ ``long double``.
+
- Improved :doc:`bugprone-optional-value-conversion
` to support detecting
conversion directly by ``std::make_unique`` and ``std::make_shared``.
@@ -230,7 +242,7 @@ Changes in existing checks
- Improved :doc:`bugprone-unchecked-optional-access
` to support
- `bsl::optional` and `bdlb::NullableValue` from
+ ``bsl::optional`` and ``bdlb::NullableValue`` from
_.
- Improved :doc:`bugprone-unhandled-self-assignment
@@ -286,13 +298,13 @@ Changes in existing checks
- Improved :doc:`misc-use-internal-linkage
` check to insert ``static``
- keyword before type qualifiers such as ``const`` and ``volatile`` and fix
- false positives for function declaration without body and fix false positives
- for C++20 export declarations and fix false positives for global scoped
+ keyword before type qualifiers such as ``const`` and ``volatile``. Also, fix
+ false positives for function declaration without body, C++20 consteval
+ functions, C++20 export declarations, and global scoped
overloaded ``operator new`` and ``operator delete``.
- Improved :doc:`modernize-avoid-c-arrays
- ` check to suggest using
+ ` check to suggest using
``std::span`` as a replacement for parameters of incomplete C array type in
C++20 and ``std::array`` or ``std::vector`` before C++20.
@@ -339,6 +351,10 @@ Changes in existing checks
` check to fix a crash when
an argument type is declared but not defined.
+- Improved :doc:`performance-unnecessary-copy-initialization`
+ check
+ to consider static member functions the same way as free functions.
+
- Improved :doc:`readability-container-contains
` check to let it work on
any class that has a ``contains`` method. Fix some false negatives in the
@@ -360,9 +376,18 @@ Changes in existing checks
case of the literal suffix in fixes and fixing false positive for implicit
conversion of comparison result in C23.
+- Improved :doc:`readability-redundant-casting
+ ` check
+ by addressing a false positive in aggregate initialization through
+ parenthesized list.
+
- Improved :doc:`readability-redundant-smartptr-get
` check to
- remove `->`, when redundant `get()` is removed.
+ remove ``->``, when redundant ``get()`` is removed.
+
+- Improved :doc:`readability-use-std-min-max
+ ` check to use correct template
+ type in ``std::min`` and ``std::max`` when operand is integer literal.
Removed checks
^^^^^^^^^^^^^^
diff --git a/clang-tools-extra/docs/clang-tidy/checks/bugprone/incorrect-enable-shared-from-this.rst b/clang-tools-extra/docs/clang-tidy/checks/bugprone/incorrect-enable-shared-from-this.rst
new file mode 100644
index 0000000000000..cc9e7be70f6ea
--- /dev/null
+++ b/clang-tools-extra/docs/clang-tidy/checks/bugprone/incorrect-enable-shared-from-this.rst
@@ -0,0 +1,34 @@
+.. title:: clang-tidy - bugprone-incorrect-enable-shared-from-this
+
+bugprone-incorrect-enable-shared-from-this
+==========================================
+
+Detect classes or structs that do not publicly inherit from
+``std::enable_shared_from_this``, because unintended behavior will
+otherwise occur when calling ``shared_from_this``.
+
+Consider the following code:
+
+.. code-block:: c++
+
+ #include
+
+ // private inheritance
+ class BadExample : std::enable_shared_from_this {
+
+ // ``shared_from_this``` unintended behaviour
+ // `libstdc++` implementation returns uninitialized ``weak_ptr``
+ public:
+ BadExample* foo() { return shared_from_this().get(); }
+ void bar() { return; }
+ };
+
+ void using_not_public() {
+ auto bad_example = std::make_shared();
+ auto* b_ex = bad_example->foo();
+ b_ex->bar();
+ }
+
+Using `libstdc++` implementation, ``shared_from_this`` will throw
+``std::bad_weak_ptr``. When ``using_not_public()`` is called, this code will
+crash without exception handling.
diff --git a/clang-tools-extra/docs/clang-tidy/checks/list.rst b/clang-tools-extra/docs/clang-tidy/checks/list.rst
index e8f9b4e829634..7b9b905ef7671 100644
--- a/clang-tools-extra/docs/clang-tidy/checks/list.rst
+++ b/clang-tools-extra/docs/clang-tidy/checks/list.rst
@@ -101,6 +101,7 @@ Clang-Tidy Checks
:doc:`bugprone-inaccurate-erase `, "Yes"
:doc:`bugprone-inc-dec-in-conditions `,
:doc:`bugprone-incorrect-enable-if `, "Yes"
+ :doc:`bugprone-incorrect-enable-shared-from-this `, "Yes"
:doc:`bugprone-incorrect-roundings `,
:doc:`bugprone-infinite-loop `,
:doc:`bugprone-integer-division `,
diff --git a/clang-tools-extra/docs/clang-tidy/checks/readability/container-size-empty.rst b/clang-tools-extra/docs/clang-tidy/checks/readability/container-size-empty.rst
index 6a007f69767ab..43ad74f60dbe5 100644
--- a/clang-tools-extra/docs/clang-tidy/checks/readability/container-size-empty.rst
+++ b/clang-tools-extra/docs/clang-tidy/checks/readability/container-size-empty.rst
@@ -9,9 +9,10 @@ with a call to ``empty()``.
The emptiness of a container should be checked using the ``empty()`` method
instead of the ``size()``/``length()`` method. It shows clearer intent to use
-``empty()``. Furthermore some containers may implement the ``empty()`` method
-but not implement the ``size()`` or ``length()`` method. Using ``empty()``
-whenever possible makes it easier to switch to another container in the future.
+``empty()``. Furthermore some containers (for example, a ``std::forward_list``)
+may implement the ``empty()`` method but not implement the ``size()`` or
+``length()`` method. Using ``empty()`` whenever possible makes it easier to
+switch to another container in the future.
The check issues warning if a container has ``empty()`` and ``size()`` or
``length()`` methods matching following signatures:
diff --git a/clang-tools-extra/test/clang-tidy/checkers/bugprone/incorrect-enable-shared-from-this.cpp b/clang-tools-extra/test/clang-tidy/checkers/bugprone/incorrect-enable-shared-from-this.cpp
new file mode 100644
index 0000000000000..d9048ef359281
--- /dev/null
+++ b/clang-tools-extra/test/clang-tidy/checkers/bugprone/incorrect-enable-shared-from-this.cpp
@@ -0,0 +1,180 @@
+// RUN: %check_clang_tidy -std=c++11-or-later %s bugprone-incorrect-enable-shared-from-this %t
+
+// NOLINTBEGIN
+namespace std {
+ template class enable_shared_from_this {};
+} //namespace std
+// NOLINTEND
+
+class BadClassExample : std::enable_shared_from_this {};
+// CHECK-MESSAGES: :[[@LINE-1]]:7: warning: 'BadClassExample' is not publicly inheriting from 'std::enable_shared_from_this', which will cause unintended behaviour when using 'shared_from_this'; make the inheritance public [bugprone-incorrect-enable-shared-from-this]
+// CHECK-FIXES: public std::enable_shared_from_this
+
+class BadClass2Example : private std::enable_shared_from_this {};
+// CHECK-MESSAGES: :[[@LINE-1]]:7: warning: 'BadClass2Example' is not publicly inheriting from 'std::enable_shared_from_this', which will cause unintended behaviour when using 'shared_from_this'; make the inheritance public [bugprone-incorrect-enable-shared-from-this]
+// CHECK-FIXES: public std::enable_shared_from_this
+
+struct BadStructExample : private std::enable_shared_from_this {};
+// CHECK-MESSAGES: :[[@LINE-1]]:8: warning: 'BadStructExample' is not publicly inheriting from 'std::enable_shared_from_this', which will cause unintended behaviour when using 'shared_from_this'; make the inheritance public [bugprone-incorrect-enable-shared-from-this]
+// CHECK-FIXES: public std::enable_shared_from_this
+
+class GoodClassExample : public std::enable_shared_from_this {};
+
+struct GoodStructExample : public std::enable_shared_from_this {};
+
+struct GoodStruct2Example : std::enable_shared_from_this {};
+
+class dummy_class1 {};
+class dummy_class2 {};
+
+class BadMultiClassExample : std::enable_shared_from_this, dummy_class1 {};
+// CHECK-MESSAGES: :[[@LINE-1]]:7: warning: 'BadMultiClassExample' is not publicly inheriting from 'std::enable_shared_from_this', which will cause unintended behaviour when using 'shared_from_this'; make the inheritance public [bugprone-incorrect-enable-shared-from-this]
+// CHECK-FIXES: public std::enable_shared_from_this, dummy_class1
+
+class BadMultiClass2Example : dummy_class1, std::enable_shared_from_this, dummy_class2 {};
+// CHECK-MESSAGES: :[[@LINE-1]]:7: warning: 'BadMultiClass2Example' is not publicly inheriting from 'std::enable_shared_from_this', which will cause unintended behaviour when using 'shared_from_this'; make the inheritance public [bugprone-incorrect-enable-shared-from-this]
+// CHECK-FIXES: dummy_class1, public std::enable_shared_from_this, dummy_class2
+
+class BadMultiClass3Example : dummy_class1, dummy_class2, std::enable_shared_from_this {};
+// CHECK-MESSAGES: :[[@LINE-1]]:7: warning: 'BadMultiClass3Example' is not publicly inheriting from 'std::enable_shared_from_this', which will cause unintended behaviour when using 'shared_from_this'; make the inheritance public [bugprone-incorrect-enable-shared-from-this]
+// CHECK-FIXES: dummy_class1, dummy_class2, public std::enable_shared_from_this
+
+class ClassBase : public std::enable_shared_from_this {};
+class PrivateInheritClassBase : private ClassBase {};
+// CHECK-MESSAGES: :[[@LINE-1]]:7: warning: 'PrivateInheritClassBase' is not publicly inheriting from 'ClassBase' which inherits from 'std::enable_shared_from_this', which will cause unintended behaviour when using 'shared_from_this'; make the inheritance public [bugprone-incorrect-enable-shared-from-this]
+
+class DefaultInheritClassBase : ClassBase {};
+// CHECK-MESSAGES: :[[@LINE-1]]:7: warning: 'DefaultInheritClassBase' is not publicly inheriting from 'ClassBase' which inherits from 'std::enable_shared_from_this', which will cause unintended behaviour when using 'shared_from_this'; make the inheritance public [bugprone-incorrect-enable-shared-from-this]
+
+class PublicInheritClassBase : public ClassBase {};
+
+struct StructBase : public std::enable_shared_from_this {};
+struct PrivateInheritStructBase : private StructBase {};
+// CHECK-MESSAGES: :[[@LINE-1]]:8: warning: 'PrivateInheritStructBase' is not publicly inheriting from 'StructBase' which inherits from 'std::enable_shared_from_this', which will cause unintended behaviour when using 'shared_from_this'; make the inheritance public [bugprone-incorrect-enable-shared-from-this]
+
+struct DefaultInheritStructBase : StructBase {};
+
+struct PublicInheritStructBase : StructBase {};
+
+//alias the template itself
+template using esft_template = std::enable_shared_from_this;
+
+class PrivateAliasTemplateClassBase : private esft_template {};
+// CHECK-MESSAGES: :[[@LINE-1]]:7: warning: 'PrivateAliasTemplateClassBase' is not publicly inheriting from 'std::enable_shared_from_this', which will cause unintended behaviour when using 'shared_from_this'; make the inheritance public [bugprone-incorrect-enable-shared-from-this]
+// CHECK-FIXES: class PrivateAliasTemplateClassBase : public esft_template {};
+
+class DefaultAliasTemplateClassBase : esft_template {};
+// CHECK-MESSAGES: :[[@LINE-1]]:7: warning: 'DefaultAliasTemplateClassBase' is not publicly inheriting from 'std::enable_shared_from_this', which will cause unintended behaviour when using 'shared_from_this'; make the inheritance public [bugprone-incorrect-enable-shared-from-this]
+// CHECK-FIXES: class DefaultAliasTemplateClassBase : public esft_template {};
+
+class PublicAliasTemplateClassBase : public esft_template {};
+
+struct PrivateAliasTemplateStructBase : private esft_template {};
+// CHECK-MESSAGES: :[[@LINE-1]]:8: warning: 'PrivateAliasTemplateStructBase' is not publicly inheriting from 'std::enable_shared_from_this', which will cause unintended behaviour when using 'shared_from_this'; make the inheritance public [bugprone-incorrect-enable-shared-from-this]
+// CHECK-FIXES: struct PrivateAliasTemplateStructBase : public esft_template {};
+
+struct DefaultAliasTemplateStructBase : esft_template {};
+
+struct PublicAliasTemplateStructBase : public esft_template {};
+
+//alias with specific instance
+using esft = std::enable_shared_from_this;
+class PrivateAliasClassBase : private esft {};
+// CHECK-MESSAGES: :[[@LINE-1]]:7: warning: 'PrivateAliasClassBase' is not publicly inheriting from 'std::enable_shared_from_this', which will cause unintended behaviour when using 'shared_from_this'; make the inheritance public [bugprone-incorrect-enable-shared-from-this]
+// CHECK-FIXES: class PrivateAliasClassBase : public esft {};
+
+class DefaultAliasClassBase : esft {};
+// CHECK-MESSAGES: :[[@LINE-1]]:7: warning: 'DefaultAliasClassBase' is not publicly inheriting from 'std::enable_shared_from_this', which will cause unintended behaviour when using 'shared_from_this'; make the inheritance public [bugprone-incorrect-enable-shared-from-this]
+// CHECK-FIXES: class DefaultAliasClassBase : public esft {};
+
+class PublicAliasClassBase : public esft {};
+
+struct PrivateAliasStructBase : private esft {};
+// CHECK-MESSAGES: :[[@LINE-1]]:8: warning: 'PrivateAliasStructBase' is not publicly inheriting from 'std::enable_shared_from_this', which will cause unintended behaviour when using 'shared_from_this'; make the inheritance public [bugprone-incorrect-enable-shared-from-this]
+// CHECK-FIXES: struct PrivateAliasStructBase : public esft {};
+
+struct DefaultAliasStructBase : esft {};
+
+struct PublicAliasStructBase : public esft {};
+
+//we can only typedef a specific instance of the template
+typedef std::enable_shared_from_this EnableSharedFromThis;
+class PrivateTypedefClassBase : private EnableSharedFromThis {};
+// CHECK-MESSAGES: :[[@LINE-1]]:7: warning: 'PrivateTypedefClassBase' is not publicly inheriting from 'std::enable_shared_from_this', which will cause unintended behaviour when using 'shared_from_this'; make the inheritance public [bugprone-incorrect-enable-shared-from-this]
+// CHECK-FIXES: class PrivateTypedefClassBase : public EnableSharedFromThis {};
+
+class DefaultTypedefClassBase : EnableSharedFromThis {};
+// CHECK-MESSAGES: :[[@LINE-1]]:7: warning: 'DefaultTypedefClassBase' is not publicly inheriting from 'std::enable_shared_from_this', which will cause unintended behaviour when using 'shared_from_this'; make the inheritance public [bugprone-incorrect-enable-shared-from-this]
+// CHECK-FIXES: class DefaultTypedefClassBase : public EnableSharedFromThis {};
+
+class PublicTypedefClassBase : public EnableSharedFromThis {};
+
+struct PrivateTypedefStructBase : private EnableSharedFromThis {};
+// CHECK-MESSAGES: :[[@LINE-1]]:8: warning: 'PrivateTypedefStructBase' is not publicly inheriting from 'std::enable_shared_from_this', which will cause unintended behaviour when using 'shared_from_this'; make the inheritance public [bugprone-incorrect-enable-shared-from-this]
+// CHECK-FIXES: struct PrivateTypedefStructBase : public EnableSharedFromThis {};
+
+struct DefaultTypedefStructBase : EnableSharedFromThis {};
+
+struct PublicTypedefStructBase : public EnableSharedFromThis {};
+
+#define PRIVATE_ESFT_CLASS(ClassName) \
+ class ClassName: private std::enable_shared_from_this { \
+ };
+
+PRIVATE_ESFT_CLASS(PrivateEsftClass);
+// CHECK-MESSAGES: :[[@LINE-1]]:20: warning: 'PrivateEsftClass' is not publicly inheriting from 'std::enable_shared_from_this', which will cause unintended behaviour when using 'shared_from_this'; make the inheritance public [bugprone-incorrect-enable-shared-from-this]
+
+#define DEFAULT_ESFT_CLASS(ClassName) \
+ class ClassName: std::enable_shared_from_this { \
+ };
+
+DEFAULT_ESFT_CLASS(DefaultEsftClass);
+// CHECK-MESSAGES: :[[@LINE-1]]:20: warning: 'DefaultEsftClass' is not publicly inheriting from 'std::enable_shared_from_this', which will cause unintended behaviour when using 'shared_from_this'; make the inheritance public [bugprone-incorrect-enable-shared-from-this]
+
+#define PUBLIC_ESFT_CLASS(ClassName) \
+ class ClassName: public std::enable_shared_from_this { \
+ };
+
+PUBLIC_ESFT_CLASS(PublicEsftClass);
+
+#define PRIVATE_ESFT_STRUCT(StructName) \
+ struct StructName: private std::enable_shared_from_this { \
+ };
+
+PRIVATE_ESFT_STRUCT(PrivateEsftStruct);
+// CHECK-MESSAGES: :[[@LINE-1]]:21: warning: 'PrivateEsftStruct' is not publicly inheriting from 'std::enable_shared_from_this', which will cause unintended behaviour when using 'shared_from_this'; make the inheritance public [bugprone-incorrect-enable-shared-from-this]
+
+#define DEFAULT_ESFT_STRUCT(StructName) \
+ struct StructName: std::enable_shared_from_this { \
+ };
+
+DEFAULT_ESFT_STRUCT(DefaultEsftStruct);
+
+#define PUBLIC_ESFT_STRUCT(StructName) \
+ struct StructName: std::enable_shared_from_this { \
+ };
+
+PUBLIC_ESFT_STRUCT(PublicEsftStruct);
+
+struct A : std::enable_shared_from_this {};
+#define MACRO_A A
+
+class B : MACRO_A {};
+// CHECK-MESSAGES: :[[@LINE-1]]:7: warning: 'B' is not publicly inheriting from 'A' which inherits from 'std::enable_shared_from_this', which will cause unintended behaviour when using 'shared_from_this'; make the inheritance public [bugprone-incorrect-enable-shared-from-this]
+
+class C : private MACRO_A {};
+// CHECK-MESSAGES: :[[@LINE-1]]:7: warning: 'C' is not publicly inheriting from 'A' which inherits from 'std::enable_shared_from_this', which will cause unintended behaviour when using 'shared_from_this'; make the inheritance public [bugprone-incorrect-enable-shared-from-this]
+
+class D : public MACRO_A {};
+
+#define MACRO_PARAM(CLASS) std::enable_shared_from_this
+
+class E : MACRO_PARAM(E) {};
+// CHECK-MESSAGES: :[[@LINE-1]]:7: warning: 'E' is not publicly inheriting from 'std::enable_shared_from_this', which will cause unintended behaviour when using 'shared_from_this'; make the inheritance public [bugprone-incorrect-enable-shared-from-this]
+// CHECK-FIXES: class E : public MACRO_PARAM(E) {};
+
+class F : private MACRO_PARAM(F) {};
+// CHECK-MESSAGES: :[[@LINE-1]]:7: warning: 'F' is not publicly inheriting from 'std::enable_shared_from_this', which will cause unintended behaviour when using 'shared_from_this'; make the inheritance public [bugprone-incorrect-enable-shared-from-this]
+// CHECK-FIXES: class F : public MACRO_PARAM(F) {};
+
+class G : public MACRO_PARAM(G) {};
diff --git a/clang-tools-extra/test/clang-tidy/checkers/bugprone/narrowing-conversions-narrowingfloatingpoint-option.cpp b/clang-tools-extra/test/clang-tidy/checkers/bugprone/narrowing-conversions-narrowingfloatingpoint-option.cpp
index 9ded2f0923f4e..180b789e45bb3 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/bugprone/narrowing-conversions-narrowingfloatingpoint-option.cpp
+++ b/clang-tools-extra/test/clang-tidy/checkers/bugprone/narrowing-conversions-narrowingfloatingpoint-option.cpp
@@ -36,6 +36,15 @@ void narrow_double_to_float_not_ok(double d) {
f = narrow_double_to_float_return();
}
+float narrow_float16_to_float_return(_Float16 f) {
+ return f;
+}
+
+_Float16 narrow_float_to_float16_return(float f) {
+ return f;
+ // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: narrowing conversion from 'float' to '_Float16' [bugprone-narrowing-conversions]
+}
+
void narrow_fp_constants() {
float f;
f = 0.5; // [dcl.init.list] 7.2 : in-range fp constant to narrower float is not a narrowing.
diff --git a/clang-tools-extra/test/clang-tidy/checkers/misc/use-internal-linkage-consteval.cpp b/clang-tools-extra/test/clang-tidy/checkers/misc/use-internal-linkage-consteval.cpp
new file mode 100644
index 0000000000000..62c9818e07c4f
--- /dev/null
+++ b/clang-tools-extra/test/clang-tidy/checkers/misc/use-internal-linkage-consteval.cpp
@@ -0,0 +1,7 @@
+// RUN: %check_clang_tidy -std=c++20 %s misc-use-internal-linkage %t -- -- -I%S/Inputs/use-internal-linkage
+
+consteval void gh122096() {}
+
+constexpr void cxf() {}
+// CHECK-MESSAGES: :[[@LINE-1]]:16: warning: function 'cxf'
+// CHECK-FIXES: static constexpr void cxf() {}
diff --git a/clang-tools-extra/test/clang-tidy/checkers/performance/unnecessary-copy-initialization.cpp b/clang-tools-extra/test/clang-tidy/checkers/performance/unnecessary-copy-initialization.cpp
index d02bb98cf583c..b5325776f54c6 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/performance/unnecessary-copy-initialization.cpp
+++ b/clang-tools-extra/test/clang-tidy/checkers/performance/unnecessary-copy-initialization.cpp
@@ -28,6 +28,8 @@ struct ExpensiveToCopyType {
template
const A &templatedAccessor() const;
operator int() const; // Implicit conversion to int.
+
+ static const ExpensiveToCopyType &instance();
};
template
@@ -100,6 +102,28 @@ void PositiveFunctionCall() {
VarCopyConstructed.constMethod();
}
+void PositiveStaticMethodCall() {
+ const auto AutoAssigned = ExpensiveToCopyType::instance();
+ // CHECK-MESSAGES: [[@LINE-1]]:14: warning: the const qualified variable 'AutoAssigned' is copy-constructed from a const reference; consider making it a const reference [performance-unnecessary-copy-initialization]
+ // CHECK-FIXES: const auto& AutoAssigned = ExpensiveToCopyType::instance();
+ AutoAssigned.constMethod();
+
+ const auto AutoCopyConstructed(ExpensiveToCopyType::instance());
+ // CHECK-MESSAGES: [[@LINE-1]]:14: warning: the const qualified variable 'AutoCopyConstructed'
+ // CHECK-FIXES: const auto& AutoCopyConstructed(ExpensiveToCopyType::instance());
+ AutoCopyConstructed.constMethod();
+
+ const ExpensiveToCopyType VarAssigned = ExpensiveToCopyType::instance();
+ // CHECK-MESSAGES: [[@LINE-1]]:29: warning: the const qualified variable 'VarAssigned'
+ // CHECK-FIXES: const ExpensiveToCopyType& VarAssigned = ExpensiveToCopyType::instance();
+ VarAssigned.constMethod();
+
+ const ExpensiveToCopyType VarCopyConstructed(ExpensiveToCopyType::instance());
+ // CHECK-MESSAGES: [[@LINE-1]]:29: warning: the const qualified variable 'VarCopyConstructed'
+ // CHECK-FIXES: const ExpensiveToCopyType& VarCopyConstructed(ExpensiveToCopyType::instance());
+ VarCopyConstructed.constMethod();
+}
+
void PositiveMethodCallConstReferenceParam(const ExpensiveToCopyType &Obj) {
const auto AutoAssigned = Obj.reference();
// CHECK-MESSAGES: [[@LINE-1]]:14: warning: the const qualified variable 'AutoAssigned'
diff --git a/clang-tools-extra/test/clang-tidy/checkers/readability/redundant-casting.cpp b/clang-tools-extra/test/clang-tidy/checkers/readability/redundant-casting.cpp
index 30cac6bd5cca0..9c3c90bfaf459 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/readability/redundant-casting.cpp
+++ b/clang-tools-extra/test/clang-tidy/checkers/readability/redundant-casting.cpp
@@ -1,10 +1,18 @@
-// RUN: %check_clang_tidy -std=c++11-or-later %s readability-redundant-casting %t -- -- -fno-delayed-template-parsing
-// RUN: %check_clang_tidy -std=c++11-or-later -check-suffix=,MACROS %s readability-redundant-casting %t -- \
+// RUN: %check_clang_tidy -std=c++11,c++14,c++17 %s readability-redundant-casting %t -- -- -fno-delayed-template-parsing
+// RUN: %check_clang_tidy -std=c++11,c++14,c++17 -check-suffix=,MACROS %s readability-redundant-casting %t -- \
// RUN: -config='{CheckOptions: { readability-redundant-casting.IgnoreMacros: false }}' \
// RUN: -- -fno-delayed-template-parsing
-// RUN: %check_clang_tidy -std=c++11-or-later -check-suffix=,ALIASES %s readability-redundant-casting %t -- \
+// RUN: %check_clang_tidy -std=c++11,c++14,c++17 -check-suffix=,ALIASES %s readability-redundant-casting %t -- \
// RUN: -config='{CheckOptions: { readability-redundant-casting.IgnoreTypeAliases: true }}' \
// RUN: -- -fno-delayed-template-parsing
+// RUN: %check_clang_tidy -std=c++20 %s readability-redundant-casting %t -- \
+// RUN: -- -fno-delayed-template-parsing -D CXX_20=1
+// RUN: %check_clang_tidy -std=c++20 -check-suffix=,MACROS %s readability-redundant-casting %t -- \
+// RUN: -config='{CheckOptions: { readability-redundant-casting.IgnoreMacros: false }}' \
+// RUN: -- -fno-delayed-template-parsing -D CXX_20=1
+// RUN: %check_clang_tidy -std=c++20 -check-suffix=,ALIASES %s readability-redundant-casting %t -- \
+// RUN: -config='{CheckOptions: { readability-redundant-casting.IgnoreTypeAliases: true }}' \
+// RUN: -- -fno-delayed-template-parsing -D CXX_20=1
struct A {};
struct B : A {};
@@ -57,6 +65,12 @@ void testDiffrentTypesCast(B& value) {
A& a7 = static_cast(value);
}
+#ifdef CXX_20
+void testParenListInitExpr(A value) {
+ B b = static_cast(value);
+}
+#endif
+
void testCastingWithAuto() {
auto a = getA();
A& a8 = static_cast(a);
diff --git a/clang-tools-extra/test/clang-tidy/checkers/readability/use-std-min-max.cpp b/clang-tools-extra/test/clang-tidy/checkers/readability/use-std-min-max.cpp
index 9c0e2eabda348..35ade8a7c6d37 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/readability/use-std-min-max.cpp
+++ b/clang-tools-extra/test/clang-tidy/checkers/readability/use-std-min-max.cpp
@@ -252,3 +252,24 @@ void testVectorSizeType() {
if (value < v.size())
value = v.size();
}
+
+namespace gh121676 {
+
+void useLeft() {
+ using U16 = unsigned short;
+ U16 I = 0;
+ // CHECK-MESSAGES: :[[@LINE+2]]:3: warning: use `std::max` instead of `<` [readability-use-std-min-max]
+ // CHECK-FIXES: I = std::max(I, 16U);
+ if (I < 16U)
+ I = 16U;
+}
+void useRight() {
+ using U16 = unsigned short;
+ U16 I = 0;
+ // CHECK-MESSAGES: :[[@LINE+2]]:3: warning: use `std::min` instead of `<` [readability-use-std-min-max]
+ // CHECK-FIXES: I = std::min(16U, I);
+ if (16U < I)
+ I = 16U;
+}
+
+} // namespace gh121676
diff --git a/clang-tools-extra/test/clang-tidy/infrastructure/Inputs/normalized-path/code.cpp b/clang-tools-extra/test/clang-tidy/infrastructure/Inputs/normalized-path/code.cpp
new file mode 100644
index 0000000000000..e69de29bb2d1d
diff --git a/clang-tools-extra/test/clang-tidy/infrastructure/Inputs/normalized-path/error-config/.clang-tidy b/clang-tools-extra/test/clang-tidy/infrastructure/Inputs/normalized-path/error-config/.clang-tidy
new file mode 100644
index 0000000000000..83bc4d519722b
--- /dev/null
+++ b/clang-tools-extra/test/clang-tidy/infrastructure/Inputs/normalized-path/error-config/.clang-tidy
@@ -0,0 +1 @@
+InvalidYamlFormat
diff --git a/clang-tools-extra/test/clang-tidy/infrastructure/normalized-path.test b/clang-tools-extra/test/clang-tidy/infrastructure/normalized-path.test
new file mode 100644
index 0000000000000..d14ad43bb8b13
--- /dev/null
+++ b/clang-tools-extra/test/clang-tidy/infrastructure/normalized-path.test
@@ -0,0 +1,3 @@
+// RUN: clang-tidy %S/Inputs/normalized-path/error-config/../code.cpp --verify-config 2>&1 | FileCheck %s
+
+// CHECK-NOT: Error parsing
diff --git a/clang-tools-extra/unittests/clang-tidy/ClangTidyOptionsTest.cpp b/clang-tools-extra/unittests/clang-tidy/ClangTidyOptionsTest.cpp
index af4f66ae3c54f..aaec0e6b50bbf 100644
--- a/clang-tools-extra/unittests/clang-tidy/ClangTidyOptionsTest.cpp
+++ b/clang-tools-extra/unittests/clang-tidy/ClangTidyOptionsTest.cpp
@@ -417,13 +417,6 @@ TEST(ValidConfiguration, ValidEnumOptions) {
CHECK_VAL(TestCheck.getIntLocal("Valid"), Colours::Red);
CHECK_VAL(TestCheck.getIntGlobal("GlobalValid"), Colours::Violet);
- CHECK_VAL(
- TestCheck.getIntLocal("ValidWrongCase", /*IgnoreCase*/ true),
- Colours::Red);
- CHECK_VAL(TestCheck.getIntGlobal("GlobalValidWrongCase",
- /*IgnoreCase*/ true),
- Colours::Violet);
-
EXPECT_FALSE(TestCheck.getIntLocal("ValidWrongCase").has_value());
EXPECT_FALSE(TestCheck.getIntLocal("NearMiss").has_value());
EXPECT_FALSE(TestCheck.getIntGlobal("GlobalInvalid").has_value());
diff --git a/clang/bindings/python/clang/cindex.py b/clang/bindings/python/clang/cindex.py
index 7caf0bbfd722a..710259de855f9 100644
--- a/clang/bindings/python/clang/cindex.py
+++ b/clang/bindings/python/clang/cindex.py
@@ -2701,6 +2701,10 @@ def spelling(self):
"""Retrieve the spelling of this Type."""
return _CXString.from_result(conf.lib.clang_getTypeSpelling(self))
+ def pretty_printed(self, policy):
+ """Pretty-prints this Type with the given PrintingPolicy"""
+ return _CXString.from_result(conf.lib.clang_getTypePrettyPrinted(self, policy))
+
def __eq__(self, other):
if type(other) != type(self):
return False
@@ -3955,6 +3959,7 @@ def set_property(self, property, value):
("clang_getTypedefDeclUnderlyingType", [Cursor], Type),
("clang_getTypedefName", [Type], _CXString),
("clang_getTypeKindSpelling", [c_uint], _CXString),
+ ("clang_getTypePrettyPrinted", [Type, PrintingPolicy], _CXString),
("clang_getTypeSpelling", [Type], _CXString),
("clang_hashCursor", [Cursor], c_uint),
("clang_isAttribute", [CursorKind], bool),
diff --git a/clang/bindings/python/tests/cindex/test_type.py b/clang/bindings/python/tests/cindex/test_type.py
index e1d8c2aad1c3a..f39da8b5faf29 100644
--- a/clang/bindings/python/tests/cindex/test_type.py
+++ b/clang/bindings/python/tests/cindex/test_type.py
@@ -1,6 +1,14 @@
import os
-from clang.cindex import Config, CursorKind, RefQualifierKind, TranslationUnit, TypeKind
+from clang.cindex import (
+ Config,
+ CursorKind,
+ PrintingPolicy,
+ PrintingPolicyProperty,
+ RefQualifierKind,
+ TranslationUnit,
+ TypeKind,
+)
if "CLANG_LIBRARY_PATH" in os.environ:
Config.set_library_path(os.environ["CLANG_LIBRARY_PATH"])
@@ -517,3 +525,12 @@ class Template {
# Variable without a template argument.
cursor = get_cursor(tu, "bar")
self.assertEqual(cursor.get_num_template_arguments(), -1)
+
+ def test_pretty(self):
+ tu = get_tu("struct X {}; X x;", lang="cpp")
+ f = get_cursor(tu, "x")
+
+ pp = PrintingPolicy.create(f)
+ self.assertEqual(f.type.get_canonical().pretty_printed(pp), "X")
+ pp.set_property(PrintingPolicyProperty.SuppressTagKeyword, False)
+ self.assertEqual(f.type.get_canonical().pretty_printed(pp), "struct X")
diff --git a/clang/docs/ClangFormatStyleOptions.rst b/clang/docs/ClangFormatStyleOptions.rst
index 637ec23e0abaf..0edf7af72c24e 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -3441,7 +3441,7 @@ the configuration (without a prefix: ``Auto``).
.. _BreakBinaryOperations:
**BreakBinaryOperations** (``BreakBinaryOperationsStyle``) :versionbadge:`clang-format 20` :ref:`¶ `
- The break constructor initializers style to use.
+ The break binary operations style to use.
Possible values:
@@ -3764,6 +3764,7 @@ the configuration (without a prefix: ``Auto``).
lists.
Important differences:
+
* No spaces inside the braced list.
* No line break before the closing brace.
* Indentation with the continuation indent, not with the block indent.
diff --git a/clang/docs/LanguageExtensions.rst b/clang/docs/LanguageExtensions.rst
index e020710c7aa4f..2eb0777dbdc6c 100644
--- a/clang/docs/LanguageExtensions.rst
+++ b/clang/docs/LanguageExtensions.rst
@@ -2137,8 +2137,8 @@ method; it specifies that the method expects its ``self`` parameter to have a
- (void) bar __attribute__((ns_consumes_self));
- (void) baz:(id) __attribute__((ns_consumed)) x;
-Further examples of these attributes are available in the static analyzer's `list of annotations for analysis
-`_.
+Further examples of these attributes are available in the static analyzer's
+`list of annotations for analysis `__.
Query for these features with ``__has_attribute(ns_consumed)``,
``__has_attribute(ns_returns_retained)``, etc.
@@ -4792,8 +4792,8 @@ Extensions for Static Analysis
Clang supports additional attributes that are useful for documenting program
invariants and rules for static analysis tools, such as the `Clang Static
Analyzer `_. These attributes are documented
-in the analyzer's `list of source-level annotations
-`_.
+in the analyzer's `list of annotations for analysis
+`__.
Extensions for Dynamic Analysis
diff --git a/clang/docs/Modules.rst b/clang/docs/Modules.rst
index 06294e3c58a4f..69a45b7fd9ace 100644
--- a/clang/docs/Modules.rst
+++ b/clang/docs/Modules.rst
@@ -152,7 +152,7 @@ first include path that would refer to the current file. ``#include_next`` is
interpreted as if the current file had been found in that path.
If this search finds a file named by a module map, the ``#include_next``
directive is translated into an import, just like for a ``#include``
-directive.``
+directive.
Module maps
-----------
diff --git a/clang/docs/OpenMPSupport.rst b/clang/docs/OpenMPSupport.rst
index a1cb7fe359ebf..673c34bf08a4a 100644
--- a/clang/docs/OpenMPSupport.rst
+++ b/clang/docs/OpenMPSupport.rst
@@ -286,6 +286,8 @@ implementation.
+------------------------------+--------------------------------------------------------------+--------------------------+-----------------------------------------------------------------------+
| memory management | 'allocator' modifier for allocate clause | :good:`done` | https://github.com/llvm/llvm-project/pull/114883 |
+------------------------------+--------------------------------------------------------------+--------------------------+-----------------------------------------------------------------------+
+| memory management | 'align' modifier for allocate clause | :good:`done` | https://github.com/llvm/llvm-project/pull/121814 |
++------------------------------+--------------------------------------------------------------+--------------------------+-----------------------------------------------------------------------+
| memory management | new memory management routines | :none:`unclaimed` | |
+------------------------------+--------------------------------------------------------------+--------------------------+-----------------------------------------------------------------------+
| memory management | changes to omp_alloctrait_key enum | :none:`unclaimed` | |
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 07a1a4195427d..794943b24a003 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -58,6 +58,29 @@ code bases.
containing strict-aliasing violations. The new default behavior can be
disabled using ``-fno-pointer-tbaa``.
+- Clang will now more aggressively use undefined behavior on pointer addition
+ overflow for optimization purposes. For example, a check like
+ ``ptr + unsigned_offset < ptr`` will now optimize to ``false``, because
+ ``ptr + unsigned_offset`` will cause undefined behavior if it overflows (or
+ advances past the end of the object).
+
+ Previously, ``ptr + unsigned_offset < ptr`` was optimized (by both Clang and
+ GCC) to ``(ssize_t)unsigned_offset < 0``. This also results in an incorrect
+ overflow check, but in a way that is less apparent when only testing with
+ pointers in the low half of the address space.
+
+ To avoid pointer addition overflow, it is necessary to perform the addition
+ on integers, for example using
+ ``(uintptr_t)ptr + unsigned_offset < (uintptr_t)ptr``. Sometimes, it is also
+ possible to rewrite checks by only comparing the offset. For example,
+ ``ptr + offset < end_ptr && ptr + offset >= ptr`` can be written as
+ ``offset < (uintptr_t)(end_ptr - ptr)``.
+
+ Undefined behavior due to pointer addition overflow can be reliably detected
+ using ``-fsanitize=pointer-overflow``. It is also possible to use
+ ``-fno-strict-overflow`` to opt-in to a language dialect where signed integer
+ and pointer overflow are well-defined.
+
C/C++ Language Potentially Breaking Changes
-------------------------------------------
@@ -147,7 +170,7 @@ C++ Specific Potentially Breaking Changes
// Fixed version:
unsigned operator""_udl_name(unsigned long long);
-- Clang will now produce an error diagnostic when [[clang::lifetimebound]] is
+- Clang will now produce an error diagnostic when ``[[clang::lifetimebound]]`` is
applied on a parameter or an implicit object parameter of a function that
returns void. This was previously ignored and had no effect. (#GH107556)
@@ -156,6 +179,21 @@ C++ Specific Potentially Breaking Changes
// Now diagnoses with an error.
void f(int& i [[clang::lifetimebound]]);
+- Clang will now produce an error diagnostic when ``[[clang::lifetimebound]]``
+ is applied on a type (instead of a function parameter or an implicit object
+ parameter); this includes the case when the attribute is specified for an
+ unnamed function parameter. These were previously ignored and had no effect.
+ (#GH118281)
+
+ .. code-block:: c++
+
+ // Now diagnoses with an error.
+ int* [[clang::lifetimebound]] x;
+ // Now diagnoses with an error.
+ void f(int* [[clang::lifetimebound]] i);
+ // Now diagnoses with an error.
+ void g(int* [[clang::lifetimebound]]);
+
- Clang now rejects all field accesses on null pointers in constant expressions. The following code
used to work but will now be rejected:
@@ -430,6 +468,10 @@ Non-comprehensive list of changes in this release
- Matrix types (a Clang extension) can now be used in pseudo-destructor expressions,
which allows them to be stored in STL containers.
+- In the ``-ftime-report`` output, the new "Clang time report" group replaces
+ the old "Clang front-end time report" and includes "Front end", "LLVM IR
+ generation", "Optimizer", and "Machine code generation".
+
New Compiler Flags
------------------
@@ -907,6 +949,7 @@ Bug Fixes to C++ Support
(`LWG3929 `__.) (#GH121278)
- Clang now identifies unexpanded parameter packs within the type constraint on a non-type template parameter. (#GH88866)
- Fixed an issue while resolving type of expression indexing into a pack of values of non-dependent type (#GH121242)
+- Fixed a crash when __PRETTY_FUNCTION__ or __FUNCSIG__ (clang-cl) appears in the trailing return type of the lambda (#GH121274)
Bug Fixes to AST Handling
^^^^^^^^^^^^^^^^^^^^^^^^^
@@ -943,6 +986,9 @@ Miscellaneous Clang Crashes Fixed
- Fixed internal assertion firing when a declaration in the implicit global
module is found through ADL. (GH#109879)
+- Fixed a crash when an unscoped enumeration declared by an opaque-enum-declaration within a class template
+ with a dependent underlying type is subject to integral promotion. (#GH117960)
+
OpenACC Specific Changes
------------------------
@@ -1022,6 +1068,9 @@ X86 Support
Arm and AArch64 Support
^^^^^^^^^^^^^^^^^^^^^^^
+- Implementation of SVE2.1 and SME2.1 in accordance with the Arm C Language
+ Extensions (ACLE) is now available.
+
- In the ARM Target, the frame pointer (FP) of a leaf function can be retained
by using the ``-fno-omit-frame-pointer`` option. If you want to eliminate the FP
in leaf functions after enabling ``-fno-omit-frame-pointer``, you can do so by adding
@@ -1065,6 +1114,12 @@ CUDA Support
- Clang now supports CUDA SDK up to 12.6
- Added support for sm_100
- Added support for `__grid_constant__` attribute.
+- CUDA now uses the new offloading driver by default. The new driver supports
+ device-side LTO, interoperability with OpenMP and other languages, and native ``-fgpu-rdc``
+ support with static libraries. The old behavior can be returned using the
+ ``--no-offload-new-driver`` flag. The binary format is no longer compatible
+ with the NVIDIA compiler's RDC-mode support. More information can be found at:
+ https://clang.llvm.org/docs/OffloadingDesign.html
AIX Support
^^^^^^^^^^^
@@ -1158,6 +1213,8 @@ libclang
--------
- Add ``clang_isBeforeInTranslationUnit``. Given two source locations, it determines
whether the first one comes strictly before the second in the source code.
+- Add ``clang_getTypePrettyPrinted``. It allows controlling the PrintingPolicy used
+ to pretty-print a type.
Static Analyzer
---------------
@@ -1298,10 +1355,13 @@ Sanitizers
Python Binding Changes
----------------------
- Fixed an issue that led to crashes when calling ``Type.get_exception_specification_kind``.
-- Added bindings for ``clang_getCursorPrettyPrinted`` and related functions,
- which allow changing the formatting of pretty-printed code.
-- Added binding for ``clang_Cursor_isAnonymousRecordDecl``, which allows checking if
- a declaration is an anonymous union or anonymous struct.
+- Added ``Cursor.pretty_printed``, a binding for ``clang_getCursorPrettyPrinted``,
+ and related functions, which allow changing the formatting of pretty-printed code.
+- Added ``Cursor.is_anonymous_record_decl``, a binding for
+ ``clang_Cursor_isAnonymousRecordDecl``, which allows checking if a
+ declaration is an anonymous union or anonymous struct.
+- Added ``Type.pretty_printed`, a binding for ``clang_getTypePrettyPrinted``,
+ which allows changing the formatting of pretty-printed types.
OpenMP Support
--------------
@@ -1313,6 +1373,7 @@ OpenMP Support
always build support for AMDGPU and NVPTX targets.
- Added support for combined masked constructs 'omp parallel masked taskloop',
'omp parallel masked taskloop simd','omp masked taskloop' and 'omp masked taskloop simd' directive.
+- Added support for align-modifier in 'allocate' clause.
Improvements
^^^^^^^^^^^^
diff --git a/clang/docs/UsersManual.rst b/clang/docs/UsersManual.rst
index 8af9f5be644a0..260e84910c6f7 100644
--- a/clang/docs/UsersManual.rst
+++ b/clang/docs/UsersManual.rst
@@ -1364,10 +1364,8 @@ Controlling Static Analyzer Diagnostics
While not strictly part of the compiler, the diagnostics from Clang's
`static analyzer `_ can also be
influenced by the user via changes to the source code. See the available
-`annotations `_ and the
-analyzer's `FAQ
-page `_ for more
-information.
+`annotations `_ and the analyzer's
+`FAQ page `_ for more information.
.. _usersmanual-precompiled-headers:
@@ -3035,6 +3033,38 @@ indexed format, regardeless whether it is produced by frontend or the IR pass.
overhead. ``prefer-atomic`` will be transformed to ``atomic`` when supported
by the target, or ``single`` otherwise.
+.. option:: -ftemporal-profile
+
+ Enables the temporal profiling extension for IRPGO to improve startup time by
+ reducing ``.text`` section page faults. To do this, we instrument function
+ timestamps to measure when each function is called for the first time and use
+ this data to generate a function order to improve startup.
+
+ The profile is generated as normal.
+
+ .. code-block:: console
+
+ $ clang++ -O2 -fprofile-generate -ftemporal-profile code.cc -o code
+ $ ./code
+ $ llvm-profdata merge -o code.profdata yyy/zzz
+
+ Using the resulting profile, we can generate a function order to pass to the
+ linker via ``--symbol-ordering-file`` for ELF or ``-order_file`` for Mach-O.
+
+ .. code-block:: console
+
+ $ llvm-profdata order code.profdata -o code.orderfile
+ $ clang++ -O2 -Wl,--symbol-ordering-file=code.orderfile code.cc -o code
+
+ Or the profile can be passed to LLD directly.
+
+ .. code-block:: console
+
+ $ clang++ -O2 -fuse-ld=lld -Wl,--irpgo-profile=code.profdata,--bp-startup-sort=function code.cc -o code
+
+ For more information, please read the RFC:
+ https://discourse.llvm.org/t/rfc-temporal-profiling-extension-for-irpgo/68068
+
Fine Tuning Profile Collection
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
diff --git a/clang/www/analyzer/images/example_attribute_nonnull.png b/clang/docs/analyzer/images/example_attribute_nonnull.png
similarity index 100%
rename from clang/www/analyzer/images/example_attribute_nonnull.png
rename to clang/docs/analyzer/images/example_attribute_nonnull.png
diff --git a/clang/www/analyzer/images/example_cf_returns_retained.png b/clang/docs/analyzer/images/example_cf_returns_retained.png
similarity index 100%
rename from clang/www/analyzer/images/example_cf_returns_retained.png
rename to clang/docs/analyzer/images/example_cf_returns_retained.png
diff --git a/clang/www/analyzer/images/example_custom_assert.png b/clang/docs/analyzer/images/example_custom_assert.png
similarity index 100%
rename from clang/www/analyzer/images/example_custom_assert.png
rename to clang/docs/analyzer/images/example_custom_assert.png
diff --git a/clang/www/analyzer/images/example_ns_returns_retained.png b/clang/docs/analyzer/images/example_ns_returns_retained.png
similarity index 100%
rename from clang/www/analyzer/images/example_ns_returns_retained.png
rename to clang/docs/analyzer/images/example_ns_returns_retained.png
diff --git a/clang/www/analyzer/images/example_null_pointer.png b/clang/docs/analyzer/images/example_null_pointer.png
similarity index 100%
rename from clang/www/analyzer/images/example_null_pointer.png
rename to clang/docs/analyzer/images/example_null_pointer.png
diff --git a/clang/www/analyzer/images/example_use_assert.png b/clang/docs/analyzer/images/example_use_assert.png
similarity index 100%
rename from clang/www/analyzer/images/example_use_assert.png
rename to clang/docs/analyzer/images/example_use_assert.png
diff --git a/clang/docs/analyzer/user-docs.rst b/clang/docs/analyzer/user-docs.rst
index dd53ae143148c..e265f033a2c54 100644
--- a/clang/docs/analyzer/user-docs.rst
+++ b/clang/docs/analyzer/user-docs.rst
@@ -12,4 +12,5 @@ Contents:
user-docs/FilingBugs
user-docs/CrossTranslationUnit
user-docs/TaintAnalysisConfiguration
+ user-docs/Annotations
user-docs/FAQ
diff --git a/clang/docs/analyzer/user-docs/Annotations.rst b/clang/docs/analyzer/user-docs/Annotations.rst
new file mode 100644
index 0000000000000..d87e8f4df99c3
--- /dev/null
+++ b/clang/docs/analyzer/user-docs/Annotations.rst
@@ -0,0 +1,689 @@
+==================
+Source Annotations
+==================
+
+The Clang frontend supports several source-level annotations in the form of
+`GCC-style attributes `_
+and pragmas that can help make using the Clang Static Analyzer more useful.
+These annotations can both help suppress false positives as well as enhance the
+analyzer's ability to find bugs.
+
+This page gives a practical overview of such annotations. For more technical
+specifics regarding Clang-specific annotations please see the Clang's list of
+`language extensions `_.
+Details of "standard" GCC attributes (that Clang also supports) can
+be found in the `GCC manual `_, with the
+majority of the relevant attributes being in the section on
+`function attributes `_.
+
+Note that attributes that are labeled **Clang-specific** are not
+recognized by GCC. Their use can be conditioned using preprocessor macros
+(examples included on this page).
+
+.. contents::
+ :local:
+
+Annotations to Enhance Generic Checks
+_____________________________________
+
+Null Pointer Checking
+#####################
+
+Attribute 'nonnull'
+-------------------
+
+The analyzer recognizes the GCC attribute 'nonnull', which indicates that a
+function expects that a given function parameter is not a null pointer.
+Specific details of the syntax of using the 'nonnull' attribute can be found in
+`GCC's documentation `_.
+
+Both the Clang compiler and GCC will flag warnings for simple cases where a
+null pointer is directly being passed to a function with a 'nonnull' parameter
+(e.g., as a constant). The analyzer extends this checking by using its deeper
+symbolic analysis to track what pointer values are potentially null and then
+flag warnings when they are passed in a function call via a 'nonnull'
+parameter.
+
+**Example**
+
+.. code-block:: c
+
+ int bar(int*p, int q, int *r) __attribute__((nonnull(1,3)));
+
+ int foo(int *p, int *q) {
+ return !p ? bar(q, 2, p)
+ : bar(p, 2, q);
+ }
+
+Running ``scan-build`` over this source produces the following output:
+
+.. image:: ../images/example_attribute_nonnull.png
+
+.. _custom_assertion_handlers:
+
+Custom Assertion Handlers
+#########################
+
+The analyzer exploits code assertions by pruning off paths where the
+assertion condition is false. The idea is capture any program invariants
+specified in the assertion that the developer may know but is not immediately
+apparent in the code itself. In this way assertions make implicit assumptions
+explicit in the code, which not only makes the analyzer more accurate when
+finding bugs, but can help others better able to understand your code as well.
+It can also help remove certain kinds of analyzer false positives by pruning off
+false paths.
+
+In order to exploit assertions, however, the analyzer must understand when it
+encounters an "assertion handler". Typically assertions are
+implemented with a macro, with the macro performing a check for the assertion
+condition and, when the check fails, calling an assertion handler. For
+example, consider the following code fragment:
+
+.. code-block: c
+
+ void foo(int *p) {
+ assert(p != NULL);
+ }
+
+When this code is preprocessed on Mac OS X it expands to the following:
+
+.. code-block: c
+
+ void foo(int *p) {
+ (__builtin_expect(!(p != NULL), 0) ? __assert_rtn(__func__, "t.c", 4, "p != NULL") : (void)0);
+ }
+
+In this example, the assertion handler is ``__assert_rtn``. When called,
+most assertion handlers typically print an error and terminate the program. The
+analyzer can exploit such semantics by ending the analysis of a path once it
+hits a call to an assertion handler.
+
+The trick, however, is that the analyzer needs to know that a called function
+is an assertion handler; otherwise the analyzer might assume the function call
+returns and it will continue analyzing the path where the assertion condition
+failed. This can lead to false positives, as the assertion condition usually
+implies a safety condition (e.g., a pointer is not null) prior to performing
+some action that depends on that condition (e.g., dereferencing a pointer).
+
+The analyzer knows about several well-known assertion handlers, but can
+automatically infer if a function should be treated as an assertion handler if
+it is annotated with the 'noreturn' attribute or the (Clang-specific)
+'analyzer_noreturn' attribute. Note that, currently, clang does not support
+these attributes on Objective-C methods and C++ methods.
+
+Attribute 'noreturn'
+--------------------
+
+The 'noreturn' attribute is a GCC attribute that can be placed on the
+declarations of functions. It means exactly what its name implies: a function
+with a 'noreturn' attribute should never return.
+
+Specific details of the syntax of using the 'noreturn' attribute can be found
+in `GCC's documentation `__.
+
+Not only does the analyzer exploit this information when pruning false paths,
+but the compiler also takes it seriously and will generate different code (and
+possibly better optimized) under the assumption that the function does not
+return.
+
+**Example**
+
+On Mac OS X, the function prototype for ``__assert_rtn`` (declared in
+``assert.h``) is specifically annotated with the 'noreturn' attribute:
+
+.. code-block: c
+
+ void __assert_rtn(const char *, const char *, int, const char *) __attribute__((__noreturn__));
+
+Attribute 'analyzer_noreturn' (Clang-specific)
+----------------------------------------------
+
+The Clang-specific 'analyzer_noreturn' attribute is almost identical to
+'noreturn' except that it is ignored by the compiler for the purposes of code
+generation.
+
+This attribute is useful for annotating assertion handlers that actually
+*can* return, but for the purpose of using the analyzer we want to
+pretend that such functions do not return.
+
+Because this attribute is Clang-specific, its use should be conditioned with
+the use of preprocessor macros.
+
+**Example**
+
+.. code-block: c
+
+ #ifndef CLANG_ANALYZER_NORETURN
+ #if __has_feature(attribute_analyzer_noreturn)
+ #define CLANG_ANALYZER_NORETURN __attribute__((analyzer_noreturn))
+ #else
+ #define CLANG_ANALYZER_NORETURN
+ #endif
+ #endif
+
+ void my_assert_rtn(const char *, const char *, int, const char *) CLANG_ANALYZER_NORETURN;
+
+Mac OS X API Annotations
+________________________
+
+.. _cocoa_mem:
+
+Cocoa & Core Foundation Memory Management Annotations
+#####################################################
+
+The analyzer supports the proper management of retain counts for
+both Cocoa and Core Foundation objects. This checking is largely based on
+enforcing Cocoa and Core Foundation naming conventions for Objective-C methods
+(Cocoa) and C functions (Core Foundation). Not strictly following these
+conventions can cause the analyzer to miss bugs or flag false positives.
+
+One can educate the analyzer (and others who read your code) about methods or
+functions that deviate from the Cocoa and Core Foundation conventions using the
+attributes described here. However, you should consider using proper naming
+conventions or the `objc_method_family `_
+attribute, if applicable.
+
+.. _ns_returns_retained:
+
+Attribute 'ns_returns_retained' (Clang-specific)
+------------------------------------------------
+
+The GCC-style (Clang-specific) attribute 'ns_returns_retained' allows one to
+annotate an Objective-C method or C function as returning a retained Cocoa
+object that the caller is responsible for releasing (via sending a
+``release`` message to the object). The Foundation framework defines a
+macro ``NS_RETURNS_RETAINED`` that is functionally equivalent to the
+one shown below.
+
+**Placing on Objective-C methods**: For Objective-C methods, this
+annotation essentially tells the analyzer to treat the method as if its name
+begins with "alloc" or "new" or contains the word
+"copy".
+
+**Placing on C functions**: For C functions returning Cocoa objects, the
+analyzer typically does not make any assumptions about whether or not the object
+is returned retained. Explicitly adding the 'ns_returns_retained' attribute to C
+functions allows the analyzer to perform extra checking.
+
+**Example**
+
+.. code-block: objc
+
+ #import ;
+
+ #ifndef __has_feature // Optional.
+ #define __has_feature(x) 0 // Compatibility with non-clang compilers.
+ #endif
+
+ #ifndef NS_RETURNS_RETAINED
+ #if __has_feature(attribute_ns_returns_retained)
+ #define NS_RETURNS_RETAINED __attribute__((ns_returns_retained))
+ #else
+ #define NS_RETURNS_RETAINED
+ #endif
+ #endif
+
+ @interface MyClass : NSObject {}
+ - (NSString*) returnsRetained NS_RETURNS_RETAINED;
+ - (NSString*) alsoReturnsRetained;
+ @end
+
+ @implementation MyClass
+ - (NSString*) returnsRetained {
+ return [[NSString alloc] initWithCString:"no leak here"];
+ }
+ - (NSString*) alsoReturnsRetained {
+ return [[NSString alloc] initWithCString:"flag a leak"];
+ }
+ @end
+
+Running ``scan-build`` on this source file produces the following output:
+
+.. image:: ../images/example_ns_returns_retained.png
+
+.. _ns_returns_not_retained:
+
+Attribute 'ns_returns_not_retained' (Clang-specific)
+----------------------------------------------------
+
+The 'ns_returns_not_retained' attribute is the complement of
+'`ns_returns_retained`_'. Where a function or method may appear to obey the
+Cocoa conventions and return a retained Cocoa object, this attribute can be
+used to indicate that the object reference returned should not be considered as
+an "owning" reference being returned to the caller. The Foundation
+framework defines a macro ``NS_RETURNS_NOT_RETAINED`` that is functionally
+equivalent to the one shown below.
+
+Usage is identical to `ns_returns_retained`_. When using the
+attribute, be sure to declare it within the proper macro that checks for
+its availability, as it is not available in earlier versions of the analyzer:
+
+.. code-block:objc
+
+ #ifndef __has_feature // Optional.
+ #define __has_feature(x) 0 // Compatibility with non-clang compilers.
+ #endif
+
+ #ifndef NS_RETURNS_NOT_RETAINED
+ #if __has_feature(attribute_ns_returns_not_retained)
+ #define NS_RETURNS_NOT_RETAINED __attribute__((ns_returns_not_retained))
+ #else
+ #define NS_RETURNS_NOT_RETAINED
+ #endif
+ #endif
+
+.. _cf_returns_retained:
+
+Attribute 'cf_returns_retained' (Clang-specific)
+------------------------------------------------
+
+The GCC-style (Clang-specific) attribute 'cf_returns_retained' allows one to
+annotate an Objective-C method or C function as returning a retained Core
+Foundation object that the caller is responsible for releasing. The
+CoreFoundation framework defines a macro ``CF_RETURNS_RETAINED`` that is
+functionally equivalent to the one shown below.
+
+**Placing on Objective-C methods**: With respect to Objective-C methods.,
+this attribute is identical in its behavior and usage to 'ns_returns_retained'
+except for the distinction of returning a Core Foundation object instead of a
+Cocoa object.
+
+This distinction is important for the following reason: as Core Foundation is a
+C API, the analyzer cannot always tell that a pointer return value refers to a
+Core Foundation object. In contrast, it is trivial for the analyzer to
+recognize if a pointer refers to a Cocoa object (given the Objective-C type
+system).
+
+**Placing on C functions**: When placing the attribute
+'cf_returns_retained' on the declarations of C functions, the analyzer
+interprets the function as:
+
+1. Returning a Core Foundation Object
+2. Treating the function as if it its name contained the keywords
+ "create" or "copy". This means the returned object as a
+ +1 retain count that must be released by the caller, either by sending a
+ ``release`` message (via toll-free bridging to an Objective-C object
+ pointer), or calling ``CFRelease`` or a similar function.
+
+**Example**
+
+.. code-block:objc
+
+ #import
+
+ #ifndef __has_feature // Optional.
+ #define __has_feature(x) 0 // Compatibility with non-clang compilers.
+ #endif
+
+ #ifndef CF_RETURNS_RETAINED
+ #if __has_feature(attribute_cf_returns_retained)
+ #define CF_RETURNS_RETAINED __attribute__((cf_returns_retained))
+ #else
+ #define CF_RETURNS_RETAINED
+ #endif
+ #endif
+
+ @interface MyClass : NSObject {}
+ - (NSDate*) returnsCFRetained CF_RETURNS_RETAINED;
+ - (NSDate*) alsoReturnsRetained;
+ - (NSDate*) returnsNSRetained NS_RETURNS_RETAINED;
+ @end
+
+ CF_RETURNS_RETAINED
+ CFDateRef returnsRetainedCFDate() {
+ return CFDateCreate(0, CFAbsoluteTimeGetCurrent());
+ }
+
+ @implementation MyClass
+ - (NSDate*) returnsCFRetained {
+ return (NSDate*) returnsRetainedCFDate(); // No leak.
+ }
+
+ - (NSDate*) alsoReturnsRetained {
+ return (NSDate*) returnsRetainedCFDate(); // Always report a leak.
+ }
+
+ - (NSDate*) returnsNSRetained {
+ return (NSDate*) returnsRetainedCFDate(); // Report a leak when using GC.
+ }
+ @end
+
+Running ``scan-build`` on this example produces the following output:
+
+.. image:: ../images/example_cf_returns_retained.png
+
+Attribute 'cf_returns_not_retained' (Clang-specific)
+----------------------------------------------------
+
+The 'cf_returns_not_retained' attribute is the complement of
+'`cf_returns_retained`_'. Where a function or method may appear to obey the
+Core Foundation or Cocoa conventions and return a retained Core Foundation
+object, this attribute can be used to indicate that the object reference
+returned should not be considered as an "owning" reference being
+returned to the caller. The CoreFoundation framework defines a macro
+**``CF_RETURNS_NOT_RETAINED``** that is functionally equivalent to the one
+shown below.
+
+Usage is identical to cf_returns_retained_. When using the attribute, be sure
+to declare it within the proper macro that checks for its availability, as it
+is not available in earlier versions of the analyzer:
+
+.. code-block:objc
+
+ #ifndef __has_feature // Optional.
+ #define __has_feature(x) 0 // Compatibility with non-clang compilers.
+ #endif
+
+ #ifndef CF_RETURNS_NOT_RETAINED
+ #if __has_feature(attribute_cf_returns_not_retained)
+ #define CF_RETURNS_NOT_RETAINED __attribute__((cf_returns_not_retained))
+ #else
+ #define CF_RETURNS_NOT_RETAINED
+ #endif
+ #endif
+
+.. _ns_consumed:
+
+Attribute 'ns_consumed' (Clang-specific)
+----------------------------------------
+
+The 'ns_consumed' attribute can be placed on a specific parameter in either
+the declaration of a function or an Objective-C method. It indicates to the
+static analyzer that a ``release`` message is implicitly sent to the
+parameter upon completion of the call to the given function or method. The
+Foundation framework defines a macro ``NS_RELEASES_ARGUMENT`` that
+is functionally equivalent to the ``NS_CONSUMED`` macro shown below.
+
+**Example**
+
+.. code-block:objc
+
+ #ifndef __has_feature // Optional.
+ #define __has_feature(x) 0 // Compatibility with non-clang compilers.
+ #endif
+
+ #ifndef NS_CONSUMED
+ #if __has_feature(attribute_ns_consumed)
+ #define NS_CONSUMED __attribute__((ns_consumed))
+ #else
+ #define NS_CONSUMED
+ #endif
+ #endif
+
+ void consume_ns(id NS_CONSUMED x);
+
+ void test() {
+ id x = [[NSObject alloc] init];
+ consume_ns(x); // No leak!
+ }
+
+ @interface Foo : NSObject
+ + (void) releaseArg:(id) NS_CONSUMED x;
+ + (void) releaseSecondArg:(id)x second:(id) NS_CONSUMED y;
+ @end
+
+ void test_method() {
+ id x = [[NSObject alloc] init];
+ [Foo releaseArg:x]; // No leak!
+ }
+
+ void test_method2() {
+ id a = [[NSObject alloc] init];
+ id b = [[NSObject alloc] init];
+ [Foo releaseSecondArg:a second:b]; // 'a' is leaked, but 'b' is released.
+ }
+
+Attribute 'cf_consumed' (Clang-specific)
+----------------------------------------
+
+The 'cf_consumed' attribute is practically identical to ns_consumed_. The
+attribute can be placed on a specific parameter in either the declaration of a
+function or an Objective-C method. It indicates to the static analyzer that the
+object reference is implicitly passed to a call to ``CFRelease`` upon
+completion of the call to the given function or method. The CoreFoundation
+framework defines a macro ``CF_RELEASES_ARGUMENT`` that is functionally
+equivalent to the ``CF_CONSUMED`` macro shown below.
+
+Operationally this attribute is nearly identical to 'ns_consumed'.
+
+**Example**
+
+.. code-block:objc
+
+ #ifndef __has_feature // Optional.
+ #define __has_feature(x) 0 // Compatibility with non-clang compilers.
+ #endif
+
+ #ifndef CF_CONSUMED
+ #if __has_feature(attribute_cf_consumed)
+ #define CF_CONSUMED __attribute__((cf_consumed))
+ #else
+ #define CF_CONSUMED
+ #endif
+ #endif
+
+ void consume_cf(id CF_CONSUMED x);
+ void consume_CFDate(CFDateRef CF_CONSUMED x);
+
+ void test() {
+ id x = [[NSObject alloc] init];
+ consume_cf(x); // No leak!
+ }
+
+ void test2() {
+ CFDateRef date = CFDateCreate(0, CFAbsoluteTimeGetCurrent());
+ consume_CFDate(date); // No leak, including under GC!
+
+ }
+
+ @interface Foo : NSObject
+ + (void) releaseArg:(CFDateRef) CF_CONSUMED x;
+ @end
+
+ void test_method() {
+ CFDateRef date = CFDateCreate(0, CFAbsoluteTimeGetCurrent());
+ [Foo releaseArg:date]; // No leak!
+ }
+
+.. _ns_consumes_self:
+
+Attribute 'ns_consumes_self' (Clang-specific)
+---------------------------------------------
+
+The 'ns_consumes_self' attribute can be placed only on an Objective-C method
+declaration. It indicates that the receiver of the message is
+"consumed" (a single reference count decremented) after the message
+is sent. This matches the semantics of all "init" methods.
+
+One use of this attribute is declare your own init-like methods that do not
+follow the standard Cocoa naming conventions.
+
+**Example**
+
+.. code-block:objc
+ #ifndef __has_feature
+ #define __has_feature(x) 0 // Compatibility with non-clang compilers.
+ #endif
+
+ #ifndef NS_CONSUMES_SELF
+ #if __has_feature((attribute_ns_consumes_self))
+ #define NS_CONSUMES_SELF __attribute__((ns_consumes_self))
+ #else
+ #define NS_CONSUMES_SELF
+ #endif
+ #endif
+
+ @interface MyClass : NSObject
+ - initWith:(MyClass *)x;
+ - nonstandardInitWith:(MyClass *)x NS_CONSUMES_SELF NS_RETURNS_RETAINED;
+ @end
+
+In this example, ``-nonstandardInitWith:`` has the same ownership
+semantics as the init method ``-initWith:``. The static analyzer will
+observe that the method consumes the receiver, and then returns an object with
+a +1 retain count.
+
+The Foundation framework defines a macro ``NS_REPLACES_RECEIVER`` which is
+functionally equivalent to the combination of ``NS_CONSUMES_SELF`` and
+``NS_RETURNS_RETAINED`` shown above.
+
+Libkern Memory Management Annotations
+#####################################
+
+`Libkern `_
+requires developers to inherit all heap allocated objects from ``OSObject`` and
+to perform manual reference counting. The reference counting model is very
+similar to MRR (manual retain-release) mode in
+`Objective-C `_
+or to CoreFoundation reference counting.
+Freshly-allocated objects start with a reference count of 1, and calls to
+``retain`` increment it, while calls to ``release`` decrement it. The object is
+deallocated whenever its reference count reaches zero.
+
+Manually incrementing and decrementing reference counts is error-prone:
+over-retains lead to leaks, and over-releases lead to uses-after-free.
+The analyzer can help the programmer to check for unbalanced
+retain/release calls.
+
+The reference count checking is based on the principle of *locality*: it should
+be possible to establish correctness (lack of leaks/uses after free) by looking
+at each function body, and the declarations (not the definitions) of all the
+functions it interacts with.
+
+In order to support such reasoning, it should be possible to *summarize* the
+behavior of each function, with respect to reference count of its returned
+values and attributes.
+
+By default, the following summaries are assumed:
+
+- All functions starting with ``get`` or ``Get``, unless they are returning
+ subclasses of ``OSIterator``, are assumed to be returning at +0. That is, the
+ caller has no reference count *obligations* with respect to the reference
+ count of the returned object and should leave it untouched.
+
+- All other functions are assumed to return at +1. That is, the caller has an
+ *obligation* to release such objects.
+
+- Functions are assumed not to change the reference count of their parameters,
+ including the implicit ``this`` parameter.
+
+These summaries can be overriden with the following
+`attributes `_:
+
+Attribute 'os_returns_retained'
+-------------------------------
+
+The ``os_returns_retained`` attribute (accessed through the macro
+``LIBKERN_RETURNS_RETAINED``) plays a role identical to `ns_returns_retained`_
+for functions returning ``OSObject`` subclasses. The attribute indicates that
+it is a callers responsibility to release the returned object.
+
+Attribute 'os_returns_not_retained'
+-----------------------------------
+
+The ``os_returns_not_retained`` attribute (accessed through the macro
+``LIBKERN_RETURNS_NOT_RETAINED``) plays a role identical to
+`ns_returns_not_retained`_ for functions returning ``OSObject`` subclasses. The
+attribute indicates that the caller should not change the retain count of the
+returned object.
+
+
+**Example**
+
+.. code-block:objc
+
+ class MyClass {
+ OSObject *f;
+ LIBKERN_RETURNS_NOT_RETAINED OSObject *myFieldGetter();
+ }
+
+
+ // Note that the annotation only has to be applied to the function declaration.
+ OSObject * MyClass::myFieldGetter() {
+ return f;
+ }
+
+Attribute 'os_consumed'
+-----------------------
+
+Similarly to `ns_consumed`_ attribute, ``os_consumed`` (accessed through
+``LIBKERN_CONSUMED``) attribute, applied to a parameter, indicates that the
+call to the function *consumes* the parameter: the callee should either release
+it or store it and release it in the destructor, while the caller should assume
+one is subtracted from the reference count after the call.
+
+.. code-block:objc
+ IOReturn addToList(LIBKERN_CONSUMED IOPMinformee *newInformee);
+
+Attribute 'os_consumes_this'
+----------------------------
+
+Similarly to `ns_consumes_self`_, the ``os_consumes_self`` attribute indicates
+that the method call *consumes* the implicit ``this`` argument: the caller
+should assume one was subtracted from the reference count of the object after
+the call, and the callee has on obligation to either release the argument, or
+store it and eventually release it in the destructor.
+
+
+.. code-block:objc
+ void addThisToList(OSArray *givenList) LIBKERN_CONSUMES_THIS;
+
+Out Parameters
+--------------
+
+A function can also return an object to a caller by a means of an out parameter
+(a pointer-to-OSObject-pointer is passed, and a callee writes a pointer to an
+object into an argument). Currently the analyzer does not track unannotated out
+parameters by default, but with annotations we distinguish four separate cases:
+
+**1. Non-retained out parameters**, identified using
+``LIBKERN_RETURNS_NOT_RETAINED`` applied to parameters, e.g.:
+
+.. code-block:objc
+ void getterViaOutParam(LIBKERN_RETURNS_NOT_RETAINED OSObject **obj)
+
+Such functions write a non-retained object into an out parameter, and the
+caller has no further obligations.
+
+**2. Retained out parameters**, identified using ``LIBKERN_RETURNS_RETAINED``:
+
+.. code-block:objc
+ void getterViaOutParam(LIBKERN_RETURNS_NOT_RETAINED OSObject **obj)
+
+In such cases a retained object is written into an out parameter, which the caller has then to release in order to avoid a leak.
+
+These two cases are simple - but in practice a functions returning an
+out-parameter usually also return a return code, and then an out parameter may
+or may not be written, which conditionally depends on the exit code, e.g.:
+
+.. code-block:objc
+ bool maybeCreateObject(LIBKERN_RETURNS_RETAINED OSObject **obj);
+
+For such functions, the usual semantics is that an object is written into on "success", and not written into on "failure".
+
+For ``LIBKERN_RETURNS_RETAINED`` we assume the following definition of
+success:
+
+- For functions returning ``OSReturn`` or ``IOReturn`` (any typedef to
+ ``kern_return_t``) success is defined as having an output of zero
+ (``kIOReturnSuccess`` is zero).
+
+- For all others, success is non-zero (e.g. non-nullptr for pointers)
+
+**3. Retained out parameters on zero return** The annotation
+``LIBKERN_RETURNS_RETAINED_ON_ZERO`` states that a retained object is written
+into if and only if the function returns a zero value:
+
+.. code-block:objc
+ bool OSUnserializeXML(void *data, LIBKERN_RETURNS_RETAINED_ON_ZERO OSString **errString);
+
+Then the caller has to release an object if the function has returned zero.
+
+**4. Retained out parameters on non-zero return** Similarly,
+``LIBKERN_RETURNS_RETAINED_ON_NONZERO`` specifies that a retained object is
+written into the parameter if and only if the function has returned a non-zero
+value.
+
+Note that for non-retained out parameters conditionals do not matter, as the
+caller has no obligations regardless of whether an object is written into or
+not.
diff --git a/clang/docs/analyzer/user-docs/FAQ.rst b/clang/docs/analyzer/user-docs/FAQ.rst
index af52e99c91d68..58eac783efccd 100644
--- a/clang/docs/analyzer/user-docs/FAQ.rst
+++ b/clang/docs/analyzer/user-docs/FAQ.rst
@@ -9,7 +9,9 @@ Custom Assertions
Q: How do I tell the analyzer that I do not want the bug being reported here since my custom error handler will safely end the execution before the bug is reached?
-You can tell the analyzer that this path is unreachable by teaching it about your `custom assertion handlers `_. For example, you can modify the code segment as following:
+.. image:: ../images/example_custom_assert.png
+
+You can tell the analyzer that this path is unreachable by teaching it about your `custom assertion handlers `__. For example, you can modify the code segment as following:
.. code-block:: c
@@ -25,6 +27,8 @@ Null Pointer Dereference
Q: The analyzer reports a null dereference, but I know that the pointer is never null. How can I tell the analyzer that a pointer can never be null?
+.. image:: ../images/example_null_pointer.png
+
The reason the analyzer often thinks that a pointer can be null is because the preceding code checked compared it against null. If you are absolutely sure that it cannot be null, remove the preceding check and, preferably, add an assertion as well. For example:
.. code-block:: c
@@ -143,6 +147,8 @@ Ensuring Loop Body Execution
Q: The analyzer assumes that a loop body is never entered. How can I tell it that the loop body will be entered at least once?
+.. image:: ../images/example_use_assert.png
+
In cases where you know that a loop will always be entered at least once, you can use assertions to inform the analyzer. For example:
.. code-block:: c
@@ -162,7 +168,7 @@ Suppressing Specific Warnings
Q: How can I suppress a specific analyzer warning?
-When you encounter an analyzer bug/false positive, check if it's one of the issues discussed above or if the analyzer `annotations `_ can resolve the issue by helping the static analyzer understand the code better. Second, please `report it `_ to help us improve user experience.
+When you encounter an analyzer bug/false positive, check if it's one of the issues discussed above or if the analyzer `annotations `__ can resolve the issue by helping the static analyzer understand the code better. Second, please `report it `_ to help us improve user experience.
Sometimes there's really no "good" way to eliminate the issue. In such cases you can "silence" it directly by annotating the problematic line of code with the help of Clang attribute 'suppress':
@@ -192,6 +198,8 @@ Sometimes there's really no "good" way to eliminate the issue. In such cases you
return *result; // as well as this leak path
}
+.. _exclude_code:
+
Excluding Code from Analysis
----------------------------
diff --git a/clang/examples/Attribute/Attribute.cpp b/clang/examples/Attribute/Attribute.cpp
index 3b90724ad2220..625f1645afbff 100644
--- a/clang/examples/Attribute/Attribute.cpp
+++ b/clang/examples/Attribute/Attribute.cpp
@@ -42,8 +42,8 @@ struct ExampleAttrInfo : public ParsedAttrInfo {
const Decl *D) const override {
// This attribute appertains to functions only.
if (!isa(D)) {
- S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type_str)
- << Attr << Attr.isRegularKeywordAttribute() << "functions";
+ S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
+ << Attr << Attr.isRegularKeywordAttribute() << ExpectedFunction;
return false;
}
return true;
@@ -99,8 +99,9 @@ struct ExampleAttrInfo : public ParsedAttrInfo {
const Stmt *St) const override {
// This attribute appertains to for loop statements only.
if (!isa(St)) {
- S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type_str)
- << Attr << Attr.isRegularKeywordAttribute() << "for loop statements";
+ S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
+ << Attr << Attr.isRegularKeywordAttribute()
+ << ExpectedForLoopStatement;
return false;
}
return true;
diff --git a/clang/examples/CallSuperAttribute/CallSuperAttrInfo.cpp b/clang/examples/CallSuperAttribute/CallSuperAttrInfo.cpp
index 12d4c311586e6..f206a84ab1311 100644
--- a/clang/examples/CallSuperAttribute/CallSuperAttrInfo.cpp
+++ b/clang/examples/CallSuperAttribute/CallSuperAttrInfo.cpp
@@ -168,8 +168,9 @@ struct CallSuperAttrInfo : public ParsedAttrInfo {
const Decl *D) const override {
const auto *TheMethod = dyn_cast_or_null(D);
if (!TheMethod || !TheMethod->isVirtual()) {
- S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type_str)
- << Attr << Attr.isRegularKeywordAttribute() << "virtual functions";
+ S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
+ << Attr << Attr.isRegularKeywordAttribute()
+ << ExpectedVirtualFunction;
return false;
}
MarkedMethods.insert(TheMethod);
diff --git a/clang/include/clang-c/Index.h b/clang/include/clang-c/Index.h
index 63d266dc60ec7..ad64497ceb802 100644
--- a/clang/include/clang-c/Index.h
+++ b/clang/include/clang-c/Index.h
@@ -4182,6 +4182,14 @@ CINDEX_LINKAGE void clang_PrintingPolicy_dispose(CXPrintingPolicy Policy);
CINDEX_LINKAGE CXString clang_getCursorPrettyPrinted(CXCursor Cursor,
CXPrintingPolicy Policy);
+/**
+ * Pretty-print the underlying type using a custom printing policy.
+ *
+ * If the type is invalid, an empty string is returned.
+ */
+CINDEX_LINKAGE CXString clang_getTypePrettyPrinted(CXType CT,
+ CXPrintingPolicy cxPolicy);
+
/**
* Retrieve the display name for the entity referenced by this cursor.
*
diff --git a/clang/include/clang/AST/Decl.h b/clang/include/clang/AST/Decl.h
index 16fc98aa1a57f..9c470f0940637 100644
--- a/clang/include/clang/AST/Decl.h
+++ b/clang/include/clang/AST/Decl.h
@@ -3154,7 +3154,9 @@ class FieldDecl : public DeclaratorDecl, public Mergeable {
/// Computes the bit width of this field, if this is a bit field.
/// May not be called on non-bitfields.
- unsigned getBitWidthValue(const ASTContext &Ctx) const;
+ /// Note that in order to successfully use this function, the bitwidth
+ /// expression must be a ConstantExpr with a valid integer result set.
+ unsigned getBitWidthValue() const;
/// Set the bit-field width for this member.
// Note: used by some clients (i.e., do not remove it).
@@ -3185,7 +3187,7 @@ class FieldDecl : public DeclaratorDecl, public Mergeable {
/// Is this a zero-length bit-field? Such bit-fields aren't really bit-fields
/// at all and instead act as a separator between contiguous runs of other
/// bit-fields.
- bool isZeroLengthBitField(const ASTContext &Ctx) const;
+ bool isZeroLengthBitField() const;
/// Determine if this field is a subobject of zero size, that is, either a
/// zero-length bit-field or a field of empty class type with the
diff --git a/clang/include/clang/AST/DeclBase.h b/clang/include/clang/AST/DeclBase.h
index 82932e098c86f..77abd8b657a61 100644
--- a/clang/include/clang/AST/DeclBase.h
+++ b/clang/include/clang/AST/DeclBase.h
@@ -1334,7 +1334,7 @@ class DeclListNode {
reference operator*() const {
assert(Ptr && "dereferencing end() iterator");
- if (DeclListNode *CurNode = Ptr.dyn_cast())
+ if (DeclListNode *CurNode = dyn_cast(Ptr))
return CurNode->D;
return cast(Ptr);
}
@@ -1344,7 +1344,7 @@ class DeclListNode {
inline iterator &operator++() { // ++It
assert(!Ptr.isNull() && "Advancing empty iterator");
- if (DeclListNode *CurNode = Ptr.dyn_cast())
+ if (DeclListNode *CurNode = dyn_cast(Ptr))
Ptr = CurNode->Rest;
else
Ptr = nullptr;
diff --git a/clang/include/clang/AST/OpenMPClause.h b/clang/include/clang/AST/OpenMPClause.h
index d2f5267e4da5e..b9088eff3bb52 100644
--- a/clang/include/clang/AST/OpenMPClause.h
+++ b/clang/include/clang/AST/OpenMPClause.h
@@ -498,6 +498,9 @@ class OMPAllocateClause final
/// Allocator specified in the clause, or 'nullptr' if the default one is
/// used.
Expr *Allocator = nullptr;
+ /// Alignment specified in the clause, or 'nullptr' if the default one is
+ /// used.
+ Expr *Alignment = nullptr;
/// Position of the ':' delimiter in the clause;
SourceLocation ColonLoc;
/// Modifier of 'allocate' clause.
@@ -505,6 +508,41 @@ class OMPAllocateClause final
/// Location of allocator modifier if any.
SourceLocation AllocatorModifierLoc;
+ // ----------------------------------------------------------------------------
+
+ /// Modifiers for 'allocate' clause.
+ enum { FIRST, SECOND, NUM_MODIFIERS };
+ OpenMPAllocateClauseModifier Modifiers[NUM_MODIFIERS];
+
+ /// Locations of modifiers.
+ SourceLocation ModifiersLoc[NUM_MODIFIERS];
+
+ /// Set the first allocate modifier.
+ ///
+ /// \param M Allocate modifier.
+ void setFirstAllocateModifier(OpenMPAllocateClauseModifier M) {
+ Modifiers[FIRST] = M;
+ }
+
+ /// Set the second allocate modifier.
+ ///
+ /// \param M Allocate modifier.
+ void setSecondAllocateModifier(OpenMPAllocateClauseModifier M) {
+ Modifiers[SECOND] = M;
+ }
+
+ /// Set location of the first allocate modifier.
+ void setFirstAllocateModifierLoc(SourceLocation Loc) {
+ ModifiersLoc[FIRST] = Loc;
+ }
+
+ /// Set location of the second allocate modifier.
+ void setSecondAllocateModifierLoc(SourceLocation Loc) {
+ ModifiersLoc[SECOND] = Loc;
+ }
+
+ // ----------------------------------------------------------------------------
+
/// Build clause with number of variables \a N.
///
/// \param StartLoc Starting location of the clause.
@@ -514,15 +552,20 @@ class OMPAllocateClause final
/// \param EndLoc Ending location of the clause.
/// \param N Number of the variables in the clause.
OMPAllocateClause(SourceLocation StartLoc, SourceLocation LParenLoc,
- Expr *Allocator, SourceLocation ColonLoc,
- OpenMPAllocateClauseModifier AllocatorModifier,
- SourceLocation AllocatorModifierLoc, SourceLocation EndLoc,
+ Expr *Allocator, Expr *Alignment, SourceLocation ColonLoc,
+ OpenMPAllocateClauseModifier Modifier1,
+ SourceLocation Modifier1Loc,
+ OpenMPAllocateClauseModifier Modifier2,
+ SourceLocation Modifier2Loc, SourceLocation EndLoc,
unsigned N)
: OMPVarListClause(llvm::omp::OMPC_allocate, StartLoc,
LParenLoc, EndLoc, N),
- Allocator(Allocator), ColonLoc(ColonLoc),
- AllocatorModifier(AllocatorModifier),
- AllocatorModifierLoc(AllocatorModifierLoc) {}
+ Allocator(Allocator), Alignment(Alignment), ColonLoc(ColonLoc) {
+ Modifiers[FIRST] = Modifier1;
+ Modifiers[SECOND] = Modifier2;
+ ModifiersLoc[FIRST] = Modifier1Loc;
+ ModifiersLoc[SECOND] = Modifier2Loc;
+ }
/// Build an empty clause.
///
@@ -530,7 +573,10 @@ class OMPAllocateClause final
explicit OMPAllocateClause(unsigned N)
: OMPVarListClause(llvm::omp::OMPC_allocate,
SourceLocation(), SourceLocation(),
- SourceLocation(), N) {}
+ SourceLocation(), N) {
+ Modifiers[FIRST] = OMPC_ALLOCATE_unknown;
+ Modifiers[SECOND] = OMPC_ALLOCATE_unknown;
+ }
/// Sets location of ':' symbol in clause.
void setColonLoc(SourceLocation CL) { ColonLoc = CL; }
@@ -539,6 +585,7 @@ class OMPAllocateClause final
void setAllocatorModifier(OpenMPAllocateClauseModifier AM) {
AllocatorModifier = AM;
}
+ void setAlignment(Expr *A) { Alignment = A; }
public:
/// Creates clause with a list of variables \a VL.
@@ -554,19 +601,42 @@ class OMPAllocateClause final
/// \param VL List of references to the variables.
static OMPAllocateClause *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc,
- Expr *Allocator, SourceLocation ColonLoc,
- OpenMPAllocateClauseModifier AllocatorModifier,
- SourceLocation AllocatorModifierLoc, SourceLocation EndLoc,
- ArrayRef VL);
+ Expr *Allocator, Expr *Alignment, SourceLocation ColonLoc,
+ OpenMPAllocateClauseModifier Modifier1, SourceLocation Modifier1Loc,
+ OpenMPAllocateClauseModifier Modifier2, SourceLocation Modifier2Loc,
+ SourceLocation EndLoc, ArrayRef VL);
/// Returns the allocator expression or nullptr, if no allocator is specified.
Expr *getAllocator() const { return Allocator; }
+ /// Returns the alignment expression or nullptr, if no alignment specified.
+ Expr *getAlignment() const { return Alignment; }
+
/// Return 'allocate' modifier.
OpenMPAllocateClauseModifier getAllocatorModifier() const {
return AllocatorModifier;
}
+ /// Get the first modifier of the clause.
+ OpenMPAllocateClauseModifier getFirstAllocateModifier() const {
+ return Modifiers[FIRST];
+ }
+
+ /// Get location of first modifier of the clause.
+ SourceLocation getFirstAllocateModifierLoc() const {
+ return ModifiersLoc[FIRST];
+ }
+
+ /// Get the second modifier of the clause.
+ OpenMPAllocateClauseModifier getSecondAllocateModifier() const {
+ return Modifiers[SECOND];
+ }
+
+ /// Get location of second modifier of the clause.
+ SourceLocation getSecondAllocateModifierLoc() const {
+ return ModifiersLoc[SECOND];
+ }
+
/// Returns the location of the ':' delimiter.
SourceLocation getColonLoc() const { return ColonLoc; }
/// Return the location of the modifier.
diff --git a/clang/include/clang/AST/Type.h b/clang/include/clang/AST/Type.h
index 09c98f642852f..78677df578c4b 100644
--- a/clang/include/clang/AST/Type.h
+++ b/clang/include/clang/AST/Type.h
@@ -4593,9 +4593,14 @@ class FunctionType : public Type {
SME_ZT0Shift = 5,
SME_ZT0Mask = 0b111 << SME_ZT0Shift,
+ // A bit to tell whether a function is agnostic about sme ZA state.
+ SME_AgnosticZAStateShift = 8,
+ SME_AgnosticZAStateMask = 1 << SME_AgnosticZAStateShift,
+
SME_AttributeMask =
- 0b111'111'11 // We can't support more than 8 bits because of
- // the bitmask in FunctionTypeExtraBitfields.
+ 0b1'111'111'11 // We can't support more than 9 bits because of
+ // the bitmask in FunctionTypeArmAttributes
+ // and ExtProtoInfo.
};
enum ArmStateValue : unsigned {
@@ -4620,7 +4625,7 @@ class FunctionType : public Type {
struct alignas(void *) FunctionTypeArmAttributes {
/// Any AArch64 SME ACLE type attributes that need to be propagated
/// on declarations and function pointers.
- unsigned AArch64SMEAttributes : 8;
+ unsigned AArch64SMEAttributes : 9;
FunctionTypeArmAttributes() : AArch64SMEAttributes(SME_NormalFunction) {}
};
@@ -5188,7 +5193,7 @@ class FunctionProtoType final
FunctionType::ExtInfo ExtInfo;
unsigned Variadic : 1;
unsigned HasTrailingReturn : 1;
- unsigned AArch64SMEAttributes : 8;
+ unsigned AArch64SMEAttributes : 9;
Qualifiers TypeQuals;
RefQualifierKind RefQualifier = RQ_None;
ExceptionSpecInfo ExceptionSpec;
diff --git a/clang/include/clang/ASTMatchers/ASTMatchers.h b/clang/include/clang/ASTMatchers/ASTMatchers.h
index f32170c93bee2..239fcba4e5e05 100644
--- a/clang/include/clang/ASTMatchers/ASTMatchers.h
+++ b/clang/include/clang/ASTMatchers/ASTMatchers.h
@@ -708,8 +708,7 @@ AST_MATCHER(FieldDecl, isBitField) {
/// fieldDecl(hasBitWidth(2))
/// matches 'int a;' and 'int c;' but not 'int b;'.
AST_MATCHER_P(FieldDecl, hasBitWidth, unsigned, Width) {
- return Node.isBitField() &&
- Node.getBitWidthValue(Finder->getASTContext()) == Width;
+ return Node.isBitField() && Node.getBitWidthValue() == Width;
}
/// Matches non-static data members that have an in-class initializer.
diff --git a/clang/include/clang/Basic/Attr.td b/clang/include/clang/Basic/Attr.td
index 5039c20d8b73b..a752d94b06fad 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -2877,6 +2877,13 @@ def ArmPreserves : TypeAttr, TargetSpecificAttr {
let Documentation = [ArmPreservesDocs];
}
+def ArmAgnostic : TypeAttr, TargetSpecificAttr {
+ let Spellings = [RegularKeyword<"__arm_agnostic">];
+ let Args = [VariadicStringArgument<"AgnosticArgs">];
+ let Subjects = SubjectList<[HasFunctionProto], ErrorDiag>;
+ let Documentation = [ArmAgnosticDocs];
+}
+
def ArmLocallyStreaming : InheritableAttr, TargetSpecificAttr {
let Spellings = [RegularKeyword<"__arm_locally_streaming">];
let Subjects = SubjectList<[Function], ErrorDiag>;
@@ -4346,6 +4353,16 @@ def HLSLLoopHint: StmtAttr {
let Documentation = [HLSLLoopHintDocs, HLSLUnrollHintDocs];
}
+def HLSLControlFlowHint: StmtAttr {
+ /// [branch]
+ /// [flatten]
+ let Spellings = [Microsoft<"branch">, Microsoft<"flatten">];
+ let Subjects = SubjectList<[IfStmt],
+ ErrorDiag, "'if' statements">;
+ let LangOpts = [HLSL];
+ let Documentation = [InternalOnly];
+}
+
def CapturedRecord : InheritableAttr {
// This attribute has no spellings as it is only ever created implicitly.
let Spellings = [];
diff --git a/clang/include/clang/Basic/AttrDocs.td b/clang/include/clang/Basic/AttrDocs.td
index 506fe38eb882b..e10f24e239ece 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -1461,7 +1461,7 @@ Mind that many more checkers are affected by dynamic memory modeling changes to
some extent.
Further reading for other annotations:
-`Source Annotations in the Clang Static Analyzer `_.
+`Source Annotations in the Clang Static Analyzer `_.
}];
}
@@ -7635,6 +7635,32 @@ The attributes ``__arm_in(S)``, ``__arm_out(S)``, ``__arm_inout(S)`` and
}];
}
+def ArmAgnosticDocs : Documentation {
+ let Category = DocCatArmSmeAttributes;
+ let Content = [{
+The ``__arm_agnostic`` keyword applies to prototyped function types and
+affects the function's calling convention for a given state S. This
+attribute allows the user to describe a function that preserves S, without
+requiring the function to share S with its callers and without making
+the assumption that S exists.
+
+If a function has the ``__arm_agnostic(S)`` attribute and calls a function
+without this attribute, then the function's object code will contain code
+to preserve state S. Otherwise, the function's object code will be the same
+as if it did not have the attribute.
+
+The attribute takes string arguments to describe state S. The supported
+states are:
+
+* ``"sme_za_state"`` for state enabled by PSTATE.ZA, such as ZA and ZT0.
+
+The attribute ``__arm_agnostic("sme_za_state")`` cannot be used in conjunction
+with ``__arm_in(S)``, ``__arm_out(S)``, ``__arm_inout(S)`` or
+``__arm_preserves(S)`` where state S describes state enabled by PSTATE.ZA,
+such as "za" or "zt0".
+ }];
+}
+
def ArmSmeLocallyStreamingDocs : Documentation {
let Category = DocCatArmSmeAttributes;
let Content = [{
diff --git a/clang/include/clang/Basic/Builtins.td b/clang/include/clang/Basic/Builtins.td
index 468c16050e2bf..ea22690ce4f5c 100644
--- a/clang/include/clang/Basic/Builtins.td
+++ b/clang/include/clang/Basic/Builtins.td
@@ -3347,10 +3347,12 @@ def VFork : LibBuiltin<"unistd.h"> {
}
// POSIX pthread.h
-// FIXME: This should be a GNULibBuiltin, but it's currently missing the prototype.
-def PthreadCreate : CustomEntry {
- let Entry = "LIBBUILTIN(pthread_create, \"\", \"fC<2,3>\", PTHREAD_H, ALL_GNU_LANGUAGES)";
+def PthreadCreate : GNULibBuiltin<"pthread.h"> {
+ let Spellings = ["pthread_create"];
+ let Attributes = [FunctionWithoutBuiltinPrefix, Callback<[2, 3]>];
+ // Note that we don't have an expressable prototype so we leave it empty.
+ let Prototype = "";
}
def SigSetJmp : LibBuiltin<"setjmp.h"> {
@@ -4865,12 +4867,6 @@ def HLSLIsinf : LangBuiltin<"HLSL_LANG"> {
let Prototype = "void(...)";
}
-def HLSLLength : LangBuiltin<"HLSL_LANG"> {
- let Spellings = ["__builtin_hlsl_length"];
- let Attributes = [NoThrow, Const];
- let Prototype = "void(...)";
-}
-
def HLSLLerp : LangBuiltin<"HLSL_LANG"> {
let Spellings = ["__builtin_hlsl_lerp"];
let Attributes = [NoThrow, Const];
diff --git a/clang/include/clang/Basic/BuiltinsAMDGPU.def b/clang/include/clang/Basic/BuiltinsAMDGPU.def
index 14c1746716cdd..1b29a8e359c20 100644
--- a/clang/include/clang/Basic/BuiltinsAMDGPU.def
+++ b/clang/include/clang/Basic/BuiltinsAMDGPU.def
@@ -489,7 +489,6 @@ TARGET_BUILTIN(__builtin_amdgcn_s_barrier_wait, "vIs", "n", "gfx12-insts")
TARGET_BUILTIN(__builtin_amdgcn_s_barrier_signal_isfirst, "bIi", "n", "gfx12-insts")
TARGET_BUILTIN(__builtin_amdgcn_s_barrier_init, "vv*i", "n", "gfx12-insts")
TARGET_BUILTIN(__builtin_amdgcn_s_barrier_join, "vv*", "n", "gfx12-insts")
-TARGET_BUILTIN(__builtin_amdgcn_s_wakeup_barrier, "vv*", "n", "gfx12-insts")
TARGET_BUILTIN(__builtin_amdgcn_s_barrier_leave, "vIs", "n", "gfx12-insts")
TARGET_BUILTIN(__builtin_amdgcn_s_get_barrier_state, "Uii", "n", "gfx12-insts")
TARGET_BUILTIN(__builtin_amdgcn_s_get_named_barrier_state, "Uiv*", "n", "gfx12-insts")
diff --git a/clang/include/clang/Basic/BuiltinsBase.td b/clang/include/clang/Basic/BuiltinsBase.td
index 1a1096d41da40..6180a94aa4b5c 100644
--- a/clang/include/clang/Basic/BuiltinsBase.td
+++ b/clang/include/clang/Basic/BuiltinsBase.td
@@ -17,6 +17,11 @@ class IndexedAttribute : Attribute {
int Index = I;
}
+class MultiIndexAttribute Is>
+ : Attribute {
+ list Indices = Is;
+}
+
// Standard Attributes
// -------------------
def NoReturn : Attribute<"r">;
@@ -77,6 +82,10 @@ def Constexpr : Attribute<"E">;
// Builtin is immediate and must be constant evaluated. Implies Constexpr, and will only be supported in C++20 mode.
def Consteval : Attribute<"EG">;
+// Callback behavior: the first index argument is called with the arguments
+// indicated by the remaining indices.
+class Callback ArgIndices> : MultiIndexAttribute<"C", ArgIndices>;
+
// Builtin kinds
// =============
@@ -92,10 +101,6 @@ class Builtin {
bit EnableOpenCLLong = 0;
}
-class CustomEntry {
- string Entry;
-}
-
class AtomicBuiltin : Builtin;
class LibBuiltin : Builtin {
diff --git a/clang/include/clang/Basic/CodeGenOptions.h b/clang/include/clang/Basic/CodeGenOptions.h
index c555fb3b72d64..b64ad74d711c6 100644
--- a/clang/include/clang/Basic/CodeGenOptions.h
+++ b/clang/include/clang/Basic/CodeGenOptions.h
@@ -384,6 +384,11 @@ class CodeGenOptions : public CodeGenOptionsBase {
/// the expense of debuggability).
SanitizerSet SanitizeMergeHandlers;
+ /// Set of thresholds in a range [0.0, 1.0]: the top hottest code responsible
+ /// for the given fraction of PGO counters will be excluded from sanitization
+ /// (0.0 [default] to skip none, 1.0 to skip all).
+ SanitizerMaskCutoffs SanitizeSkipHotCutoffs;
+
/// List of backend command-line options for -fembed-bitcode.
std::vector CmdArgs;
diff --git a/clang/include/clang/Basic/DiagnosticParseKinds.td b/clang/include/clang/Basic/DiagnosticParseKinds.td
index 86fcae209c40d..3309f59a981fc 100644
--- a/clang/include/clang/Basic/DiagnosticParseKinds.td
+++ b/clang/include/clang/Basic/DiagnosticParseKinds.td
@@ -1658,6 +1658,8 @@ def warn_omp_depend_in_ordered_deprecated : Warning<"'depend' clause for"
def warn_omp_invalid_attribute_for_ompx_attributes : Warning<"'ompx_attribute' clause only allows "
"'amdgpu_flat_work_group_size', 'amdgpu_waves_per_eu', and 'launch_bounds'; "
"%0 is ignored">, InGroup;
+def err_omp_duplicate_modifier : Error<"duplicate modifier '%0' in '%1' clause">;
+def err_omp_expected_modifier : Error<"expected modifier in '%0' clause">;
// Pragma loop support.
def err_pragma_loop_missing_argument : Error<
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index d4e897868f1a9..8be4f946dce1c 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -3799,7 +3799,14 @@ def warn_attribute_wrong_decl_type : Warning<
"|types and namespaces"
"|variables, functions and classes"
"|kernel functions"
- "|non-K&R-style functions}2">,
+ "|non-K&R-style functions"
+ "|for loop statements"
+ "|virtual functions"
+ "|parameters and implicit object parameters"
+ "|non-member functions"
+ "|functions, classes, or enumerations"
+ "|classes"
+ "|typedefs}2">,
InGroup;
def err_attribute_wrong_decl_type : Error;
def warn_type_attribute_wrong_type : Warning<
@@ -3835,6 +3842,9 @@ def err_sme_unimplemented_za_save_restore : Error<
"call to a function that shares state other than 'za' from a "
"function that has live 'za' state requires a spill/fill of ZA, which is not yet "
"implemented">;
+def err_sme_unsupported_agnostic_new : Error<
+ "__arm_agnostic(\"sme_za_state\") is not supported together with "
+ "__arm_new(\"za\") or __arm_new(\"zt0\")">;
def note_sme_use_preserves_za : Note<
"add '__arm_preserves(\"za\")' to the callee if it preserves ZA">;
def err_sme_definition_using_sm_in_non_sme_target : Error<
@@ -3851,6 +3861,8 @@ def warn_sme_locally_streaming_has_vl_args_returns : Warning<
"%select{returning|passing}0 a VL-dependent argument %select{from|to}0 a locally streaming function is undefined"
" behaviour when the streaming and non-streaming vector lengths are different at runtime">,
InGroup, DefaultIgnore;
+def err_conflicting_attributes_arm_agnostic : Error<
+ "__arm_agnostic(\"sme_za_state\") cannot share ZA state with its caller">;
def err_conflicting_attributes_arm_state : Error<
"conflicting attributes for state '%0'">;
def err_unknown_arm_state : Error<
diff --git a/clang/include/clang/Basic/OpenMPKinds.def b/clang/include/clang/Basic/OpenMPKinds.def
index 3f25e7aafe23b..76a861f416fd5 100644
--- a/clang/include/clang/Basic/OpenMPKinds.def
+++ b/clang/include/clang/Basic/OpenMPKinds.def
@@ -219,6 +219,7 @@ OPENMP_NUMTASKS_MODIFIER(strict)
// Modifiers for 'allocate' clause.
OPENMP_ALLOCATE_MODIFIER(allocator)
+OPENMP_ALLOCATE_MODIFIER(align)
// Modifiers for the 'doacross' clause.
OPENMP_DOACROSS_MODIFIER(source)
diff --git a/clang/include/clang/Basic/OpenMPKinds.h b/clang/include/clang/Basic/OpenMPKinds.h
index 900ad6ca6d66f..3e5da2a6abc01 100644
--- a/clang/include/clang/Basic/OpenMPKinds.h
+++ b/clang/include/clang/Basic/OpenMPKinds.h
@@ -230,6 +230,10 @@ enum OpenMPAllocateClauseModifier {
OMPC_ALLOCATE_unknown
};
+/// Number of allowed allocate-modifiers.
+static constexpr unsigned NumberOfOMPAllocateClauseModifiers =
+ OMPC_ALLOCATE_unknown;
+
/// Contains 'interop' data for 'append_args' and 'init' clauses.
class Expr;
struct OMPInteropInfo final {
diff --git a/clang/include/clang/Basic/Sanitizers.h b/clang/include/clang/Basic/Sanitizers.h
index c890242269b33..fc0576d452b17 100644
--- a/clang/include/clang/Basic/Sanitizers.h
+++ b/clang/include/clang/Basic/Sanitizers.h
@@ -154,6 +154,16 @@ struct SanitizerKind {
#include "clang/Basic/Sanitizers.def"
}; // SanitizerKind
+class SanitizerMaskCutoffs {
+ std::vector Cutoffs;
+
+public:
+ std::optional operator[](unsigned Kind) const;
+
+ void set(SanitizerMask K, double V);
+ void clear(SanitizerMask K = SanitizerKind::All);
+};
+
struct SanitizerSet {
/// Check if a certain (single) sanitizer is enabled.
bool has(SanitizerMask K) const {
@@ -161,6 +171,10 @@ struct SanitizerSet {
return static_cast(Mask & K);
}
+ bool has(SanitizerKind::SanitizerOrdinal O) const {
+ return has(SanitizerMask::bitPosToMask(O));
+ }
+
/// Check if one or more sanitizers are enabled.
bool hasOneOf(SanitizerMask K) const { return static_cast(Mask & K); }
@@ -186,10 +200,24 @@ struct SanitizerSet {
/// Returns a non-zero SanitizerMask, or \c 0 if \p Value is not known.
SanitizerMask parseSanitizerValue(StringRef Value, bool AllowGroups);
+/// Parse a single weighted value (e.g., 'undefined=0.05') from a -fsanitize= or
+/// -fno-sanitize= value list.
+/// The relevant weight(s) are updated in the passed Cutoffs parameter.
+/// Individual Cutoffs are never reset to zero unless explicitly set
+/// (e.g., 'null=0.0').
+/// Returns \c false if \p Value is not known or the weight is not valid.
+bool parseSanitizerWeightedValue(StringRef Value, bool AllowGroups,
+ SanitizerMaskCutoffs &Cutoffs);
+
/// Serialize a SanitizerSet into values for -fsanitize= or -fno-sanitize=.
void serializeSanitizerSet(SanitizerSet Set,
SmallVectorImpl &Values);
+/// Serialize a SanitizerMaskCutoffs into values for -fsanitize= or
+/// -fno-sanitize=.
+void serializeSanitizerMaskCutoffs(const SanitizerMaskCutoffs &Cutoffs,
+ SmallVectorImpl &Values);
+
/// For each sanitizer group bit set in \p Kinds, set the bits for sanitizers
/// this group enables.
SanitizerMask expandSanitizerGroups(SanitizerMask Kinds);
diff --git a/clang/include/clang/Basic/arm_sve.td b/clang/include/clang/Basic/arm_sve.td
index 1c6bdb8cad2d1..47f1754aeb629 100644
--- a/clang/include/clang/Basic/arm_sve.td
+++ b/clang/include/clang/Basic/arm_sve.td
@@ -1988,7 +1988,7 @@ def SVSM4E : SInst<"svsm4e[_{d}]", "ddd", "Ui", MergeNone, "aarch64_sve_sm
def SVSM4EKEY : SInst<"svsm4ekey[_{d}]", "ddd", "Ui", MergeNone, "aarch64_sve_sm4ekey", [IsOverloadNone]>;
}
-let SVETargetGuard = "sve2-bitperm", SMETargetGuard = InvalidMode in {
+let SVETargetGuard = "sve2,sve-bitperm", SMETargetGuard = InvalidMode in {
def SVBDEP : SInst<"svbdep[_{d}]", "ddd", "UcUsUiUl", MergeNone, "aarch64_sve_bdep_x">;
def SVBDEP_N : SInst<"svbdep[_n_{d}]", "dda", "UcUsUiUl", MergeNone, "aarch64_sve_bdep_x">;
def SVBEXT : SInst<"svbext[_{d}]", "ddd", "UcUsUiUl", MergeNone, "aarch64_sve_bext_x">;
diff --git a/clang/include/clang/CodeGen/BackendUtil.h b/clang/include/clang/CodeGen/BackendUtil.h
index 7aa4f9db6c2e4..78d1e5ee8e6d5 100644
--- a/clang/include/clang/CodeGen/BackendUtil.h
+++ b/clang/include/clang/CodeGen/BackendUtil.h
@@ -25,11 +25,9 @@ class FileSystem;
} // namespace llvm
namespace clang {
+class CompilerInstance;
class DiagnosticsEngine;
-class HeaderSearchOptions;
class CodeGenOptions;
-class TargetOptions;
-class LangOptions;
class BackendConsumer;
enum BackendAction {
@@ -41,10 +39,8 @@ enum BackendAction {
Backend_EmitObj ///< Emit native object files
};
-void EmitBackendOutput(DiagnosticsEngine &Diags, const HeaderSearchOptions &,
- const CodeGenOptions &CGOpts, const TargetOptions &TOpts,
- const LangOptions &LOpts, StringRef TDesc,
- llvm::Module *M, BackendAction Action,
+void emitBackendOutput(CompilerInstance &CI, StringRef TDesc, llvm::Module *M,
+ BackendAction Action,
llvm::IntrusiveRefCntPtr VFS,
std::unique_ptr OS,
BackendConsumer *BC = nullptr);
diff --git a/clang/include/clang/Driver/Options.td b/clang/include/clang/Driver/Options.td
index eb860f73121fd..7c41d38e00a49 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -1796,6 +1796,9 @@ def fprofile_generate_cold_function_coverage : Flag<["-"], "fprofile-generate-co
def fprofile_generate_cold_function_coverage_EQ : Joined<["-"], "fprofile-generate-cold-function-coverage=">,
Group, Visibility<[ClangOption, CLOption]>, MetaVarName<"">,
HelpText<"Generate instrumented code to collect coverage info for cold functions into /default.profraw (overridden by LLVM_PROFILE_FILE env var)">;
+def ftemporal_profile : Flag<["-"], "ftemporal-profile">,
+ Group, Visibility<[ClangOption, CLOption]>,
+ HelpText<"Generate instrumented code to collect temporal information">;
def fprofile_instr_generate : Flag<["-"], "fprofile-instr-generate">,
Group, Visibility<[ClangOption, CLOption]>,
HelpText<"Generate instrumented code to collect execution counts into default.profraw file (overridden by '=' form of option or LLVM_PROFILE_FILE env var)">;
@@ -1891,7 +1894,7 @@ defm pseudo_probe_for_profiling : BoolFOption<"pseudo-probe-for-profiling",
" pseudo probes for sample profiling">>;
def forder_file_instrumentation : Flag<["-"], "forder-file-instrumentation">,
Group, Visibility<[ClangOption, CC1Option, CLOption]>,
- HelpText<"Generate instrumented code to collect order file into default.profraw file (overridden by '=' form of option or LLVM_PROFILE_FILE env var). Deprecated, please use temporal profiling.">;
+ HelpText<"Generate instrumented code to collect order file into default.profraw file (overridden by '=' form of option or LLVM_PROFILE_FILE env var). Deprecated, please use -ftemporal-profile">;
def fprofile_list_EQ : Joined<["-"], "fprofile-list=">,
Group, Visibility<[ClangOption, CC1Option, CLOption]>,
HelpText<"Filename defining the list of functions/files to instrument. "
@@ -2652,6 +2655,14 @@ def fsanitize_undefined_strip_path_components_EQ : Joined<["-"], "fsanitize-unde
HelpText<"Strip (or keep only, if negative) a given number of path components "
"when emitting check metadata.">,
MarshallingInfoInt, "0", "int">;
+def fsanitize_skip_hot_cutoff_EQ
+ : CommaJoined<["-"], "fsanitize-skip-hot-cutoff=">,
+ Group,
+ HelpText<
+ "Exclude sanitization for the top hottest code responsible for "
+ "the given fraction of PGO counters "
+ "(0.0 [default] = skip none; 1.0 = skip all). "
+ "Argument format: =,=,...">;
} // end -f[no-]sanitize* flags
@@ -4353,7 +4364,7 @@ defm split_machine_functions: BoolFOption<"split-machine-functions",
CodeGenOpts<"SplitMachineFunctions">, DefaultFalse,
PosFlag,
NegFlag,
- BothFlags<[], [ClangOption], " late function splitting using profile information (x86 ELF)">>;
+ BothFlags<[], [ClangOption], " late function splitting using profile information (x86 and aarch64 ELF)">>;
defm strict_return : BoolFOption<"strict-return",
CodeGenOpts<"StrictReturn">, DefaultTrue,
@@ -5745,6 +5756,8 @@ def print_multi_directory : Flag<["-", "--"], "print-multi-directory">;
def print_multi_lib : Flag<["-", "--"], "print-multi-lib">;
def print_multi_flags : Flag<["-", "--"], "print-multi-flags-experimental">,
HelpText<"Print the flags used for selecting multilibs (experimental)">;
+def fmultilib_flag : Joined<["-", "--"], "fmultilib-flag=">,
+ Visibility<[ClangOption]>;
def print_multi_os_directory : Flag<["-", "--"], "print-multi-os-directory">,
Flags<[Unsupported]>;
def print_target_triple : Flag<["-", "--"], "print-target-triple">,
diff --git a/clang/include/clang/Driver/SanitizerArgs.h b/clang/include/clang/Driver/SanitizerArgs.h
index 3b275092bbbe8..a54995e2b153b 100644
--- a/clang/include/clang/Driver/SanitizerArgs.h
+++ b/clang/include/clang/Driver/SanitizerArgs.h
@@ -26,6 +26,7 @@ class SanitizerArgs {
SanitizerSet RecoverableSanitizers;
SanitizerSet TrapSanitizers;
SanitizerSet MergeHandlers;
+ SanitizerMaskCutoffs SkipHotCutoffs;
std::vector UserIgnorelistFiles;
std::vector SystemIgnorelistFiles;
diff --git a/clang/include/clang/Format/Format.h b/clang/include/clang/Format/Format.h
index 8d41077549690..7c2afd4d94ab0 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -2298,7 +2298,7 @@ struct FormatStyle {
BBO_RespectPrecedence
};
- /// The break constructor initializers style to use.
+ /// The break binary operations style to use.
/// \version 20
BreakBinaryOperationsStyle BreakBinaryOperations;
@@ -2510,6 +2510,7 @@ struct FormatStyle {
/// lists.
///
/// Important differences:
+ ///
/// * No spaces inside the braced list.
/// * No line break before the closing brace.
/// * Indentation with the continuation indent, not with the block indent.
diff --git a/clang/include/clang/Frontend/CompilerInstance.h b/clang/include/clang/Frontend/CompilerInstance.h
index 1220a4e29471d..8b539dfc92960 100644
--- a/clang/include/clang/Frontend/CompilerInstance.h
+++ b/clang/include/clang/Frontend/CompilerInstance.h
@@ -118,7 +118,7 @@ class CompilerInstance : public ModuleLoader {
std::unique_ptr TheSema;
/// The frontend timer group.
- std::unique_ptr FrontendTimerGroup;
+ std::unique_ptr timerGroup;
/// The frontend timer.
std::unique_ptr FrontendTimer;
@@ -630,7 +630,7 @@ class CompilerInstance : public ModuleLoader {
/// @name Frontend timer
/// @{
- bool hasFrontendTimer() const { return (bool)FrontendTimer; }
+ llvm::TimerGroup &getTimerGroup() const { return *timerGroup; }
llvm::Timer &getFrontendTimer() const {
assert(FrontendTimer && "Compiler instance has no frontend timer!");
diff --git a/clang/include/clang/Frontend/Utils.h b/clang/include/clang/Frontend/Utils.h
index 8ed17179c9824..604e42067a3f1 100644
--- a/clang/include/clang/Frontend/Utils.h
+++ b/clang/include/clang/Frontend/Utils.h
@@ -120,7 +120,6 @@ class DependencyFileGenerator : public DependencyCollector {
private:
void outputDependencyFile(DiagnosticsEngine &Diags);
- llvm::IntrusiveRefCntPtr FS;
std::string OutputFile;
std::vector Targets;
bool IncludeSystemHeaders;
diff --git a/clang/include/clang/Sema/ParsedAttr.h b/clang/include/clang/Sema/ParsedAttr.h
index 4fa5fbdb5a7f6..e1faab205f647 100644
--- a/clang/include/clang/Sema/ParsedAttr.h
+++ b/clang/include/clang/Sema/ParsedAttr.h
@@ -1099,6 +1099,13 @@ enum AttributeDeclKind {
ExpectedFunctionVariableOrClass,
ExpectedKernelFunction,
ExpectedFunctionWithProtoType,
+ ExpectedForLoopStatement,
+ ExpectedVirtualFunction,
+ ExpectedParameterOrImplicitObjectParameter,
+ ExpectedNonMemberFunction,
+ ExpectedFunctionOrClassOrEnum,
+ ExpectedClass,
+ ExpectedTypedef,
};
inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
diff --git a/clang/include/clang/Sema/SemaARM.h b/clang/include/clang/Sema/SemaARM.h
index 8c4c56e222130..7beb1906a122f 100644
--- a/clang/include/clang/Sema/SemaARM.h
+++ b/clang/include/clang/Sema/SemaARM.h
@@ -79,6 +79,8 @@ class SemaARM : public SemaBase {
void handleNewAttr(Decl *D, const ParsedAttr &AL);
void handleCmseNSEntryAttr(Decl *D, const ParsedAttr &AL);
void handleInterruptAttr(Decl *D, const ParsedAttr &AL);
+
+ void CheckSMEFunctionDefAttributes(const FunctionDecl *FD);
};
SemaARM::ArmStreamingType getArmStreamingFnType(const FunctionDecl *FD);
diff --git a/clang/include/clang/Sema/SemaOpenMP.h b/clang/include/clang/Sema/SemaOpenMP.h
index 3d1cc4fab1c10..a056a96f50233 100644
--- a/clang/include/clang/Sema/SemaOpenMP.h
+++ b/clang/include/clang/Sema/SemaOpenMP.h
@@ -1148,7 +1148,12 @@ class SemaOpenMP : public SemaBase {
SourceLocation OmpAllMemoryLoc;
SourceLocation
StepModifierLoc; /// 'step' modifier location for linear clause
- OpenMPAllocateClauseModifier AllocClauseModifier = OMPC_ALLOCATE_unknown;
+ SmallVector
+ AllocClauseModifiers;
+ SmallVector
+ AllocClauseModifiersLoc;
+ Expr *AllocateAlignment = nullptr;
};
OMPClause *ActOnOpenMPVarListClause(OpenMPClauseKind Kind,
@@ -1166,10 +1171,15 @@ class SemaOpenMP : public SemaBase {
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'allocate' clause.
- OMPClause *ActOnOpenMPAllocateClause(
- Expr *Allocator, OpenMPAllocateClauseModifier ACModifier,
- ArrayRef VarList, SourceLocation StartLoc,
- SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc);
+ OMPClause *
+ ActOnOpenMPAllocateClause(Expr *Allocator, Expr *Alignment,
+ OpenMPAllocateClauseModifier FirstModifier,
+ SourceLocation FirstModifierLoc,
+ OpenMPAllocateClauseModifier SecondModifier,
+ SourceLocation SecondModifierLoc,
+ ArrayRef VarList, SourceLocation StartLoc,
+ SourceLocation ColonLoc, SourceLocation LParenLoc,
+ SourceLocation EndLoc);
/// Called on well-formed 'private' clause.
OMPClause *ActOnOpenMPPrivateClause(ArrayRef VarList,
SourceLocation StartLoc,
diff --git a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
index b34e940682fc5..1361da46c3c81 100644
--- a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
+++ b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
@@ -206,7 +206,12 @@ def CallAndMessageChecker : Checker<"CallAndMessage">,
Documentation,
Dependencies<[CallAndMessageModeling]>;
-def DereferenceChecker : Checker<"NullDereference">,
+def DereferenceModeling : Checker<"DereferenceModeling">,
+ HelpText<"General support for dereference related checkers">,
+ Documentation,
+ Hidden;
+
+def NullDereferenceChecker : Checker<"NullDereference">,
HelpText<"Check for dereferences of null pointers">,
CheckerOptions<[
CmdLineOption,
"true",
Released>
]>,
- Documentation;
+ Documentation,
+ Dependencies<[DereferenceModeling]>;
def NonNullParamChecker : Checker<"NonNullParamChecker">,
HelpText<"Check for null pointers passed as arguments to a function whose "
diff --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h
index c530dff495238..cbbea1b56bb40 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h
@@ -113,10 +113,10 @@ class SymbolConjured : public SymbolData {
void dumpToStream(raw_ostream &os) const override;
- static void Profile(llvm::FoldingSetNodeID& profile, const Stmt *S,
- QualType T, unsigned Count, const LocationContext *LCtx,
+ static void Profile(llvm::FoldingSetNodeID &profile, const Stmt *S,
+ const LocationContext *LCtx, QualType T, unsigned Count,
const void *SymbolTag) {
- profile.AddInteger((unsigned) SymbolConjuredKind);
+ profile.AddInteger((unsigned)SymbolConjuredKind);
profile.AddPointer(S);
profile.AddPointer(LCtx);
profile.Add(T);
@@ -125,7 +125,7 @@ class SymbolConjured : public SymbolData {
}
void Profile(llvm::FoldingSetNodeID& profile) override {
- Profile(profile, S, T, Count, LCtx, SymbolTag);
+ Profile(profile, S, LCtx, T, Count, SymbolTag);
}
// Implement isa support.
@@ -224,6 +224,8 @@ class SymbolMetadata : public SymbolData {
const Stmt *S;
QualType T;
const LocationContext *LCtx;
+ /// Count can be used to differentiate regions corresponding to
+ /// different loop iterations, thus, making the symbol path-dependent.
unsigned Count;
const void *Tag;
@@ -525,14 +527,18 @@ class SymbolManager {
static bool canSymbolicate(QualType T);
- /// Make a unique symbol for MemRegion R according to its kind.
- const SymbolRegionValue* getRegionValueSymbol(const TypedValueRegion* R);
+ /// Create or retrieve a SymExpr of type \p SymExprT for the given arguments.
+ /// Use the arguments to check for an existing SymExpr and return it,
+ /// otherwise, create a new one and keep a pointer to it to avoid duplicates.
+ template
+ const SymExprT *acquire(Args &&...args);
- const SymbolConjured* conjureSymbol(const Stmt *E,
- const LocationContext *LCtx,
- QualType T,
+ const SymbolConjured *conjureSymbol(const Stmt *E,
+ const LocationContext *LCtx, QualType T,
unsigned VisitCount,
- const void *SymbolTag = nullptr);
+ const void *SymbolTag = nullptr) {
+ return acquire(E, LCtx, T, VisitCount, SymbolTag);
+ }
const SymbolConjured* conjureSymbol(const Expr *E,
const LocationContext *LCtx,
@@ -541,41 +547,6 @@ class SymbolManager {
return conjureSymbol(E, LCtx, E->getType(), VisitCount, SymbolTag);
}
- const SymbolDerived *getDerivedSymbol(SymbolRef parentSymbol,
- const TypedValueRegion *R);
-
- const SymbolExtent *getExtentSymbol(const SubRegion *R);
-
- /// Creates a metadata symbol associated with a specific region.
- ///
- /// VisitCount can be used to differentiate regions corresponding to
- /// different loop iterations, thus, making the symbol path-dependent.
- const SymbolMetadata *getMetadataSymbol(const MemRegion *R, const Stmt *S,
- QualType T,
- const LocationContext *LCtx,
- unsigned VisitCount,
- const void *SymbolTag = nullptr);
-
- const SymbolCast* getCastSymbol(const SymExpr *Operand,
- QualType From, QualType To);
-
- const SymIntExpr *getSymIntExpr(const SymExpr *lhs, BinaryOperator::Opcode op,
- APSIntPtr rhs, QualType t);
-
- const SymIntExpr *getSymIntExpr(const SymExpr &lhs, BinaryOperator::Opcode op,
- APSIntPtr rhs, QualType t) {
- return getSymIntExpr(&lhs, op, rhs, t);
- }
-
- const IntSymExpr *getIntSymExpr(APSIntPtr lhs, BinaryOperator::Opcode op,
- const SymExpr *rhs, QualType t);
-
- const SymSymExpr *getSymSymExpr(const SymExpr *lhs, BinaryOperator::Opcode op,
- const SymExpr *rhs, QualType t);
-
- const UnarySymExpr *getUnarySymExpr(const SymExpr *operand,
- UnaryOperator::Opcode op, QualType t);
-
QualType getType(const SymExpr *SE) const {
return SE->getType();
}
@@ -707,6 +678,19 @@ class SymbolVisitor {
virtual bool VisitMemRegion(const MemRegion *) { return true; }
};
+template
+const T *SymbolManager::acquire(Args &&...args) {
+ llvm::FoldingSetNodeID profile;
+ T::Profile(profile, args...);
+ void *InsertPos;
+ SymExpr *SD = DataSet.FindNodeOrInsertPos(profile, InsertPos);
+ if (!SD) {
+ SD = Alloc.make