[clang] [Clang] Drop workaround for old gcc versions (PR #78803)

2024-01-19 Thread via cfe-commits


@@ -6081,11 +6081,10 @@ QualType
 TreeTransform::TransformFunctionProtoType(TypeLocBuilder &TLB,
FunctionProtoTypeLoc TL) {
   SmallVector ExceptionStorage;
-  TreeTransform *This = this; // Work around gcc.gnu.org/PR56135.
   return getDerived().TransformFunctionProtoType(
   TLB, TL, nullptr, Qualifiers(),
   [&](FunctionProtoType::ExceptionSpecInfo &ESI, bool &Changed) {
-return This->getDerived().TransformExceptionSpec(
+return this->getDerived().TransformExceptionSpec(

cor3ntin wrote:

```suggestion
return getDerived().TransformExceptionSpec(
```

https://github.com/llvm/llvm-project/pull/78803
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang] Drop workaround for old gcc versions (PR #78803)

2024-01-19 Thread via cfe-commits

https://github.com/cor3ntin approved this pull request.

LGTM modulo nits

https://github.com/llvm/llvm-project/pull/78803
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang] Drop workaround for old gcc versions (PR #78803)

2024-01-19 Thread via cfe-commits


@@ -13637,11 +13636,10 @@ 
TreeTransform::TransformLambdaExpr(LambdaExpr *E) {
 auto TransformFunctionProtoTypeLoc =
 [this](TypeLocBuilder &TLB, FunctionProtoTypeLoc FPTL) -> QualType {
   SmallVector ExceptionStorage;
-  TreeTransform *This = this; // Work around gcc.gnu.org/PR56135.
   return this->TransformFunctionProtoType(
   TLB, FPTL, nullptr, Qualifiers(),
   [&](FunctionProtoType::ExceptionSpecInfo &ESI, bool &Changed) {
-return This->TransformExceptionSpec(FPTL.getBeginLoc(), ESI,
+return this->TransformExceptionSpec(FPTL.getBeginLoc(), ESI,

cor3ntin wrote:

```suggestion
return TransformExceptionSpec(FPTL.getBeginLoc(), ESI,
```

https://github.com/llvm/llvm-project/pull/78803
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang] Drop workaround for old gcc versions (PR #78803)

2024-01-19 Thread via cfe-commits

https://github.com/cor3ntin edited 
https://github.com/llvm/llvm-project/pull/78803
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang-tidy] Fix crash in modernize-loop-convert when int is used as iterator (PR #78796)

2024-01-19 Thread Piotr Zegar via cfe-commits

https://github.com/PiotrZSL closed 
https://github.com/llvm/llvm-project/pull/78796
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] 296fbee - [clang-tidy] Fix crash in modernize-loop-convert when int is used as iterator (#78796)

2024-01-19 Thread via cfe-commits

Author: Piotr Zegar
Date: 2024-01-20T08:48:09+01:00
New Revision: 296fbee5af89e8e4c31dd98f48a9770c4eb3ca4d

URL: 
https://github.com/llvm/llvm-project/commit/296fbee5af89e8e4c31dd98f48a9770c4eb3ca4d
DIFF: 
https://github.com/llvm/llvm-project/commit/296fbee5af89e8e4c31dd98f48a9770c4eb3ca4d.diff

LOG: [clang-tidy] Fix crash in modernize-loop-convert when int is used as 
iterator (#78796)

Fix crash when built-in type (like int) is used as iterator, or when
call to begin() return integer.

Closes #78381

Added: 


Modified: 
clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp
clang-tools-extra/docs/ReleaseNotes.rst
clang-tools-extra/test/clang-tidy/checkers/modernize/loop-convert-basic.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp
index 8beaa62c78ba0a..f0791da143ad9d 100644
--- a/clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp
@@ -942,11 +942,15 @@ bool LoopConvertCheck::isConvertible(ASTContext *Context,
 CanonicalInitVarType->isPointerType()) {
   // If the initializer and the variable are both pointers check if the
   // un-qualified pointee types match, otherwise we don't use auto.
-  if (!Context->hasSameUnqualifiedType(
-  CanonicalBeginType->getPointeeType(),
-  CanonicalInitVarType->getPointeeType()))
-return false;
+  return Context->hasSameUnqualifiedType(
+  CanonicalBeginType->getPointeeType(),
+  CanonicalInitVarType->getPointeeType());
 }
+
+if (CanonicalBeginType->isBuiltinType() ||
+CanonicalInitVarType->isBuiltinType())
+  return false;
+
   } else if (FixerKind == LFK_PseudoArray) {
 if (const auto *EndCall = Nodes.getNodeAs(EndCallName)) 
{
   // This call is required to obtain the container.

diff  --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index d77267588db915..7f618e71afd1ce 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -410,7 +410,8 @@ Changes in existing checks
 - Improved :doc:`modernize-loop-convert
   ` to support for-loops with
   iterators initialized by free functions like ``begin``, ``end``, or ``size``
-  and avoid crash for array of dependent array.
+  and avoid crash for array of dependent array and non-dereferenceable builtin
+  types used as iterators.
 
 - Improved :doc:`modernize-make-shared
   ` check to support
@@ -502,7 +503,7 @@ Changes in existing checks
   ` check to take
   do-while loops into account for the `AllowIntegerConditions` and
   `AllowPointerConditions` options. It also now provides more consistent
-  suggestions when parentheses are added to the return value or expressions. 
+  suggestions when parentheses are added to the return value or expressions.
   It also ignores false-positives for comparison containing bool bitfield.
 
 - Improved :doc:`readability-misleading-indentation

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/loop-convert-basic.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/loop-convert-basic.cpp
index e2b9336d620f50..c29fbc9f9b23b7 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/loop-convert-basic.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/loop-convert-basic.cpp
@@ -954,3 +954,16 @@ void dependenceArrayTest() {
 }
 
 } // namespace PseudoArray
+
+namespace PR78381 {
+  struct blocked_range {
+int begin() const;
+int end() const;
+  };
+
+  void test() {
+blocked_range r;
+for (auto i = r.begin(); i!=r.end(); ++i) {
+}
+  }
+}



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] Add option -fstdlib-hardening= (PR #78763)

2024-01-19 Thread Sam James via cfe-commits

thesamesam wrote:

> No other thoughts for now. GCC has `-fhardened` now, which already defines 
> that macro. This seems kinda redundant with it.

Yes, please, unless there's a strong reason not to, consider `-fhardened`. 
Otherwise we may as well just be telling people to set `-D...` themselves.


https://github.com/llvm/llvm-project/pull/78763
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[llvm] [clang] [libcxx] [mlir] [compiler-rt] [sanitizer] Skip /include/c++/ from summary (PR #78534)

2024-01-19 Thread Vitaly Buka via cfe-commits

vitalybuka wrote:

Thanks, I guess symbolizer on Darwin somehow strip inlude/c++ path

https://github.com/llvm/llvm-project/pull/78534
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [workflows] Split pr-code-format into two parts to make it more secure (PR #78216)

2024-01-19 Thread via cfe-commits

github-actions[bot] wrote:




:warning: C/C++ code formatter, clang-format found issues in your code. 
:warning:



You can test this locally with the following command:


``bash
git-clang-format --diff 66786a79d6f622012879e94a92838449bf175a71 
2ccc8284d479ddb8b4f8c5cce4a630b67616f269 -- clang/lib/Driver/ToolChain.cpp 
clang/test/CodeGen/dwarf-version.c clang/test/Driver/cl-options.c 
clang/test/Driver/clang-g-opts.c clang/test/Driver/ve-toolchain.c 
clang/test/Driver/ve-toolchain.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/Driver/ToolChain.cpp b/clang/lib/Driver/ToolChain.cpp
index 56c7d0e8db..0250ecdd54 100644
--- a/clang/lib/Driver/ToolChain.cpp
+++ b/clang/lib/Driver/ToolChain.cpp
@@ -427,9 +427,7 @@ ToolChain::getDefaultUnwindTableLevel(const ArgList &Args) 
const {
   return UnwindTableLevel::None;
 }
 
-unsigned ToolChain::GetDefaultDwarfVersion() const {
-  return 4;
-}
+unsigned ToolChain::GetDefaultDwarfVersion() const { return 4; }
 
 Tool *ToolChain::getClang() const {
   if (!Clang)

``




https://github.com/llvm/llvm-project/pull/78216
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [workflows] Split pr-code-format into two parts to make it more secure (PR #78216)

2024-01-19 Thread Tom Stellard via cfe-commits

https://github.com/tstellar updated 
https://github.com/llvm/llvm-project/pull/78216

>From 035d4129ff02b776df53bfe149ce4af4af6072c4 Mon Sep 17 00:00:00 2001
From: Konrad Kleine 
Date: Thu, 24 Mar 2022 09:44:21 +0100
Subject: [PATCH 01/10] Produce DWARF4 by default

Have a look at the following commit to see when the move from DWARF 4 to 5 
first happened upstream:

https://github.com/llvm/llvm-project/commit/d3b26dea16108c427b19b5480c9edc76edf8f5b4?diff=unified
---
 clang/lib/Driver/ToolChain.cpp | 4 +---
 clang/test/CodeGen/dwarf-version.c | 8 
 clang/test/Driver/as-options.s | 4 ++--
 clang/test/Driver/cl-options.c | 2 +-
 clang/test/Driver/clang-g-opts.c   | 2 +-
 clang/test/Driver/ve-toolchain.c   | 2 +-
 clang/test/Driver/ve-toolchain.cpp | 2 +-
 7 files changed, 11 insertions(+), 13 deletions(-)

diff --git a/clang/lib/Driver/ToolChain.cpp b/clang/lib/Driver/ToolChain.cpp
index 96a57927339a97..56c7d0e8db02c9 100644
--- a/clang/lib/Driver/ToolChain.cpp
+++ b/clang/lib/Driver/ToolChain.cpp
@@ -428,9 +428,7 @@ ToolChain::getDefaultUnwindTableLevel(const ArgList &Args) 
const {
 }
 
 unsigned ToolChain::GetDefaultDwarfVersion() const {
-  // TODO: Remove the RISC-V special case when R_RISCV_SET_ULEB128 linker
-  // support becomes more widely available.
-  return getTriple().isRISCV() ? 4 : 5;
+  return 4;
 }
 
 Tool *ToolChain::getClang() const {
diff --git a/clang/test/CodeGen/dwarf-version.c 
b/clang/test/CodeGen/dwarf-version.c
index e63316ace69c87..3d68b06c58ff8b 100644
--- a/clang/test/CodeGen/dwarf-version.c
+++ b/clang/test/CodeGen/dwarf-version.c
@@ -2,10 +2,10 @@
 // RUN: %clang -target x86_64-linux-gnu -gdwarf-3 -S -emit-llvm -o - %s | 
FileCheck %s --check-prefix=VER3
 // RUN: %clang -target x86_64-linux-gnu -gdwarf-4 -S -emit-llvm -o - %s | 
FileCheck %s --check-prefix=VER4
 // RUN: %clang -target x86_64-linux-gnu -gdwarf-5 -S -emit-llvm -o - %s | 
FileCheck %s --check-prefix=VER5
-// RUN: %clang -target x86_64-linux-gnu -g -S -emit-llvm -o - %s | FileCheck 
%s --check-prefix=VER5
-// RUN: %clang -target x86_64-linux-gnu -gdwarf -S -emit-llvm -o - %s | 
FileCheck %s --check-prefix=VER5
-// RUN: %clang --target=i386-pc-solaris -g -S -emit-llvm -o - %s | FileCheck 
%s --check-prefix=VER5
-// RUN: %clang --target=i386-pc-solaris -gdwarf -S -emit-llvm -o - %s | 
FileCheck %s --check-prefix=VER5
+// RUN: %clang -target x86_64-linux-gnu -g -S -emit-llvm -o - %s | FileCheck 
%s --check-prefix=VER4
+// RUN: %clang -target x86_64-linux-gnu -gdwarf -S -emit-llvm -o - %s | 
FileCheck %s --check-prefix=VER4
+// RUN: %clang --target=i386-pc-solaris -g -S -emit-llvm -o - %s | FileCheck 
%s --check-prefix=VER4
+// RUN: %clang --target=i386-pc-solaris -gdwarf -S -emit-llvm -o - %s | 
FileCheck %s --check-prefix=VER4
 
 // The -isysroot is used as a hack to avoid LIT messing with the SDKROOT
 // environment variable which indirecty overrides the version in the target
diff --git a/clang/test/Driver/as-options.s b/clang/test/Driver/as-options.s
index 73d002c7ef7ed3..71d55f7fd53761 100644
--- a/clang/test/Driver/as-options.s
+++ b/clang/test/Driver/as-options.s
@@ -122,7 +122,7 @@
 // RUN:   FileCheck --check-prefix=DEBUG %s
 // RUN: %clang --target=aarch64-linux-gnu -fno-integrated-as -g0 -g %s -### 
2>&1 | \
 // RUN:   FileCheck --check-prefix=DEBUG %s
-// DEBUG: "-g" "-gdwarf-5"
+// DEBUG: "-g" "-gdwarf-4"
 // RUN: %clang --target=aarch64-linux-gnu -fno-integrated-as -g -g0 %s -### 
2>&1 | \
 // RUN:   FileCheck --check-prefix=NODEBUG %s
 // RUN: %clang --target=aarch64-linux-gnu -fno-integrated-as -gdwarf-5 -g0 %s 
-### 2>&1 | \
@@ -141,7 +141,7 @@
 // RUN: %clang --target=aarch64-linux-gnu -fno-integrated-as -gdwarf-2 %s -### 
2>&1 | \
 // RUN:   FileCheck --check-prefix=GDWARF2 %s
 // RUN: %clang --target=aarch64-linux-gnu -fno-integrated-as -gdwarf %s -### 
2>&1 | \
-// RUN:   FileCheck --check-prefix=GDWARF5 %s
+// RUN:   FileCheck --check-prefix=GDWARF4 %s
 
 // RUN: %clang --target=aarch64-linux-gnu -fno-integrated-as -gdwarf-5 %s -### 
2>&1 | \
 // RUN:   FileCheck --check-prefix=GDWARF5 %s
diff --git a/clang/test/Driver/cl-options.c b/clang/test/Driver/cl-options.c
index 5b6dfe308a76ea..4da65272a1b0df 100644
--- a/clang/test/Driver/cl-options.c
+++ b/clang/test/Driver/cl-options.c
@@ -571,7 +571,7 @@
 // RUN: %clang_cl -gdwarf /Z7 /c -### -- %s 2>&1 | FileCheck 
-check-prefix=Z7_gdwarf %s
 // Z7_gdwarf-NOT: "-gcodeview"
 // Z7_gdwarf: "-debug-info-kind=constructor"
-// Z7_gdwarf: "-dwarf-version=
+// Z7_gdwarf: "-dwarf-version=4
 
 // RUN: %clang_cl /ZH:MD5 /c -### -- %s 2>&1 | FileCheck -check-prefix=ZH_MD5 
%s
 // ZH_MD5: "-gsrc-hash=md5"
diff --git a/clang/test/Driver/clang-g-opts.c b/clang/test/Driver/clang-g-opts.c
index b73602a155b009..b0cf6467425340 100644
--- a/clang/test/Driver/clang-g-opts.c
+++ b/clang/test/Driver/clang-g-opts.c
@@ -36,7 +36,7 @@
 
 // CHECK-WITHOUT-G-NOT: -debug-info-kind
 // CHECK-WITH-G: "-debug-info-kind=constructor"
-// CHECK-WITH-G: "-dwarf-ver

[clang] 10886a8 - [Driver] Use SmallString::operator std::string (NFC)

2024-01-19 Thread Kazu Hirata via cfe-commits

Author: Kazu Hirata
Date: 2024-01-19T22:24:09-08:00
New Revision: 10886a8f0a054d8d97708fcfbe03313d81fae35e

URL: 
https://github.com/llvm/llvm-project/commit/10886a8f0a054d8d97708fcfbe03313d81fae35e
DIFF: 
https://github.com/llvm/llvm-project/commit/10886a8f0a054d8d97708fcfbe03313d81fae35e.diff

LOG: [Driver] Use SmallString::operator std::string (NFC)

Added: 


Modified: 
clang/lib/Driver/Driver.cpp
clang/lib/Driver/SanitizerArgs.cpp
clang/lib/Driver/ToolChain.cpp
clang/lib/Driver/ToolChains/AVR.cpp
clang/lib/Driver/ToolChains/CSKYToolChain.cpp
clang/lib/Driver/ToolChains/Cuda.cpp
clang/lib/Driver/ToolChains/Fuchsia.cpp
clang/lib/Driver/ToolChains/Hexagon.cpp
clang/lib/Driver/ToolChains/MSP430.cpp
clang/lib/Driver/ToolChains/MSVC.cpp
clang/lib/Driver/ToolChains/MipsLinux.cpp
clang/lib/Driver/ToolChains/OpenBSD.cpp
clang/lib/Driver/ToolChains/PS4CPU.cpp
clang/lib/Driver/ToolChains/RISCVToolchain.cpp

Removed: 




diff  --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index 35d563b9a87fac4..10f7b99a59bd61a 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -186,7 +186,7 @@ std::string Driver::GetResourcesPath(StringRef BinaryPath,
 CLANG_VERSION_MAJOR_STRING);
   }
 
-  return std::string(P.str());
+  return std::string(P);
 }
 
 Driver::Driver(StringRef ClangExecutable, StringRef TargetTriple,
@@ -1831,7 +1831,7 @@ void Driver::generateCompilationDiagnostics(
   ScriptOS << "\n# Additional information: " << AdditionalInformation
<< "\n";
 if (Report)
-  Report->TemporaryFiles.push_back(std::string(Script.str()));
+  Report->TemporaryFiles.push_back(std::string(Script));
 Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
   }
 
@@ -6073,17 +6073,17 @@ std::string Driver::GetFilePath(StringRef Name, const 
ToolChain &TC) const {
   SmallString<128> R(ResourceDir);
   llvm::sys::path::append(R, Name);
   if (llvm::sys::fs::exists(Twine(R)))
-return std::string(R.str());
+return std::string(R);
 
   SmallString<128> P(TC.getCompilerRTPath());
   llvm::sys::path::append(P, Name);
   if (llvm::sys::fs::exists(Twine(P)))
-return std::string(P.str());
+return std::string(P);
 
   SmallString<128> D(Dir);
   llvm::sys::path::append(D, "..", Name);
   if (llvm::sys::fs::exists(Twine(D)))
-return std::string(D.str());
+return std::string(D);
 
   if (auto P = SearchPaths(TC.getLibraryPaths()))
 return *P;
@@ -6120,11 +6120,11 @@ std::string Driver::GetProgramPath(StringRef Name, 
const ToolChain &TC) const {
 if (llvm::sys::fs::is_directory(PrefixDir)) {
   SmallString<128> P(PrefixDir);
   if (ScanDirForExecutable(P, Name))
-return std::string(P.str());
+return std::string(P);
 } else {
   SmallString<128> P((PrefixDir + Name).str());
   if (llvm::sys::fs::can_execute(Twine(P)))
-return std::string(P.str());
+return std::string(P);
 }
   }
 
@@ -6140,7 +6140,7 @@ std::string Driver::GetProgramPath(StringRef Name, const 
ToolChain &TC) const {
 for (const auto &Path : List) {
   SmallString<128> P(Path);
   if (ScanDirForExecutable(P, TargetSpecificExecutable))
-return std::string(P.str());
+return std::string(P);
 }
 
 // Fall back to the path
@@ -6160,7 +6160,7 @@ std::string Driver::GetTemporaryPath(StringRef Prefix, 
StringRef Suffix) const {
 return "";
   }
 
-  return std::string(Path.str());
+  return std::string(Path);
 }
 
 std::string Driver::GetTemporaryDirectory(StringRef Prefix) const {
@@ -6171,7 +6171,7 @@ std::string Driver::GetTemporaryDirectory(StringRef 
Prefix) const {
 return "";
   }
 
-  return std::string(Path.str());
+  return std::string(Path);
 }
 
 std::string Driver::GetClPchPath(Compilation &C, StringRef BaseName) const {
@@ -6193,7 +6193,7 @@ std::string Driver::GetClPchPath(Compilation &C, 
StringRef BaseName) const {
   Output = BaseName;
 llvm::sys::path::replace_extension(Output, ".pch");
   }
-  return std::string(Output.str());
+  return std::string(Output);
 }
 
 const ToolChain &Driver::getToolChain(const ArgList &Args,

diff  --git a/clang/lib/Driver/SanitizerArgs.cpp 
b/clang/lib/Driver/SanitizerArgs.cpp
index 9d6ea371f9f6dd5..56d497eb4c32b86 100644
--- a/clang/lib/Driver/SanitizerArgs.cpp
+++ b/clang/lib/Driver/SanitizerArgs.cpp
@@ -190,7 +190,7 @@ static void addDefaultIgnorelists(const Driver &D, 
SanitizerMask Kinds,
 clang::SmallString<64> Path(D.ResourceDir);
 llvm::sys::path::append(Path, "share", BL.File);
 if (D.getVFS().exists(Path))
-  IgnorelistFiles.push_back(std::string(Path.str()));
+  IgnorelistFiles.push_back(std::string(Path));
 else if (BL.Mask == SanitizerKind::CFI && DiagnoseErrors)
   // If cfi_ignorelist.txt cannot be found i

[clang] [clang] reject to capture variable in `RequiresExprBodyDecl` (PR #78598)

2024-01-19 Thread Congcong Cai via cfe-commits

HerrCai0907 wrote:

> Thanks for the patch!
> 
> Requires Expressions should be in an unevaluated context, so we should never 
> try to capture variables they mentioned.
> 
> Maybe we need to test the evaluation context in either `tryCaptureVariable` 
> or `NeedToCaptureVariable`, rather than a specific handling for requires 
> expressions
> 
> https://eel.is/c++draft/expr.prim.lambda.capture#7.sentence-2
> 
> WDYT?
> 
> @erichkeane

We will use `tryCaptureVariable` to diagnose `-Wunused-lambda-capture`. So 
simply ignoring them in an unevaluated context is not a good idea. I have 
changed the PR to match this function work even for `RequiresExprBodyDecl`.

https://github.com/llvm/llvm-project/pull/78598
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] reject to capture variable in `RequiresExprBodyDecl` (PR #78598)

2024-01-19 Thread Congcong Cai via cfe-commits

https://github.com/HerrCai0907 updated 
https://github.com/llvm/llvm-project/pull/78598

>From 8fa3dc43e770025308da47f6aff309fa58c47fc3 Mon Sep 17 00:00:00 2001
From: Congcong Cai 
Date: Thu, 18 Jan 2024 23:12:23 +0800
Subject: [PATCH 1/3] [clang] reject to capture variable in
 `RequiresExprBodyDecl`

Expression in `RequiresExprBodyDecl` is resolved as constants and should not be 
captured.
Fixes: #69307, #76593.
---
 clang/lib/Sema/SemaExpr.cpp   | 21 ++--
 ...uires-expression-with-capture-variable.cpp | 25 +++
 2 files changed, 38 insertions(+), 8 deletions(-)
 create mode 100644 
clang/test/SemaCXX/requires-expression-with-capture-variable.cpp

diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index 6413a48f809ac9c..580e759f634956b 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -19704,6 +19704,12 @@ static void buildLambdaCaptureFixit(Sema &Sema, 
LambdaScopeInfo *LSI,
   }
 }
 
+static DeclContext *ignoreReuquiresBodyDecl(DeclContext *DC) {
+  if (isa_and_present(DC))
+return DC->getParent();
+  return DC;
+}
+
 bool Sema::tryCaptureVariable(
 ValueDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
@@ -19711,15 +19717,15 @@ bool Sema::tryCaptureVariable(
   // An init-capture is notionally from the context surrounding its
   // declaration, but its parent DC is the lambda class.
   DeclContext *VarDC = Var->getDeclContext();
-  DeclContext *DC = CurContext;
-
   // tryCaptureVariable is called every time a DeclRef is formed,
   // it can therefore have non-negigible impact on performances.
   // For local variables and when there is no capturing scope,
   // we can bailout early.
-  if (CapturingFunctionScopes == 0 && (!BuildAndDiagnose || VarDC == DC))
+  if (CapturingFunctionScopes == 0 && (!BuildAndDiagnose || VarDC == 
CurContext))
 return true;
 
+  DeclContext *DC = ignoreReuquiresBodyDecl(CurContext);
+
   const auto *VD = dyn_cast(Var);
   if (VD) {
 if (VD->isInitCapture())
@@ -19789,11 +19795,10 @@ bool Sema::tryCaptureVariable(
 
 // Only block literals, captured statements, and lambda expressions can
 // capture; other scopes don't work.
-DeclContext *ParentDC =
-!IsInScopeDeclarationContext
-? DC->getParent()
-: getParentOfCapturingContextOrNull(DC, Var, ExprLoc,
-BuildAndDiagnose, *this);
+DeclContext *ParentDC = IsInScopeDeclarationContext
+? getParentOfCapturingContextOrNull(
+  DC, Var, ExprLoc, BuildAndDiagnose, 
*this)
+: DC->getParent();
 // We need to check for the parent *first* because, if we *have*
 // private-captured a global variable, we need to recursively capture it in
 // intermediate blocks, lambdas, etc.
diff --git a/clang/test/SemaCXX/requires-expression-with-capture-variable.cpp 
b/clang/test/SemaCXX/requires-expression-with-capture-variable.cpp
new file mode 100644
index 000..d01a54133f6c39b
--- /dev/null
+++ b/clang/test/SemaCXX/requires-expression-with-capture-variable.cpp
@@ -0,0 +1,25 @@
+// RUN: %clang -fsyntax-only -std=c++20 -Xclang -verify %s
+
+// expected-no-diagnostics
+
+auto GH69307_Func_1() {
+  constexpr auto b = 1;
+  return [&](auto c) -> int
+   requires requires { b + c; }
+  { return 1; };
+};
+auto GH69307_Func_Ret = GH69307_Func_1()(1);
+
+auto GH69307_Lambda_1 = []() {
+  return [&](auto c) -> int
+   requires requires { c; }
+  { return 1; };
+};
+auto GH69307_Lambda_1_Ret = GH69307_Lambda_1()(1);
+
+auto GH69307_Lambda_2 = [](auto c) {
+  return [&]() -> int
+   requires requires { c; }
+  { return 1; };
+};
+auto GH69307_Lambda_2_Ret = GH69307_Lambda_2(1)();

>From a99f16ff51702ff249cdf8a47de0cf24a08f694a Mon Sep 17 00:00:00 2001
From: Congcong Cai 
Date: Sat, 20 Jan 2024 13:40:12 +0800
Subject: [PATCH 2/3] another test

---
 clang/test/SemaCXX/warn-unused-lambda-capture-cxx20.cpp | 7 +++
 clang/test/SemaCXX/warn-unused-lambda-capture.cpp   | 4 
 2 files changed, 11 insertions(+)
 create mode 100644 clang/test/SemaCXX/warn-unused-lambda-capture-cxx20.cpp

diff --git a/clang/test/SemaCXX/warn-unused-lambda-capture-cxx20.cpp 
b/clang/test/SemaCXX/warn-unused-lambda-capture-cxx20.cpp
new file mode 100644
index 000..b787edb188ed8b5
--- /dev/null
+++ b/clang/test/SemaCXX/warn-unused-lambda-capture-cxx20.cpp
@@ -0,0 +1,7 @@
+// RUN: %clang_cc1 -fsyntax-only -Wunused-lambda-capture 
-Wused-but-marked-unused -Wno-uninitialized -verify -std=c++20 %s
+
+void test() {
+  int i;
+  auto explicit_by_value_unused_requires = [i] (auto) requires requires { i; } 
{}; // expected-warning{{lambda capture 'i' is not required to be captured for 
this use}}
+  explicit_by_value_unused_requires(1);
+}
diff --

[clang] [clang] reject to capture variable in `RequiresExprBodyDecl` (PR #78598)

2024-01-19 Thread Congcong Cai via cfe-commits

https://github.com/HerrCai0907 edited 
https://github.com/llvm/llvm-project/pull/78598
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] reject to capture variable in `RequiresExprBodyDecl` (PR #78598)

2024-01-19 Thread Congcong Cai via cfe-commits

https://github.com/HerrCai0907 edited 
https://github.com/llvm/llvm-project/pull/78598
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] reject to capture variable in `RequiresExprBodyDecl` (PR #78598)

2024-01-19 Thread via cfe-commits

github-actions[bot] wrote:




:warning: C/C++ code formatter, clang-format found issues in your code. 
:warning:



You can test this locally with the following command:


``bash
git-clang-format --diff e611a4cf8060bf0a95b4acd9e136733425da085a 
a99f16ff51702ff249cdf8a47de0cf24a08f694a -- 
clang/test/SemaCXX/requires-expression-with-capture-variable.cpp 
clang/test/SemaCXX/warn-unused-lambda-capture-cxx20.cpp 
clang/lib/Sema/SemaExpr.cpp clang/test/SemaCXX/warn-unused-lambda-capture.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index 580e759f63..04cfe5435e 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -19721,7 +19721,8 @@ bool Sema::tryCaptureVariable(
   // it can therefore have non-negigible impact on performances.
   // For local variables and when there is no capturing scope,
   // we can bailout early.
-  if (CapturingFunctionScopes == 0 && (!BuildAndDiagnose || VarDC == 
CurContext))
+  if (CapturingFunctionScopes == 0 &&
+  (!BuildAndDiagnose || VarDC == CurContext))
 return true;
 
   DeclContext *DC = ignoreReuquiresBodyDecl(CurContext);

``




https://github.com/llvm/llvm-project/pull/78598
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] reject to capture variable in `RequiresExprBodyDecl` (PR #78598)

2024-01-19 Thread Congcong Cai via cfe-commits

https://github.com/HerrCai0907 updated 
https://github.com/llvm/llvm-project/pull/78598

>From 8fa3dc43e770025308da47f6aff309fa58c47fc3 Mon Sep 17 00:00:00 2001
From: Congcong Cai 
Date: Thu, 18 Jan 2024 23:12:23 +0800
Subject: [PATCH 1/2] [clang] reject to capture variable in
 `RequiresExprBodyDecl`

Expression in `RequiresExprBodyDecl` is resolved as constants and should not be 
captured.
Fixes: #69307, #76593.
---
 clang/lib/Sema/SemaExpr.cpp   | 21 ++--
 ...uires-expression-with-capture-variable.cpp | 25 +++
 2 files changed, 38 insertions(+), 8 deletions(-)
 create mode 100644 
clang/test/SemaCXX/requires-expression-with-capture-variable.cpp

diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index 6413a48f809ac9..580e759f634956 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -19704,6 +19704,12 @@ static void buildLambdaCaptureFixit(Sema &Sema, 
LambdaScopeInfo *LSI,
   }
 }
 
+static DeclContext *ignoreReuquiresBodyDecl(DeclContext *DC) {
+  if (isa_and_present(DC))
+return DC->getParent();
+  return DC;
+}
+
 bool Sema::tryCaptureVariable(
 ValueDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
@@ -19711,15 +19717,15 @@ bool Sema::tryCaptureVariable(
   // An init-capture is notionally from the context surrounding its
   // declaration, but its parent DC is the lambda class.
   DeclContext *VarDC = Var->getDeclContext();
-  DeclContext *DC = CurContext;
-
   // tryCaptureVariable is called every time a DeclRef is formed,
   // it can therefore have non-negigible impact on performances.
   // For local variables and when there is no capturing scope,
   // we can bailout early.
-  if (CapturingFunctionScopes == 0 && (!BuildAndDiagnose || VarDC == DC))
+  if (CapturingFunctionScopes == 0 && (!BuildAndDiagnose || VarDC == 
CurContext))
 return true;
 
+  DeclContext *DC = ignoreReuquiresBodyDecl(CurContext);
+
   const auto *VD = dyn_cast(Var);
   if (VD) {
 if (VD->isInitCapture())
@@ -19789,11 +19795,10 @@ bool Sema::tryCaptureVariable(
 
 // Only block literals, captured statements, and lambda expressions can
 // capture; other scopes don't work.
-DeclContext *ParentDC =
-!IsInScopeDeclarationContext
-? DC->getParent()
-: getParentOfCapturingContextOrNull(DC, Var, ExprLoc,
-BuildAndDiagnose, *this);
+DeclContext *ParentDC = IsInScopeDeclarationContext
+? getParentOfCapturingContextOrNull(
+  DC, Var, ExprLoc, BuildAndDiagnose, 
*this)
+: DC->getParent();
 // We need to check for the parent *first* because, if we *have*
 // private-captured a global variable, we need to recursively capture it in
 // intermediate blocks, lambdas, etc.
diff --git a/clang/test/SemaCXX/requires-expression-with-capture-variable.cpp 
b/clang/test/SemaCXX/requires-expression-with-capture-variable.cpp
new file mode 100644
index 00..d01a54133f6c39
--- /dev/null
+++ b/clang/test/SemaCXX/requires-expression-with-capture-variable.cpp
@@ -0,0 +1,25 @@
+// RUN: %clang -fsyntax-only -std=c++20 -Xclang -verify %s
+
+// expected-no-diagnostics
+
+auto GH69307_Func_1() {
+  constexpr auto b = 1;
+  return [&](auto c) -> int
+   requires requires { b + c; }
+  { return 1; };
+};
+auto GH69307_Func_Ret = GH69307_Func_1()(1);
+
+auto GH69307_Lambda_1 = []() {
+  return [&](auto c) -> int
+   requires requires { c; }
+  { return 1; };
+};
+auto GH69307_Lambda_1_Ret = GH69307_Lambda_1()(1);
+
+auto GH69307_Lambda_2 = [](auto c) {
+  return [&]() -> int
+   requires requires { c; }
+  { return 1; };
+};
+auto GH69307_Lambda_2_Ret = GH69307_Lambda_2(1)();

>From a99f16ff51702ff249cdf8a47de0cf24a08f694a Mon Sep 17 00:00:00 2001
From: Congcong Cai 
Date: Sat, 20 Jan 2024 13:40:12 +0800
Subject: [PATCH 2/2] another test

---
 clang/test/SemaCXX/warn-unused-lambda-capture-cxx20.cpp | 7 +++
 clang/test/SemaCXX/warn-unused-lambda-capture.cpp   | 4 
 2 files changed, 11 insertions(+)
 create mode 100644 clang/test/SemaCXX/warn-unused-lambda-capture-cxx20.cpp

diff --git a/clang/test/SemaCXX/warn-unused-lambda-capture-cxx20.cpp 
b/clang/test/SemaCXX/warn-unused-lambda-capture-cxx20.cpp
new file mode 100644
index 00..b787edb188ed8b
--- /dev/null
+++ b/clang/test/SemaCXX/warn-unused-lambda-capture-cxx20.cpp
@@ -0,0 +1,7 @@
+// RUN: %clang_cc1 -fsyntax-only -Wunused-lambda-capture 
-Wused-but-marked-unused -Wno-uninitialized -verify -std=c++20 %s
+
+void test() {
+  int i;
+  auto explicit_by_value_unused_requires = [i] (auto) requires requires { i; } 
{}; // expected-warning{{lambda capture 'i' is not required to be captured for 
this use}}
+  explicit_by_value_unused_requires(1);
+}
diff --git a/

[clang] [flang] [libc] [mlir] [clang-tools-extra] [openmp] [libcxx] [compiler-rt] [lldb] [lld] [llvm] [libc++][format] P2637R3: Member `visit` (`std::basic_format_arg`) (PR #76449)

2024-01-19 Thread Hristo Hristov via cfe-commits


@@ -144,7 +144,8 @@ _LIBCPP_HIDE_FROM_ABI decltype(auto) 
__visit_format_arg(_Visitor&& __vis, basic_
   __libcpp_unreachable();
 }
 
-#  if _LIBCPP_STD_VER >= 26
+#  if _LIBCPP_STD_VER >= 26 && (!defined(_LIBCPP_COMPILER_CLANG_BASED) || 
_LIBCPP_CLANG_VER >= 1800)

H-G-Hristov wrote:

> I would go with with a new config variable 
> `_LIBCPP_HAS_EXPLICIT_THIS_PARAMETER`
> 
> ```
> // Clang-18 has support for deducing this, but it does not set the FTM.
> #if defined(__cpp_explicit_this_parameter) || (defined(_LIBCPP_CLANG_VER ) 
> &&_LIBCPP_CLANG_VER >= 1800))
> #  define _LIBCPP_HAS_EXPLICIT_THIS_PARAMETER
> #endif
> ```
> 
> This allows to easily add AppleClang when they support it. For the library we 
> only support GCC and Clang based compilers.

Thank you! Done!

I think we also need to disable the test on Apple Clang, so I added:
`// UNSUPPORTED: clang-16 || clang-17 || apple-clang`

I hope this is the way.

https://github.com/llvm/llvm-project/pull/76449
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][Driver] Fix `--save-temps` for OpenCL AoT compilation (PR #78333)

2024-01-19 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Shilei Tian (shiltian)


Changes

We can directly call `clang -c -x cl -target amdgcn -mcpu=gfx90a test.cl -o 
test.o`
to compile an OpenCL kernel file. However, when `--save-temps` is enabled, it 
doesn't
work because the preprocessed file (`.i` file)  is taken as C source file when 
it
is fed to the front end, thus causing compilation error because those OpenCL 
keywords
can't be recognized. This patch fixes the issue.


---
Full diff: https://github.com/llvm/llvm-project/pull/78333.diff


3 Files Affected:

- (modified) clang/include/clang/Driver/Types.def (+4-2) 
- (modified) clang/lib/Driver/Types.cpp (+6-1) 
- (added) clang/test/Driver/opencl_aot_save_temps.cl (+9) 


``diff
diff --git a/clang/include/clang/Driver/Types.def 
b/clang/include/clang/Driver/Types.def
index b889883125c4c16..f72c27e1ee70193 100644
--- a/clang/include/clang/Driver/Types.def
+++ b/clang/include/clang/Driver/Types.def
@@ -37,8 +37,10 @@
 // C family source language (with and without preprocessing).
 TYPE("cpp-output",   PP_C, INVALID, "i",  
phases::Compile, phases::Backend, phases::Assemble, phases::Link)
 TYPE("c",C,PP_C,"c",  
phases::Preprocess, phases::Compile, phases::Backend, phases::Assemble, 
phases::Link)
-TYPE("cl",   CL,   PP_C,"cl", 
phases::Preprocess, phases::Compile, phases::Backend, phases::Assemble, 
phases::Link)
-TYPE("clcpp",CLCXX,PP_CXX,  "clcpp",  
phases::Preprocess, phases::Compile, phases::Backend, phases::Assemble, 
phases::Link)
+TYPE("cl",   CL,   PP_CL,   "cl", 
phases::Preprocess, phases::Compile, phases::Backend, phases::Assemble, 
phases::Link)
+TYPE("cl-cpp-output",PP_CL,INVALID, "cli",
phases::Compile, phases::Backend, phases::Assemble, phases::Link)
+TYPE("clcpp",CLCXX,PP_CLCXX,"clcpp",  
phases::Preprocess, phases::Compile, phases::Backend, phases::Assemble, 
phases::Link)
+TYPE("clcpp-cpp-output", PP_CLCXX, INVALID, "clii",   
phases::Compile, phases::Backend, phases::Assemble, phases::Link)
 TYPE("cuda-cpp-output",  PP_CUDA,  INVALID, "cui",
phases::Compile, phases::Backend, phases::Assemble, phases::Link)
 TYPE("cuda", CUDA, PP_CUDA, "cu", 
phases::Preprocess, phases::Compile, phases::Backend, phases::Assemble, 
phases::Link)
 TYPE("cuda", CUDA_DEVICE,  PP_CUDA, "cu", 
phases::Preprocess, phases::Compile, phases::Backend, phases::Assemble, 
phases::Link)
diff --git a/clang/lib/Driver/Types.cpp b/clang/lib/Driver/Types.cpp
index 08df34ade7b6530..a7b6b9000e1d2b1 100644
--- a/clang/lib/Driver/Types.cpp
+++ b/clang/lib/Driver/Types.cpp
@@ -133,7 +133,7 @@ bool types::isAcceptedByClang(ID Id) {
 
   case TY_Asm:
   case TY_C: case TY_PP_C:
-  case TY_CL: case TY_CLCXX:
+  case TY_CL: case TY_PP_CL: case TY_CLCXX: case TY_PP_CLCXX:
   case TY_CUDA: case TY_PP_CUDA:
   case TY_CUDA_DEVICE:
   case TY_HIP:
@@ -181,7 +181,9 @@ bool types::isDerivedFromC(ID Id) {
   case TY_PP_C:
   case TY_C:
   case TY_CL:
+  case TY_PP_CL:
   case TY_CLCXX:
+  case TY_PP_CLCXX:
   case TY_PP_CUDA:
   case TY_CUDA:
   case TY_CUDA_DEVICE:
@@ -241,6 +243,7 @@ bool types::isCXX(ID Id) {
   case TY_PP_CXXHeaderUnit:
   case TY_ObjCXXHeader: case TY_PP_ObjCXXHeader:
   case TY_CXXModule: case TY_PP_CXXModule:
+  case TY_PP_CLCXX:
   case TY_CUDA: case TY_PP_CUDA: case TY_CUDA_DEVICE:
   case TY_HIP:
   case TY_PP_HIP:
@@ -310,7 +313,9 @@ types::ID types::lookupTypeForExtension(llvm::StringRef 
Ext) {
   .Case("cc", TY_CXX)
   .Case("CC", TY_CXX)
   .Case("cl", TY_CL)
+  .Case("cli", TY_PP_CL)
   .Case("clcpp", TY_CLCXX)
+  .Case("clii", TY_PP_CLCXX)
   .Case("cp", TY_CXX)
   .Case("cu", TY_CUDA)
   .Case("hh", TY_CXXHeader)
diff --git a/clang/test/Driver/opencl_aot_save_temps.cl 
b/clang/test/Driver/opencl_aot_save_temps.cl
new file mode 100644
index 000..d858992eb59b789
--- /dev/null
+++ b/clang/test/Driver/opencl_aot_save_temps.cl
@@ -0,0 +1,9 @@
+// RUN: %clang -x cl -c %s
+// RUN: %clang -x cl --save-temps -c %s
+
+uint3 add(uint3 a, uint3 b) {
+  ulong x = a.x + (ulong)b.x;
+  ulong y = a.y + (ulong)b.y + (x >> 32);
+  uint z = a.z + b.z + (y >> 32);
+  return (uint3)(x, y, z);
+}

``




https://github.com/llvm/llvm-project/pull/78333
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][Driver] Fix `--save-temps` for OpenCL AoT compilation (PR #78333)

2024-01-19 Thread Shilei Tian via cfe-commits

https://github.com/shiltian ready_for_review 
https://github.com/llvm/llvm-project/pull/78333
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][Driver] Fix `--save-temps` for OpenCL AoT compilation (PR #78333)

2024-01-19 Thread Shilei Tian via cfe-commits

https://github.com/shiltian updated 
https://github.com/llvm/llvm-project/pull/78333

>From 837a9fd2c1fac7dcdf2c8538e6634eccf36ee7b6 Mon Sep 17 00:00:00 2001
From: Shilei Tian 
Date: Fri, 19 Jan 2024 23:46:54 -0500
Subject: [PATCH] [Clang][Driver] Fix `--save-temps` for OpenCL AoT compilation

We can directly call `clang -c -x cl -target amdgcn -mcpu=gfx90a test.cl -o 
test.o`
to compile an OpenCL kernel file. However, when `--save-temps` is enabled, it 
doesn't
work because the preprocessed file (`.i` file)  is taken as C source file when 
it
is fed to the front end, thus causing compilation error because those OpenCL 
keywords
can't be recognized. This patch fixes the issue.
---
 clang/include/clang/Driver/Types.def   | 6 --
 clang/lib/Driver/Types.cpp | 7 ++-
 clang/test/Driver/opencl_aot_save_temps.cl | 9 +
 3 files changed, 19 insertions(+), 3 deletions(-)
 create mode 100644 clang/test/Driver/opencl_aot_save_temps.cl

diff --git a/clang/include/clang/Driver/Types.def 
b/clang/include/clang/Driver/Types.def
index b889883125c4c16..f72c27e1ee70193 100644
--- a/clang/include/clang/Driver/Types.def
+++ b/clang/include/clang/Driver/Types.def
@@ -37,8 +37,10 @@
 // C family source language (with and without preprocessing).
 TYPE("cpp-output",   PP_C, INVALID, "i",  
phases::Compile, phases::Backend, phases::Assemble, phases::Link)
 TYPE("c",C,PP_C,"c",  
phases::Preprocess, phases::Compile, phases::Backend, phases::Assemble, 
phases::Link)
-TYPE("cl",   CL,   PP_C,"cl", 
phases::Preprocess, phases::Compile, phases::Backend, phases::Assemble, 
phases::Link)
-TYPE("clcpp",CLCXX,PP_CXX,  "clcpp",  
phases::Preprocess, phases::Compile, phases::Backend, phases::Assemble, 
phases::Link)
+TYPE("cl",   CL,   PP_CL,   "cl", 
phases::Preprocess, phases::Compile, phases::Backend, phases::Assemble, 
phases::Link)
+TYPE("cl-cpp-output",PP_CL,INVALID, "cli",
phases::Compile, phases::Backend, phases::Assemble, phases::Link)
+TYPE("clcpp",CLCXX,PP_CLCXX,"clcpp",  
phases::Preprocess, phases::Compile, phases::Backend, phases::Assemble, 
phases::Link)
+TYPE("clcpp-cpp-output", PP_CLCXX, INVALID, "clii",   
phases::Compile, phases::Backend, phases::Assemble, phases::Link)
 TYPE("cuda-cpp-output",  PP_CUDA,  INVALID, "cui",
phases::Compile, phases::Backend, phases::Assemble, phases::Link)
 TYPE("cuda", CUDA, PP_CUDA, "cu", 
phases::Preprocess, phases::Compile, phases::Backend, phases::Assemble, 
phases::Link)
 TYPE("cuda", CUDA_DEVICE,  PP_CUDA, "cu", 
phases::Preprocess, phases::Compile, phases::Backend, phases::Assemble, 
phases::Link)
diff --git a/clang/lib/Driver/Types.cpp b/clang/lib/Driver/Types.cpp
index 08df34ade7b6530..a7b6b9000e1d2b1 100644
--- a/clang/lib/Driver/Types.cpp
+++ b/clang/lib/Driver/Types.cpp
@@ -133,7 +133,7 @@ bool types::isAcceptedByClang(ID Id) {
 
   case TY_Asm:
   case TY_C: case TY_PP_C:
-  case TY_CL: case TY_CLCXX:
+  case TY_CL: case TY_PP_CL: case TY_CLCXX: case TY_PP_CLCXX:
   case TY_CUDA: case TY_PP_CUDA:
   case TY_CUDA_DEVICE:
   case TY_HIP:
@@ -181,7 +181,9 @@ bool types::isDerivedFromC(ID Id) {
   case TY_PP_C:
   case TY_C:
   case TY_CL:
+  case TY_PP_CL:
   case TY_CLCXX:
+  case TY_PP_CLCXX:
   case TY_PP_CUDA:
   case TY_CUDA:
   case TY_CUDA_DEVICE:
@@ -241,6 +243,7 @@ bool types::isCXX(ID Id) {
   case TY_PP_CXXHeaderUnit:
   case TY_ObjCXXHeader: case TY_PP_ObjCXXHeader:
   case TY_CXXModule: case TY_PP_CXXModule:
+  case TY_PP_CLCXX:
   case TY_CUDA: case TY_PP_CUDA: case TY_CUDA_DEVICE:
   case TY_HIP:
   case TY_PP_HIP:
@@ -310,7 +313,9 @@ types::ID types::lookupTypeForExtension(llvm::StringRef 
Ext) {
   .Case("cc", TY_CXX)
   .Case("CC", TY_CXX)
   .Case("cl", TY_CL)
+  .Case("cli", TY_PP_CL)
   .Case("clcpp", TY_CLCXX)
+  .Case("clii", TY_PP_CLCXX)
   .Case("cp", TY_CXX)
   .Case("cu", TY_CUDA)
   .Case("hh", TY_CXXHeader)
diff --git a/clang/test/Driver/opencl_aot_save_temps.cl 
b/clang/test/Driver/opencl_aot_save_temps.cl
new file mode 100644
index 000..d858992eb59b789
--- /dev/null
+++ b/clang/test/Driver/opencl_aot_save_temps.cl
@@ -0,0 +1,9 @@
+// RUN: %clang -x cl -c %s
+// RUN: %clang -x cl --save-temps -c %s
+
+uint3 add(uint3 a, uint3 b) {
+  ulong x = a.x + (ulong)b.x;
+  ulong y = a.y + (ulong)b.y + (x >> 32);
+  uint z = a.z + b.z + (y >> 32);
+  return (uint3)(x, y, z);
+}

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang-repl] Add a interpreter-specific overload of operator new for C++ (PR #76218)

2024-01-19 Thread Vitaly Buka via cfe-commits

vitalybuka wrote:

Yes, it fixes the leak but on asan bot it's mismatch 

https://lab.llvm.org/buildbot/#/builders/168/builds/18159/steps/10/logs/stdio

https://github.com/llvm/llvm-project/pull/76218
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[llvm] [lld] [clang] [SHT_LLVM_BB_ADDR_MAP] Allow basic-block-sections and labels be used together by decoupling the handling of the two features. (PR #74128)

2024-01-19 Thread via cfe-commits


@@ -1401,17 +1406,48 @@ void AsmPrinter::emitBBAddrMapSection(const 
MachineFunction &MF) {
   uint8_t BBAddrMapVersion = OutStreamer->getContext().getBBAddrMapVersion();
   OutStreamer->emitInt8(BBAddrMapVersion);
   OutStreamer->AddComment("feature");
-  auto FeaturesBits = static_cast(PgoAnalysisMapFeatures.getBits());
-  OutStreamer->emitInt8(FeaturesBits);
-  OutStreamer->AddComment("function address");
-  OutStreamer->emitSymbolValue(FunctionSymbol, getPointerSize());
-  OutStreamer->AddComment("number of basic blocks");
-  OutStreamer->emitULEB128IntValue(MF.size());
-  const MCSymbol *PrevMBBEndSymbol = FunctionSymbol;
+  auto Features = getBBAddrMapFeature(MF, MBBSectionRanges.size());
+  OutStreamer->emitInt8(Features.encode());
   // Emit BB Information for each basic block in the function.
+  if (Features.MultiBBRange) {
+OutStreamer->AddComment("number of basic block ranges");
+OutStreamer->emitULEB128IntValue(MBBSectionRanges.size());
+  }
+  // Number of blocks in each MBB section.
+  MapVector MBBSectionNumBlocks;
+  const MCSymbol *PrevMBBEndSymbol = nullptr;
+  if (!Features.MultiBBRange) {
+OutStreamer->AddComment("function address");

lifengxiang1025 wrote:

Thanks. I understand your point now.

https://github.com/llvm/llvm-project/pull/74128
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][Sema] fix outline member function template with default align crash (PR #78400)

2024-01-19 Thread Qizhi Hu via cfe-commits

https://github.com/jcsxky updated 
https://github.com/llvm/llvm-project/pull/78400

>From 774f1abbe16cd642b0838105f68e5c5d02e37aef Mon Sep 17 00:00:00 2001
From: huqizhi 
Date: Wed, 17 Jan 2024 14:16:34 +0800
Subject: [PATCH] [Clang][Sema] fix outline member function template with
 default align crash

---
 clang/lib/Sema/SemaTemplateInstantiate.cpp| 12 -
 clang/test/SemaTemplate/default-parm-init.cpp | 50 +++
 2 files changed, 60 insertions(+), 2 deletions(-)
 create mode 100644 clang/test/SemaTemplate/default-parm-init.cpp

diff --git a/clang/lib/Sema/SemaTemplateInstantiate.cpp 
b/clang/lib/Sema/SemaTemplateInstantiate.cpp
index fc80515b45e35b..1ed63db75294aa 100644
--- a/clang/lib/Sema/SemaTemplateInstantiate.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiate.cpp
@@ -3051,6 +3051,7 @@ bool Sema::SubstDefaultArgument(
 //   default argument expression appears.
 ContextRAII SavedContext(*this, FD);
 std::unique_ptr LIS;
+auto NewTemplateArgs = TemplateArgs;
 
 if (ForCallExpr) {
   // When instantiating a default argument due to use in a call expression,
@@ -3063,11 +3064,18 @@ bool Sema::SubstDefaultArgument(
   /*ForDefinition*/ false);
   if (addInstantiatedParametersToScope(FD, PatternFD, *LIS, TemplateArgs))
 return true;
+  if (FD->isOutOfLine()) {
+auto *CurrentTemplateArgumentList = TemplateArgumentList::CreateCopy(
+getASTContext(), TemplateArgs.getInnermost());
+NewTemplateArgs = getTemplateInstantiationArgs(
+FD, FD->getDeclContext(), true, CurrentTemplateArgumentList, true,
+nullptr, false, false);
+  }
 }
 
 runWithSufficientStackSpace(Loc, [&] {
-  Result = SubstInitializer(PatternExpr, TemplateArgs,
-/*DirectInit*/false);
+  Result = SubstInitializer(PatternExpr, NewTemplateArgs,
+/*DirectInit*/ false);
 });
   }
   if (Result.isInvalid())
diff --git a/clang/test/SemaTemplate/default-parm-init.cpp 
b/clang/test/SemaTemplate/default-parm-init.cpp
new file mode 100644
index 00..4bcea7eaa10176
--- /dev/null
+++ b/clang/test/SemaTemplate/default-parm-init.cpp
@@ -0,0 +1,50 @@
+// RUN: %clang_cc1 -fsyntax-only -std=c++17 -verify %s
+// RUN: %clang_cc1 -fsyntax-only -std=c++20 -verify %s
+// expected-no-diagnostics
+
+template
+struct Problem{
+  template
+  constexpr int FuncAlign(int param = alignof(FunctionTemplateParam));
+
+  template
+  constexpr int FuncSizeof(int param = sizeof(FunctionTemplateParam));
+
+  template
+  constexpr int FuncAlign2(int param = alignof(TemplateParam));
+
+  template
+  constexpr int FuncSizeof2(int param = sizeof(TemplateParam));
+};
+
+template <>
+template
+constexpr int Problem::FuncAlign(int param) {
+   return param;
+}
+
+template <>
+template
+constexpr int Problem::FuncSizeof(int param) {
+   return param;
+}
+
+template <>
+template
+constexpr int Problem::FuncAlign2(int param) {
+   return param;
+}
+
+template <>
+template
+constexpr int Problem::FuncSizeof2(int param) {
+   return param;
+}
+
+int main(){
+Problem p = {};
+static_assert(p.FuncAlign() == alignof(char));
+static_assert(p.FuncSizeof() == sizeof(char));
+static_assert(p.FuncAlign2() == alignof(int));
+static_assert(p.FuncSizeof2() == sizeof(int));
+}

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang] [libc] [libunwind] [lldb] [flang] [llvm] [libcxxabi] [compiler-rt] [libcxx] [libc++][span] P2447R4: `std::span` over an initializer list (PR #78157)

2024-01-19 Thread Hristo Hristov via cfe-commits

https://github.com/Zingam closed https://github.com/llvm/llvm-project/pull/78157
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang] [libc] [libunwind] [lldb] [polly] [flang] [llvm] [libcxxabi] [compiler-rt] [libcxx] [mlir] [libc++][any] LWG3305: `any_cast` (PR #78215)

2024-01-19 Thread Hristo Hristov via cfe-commits

https://github.com/Zingam closed https://github.com/llvm/llvm-project/pull/78215
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang] [openmp] [libc] [lldb] [lld] [flang] [llvm] [compiler-rt] [libcxx] [mlir] [libc++][memory] P2868R1: Removing deprecated typedef `std::allocator::is_always_equal` (PR #78562

2024-01-19 Thread Hristo Hristov via cfe-commits

https://github.com/Zingam closed https://github.com/llvm/llvm-project/pull/78562
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang] [libc] [lldb] [lld] [flang] [llvm] [compiler-rt] [libcxx] [mlir] Reland "[clang] Fix CTAD for aggregates for nested template classes" (PR #78670)

2024-01-19 Thread via cfe-commits

https://github.com/antangelo closed 
https://github.com/llvm/llvm-project/pull/78670
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] b3ea9b3 - Reland "[clang] Fix CTAD for aggregates for nested template classes" (#78670)

2024-01-19 Thread via cfe-commits

Author: antangelo
Date: 2024-01-19T23:06:44-05:00
New Revision: b3ea9b398fe656fab5d78d6b2c58bba975badc07

URL: 
https://github.com/llvm/llvm-project/commit/b3ea9b398fe656fab5d78d6b2c58bba975badc07
DIFF: 
https://github.com/llvm/llvm-project/commit/b3ea9b398fe656fab5d78d6b2c58bba975badc07.diff

LOG: Reland "[clang] Fix CTAD for aggregates for nested template classes" 
(#78670)

Reland of #78387

Use the template pattern in determining whether to synthesize the
aggregate deduction guide, and update
DeclareImplicitDeductionGuideFromInitList to substitute outer template
arguments.

The tests in the original patch made an assumption about the size of a
pointer type, and this led to them failing on targets with 32-bit
pointers. The tests have been updated to not depend on the size of any
type. This only requires updates to the test file, no functionality has
otherwise changed between this and the original patch.

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Sema/SemaInit.cpp
clang/lib/Sema/SemaTemplate.cpp
clang/test/SemaTemplate/nested-implicit-deduction-guides.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 585e1535b15852..08e79984fe3362 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -1001,6 +1001,9 @@ Bug Fixes to C++ Support
 - Clang now allows parenthesized initialization of arrays in `operator new[]`.
   Fixes: (`#68198 `_)
 
+- Fixes CTAD for aggregates on nested template classes. Fixes:
+  (`#77599 `_)
+
 - Fix crash when importing the same module with an dynamic initializer twice
   in 
diff erent visibility.
   Fixes (`#67893 `_)

diff  --git a/clang/lib/Sema/SemaInit.cpp b/clang/lib/Sema/SemaInit.cpp
index 3170f41e8033f2..91e4cb7b68a24a 100644
--- a/clang/lib/Sema/SemaInit.cpp
+++ b/clang/lib/Sema/SemaInit.cpp
@@ -10751,7 +10751,14 @@ QualType 
Sema::DeduceTemplateSpecializationFromInitializer(
 bool HasAnyDeductionGuide = false;
 
 auto SynthesizeAggrGuide = [&](InitListExpr *ListInit) {
-  auto *RD = cast(Template->getTemplatedDecl());
+  auto *Pattern = Template;
+  while (Pattern->getInstantiatedFromMemberTemplate()) {
+if (Pattern->isMemberSpecialization())
+  break;
+Pattern = Pattern->getInstantiatedFromMemberTemplate();
+  }
+
+  auto *RD = cast(Pattern->getTemplatedDecl());
   if (!(RD->getDefinition() && RD->isAggregate()))
 return;
   QualType Ty = Context.getRecordType(RD);

diff  --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp
index 0655d363352067..839d508b911f06 100644
--- a/clang/lib/Sema/SemaTemplate.cpp
+++ b/clang/lib/Sema/SemaTemplate.cpp
@@ -2418,6 +2418,9 @@ struct ConvertConstructorToDeductionGuideTransform {
 QualType Result = SemaRef.BuildFunctionType(DeducedType, ParamTypes, Loc,
 DeductionGuideName, EPI);
 TypeSourceInfo *TSI = SemaRef.Context.getTrivialTypeSourceInfo(Result, 
Loc);
+if (NestedPattern)
+  TSI = SemaRef.SubstType(TSI, OuterInstantiationArgs, Loc,
+  DeductionGuideName);
 
 FunctionProtoTypeLoc FPTL =
 TSI->getTypeLoc().castAs();
@@ -2425,9 +2428,13 @@ struct ConvertConstructorToDeductionGuideTransform {
 // Build the parameters, needed during deduction / substitution.
 SmallVector Params;
 for (auto T : ParamTypes) {
-  ParmVarDecl *NewParam = ParmVarDecl::Create(
-  SemaRef.Context, DC, Loc, Loc, nullptr, T,
-  SemaRef.Context.getTrivialTypeSourceInfo(T, Loc), SC_None, nullptr);
+  auto *TSI = SemaRef.Context.getTrivialTypeSourceInfo(T, Loc);
+  if (NestedPattern)
+TSI = SemaRef.SubstType(TSI, OuterInstantiationArgs, Loc,
+DeclarationName());
+  ParmVarDecl *NewParam =
+  ParmVarDecl::Create(SemaRef.Context, DC, Loc, Loc, nullptr,
+  TSI->getType(), TSI, SC_None, nullptr);
   NewParam->setScopeInfo(0, Params.size());
   FPTL.setParam(Params.size(), NewParam);
   Params.push_back(NewParam);
@@ -2670,8 +2677,14 @@ FunctionTemplateDecl 
*Sema::DeclareImplicitDeductionGuideFromInitList(
   if (BuildingDeductionGuides.isInvalid())
 return nullptr;
 
-  return cast(
+  ClassTemplateDecl *Pattern =
+  Transform.NestedPattern ? Transform.NestedPattern : Transform.Template;
+  ContextRAII SavedContext(*this, Pattern->getTemplatedDecl());
+
+  auto *DG = cast(
   Transform.buildSimpleDeductionGuide(ParamTypes));
+  SavedContext.pop();
+  return DG;
 }
 
 void Sema::DeclareImplicitDeductionGuides(TemplateDecl *Template,

diff  --git a/clang/test/SemaTemplate/nested-implicit-deduction-guide

[clang-tools-extra] [clang] [libc] [lldb] [lld] [flang] [llvm] [compiler-rt] [libcxx] [mlir] Reland "[clang] Fix CTAD for aggregates for nested template classes" (PR #78670)

2024-01-19 Thread via cfe-commits

antangelo wrote:

Thanks for the review! Apologies for the delayed response but I'm available to 
merge this in now.

https://github.com/llvm/llvm-project/pull/78670
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][CodeGen] Emit atomic IR in place of optimized libcalls. (PR #73176)

2024-01-19 Thread James Y Knight via cfe-commits

jyknight wrote:

BTW, please don't rebase/amend commits and force-push, it makes a it extremely 
difficult to review the changes since the previous review -- especially if the 
new changes are commingled with a rebase.

Much better to simply push new commits on top of your existing branch. And if 
you need an updated baseline, you can `git merge origin/main` in your PR branch.

https://github.com/llvm/llvm-project/pull/73176
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[llvm] [clang] [clang, SystemZ] Pass HasDef flag to getMinGlobalAlign(). (PR #73511)

2024-01-19 Thread NAKAMURA Takumi via cfe-commits

https://github.com/chapuni approved this pull request.

Looks good from my side -- please wait for other opinions.

https://github.com/llvm/llvm-project/pull/73511
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[llvm] [clang] [clang, SystemZ] Pass HasDef flag to getMinGlobalAlign(). (PR #73511)

2024-01-19 Thread NAKAMURA Takumi via cfe-commits


@@ -11,6 +11,7 @@
 
//===--===//
 
 #include "SystemZ.h"
+#include "clang/AST/Decl.h"

chapuni wrote:

Thanks!

https://github.com/llvm/llvm-project/pull/73511
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][analyzer] Support 'getdelim' and 'getline' in StreamChecker (PR #78693)

2024-01-19 Thread Ben Shi via cfe-commits

benshi001 wrote:

> I have already a working code to simplify code repetitions, but want to merge 
> first patches #76979 and #78180 (@NagyDonat could you look at these too?).

How about merge this patch first, then apply your simplification one? Since my 
current one also is affected.

https://github.com/llvm/llvm-project/pull/78693
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][analyzer] Add missing stream related functions to StdLibraryFunctionsChecker. (PR #76979)

2024-01-19 Thread Ben Shi via cfe-commits
=?utf-8?q?Bal=C3=A1zs_K=C3=A9ri?= ,
=?utf-8?q?Bal=C3=A1zs_K=C3=A9ri?= ,
=?utf-8?q?Bal=C3=A1zs_K=C3=A9ri?= 
Message-ID:
In-Reply-To: 



@@ -2201,6 +2214,56 @@ void StdLibraryFunctionsChecker::initFunctionSummaries(
   ErrnoNEZeroIrrelevant, GenericFailureMsg)
 .ArgConstraint(NotNull(ArgNo(0;
 
+// int fgetc(FILE *stream);
+// 'getc' is the same as 'fgetc' but may be a macro
+addToFunctionSummaryMap(
+{"getc", "fgetc"}, Signature(ArgTypes{FilePtrTy}, RetType{IntTy}),
+Summary(NoEvalCall)
+.Case({ReturnValueCondition(WithinRange, {{0, UCharRangeMax}})},
+  ErrnoMustNotBeChecked, GenericSuccessMsg)
+.Case({ReturnValueCondition(WithinRange, SingleValue(EOFv))},
+  ErrnoNEZeroIrrelevant, GenericFailureMsg)
+.ArgConstraint(NotNull(ArgNo(0;
+
+// int fputc(int c, FILE *stream);
+// 'putc' is the same as 'fputc' but may be a macro
+addToFunctionSummaryMap(
+{"putc", "fputc"},
+Signature(ArgTypes{IntTy, FilePtrTy}, RetType{IntTy}),
+Summary(NoEvalCall)
+.Case({ReturnValueCondition(BO_EQ, ArgNo(0))},
+  ErrnoMustNotBeChecked, GenericSuccessMsg)
+.Case({ReturnValueCondition(WithinRange, SingleValue(EOFv))},
+  ErrnoNEZeroIrrelevant, GenericFailureMsg)
+.ArgConstraint(NotNull(ArgNo(1)))
+.ArgConstraint(
+ArgumentCondition(0, WithinRange, {{0, UCharRangeMax}})));
+
+// char *fgets(char *restrict s, int n, FILE *restrict stream);
+addToFunctionSummaryMap(
+"fgets",
+Signature(ArgTypes{CharPtrRestrictTy, IntTy, FilePtrRestrictTy},
+  RetType{CharPtrTy}),
+Summary(NoEvalCall)
+.Case({ReturnValueCondition(BO_EQ, ArgNo(0))},
+  ErrnoMustNotBeChecked, GenericSuccessMsg)
+.Case({IsNull(Ret)}, ErrnoNEZeroIrrelevant, GenericFailureMsg)
+.ArgConstraint(NotNull(ArgNo(0)))

benshi001 wrote:

also it would be better to add a `FIXME` here.

https://github.com/llvm/llvm-project/pull/76979
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][analyzer] Add missing stream related functions to StdLibraryFunctionsChecker. (PR #76979)

2024-01-19 Thread Ben Shi via cfe-commits
=?utf-8?q?Balázs_Kéri?= ,
=?utf-8?q?Balázs_Kéri?= ,
=?utf-8?q?Balázs_Kéri?= 
Message-ID:
In-Reply-To: 



@@ -2201,6 +2214,56 @@ void StdLibraryFunctionsChecker::initFunctionSummaries(
   ErrnoNEZeroIrrelevant, GenericFailureMsg)
 .ArgConstraint(NotNull(ArgNo(0;
 
+// int fgetc(FILE *stream);
+// 'getc' is the same as 'fgetc' but may be a macro
+addToFunctionSummaryMap(
+{"getc", "fgetc"}, Signature(ArgTypes{FilePtrTy}, RetType{IntTy}),
+Summary(NoEvalCall)
+.Case({ReturnValueCondition(WithinRange, {{0, UCharRangeMax}})},
+  ErrnoMustNotBeChecked, GenericSuccessMsg)
+.Case({ReturnValueCondition(WithinRange, SingleValue(EOFv))},
+  ErrnoNEZeroIrrelevant, GenericFailureMsg)
+.ArgConstraint(NotNull(ArgNo(0;

benshi001 wrote:

As far as my understanding, `fgetc` does not always set the `errno` even if 
`EOF` is returned, this happens if there is no error but reach the end of file.

https://pubs.opengroup.org/onlinepubs/9699919799/

https://github.com/llvm/llvm-project/pull/76979
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][analyzer] Add missing stream related functions to StdLibraryFunctionsChecker. (PR #76979)

2024-01-19 Thread Ben Shi via cfe-commits
=?utf-8?q?Bal=C3=A1zs_K=C3=A9ri?= ,
=?utf-8?q?Bal=C3=A1zs_K=C3=A9ri?= ,
=?utf-8?q?Bal=C3=A1zs_K=C3=A9ri?= 
Message-ID:
In-Reply-To: 



@@ -2201,6 +2214,56 @@ void StdLibraryFunctionsChecker::initFunctionSummaries(
   ErrnoNEZeroIrrelevant, GenericFailureMsg)
 .ArgConstraint(NotNull(ArgNo(0;
 
+// int fgetc(FILE *stream);
+// 'getc' is the same as 'fgetc' but may be a macro
+addToFunctionSummaryMap(
+{"getc", "fgetc"}, Signature(ArgTypes{FilePtrTy}, RetType{IntTy}),
+Summary(NoEvalCall)
+.Case({ReturnValueCondition(WithinRange, {{0, UCharRangeMax}})},
+  ErrnoMustNotBeChecked, GenericSuccessMsg)
+.Case({ReturnValueCondition(WithinRange, SingleValue(EOFv))},
+  ErrnoNEZeroIrrelevant, GenericFailureMsg)
+.ArgConstraint(NotNull(ArgNo(0;
+
+// int fputc(int c, FILE *stream);
+// 'putc' is the same as 'fputc' but may be a macro
+addToFunctionSummaryMap(
+{"putc", "fputc"},
+Signature(ArgTypes{IntTy, FilePtrTy}, RetType{IntTy}),
+Summary(NoEvalCall)
+.Case({ReturnValueCondition(BO_EQ, ArgNo(0))},
+  ErrnoMustNotBeChecked, GenericSuccessMsg)
+.Case({ReturnValueCondition(WithinRange, SingleValue(EOFv))},
+  ErrnoNEZeroIrrelevant, GenericFailureMsg)
+.ArgConstraint(NotNull(ArgNo(1)))
+.ArgConstraint(
+ArgumentCondition(0, WithinRange, {{0, UCharRangeMax}})));
+
+// char *fgets(char *restrict s, int n, FILE *restrict stream);
+addToFunctionSummaryMap(
+"fgets",
+Signature(ArgTypes{CharPtrRestrictTy, IntTy, FilePtrRestrictTy},
+  RetType{CharPtrTy}),
+Summary(NoEvalCall)
+.Case({ReturnValueCondition(BO_EQ, ArgNo(0))},
+  ErrnoMustNotBeChecked, GenericSuccessMsg)
+.Case({IsNull(Ret)}, ErrnoNEZeroIrrelevant, GenericFailureMsg)
+.ArgConstraint(NotNull(ArgNo(0)))

benshi001 wrote:

The same concern if `EOF` is returned but no error happened, as `fgetc`

https://github.com/llvm/llvm-project/pull/76979
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][analyzer] Add missing stream related functions to StdLibraryFunctionsChecker. (PR #76979)

2024-01-19 Thread Ben Shi via cfe-commits
=?utf-8?q?Balázs_Kéri?= ,
=?utf-8?q?Balázs_Kéri?= ,
=?utf-8?q?Balázs_Kéri?= 
Message-ID:
In-Reply-To: 



@@ -2201,6 +2214,56 @@ void StdLibraryFunctionsChecker::initFunctionSummaries(
   ErrnoNEZeroIrrelevant, GenericFailureMsg)
 .ArgConstraint(NotNull(ArgNo(0;
 
+// int fgetc(FILE *stream);
+// 'getc' is the same as 'fgetc' but may be a macro
+addToFunctionSummaryMap(
+{"getc", "fgetc"}, Signature(ArgTypes{FilePtrTy}, RetType{IntTy}),
+Summary(NoEvalCall)
+.Case({ReturnValueCondition(WithinRange, {{0, UCharRangeMax}})},
+  ErrnoMustNotBeChecked, GenericSuccessMsg)
+.Case({ReturnValueCondition(WithinRange, SingleValue(EOFv))},
+  ErrnoNEZeroIrrelevant, GenericFailureMsg)
+.ArgConstraint(NotNull(ArgNo(0;

benshi001 wrote:

I accept this form. But it would be better to add a `FIXME: when reaching the 
end of  file, EOF is returned but errno is not set`.

https://github.com/llvm/llvm-project/pull/76979
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][analyzer] Add missing stream related functions to StdLibraryFunctionsChecker. (PR #76979)

2024-01-19 Thread Ben Shi via cfe-commits
=?utf-8?q?Balázs_Kéri?= ,
=?utf-8?q?Balázs_Kéri?= ,
=?utf-8?q?Balázs_Kéri?= 
Message-ID:
In-Reply-To: 



@@ -2201,6 +2214,56 @@ void StdLibraryFunctionsChecker::initFunctionSummaries(
   ErrnoNEZeroIrrelevant, GenericFailureMsg)
 .ArgConstraint(NotNull(ArgNo(0;
 
+// int fgetc(FILE *stream);
+// 'getc' is the same as 'fgetc' but may be a macro
+addToFunctionSummaryMap(
+{"getc", "fgetc"}, Signature(ArgTypes{FilePtrTy}, RetType{IntTy}),
+Summary(NoEvalCall)
+.Case({ReturnValueCondition(WithinRange, {{0, UCharRangeMax}})},
+  ErrnoMustNotBeChecked, GenericSuccessMsg)
+.Case({ReturnValueCondition(WithinRange, SingleValue(EOFv))},
+  ErrnoNEZeroIrrelevant, GenericFailureMsg)
+.ArgConstraint(NotNull(ArgNo(0;
+
+// int fputc(int c, FILE *stream);
+// 'putc' is the same as 'fputc' but may be a macro
+addToFunctionSummaryMap(
+{"putc", "fputc"},
+Signature(ArgTypes{IntTy, FilePtrTy}, RetType{IntTy}),
+Summary(NoEvalCall)
+.Case({ReturnValueCondition(BO_EQ, ArgNo(0))},
+  ErrnoMustNotBeChecked, GenericSuccessMsg)
+.Case({ReturnValueCondition(WithinRange, SingleValue(EOFv))},
+  ErrnoNEZeroIrrelevant, GenericFailureMsg)
+.ArgConstraint(NotNull(ArgNo(1)))
+.ArgConstraint(
+ArgumentCondition(0, WithinRange, {{0, UCharRangeMax}})));
+
+// char *fgets(char *restrict s, int n, FILE *restrict stream);
+addToFunctionSummaryMap(
+"fgets",
+Signature(ArgTypes{CharPtrRestrictTy, IntTy, FilePtrRestrictTy},
+  RetType{CharPtrTy}),
+Summary(NoEvalCall)
+.Case({ReturnValueCondition(BO_EQ, ArgNo(0))},
+  ErrnoMustNotBeChecked, GenericSuccessMsg)
+.Case({IsNull(Ret)}, ErrnoNEZeroIrrelevant, GenericFailureMsg)
+.ArgConstraint(NotNull(ArgNo(0)))
+.ArgConstraint(ArgumentCondition(1, WithinRange, Range(0, IntMax)))
+.ArgConstraint(NotNull(ArgNo(2;

benshi001 wrote:

```
.ArgConstraint(
BufferSize(/*Buffer*/ ArgNo(0), /*BufSize*/ ArgNo(1)))
```

https://github.com/llvm/llvm-project/pull/76979
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][analyzer] Add missing stream related functions to StdLibraryFunctionsChecker. (PR #76979)

2024-01-19 Thread Ben Shi via cfe-commits
=?utf-8?q?Balázs_Kéri?= ,
=?utf-8?q?Balázs_Kéri?= ,
=?utf-8?q?Balázs_Kéri?= 
Message-ID:
In-Reply-To: 


https://github.com/benshi001 edited 
https://github.com/llvm/llvm-project/pull/76979
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][analyzer] Add missing stream related functions to StdLibraryFunctionsChecker. (PR #76979)

2024-01-19 Thread Ben Shi via cfe-commits
=?utf-8?q?Balázs_Kéri?= ,
=?utf-8?q?Balázs_Kéri?= ,
=?utf-8?q?Balázs_Kéri?= 
Message-ID:
In-Reply-To: 



@@ -2201,6 +2214,56 @@ void StdLibraryFunctionsChecker::initFunctionSummaries(
   ErrnoNEZeroIrrelevant, GenericFailureMsg)
 .ArgConstraint(NotNull(ArgNo(0;
 
+// int fgetc(FILE *stream);
+// 'getc' is the same as 'fgetc' but may be a macro
+addToFunctionSummaryMap(
+{"getc", "fgetc"}, Signature(ArgTypes{FilePtrTy}, RetType{IntTy}),
+Summary(NoEvalCall)
+.Case({ReturnValueCondition(WithinRange, {{0, UCharRangeMax}})},
+  ErrnoMustNotBeChecked, GenericSuccessMsg)
+.Case({ReturnValueCondition(WithinRange, SingleValue(EOFv))},
+  ErrnoNEZeroIrrelevant, GenericFailureMsg)
+.ArgConstraint(NotNull(ArgNo(0;
+
+// int fputc(int c, FILE *stream);
+// 'putc' is the same as 'fputc' but may be a macro
+addToFunctionSummaryMap(
+{"putc", "fputc"},
+Signature(ArgTypes{IntTy, FilePtrTy}, RetType{IntTy}),
+Summary(NoEvalCall)
+.Case({ReturnValueCondition(BO_EQ, ArgNo(0))},
+  ErrnoMustNotBeChecked, GenericSuccessMsg)
+.Case({ReturnValueCondition(WithinRange, SingleValue(EOFv))},
+  ErrnoNEZeroIrrelevant, GenericFailureMsg)
+.ArgConstraint(NotNull(ArgNo(1)))
+.ArgConstraint(
+ArgumentCondition(0, WithinRange, {{0, UCharRangeMax}})));

benshi001 wrote:

I would prefer

```
addToFunctionSummaryMap(
"fputc", Signature(ArgTypes{IntTy, FilePtrTy}, RetType{IntTy}),
Summary(NoEvalCall)
.Case({ArgumentCondition(0, WithinRange, Range(0, UCharRangeMax)),
   ReturnValueCondition(BO_EQ, ArgNo(0))},
  ErrnoMustNotBeChecked, GenericSuccessMsg)
.Case({ArgumentCondition(0, OutOfRange, Range(0, UCharRangeMax)),
   ReturnValueCondition(WithinRange, Range(0, UCharRangeMax))},
  ErrnoMustNotBeChecked, GenericSuccessMsg)
.Case({ReturnValueCondition(WithinRange, SingleValue(EOFv))},
  ErrnoNEZeroIrrelevant, GenericFailureMsg)
.ArgConstraint(NotNull(ArgNo(1;
```


https://github.com/llvm/llvm-project/pull/76979
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][analyzer] Add missing stream related functions to StdLibraryFunctionsChecker. (PR #76979)

2024-01-19 Thread Ben Shi via cfe-commits
=?utf-8?q?Bal=C3=A1zs_K=C3=A9ri?= ,
=?utf-8?q?Bal=C3=A1zs_K=C3=A9ri?= ,
=?utf-8?q?Bal=C3=A1zs_K=C3=A9ri?= 
Message-ID:
In-Reply-To: 


https://github.com/benshi001 approved this pull request.


https://github.com/llvm/llvm-project/pull/76979
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[llvm] [clang] [clang-tools-extra] [clang-tidy] fix modernize-use-auto incorrect fix hints for pointer (PR #77943)

2024-01-19 Thread Congcong Cai via cfe-commits

https://github.com/HerrCai0907 updated 
https://github.com/llvm/llvm-project/pull/77943

>From 537d283288f555c2bb7cff90aee89fe9b18f08b8 Mon Sep 17 00:00:00 2001
From: Congcong Cai 
Date: Sat, 13 Jan 2024 00:31:33 +0800
Subject: [PATCH 1/4] [clang-tid]fix modernize-use-auto incorrect fix hints for
 pointer

avoid create incorrect fix hints for pointer to array type and pointer to 
function type
Fixes: #77891
---
 .../clang-tidy/modernize/UseAutoCheck.cpp | 52 ++-
 clang-tools-extra/docs/ReleaseNotes.rst   |  4 ++
 2 files changed, 42 insertions(+), 14 deletions(-)

diff --git a/clang-tools-extra/clang-tidy/modernize/UseAutoCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseAutoCheck.cpp
index 7af30e688b6a716..af41c4b50717968 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseAutoCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/UseAutoCheck.cpp
@@ -8,10 +8,12 @@
 
 #include "UseAutoCheck.h"
 #include "clang/AST/ASTContext.h"
+#include "clang/AST/TypeLoc.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
 #include "clang/ASTMatchers/ASTMatchers.h"
 #include "clang/Basic/CharInfo.h"
 #include "clang/Tooling/FixIt.h"
+#include "llvm/ADT/STLExtras.h"
 
 using namespace clang;
 using namespace clang::ast_matchers;
@@ -333,6 +335,26 @@ void UseAutoCheck::replaceIterators(const DeclStmt *D, 
ASTContext *Context) {
   << FixItHint::CreateReplacement(Range, "auto");
 }
 
+namespace {
+
+void ignoreTypeLocClasses(
+TypeLoc &Loc, llvm::SmallVector const &LocClasses) {
+  while (llvm::is_contained(LocClasses, Loc.getTypeLocClass()))
+Loc = Loc.getNextTypeLoc();
+}
+
+bool isMutliLevelPointerToTypeLocClasses(
+TypeLoc Loc, llvm::SmallVector const &LocClasses) {
+  ignoreTypeLocClasses(Loc, {TypeLoc::Paren, TypeLoc::Qualified});
+  if (Loc.getTypeLocClass() != TypeLoc::Pointer)
+return false;
+  ignoreTypeLocClasses(Loc,
+   {TypeLoc::Paren, TypeLoc::Qualified, TypeLoc::Pointer});
+  return llvm::is_contained(LocClasses, Loc.getTypeLocClass());
+}
+
+} // namespace
+
 void UseAutoCheck::replaceExpr(
 const DeclStmt *D, ASTContext *Context,
 llvm::function_ref GetType, StringRef Message) {
@@ -384,16 +406,10 @@ void UseAutoCheck::replaceExpr(
   // information is not reliable where CV qualifiers are concerned so we can't
   // do anything about this case for now.
   TypeLoc Loc = FirstDecl->getTypeSourceInfo()->getTypeLoc();
-  if (!RemoveStars) {
-while (Loc.getTypeLocClass() == TypeLoc::Pointer ||
-   Loc.getTypeLocClass() == TypeLoc::Qualified)
-  Loc = Loc.getNextTypeLoc();
-  }
-  while (Loc.getTypeLocClass() == TypeLoc::LValueReference ||
- Loc.getTypeLocClass() == TypeLoc::RValueReference ||
- Loc.getTypeLocClass() == TypeLoc::Qualified) {
-Loc = Loc.getNextTypeLoc();
-  }
+  if (!RemoveStars)
+ignoreTypeLocClasses(Loc, {TypeLoc::Pointer, TypeLoc::Qualified});
+  ignoreTypeLocClasses(Loc, {TypeLoc::LValueReference, 
TypeLoc::RValueReference,
+ TypeLoc::Qualified});
   SourceRange Range(Loc.getSourceRange());
 
   if (MinTypeNameLength != 0 &&
@@ -405,12 +421,20 @@ void UseAutoCheck::replaceExpr(
 
   auto Diag = diag(Range.getBegin(), Message);
 
+  bool ShouldReplenishVariableName = isMutliLevelPointerToTypeLocClasses(
+  FirstDecl->getTypeSourceInfo()->getTypeLoc(),
+  {TypeLoc::FunctionProto, TypeLoc::ConstantArray});
+
   // Space after 'auto' to handle cases where the '*' in the pointer type is
   // next to the identifier. This avoids changing 'int *p' into 'autop'.
-  // FIXME: This doesn't work for function pointers because the variable name
-  // is inside the type.
-  Diag << FixItHint::CreateReplacement(Range, RemoveStars ? "auto " : "auto")
-   << StarRemovals;
+  llvm::StringRef Auto = ShouldReplenishVariableName
+ ? (RemoveStars ? "auto " : "auto *")
+ : (RemoveStars ? "auto " : "auto");
+  std::string ReplenishedVariableName =
+  ShouldReplenishVariableName ? FirstDecl->getQualifiedNameAsString() : "";
+  std::string Replacement =
+  (Auto + llvm::StringRef{ReplenishedVariableName}).str();
+  Diag << FixItHint::CreateReplacement(Range, Replacement) << StarRemovals;
 }
 
 void UseAutoCheck::check(const MatchFinder::MatchResult &Result) {
diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index b4d87e0ed2a67ae..9bf34177ebff2cf 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -405,6 +405,10 @@ Changes in existing checks
   false-positives when constructing the container with ``count`` copies of
   elements with value ``value``.
 
+- Improved :doc:`modernize-use-auto
+  ` to avoid create incorrect fix hints
+  for pointer to array type and pointer to function type.
+
 - Improved :doc:`modernize-use-emplace
   ` to not replace aggregates that
   ``emplace`` cannot construct with aggre

[clang] [Clang] Implement the 'counted_by' attribute (PR #76348)

2024-01-19 Thread Sean McBride via cfe-commits

seanm wrote:

@bwendling is there any plan / possibility for simple expressions (with no side 
effects)?  Like:

```c
struct libusb_bos_dev_capability_descriptor {
uint8_t  bLength;
uint8_t  bDescriptorType;
uint8_t  bDevCapabilityType;
uint8_t  dev_capability_data[] __attribute__((counted_by(bLength - 3)));
};
```


https://github.com/llvm/llvm-project/pull/76348
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][analyzer] Improve modeling of 'fdopen' in StdLibraryFunctionsChecker (PR #78680)

2024-01-19 Thread Ben Shi via cfe-commits

https://github.com/benshi001 closed 
https://github.com/llvm/llvm-project/pull/78680
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 0223230 - [clang][analyzer] Improve modeling of 'fdopen' in StdLibraryFunctionsChecker (#78680)

2024-01-19 Thread via cfe-commits

Author: Ben Shi
Date: 2024-01-20T11:02:40+08:00
New Revision: 02232307ce18c095ef0bf26b5cef23e4efbc1e4b

URL: 
https://github.com/llvm/llvm-project/commit/02232307ce18c095ef0bf26b5cef23e4efbc1e4b
DIFF: 
https://github.com/llvm/llvm-project/commit/02232307ce18c095ef0bf26b5cef23e4efbc1e4b.diff

LOG: [clang][analyzer] Improve modeling of 'fdopen' in 
StdLibraryFunctionsChecker (#78680)

Added: 


Modified: 
clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
clang/test/Analysis/std-c-library-functions-POSIX.c
clang/test/Analysis/stream-errno.c
clang/test/Analysis/stream-note.c

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
index 83f972c7072ec5..d0eb5091444f6b 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
@@ -2171,6 +2171,16 @@ void StdLibraryFunctionsChecker::initFunctionSummaries(
 .ArgConstraint(NotNull(ArgNo(0)))
 .ArgConstraint(NotNull(ArgNo(1;
 
+// FILE *fdopen(int fd, const char *mode);
+addToFunctionSummaryMap(
+"fdopen",
+Signature(ArgTypes{IntTy, ConstCharPtrTy}, RetType{FilePtrTy}),
+Summary(NoEvalCall)
+.Case({NotNull(Ret)}, ErrnoMustNotBeChecked, GenericSuccessMsg)
+.Case({IsNull(Ret)}, ErrnoNEZeroIrrelevant, GenericFailureMsg)
+.ArgConstraint(ArgumentCondition(0, WithinRange, Range(0, IntMax)))
+.ArgConstraint(NotNull(ArgNo(1;
+
 // FILE *tmpfile(void);
 addToFunctionSummaryMap(
 "tmpfile", Signature(ArgTypes{}, RetType{FilePtrTy}),
@@ -2853,15 +2863,6 @@ void StdLibraryFunctionsChecker::initFunctionSummaries(
 "pathconf", Signature(ArgTypes{ConstCharPtrTy, IntTy}, 
RetType{LongTy}),
 Summary(NoEvalCall).ArgConstraint(NotNull(ArgNo(0;
 
-// FILE *fdopen(int fd, const char *mode);
-// FIXME: Improve for errno modeling.
-addToFunctionSummaryMap(
-"fdopen",
-Signature(ArgTypes{IntTy, ConstCharPtrTy}, RetType{FilePtrTy}),
-Summary(NoEvalCall)
-.ArgConstraint(ArgumentCondition(0, WithinRange, Range(0, IntMax)))
-.ArgConstraint(NotNull(ArgNo(1;
-
 // void rewinddir(DIR *dir);
 addToFunctionSummaryMap(
 "rewinddir", Signature(ArgTypes{DirPtrTy}, RetType{VoidTy}),

diff  --git a/clang/test/Analysis/std-c-library-functions-POSIX.c 
b/clang/test/Analysis/std-c-library-functions-POSIX.c
index 8a26e0b0f27286..51b136d9ba3567 100644
--- a/clang/test/Analysis/std-c-library-functions-POSIX.c
+++ b/clang/test/Analysis/std-c-library-functions-POSIX.c
@@ -17,6 +17,7 @@
 // RUN:   -triple i686-unknown-linux 2>&1 | FileCheck %s
 
 // CHECK: Loaded summary for: FILE *fopen(const char *restrict pathname, const 
char *restrict mode)
+// CHECK: Loaded summary for: FILE *fdopen(int fd, const char *mode)
 // CHECK: Loaded summary for: FILE *tmpfile(void)
 // CHECK: Loaded summary for: FILE *freopen(const char *restrict pathname, 
const char *restrict mode, FILE *restrict stream)
 // CHECK: Loaded summary for: int fclose(FILE *stream)
@@ -78,7 +79,6 @@
 // CHECK: Loaded summary for: int close(int fildes)
 // CHECK: Loaded summary for: long fpathconf(int fildes, int name)
 // CHECK: Loaded summary for: long pathconf(const char *path, int name)
-// CHECK: Loaded summary for: FILE *fdopen(int fd, const char *mode)
 // CHECK: Loaded summary for: void rewinddir(DIR *dir)
 // CHECK: Loaded summary for: void seekdir(DIR *dirp, long loc)
 // CHECK: Loaded summary for: int rand_r(unsigned int *seedp)

diff  --git a/clang/test/Analysis/stream-errno.c 
b/clang/test/Analysis/stream-errno.c
index 13981e9094d1c9..fab6a58b3275a8 100644
--- a/clang/test/Analysis/stream-errno.c
+++ b/clang/test/Analysis/stream-errno.c
@@ -18,6 +18,16 @@ void check_fopen(void) {
   if (errno) {} // expected-warning{{An undefined value may be read from 
'errno' [unix.Errno]}}
 }
 
+void check_fdopen(int Fd) {
+  FILE *F = fdopen(Fd, "r");
+  if (!F) {
+clang_analyzer_eval(errno != 0); // expected-warning{{TRUE}}
+if (errno) {}// no-warning
+  } else {
+if (errno) {}// expected-warning{{An undefined value 
may be read from 'errno' [unix.Errno]}}
+  }
+}
+
 void check_tmpfile(void) {
   FILE *F = tmpfile();
   if (!F) {

diff  --git a/clang/test/Analysis/stream-note.c 
b/clang/test/Analysis/stream-note.c
index e412015eb68393..abb4784c078aa8 100644
--- a/clang/test/Analysis/stream-note.c
+++ b/clang/test/Analysis/stream-note.c
@@ -56,6 +56,7 @@ void check_note_freopen(void) {
 
 void check_note_fdopen(int fd) {
   FILE *F = fdopen(fd, "r"); // expected-note {{Stream opened here}}
+  // stdargs-note@-1 {{'fdopen' is successful}}
   if (!F)
 // expected-no

[clang-tools-extra] [llvm] [PGO] Sampled instrumentation in PGO to speed up instrumentation binary (PR #69535)

2024-01-19 Thread via cfe-commits

WenleiHe wrote:

Any follow ups on this patch? Once it's in we'd like to give it a try as well. 

https://github.com/llvm/llvm-project/pull/69535
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Headers][X86] Add macro descriptions to ia32intrin.h (PR #78613)

2024-01-19 Thread Phoebe Wang via cfe-commits

https://github.com/phoebewang approved this pull request.

LGTM.

https://github.com/llvm/llvm-project/pull/78613
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang] fix static operator()/[] call not evaluating object (PR #78356)

2024-01-19 Thread A. Jiang via cfe-commits


@@ -598,3 +600,27 @@ namespace B {
 }
 void g(B::X x) { A::f(x); }
 }
+
+namespace static_operator {
+#if __cplusplus >= 201703L

frederick-vs-ja wrote:

> No way to modify things in a C++11/14 constexpr function (`++x` is not a 
> constant expression), so no way to make a positive test that the expression 
> was evaluated. Though I guess I should have done `(non_constexpr_fn(), 
> X())()` and see if that failed.

Oh I see. It's inconvenient that runtime results can't be easily asserted in 
this test file.

I think the related changes of constexpr were made in C++14 
([N3652](https://wg21.link/n3652)).

https://github.com/llvm/llvm-project/pull/78356
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][Sema] fix outline member function template with default align crash (PR #78400)

2024-01-19 Thread Qizhi Hu via cfe-commits

https://github.com/jcsxky updated 
https://github.com/llvm/llvm-project/pull/78400

>From 07b6d2105b84ba045bc8093ac0541d2db6e29cd5 Mon Sep 17 00:00:00 2001
From: huqizhi 
Date: Wed, 17 Jan 2024 14:16:34 +0800
Subject: [PATCH] [Clang][Sema] fix outline member function template with
 default align crash

---
 clang/lib/Sema/SemaTemplateInstantiate.cpp| 12 -
 clang/test/SemaTemplate/default-parm-init.cpp | 51 +++
 2 files changed, 61 insertions(+), 2 deletions(-)
 create mode 100644 clang/test/SemaTemplate/default-parm-init.cpp

diff --git a/clang/lib/Sema/SemaTemplateInstantiate.cpp 
b/clang/lib/Sema/SemaTemplateInstantiate.cpp
index fc80515b45e35b..1ed63db75294aa 100644
--- a/clang/lib/Sema/SemaTemplateInstantiate.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiate.cpp
@@ -3051,6 +3051,7 @@ bool Sema::SubstDefaultArgument(
 //   default argument expression appears.
 ContextRAII SavedContext(*this, FD);
 std::unique_ptr LIS;
+auto NewTemplateArgs = TemplateArgs;
 
 if (ForCallExpr) {
   // When instantiating a default argument due to use in a call expression,
@@ -3063,11 +3064,18 @@ bool Sema::SubstDefaultArgument(
   /*ForDefinition*/ false);
   if (addInstantiatedParametersToScope(FD, PatternFD, *LIS, TemplateArgs))
 return true;
+  if (FD->isOutOfLine()) {
+auto *CurrentTemplateArgumentList = TemplateArgumentList::CreateCopy(
+getASTContext(), TemplateArgs.getInnermost());
+NewTemplateArgs = getTemplateInstantiationArgs(
+FD, FD->getDeclContext(), true, CurrentTemplateArgumentList, true,
+nullptr, false, false);
+  }
 }
 
 runWithSufficientStackSpace(Loc, [&] {
-  Result = SubstInitializer(PatternExpr, TemplateArgs,
-/*DirectInit*/false);
+  Result = SubstInitializer(PatternExpr, NewTemplateArgs,
+/*DirectInit*/ false);
 });
   }
   if (Result.isInvalid())
diff --git a/clang/test/SemaTemplate/default-parm-init.cpp 
b/clang/test/SemaTemplate/default-parm-init.cpp
new file mode 100644
index 00..ecdffa9c21d373
--- /dev/null
+++ b/clang/test/SemaTemplate/default-parm-init.cpp
@@ -0,0 +1,51 @@
+// RUN: %clang_cc1 -fsyntax-only -std=c++11 -verify %s
+// RUN: %clang_cc1 -fsyntax-only -std=c++14 -verify %s
+// RUN: %clang_cc1 -fsyntax-only -std=c++20 -verify %s
+// expected-no-diagnostics
+
+template
+struct Problem{
+  template
+  constexpr int FuncAlign(int param = alignof(FunctionTemplateParam));
+
+  template
+  constexpr int FuncSizeof(int param = sizeof(FunctionTemplateParam));
+
+  template
+  constexpr int FuncAlign2(int param = alignof(TemplateParam));
+
+  template
+  constexpr int FuncSizeof2(int param = sizeof(TemplateParam));
+};
+
+template <>
+template
+constexpr int Problem::FuncAlign(int param) {
+   return param;
+}
+
+template <>
+template
+constexpr int Problem::FuncSizeof(int param) {
+   return param;
+}
+
+template <>
+template
+constexpr int Problem::FuncAlign2(int param) {
+   return param;
+}
+
+template <>
+template
+constexpr int Problem::FuncSizeof2(int param) {
+   return param;
+}
+
+int main(){
+Problem p = {};
+static_assert(p.FuncAlign() == alignof(char));
+static_assert(p.FuncSizeof() == sizeof(char));
+static_assert(p.FuncAlign2() == alignof(int));
+static_assert(p.FuncSizeof2() == sizeof(int));
+}

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][Sema] fix outline member function template with default align crash (PR #78400)

2024-01-19 Thread Qizhi Hu via cfe-commits

https://github.com/jcsxky updated 
https://github.com/llvm/llvm-project/pull/78400

>From 9bb08560d401018cc63dc3b3e635c4f95cad7819 Mon Sep 17 00:00:00 2001
From: huqizhi 
Date: Wed, 17 Jan 2024 14:16:34 +0800
Subject: [PATCH] [Clang][Sema] fix outline member function template with
 default align crash

---
 clang/lib/Sema/SemaTemplateInstantiate.cpp| 12 -
 clang/test/SemaTemplate/default-parm-init.cpp | 51 +++
 2 files changed, 61 insertions(+), 2 deletions(-)
 create mode 100644 clang/test/SemaTemplate/default-parm-init.cpp

diff --git a/clang/lib/Sema/SemaTemplateInstantiate.cpp 
b/clang/lib/Sema/SemaTemplateInstantiate.cpp
index fc80515b45e35b4..1ed63db75294aab 100644
--- a/clang/lib/Sema/SemaTemplateInstantiate.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiate.cpp
@@ -3051,6 +3051,7 @@ bool Sema::SubstDefaultArgument(
 //   default argument expression appears.
 ContextRAII SavedContext(*this, FD);
 std::unique_ptr LIS;
+auto NewTemplateArgs = TemplateArgs;
 
 if (ForCallExpr) {
   // When instantiating a default argument due to use in a call expression,
@@ -3063,11 +3064,18 @@ bool Sema::SubstDefaultArgument(
   /*ForDefinition*/ false);
   if (addInstantiatedParametersToScope(FD, PatternFD, *LIS, TemplateArgs))
 return true;
+  if (FD->isOutOfLine()) {
+auto *CurrentTemplateArgumentList = TemplateArgumentList::CreateCopy(
+getASTContext(), TemplateArgs.getInnermost());
+NewTemplateArgs = getTemplateInstantiationArgs(
+FD, FD->getDeclContext(), true, CurrentTemplateArgumentList, true,
+nullptr, false, false);
+  }
 }
 
 runWithSufficientStackSpace(Loc, [&] {
-  Result = SubstInitializer(PatternExpr, TemplateArgs,
-/*DirectInit*/false);
+  Result = SubstInitializer(PatternExpr, NewTemplateArgs,
+/*DirectInit*/ false);
 });
   }
   if (Result.isInvalid())
diff --git a/clang/test/SemaTemplate/default-parm-init.cpp 
b/clang/test/SemaTemplate/default-parm-init.cpp
new file mode 100644
index 000..78ad71ee7141d66
--- /dev/null
+++ b/clang/test/SemaTemplate/default-parm-init.cpp
@@ -0,0 +1,51 @@
+// RUN: %clang_cc1 -fsyntax-only -std=c++11 -verify %s
+// RUN: %clang_cc1 -fsyntax-only -std=c++14 -verify %s
+// RUN: %clang_cc1 -fsyntax-only -std=c++20 -verify %s
+// expected-no-diagnostics
+
+template
+struct Problem{
+  template
+  constexpr int FuncAlign(int param = alignof(FunctionTemplateParam));
+
+  template
+  constexpr int FuncSizeof(int param = sizeof(FunctionTemplateParam));
+
+  template
+  constexpr int FuncAlign2(int param = alignof(TemplateParam));
+
+  template
+  constexpr int FuncSizeof2(int param = sizeof(TemplateParam));
+};
+
+template <>
+template
+constexpr int Problem::FuncAlign(int param) {
+   return param;
+}
+
+template <>
+template
+constexpr int Problem::FuncSizeof(int param) {
+   return param;
+}
+
+template <>
+template
+constexpr int Problem::FuncAlign2(int param) {
+   return param;
+}
+
+template <>
+template
+constexpr int Problem::FuncSizeof2(int param) {
+   return param;
+}
+
+int main(){
+Problem p = {};
+static_assert(p.FuncAlign() == alignof(char));
+static_assert(p.FuncSizeof() == sizeof(char));
+static_assert(p.FuncAlign2() == alignof(int));
+static_assert(p.FuncSizeof2() == sizeof(int));
+}
\ No newline at end of file

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][Sema] fix outline member function template with default align crash (PR #78400)

2024-01-19 Thread Qizhi Hu via cfe-commits

https://github.com/jcsxky edited https://github.com/llvm/llvm-project/pull/78400
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][modules] Fix CodeGen options that can affect the AST. (PR #78816)

2024-01-19 Thread Michael Spencer via cfe-commits

https://github.com/Bigcheese approved this pull request.

LGTM, although are we sure none of the other options should be affecting? I 
just did a quick search and it seems like this is it.

I don't think it matters here, but the actual option that controls the macro is 
on `LangOptions` and where it's set has a "FIXME: Eliminate this dependency" 
where it directly parses the command line. As long as we're not changing the 
value the `LangOptions` version should always match.

https://github.com/llvm/llvm-project/pull/78816
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][Sema] fix outline member function template with default align crash (PR #78400)

2024-01-19 Thread Qizhi Hu via cfe-commits

https://github.com/jcsxky updated 
https://github.com/llvm/llvm-project/pull/78400

>From e8a5715a6255bc110823dbe36734bb7bd17753d5 Mon Sep 17 00:00:00 2001
From: huqizhi 
Date: Wed, 17 Jan 2024 14:16:34 +0800
Subject: [PATCH] [Clang][Sema] fix outline member function template with
 default align crash

---
 clang/lib/Sema/SemaTemplateInstantiate.cpp | 12 ++--
 1 file changed, 10 insertions(+), 2 deletions(-)

diff --git a/clang/lib/Sema/SemaTemplateInstantiate.cpp 
b/clang/lib/Sema/SemaTemplateInstantiate.cpp
index fc80515b45e35b4..1ed63db75294aab 100644
--- a/clang/lib/Sema/SemaTemplateInstantiate.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiate.cpp
@@ -3051,6 +3051,7 @@ bool Sema::SubstDefaultArgument(
 //   default argument expression appears.
 ContextRAII SavedContext(*this, FD);
 std::unique_ptr LIS;
+auto NewTemplateArgs = TemplateArgs;
 
 if (ForCallExpr) {
   // When instantiating a default argument due to use in a call expression,
@@ -3063,11 +3064,18 @@ bool Sema::SubstDefaultArgument(
   /*ForDefinition*/ false);
   if (addInstantiatedParametersToScope(FD, PatternFD, *LIS, TemplateArgs))
 return true;
+  if (FD->isOutOfLine()) {
+auto *CurrentTemplateArgumentList = TemplateArgumentList::CreateCopy(
+getASTContext(), TemplateArgs.getInnermost());
+NewTemplateArgs = getTemplateInstantiationArgs(
+FD, FD->getDeclContext(), true, CurrentTemplateArgumentList, true,
+nullptr, false, false);
+  }
 }
 
 runWithSufficientStackSpace(Loc, [&] {
-  Result = SubstInitializer(PatternExpr, TemplateArgs,
-/*DirectInit*/false);
+  Result = SubstInitializer(PatternExpr, NewTemplateArgs,
+/*DirectInit*/ false);
 });
   }
   if (Result.isInvalid())

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[flang] [llvm] [libcxx] [clang] [libc] [clang-tools-extra] [compiler-rt] [mlir] [lld] [lldb] Reland "[clang] Fix CTAD for aggregates for nested template classes" (PR #78670)

2024-01-19 Thread via cfe-commits

https://github.com/antangelo updated 
https://github.com/llvm/llvm-project/pull/78670

>From 227504aa6da6dd2199c83563b9149dd3873e1a11 Mon Sep 17 00:00:00 2001
From: Antonio Abbatangelo 
Date: Thu, 18 Jan 2024 23:27:16 -0500
Subject: [PATCH] Reland "[clang] Fix CTAD for aggregates for nested template
 classes"

Reland of #78387

Use the template pattern in determining whether to synthesize the
aggregate deduction guide, and update DeclareImplicitDeductionGuideFromInitList
to substitute outer template arguments.

The tests in the original patch made an assumption about the size of a
pointer type, and this led to them failing on systems with 32-bit
pointers. The tests have been updated to not depend on the size of any
type. This only requires updates to the test file, no functionality has
otherwise changed between this and the original patch.
---
 clang/docs/ReleaseNotes.rst   |  3 ++
 clang/lib/Sema/SemaInit.cpp   |  9 -
 clang/lib/Sema/SemaTemplate.cpp   | 21 +---
 .../nested-implicit-deduction-guides.cpp  | 34 ---
 4 files changed, 58 insertions(+), 9 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index b400d75095421c..ee431587a7853d 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -979,6 +979,9 @@ Bug Fixes to C++ Support
 - Clang now allows parenthesized initialization of arrays in `operator new[]`.
   Fixes: (`#68198 `_)
 
+- Fixes CTAD for aggregates on nested template classes. Fixes:
+  (`#77599 `_)
+
 Bug Fixes to AST Handling
 ^
 - Fixed an import failure of recursive friend class template.
diff --git a/clang/lib/Sema/SemaInit.cpp b/clang/lib/Sema/SemaInit.cpp
index 18440a69e3a3d9..457fa377355a97 100644
--- a/clang/lib/Sema/SemaInit.cpp
+++ b/clang/lib/Sema/SemaInit.cpp
@@ -10731,7 +10731,14 @@ QualType 
Sema::DeduceTemplateSpecializationFromInitializer(
 bool HasAnyDeductionGuide = false;
 
 auto SynthesizeAggrGuide = [&](InitListExpr *ListInit) {
-  auto *RD = cast(Template->getTemplatedDecl());
+  auto *Pattern = Template;
+  while (Pattern->getInstantiatedFromMemberTemplate()) {
+if (Pattern->isMemberSpecialization())
+  break;
+Pattern = Pattern->getInstantiatedFromMemberTemplate();
+  }
+
+  auto *RD = cast(Pattern->getTemplatedDecl());
   if (!(RD->getDefinition() && RD->isAggregate()))
 return;
   QualType Ty = Context.getRecordType(RD);
diff --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp
index 0655d363352067..839d508b911f06 100644
--- a/clang/lib/Sema/SemaTemplate.cpp
+++ b/clang/lib/Sema/SemaTemplate.cpp
@@ -2418,6 +2418,9 @@ struct ConvertConstructorToDeductionGuideTransform {
 QualType Result = SemaRef.BuildFunctionType(DeducedType, ParamTypes, Loc,
 DeductionGuideName, EPI);
 TypeSourceInfo *TSI = SemaRef.Context.getTrivialTypeSourceInfo(Result, 
Loc);
+if (NestedPattern)
+  TSI = SemaRef.SubstType(TSI, OuterInstantiationArgs, Loc,
+  DeductionGuideName);
 
 FunctionProtoTypeLoc FPTL =
 TSI->getTypeLoc().castAs();
@@ -2425,9 +2428,13 @@ struct ConvertConstructorToDeductionGuideTransform {
 // Build the parameters, needed during deduction / substitution.
 SmallVector Params;
 for (auto T : ParamTypes) {
-  ParmVarDecl *NewParam = ParmVarDecl::Create(
-  SemaRef.Context, DC, Loc, Loc, nullptr, T,
-  SemaRef.Context.getTrivialTypeSourceInfo(T, Loc), SC_None, nullptr);
+  auto *TSI = SemaRef.Context.getTrivialTypeSourceInfo(T, Loc);
+  if (NestedPattern)
+TSI = SemaRef.SubstType(TSI, OuterInstantiationArgs, Loc,
+DeclarationName());
+  ParmVarDecl *NewParam =
+  ParmVarDecl::Create(SemaRef.Context, DC, Loc, Loc, nullptr,
+  TSI->getType(), TSI, SC_None, nullptr);
   NewParam->setScopeInfo(0, Params.size());
   FPTL.setParam(Params.size(), NewParam);
   Params.push_back(NewParam);
@@ -2670,8 +2677,14 @@ FunctionTemplateDecl 
*Sema::DeclareImplicitDeductionGuideFromInitList(
   if (BuildingDeductionGuides.isInvalid())
 return nullptr;
 
-  return cast(
+  ClassTemplateDecl *Pattern =
+  Transform.NestedPattern ? Transform.NestedPattern : Transform.Template;
+  ContextRAII SavedContext(*this, Pattern->getTemplatedDecl());
+
+  auto *DG = cast(
   Transform.buildSimpleDeductionGuide(ParamTypes));
+  SavedContext.pop();
+  return DG;
 }
 
 void Sema::DeclareImplicitDeductionGuides(TemplateDecl *Template,
diff --git a/clang/test/SemaTemplate/nested-implicit-deduction-guides.cpp 
b/clang/test/SemaTemplate/nested-implicit-deduction-guides.cpp
index c44ec6918c7afb..38b6706595a116 100644
--- a/clang

[clang] [Clang][Sema] fix outline member function template with default align crash (PR #78400)

2024-01-19 Thread Qizhi Hu via cfe-commits

https://github.com/jcsxky updated 
https://github.com/llvm/llvm-project/pull/78400

>From 1a1ae44bc9b937f8a79afa3b40c7ad32e1fde8dd Mon Sep 17 00:00:00 2001
From: huqizhi 
Date: Wed, 17 Jan 2024 14:16:34 +0800
Subject: [PATCH] fix

---
 clang/lib/Sema/SemaTemplateInstantiate.cpp | 12 ++--
 1 file changed, 10 insertions(+), 2 deletions(-)

diff --git a/clang/lib/Sema/SemaTemplateInstantiate.cpp 
b/clang/lib/Sema/SemaTemplateInstantiate.cpp
index fc80515b45e35b..1ed63db75294aa 100644
--- a/clang/lib/Sema/SemaTemplateInstantiate.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiate.cpp
@@ -3051,6 +3051,7 @@ bool Sema::SubstDefaultArgument(
 //   default argument expression appears.
 ContextRAII SavedContext(*this, FD);
 std::unique_ptr LIS;
+auto NewTemplateArgs = TemplateArgs;
 
 if (ForCallExpr) {
   // When instantiating a default argument due to use in a call expression,
@@ -3063,11 +3064,18 @@ bool Sema::SubstDefaultArgument(
   /*ForDefinition*/ false);
   if (addInstantiatedParametersToScope(FD, PatternFD, *LIS, TemplateArgs))
 return true;
+  if (FD->isOutOfLine()) {
+auto *CurrentTemplateArgumentList = TemplateArgumentList::CreateCopy(
+getASTContext(), TemplateArgs.getInnermost());
+NewTemplateArgs = getTemplateInstantiationArgs(
+FD, FD->getDeclContext(), true, CurrentTemplateArgumentList, true,
+nullptr, false, false);
+  }
 }
 
 runWithSufficientStackSpace(Loc, [&] {
-  Result = SubstInitializer(PatternExpr, TemplateArgs,
-/*DirectInit*/false);
+  Result = SubstInitializer(PatternExpr, NewTemplateArgs,
+/*DirectInit*/ false);
 });
   }
   if (Result.isInvalid())

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang-tidy] Added new check to detect redundant inline keyword (PR #73069)

2024-01-19 Thread Félix-Antoine Constantin via cfe-commits

https://github.com/felix642 updated 
https://github.com/llvm/llvm-project/pull/73069

From 286c4445f8cba6ea2f49fb9e8f732f04ebdb6c97 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?F=C3=A9lix-Antoine=20Constantin?=
 
Date: Thu, 16 Nov 2023 22:03:15 -0500
Subject: [PATCH] =?UTF-8?q?[clang-tidy]=C2=A0Added=20check=20to=20detect?=
 =?UTF-8?q?=20redundant=20inline=20keyword?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

This checks find usages of the inline keywork where it is
already implicitly defined by the compiler and suggests it's removal.

Fixes #72397
---
 .../clang-tidy/readability/CMakeLists.txt |   1 +
 .../readability/ReadabilityTidyModule.cpp |   3 +
 .../RedundantInlineSpecifierCheck.cpp | 132 +
 .../RedundantInlineSpecifierCheck.h   |  42 ++
 clang-tools-extra/docs/ReleaseNotes.rst   |   5 +
 .../docs/clang-tidy/checks/list.rst   |   1 +
 .../redundant-inline-specifier.rst|  32 
 .../redundant-inline-specifier.cpp| 137 ++
 8 files changed, 353 insertions(+)
 create mode 100644 
clang-tools-extra/clang-tidy/readability/RedundantInlineSpecifierCheck.cpp
 create mode 100644 
clang-tools-extra/clang-tidy/readability/RedundantInlineSpecifierCheck.h
 create mode 100644 
clang-tools-extra/docs/clang-tidy/checks/readability/redundant-inline-specifier.rst
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/readability/redundant-inline-specifier.cpp

diff --git a/clang-tools-extra/clang-tidy/readability/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/readability/CMakeLists.txt
index fa571d5dd7650d1..1d15228da694510 100644
--- a/clang-tools-extra/clang-tidy/readability/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/readability/CMakeLists.txt
@@ -22,6 +22,7 @@ add_clang_library(clangTidyReadabilityModule
   IdentifierLengthCheck.cpp
   IdentifierNamingCheck.cpp
   ImplicitBoolConversionCheck.cpp
+  RedundantInlineSpecifierCheck.cpp
   InconsistentDeclarationParameterNameCheck.cpp
   IsolateDeclarationCheck.cpp
   MagicNumbersCheck.cpp
diff --git a/clang-tools-extra/clang-tidy/readability/ReadabilityTidyModule.cpp 
b/clang-tools-extra/clang-tidy/readability/ReadabilityTidyModule.cpp
index f769752c5de5fa7..521dacd6f9df3e2 100644
--- a/clang-tools-extra/clang-tidy/readability/ReadabilityTidyModule.cpp
+++ b/clang-tools-extra/clang-tidy/readability/ReadabilityTidyModule.cpp
@@ -41,6 +41,7 @@
 #include "RedundantControlFlowCheck.h"
 #include "RedundantDeclarationCheck.h"
 #include "RedundantFunctionPtrDereferenceCheck.h"
+#include "RedundantInlineSpecifierCheck.h"
 #include "RedundantMemberInitCheck.h"
 #include "RedundantPreprocessorCheck.h"
 #include "RedundantSmartptrGetCheck.h"
@@ -99,6 +100,8 @@ class ReadabilityModule : public ClangTidyModule {
 "readability-identifier-naming");
 CheckFactories.registerCheck(
 "readability-implicit-bool-conversion");
+CheckFactories.registerCheck(
+"readability-redundant-inline-specifier");
 CheckFactories.registerCheck(
 "readability-inconsistent-declaration-parameter-name");
 CheckFactories.registerCheck(
diff --git 
a/clang-tools-extra/clang-tidy/readability/RedundantInlineSpecifierCheck.cpp 
b/clang-tools-extra/clang-tidy/readability/RedundantInlineSpecifierCheck.cpp
new file mode 100644
index 000..0e8d17d4442478c
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/readability/RedundantInlineSpecifierCheck.cpp
@@ -0,0 +1,132 @@
+//===--- RedundantInlineSpecifierCheck.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 "RedundantInlineSpecifierCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Decl.h"
+#include "clang/AST/DeclCXX.h"
+#include "clang/AST/DeclTemplate.h"
+#include "clang/AST/ExprCXX.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/Basic/Diagnostic.h"
+#include "clang/Basic/SourceLocation.h"
+#include "clang/Basic/SourceManager.h"
+#include "clang/Lex/Token.h"
+
+#include "../utils/LexerUtils.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::readability {
+
+namespace {
+AST_POLYMORPHIC_MATCHER(isInlineSpecified,
+AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
+VarDecl)) {
+  if (const auto *FD = dyn_cast(&Node))
+return FD->isInlineSpecified();
+  if (const auto *VD = dyn_cast(&Node))
+return VD->isInlineSpecified();
+  llvm_unreachable("Not a valid polymorphic type");
+}
+
+AST_POLYMORPHIC_MATCHER_P(isInternalLinkage,
+  AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
+ 

[clang] fd49ef1 - Removed a late added test-case from the tests for #74629

2024-01-19 Thread Ben Dunbobbin via cfe-commits

Author: Ben Dunbobbin
Date: 2024-01-20T01:35:06Z
New Revision: fd49ef1eb3de7eb2be5f7ddd469a005917cc1988

URL: 
https://github.com/llvm/llvm-project/commit/fd49ef1eb3de7eb2be5f7ddd469a005917cc1988
DIFF: 
https://github.com/llvm/llvm-project/commit/fd49ef1eb3de7eb2be5f7ddd469a005917cc1988.diff

LOG: Removed a late added test-case from the tests for #74629

This test-case was generating invalid IR and causing the test to fail.

Given that the reviewer initially accepted the change without this
test case I feel that it is appropriate to remove this test case,
to get the build to pass, and find a way to reimplement this test-case
in a later commit.

Added: 


Modified: 
clang/test/CodeGenCXX/visibility-dllstorageclass.cpp

Removed: 




diff  --git a/clang/test/CodeGenCXX/visibility-dllstorageclass.cpp 
b/clang/test/CodeGenCXX/visibility-dllstorageclass.cpp
index a44ff1316d94c5..3ea00bd4889923 100644
--- a/clang/test/CodeGenCXX/visibility-dllstorageclass.cpp
+++ b/clang/test/CodeGenCXX/visibility-dllstorageclass.cpp
@@ -43,17 +43,6 @@
 // RUN: -x c++  %s -S -emit-llvm -o - | \
 // RUN:   FileCheck %s --check-prefixes=ALL_KEEP
 
- Show that omitting -fvisibility-from-dllstorageclass causes the other 
options to be ignored.
-// RUN: %clang_cc1 -triple x86_64-unknown-windows-itanium -fdeclspec \
-// RUN: -fvisibility=hidden \
-// RUN: -fapply-global-visibility-to-externs \
-// RUN: -fvisibility-dllexport=protected \
-// RUN: -fvisibility-nodllstorageclass=protected \
-// RUN: -fvisibility-externs-dllimport=protected \
-// RUN: -fvisibility-externs-nodllstorageclass=protected \
-// RUN: -x c++  %s -S -emit-llvm -o - | \
-// RUN:   FileCheck %s --check-prefixes=ALL_KEEP
-
 // Local
 static void l() {}
 void use_locals(){l();}



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[libcxx] [llvm] [clang] [clang-tools-extra] [libc++][hardening] Classify assertions related to leaks and syscalls. (PR #77164)

2024-01-19 Thread Konstantin Varlamov via cfe-commits

https://github.com/var-const updated 
https://github.com/llvm/llvm-project/pull/77164

>From e28e7b3e1337cb960cdc8028a70a43740fa7d636 Mon Sep 17 00:00:00 2001
From: Konstantin Varlamov 
Date: Thu, 21 Dec 2023 14:36:47 -0800
Subject: [PATCH 1/3] [libc++][hardening] Classify assertions related to leaks
 and syscalls.

Introduce two new categories:
- `_LIBCPP_ASSERT_VALID_DEALLOCATION`;
- `_LIBCPP_ASSERT_VALID_EXTERNAL_API_CALL`.
---
 libcxx/include/__config  | 16 
 libcxx/include/__coroutine/coroutine_handle.h| 16 
 .../__memory_resource/polymorphic_allocator.h|  3 ++-
 libcxx/src/filesystem/operations.cpp |  8 +---
 libcxx/src/memory_resource.cpp   |  3 ++-
 libcxx/src/mutex.cpp |  8 +---
 6 files changed, 38 insertions(+), 16 deletions(-)

diff --git a/libcxx/include/__config b/libcxx/include/__config
index 082c73e672c749..4d74b564864272 100644
--- a/libcxx/include/__config
+++ b/libcxx/include/__config
@@ -280,6 +280,14 @@
 // - `_LIBCPP_ASSERT_NON_OVERLAPPING_RANGES` -- for functions that take 
several ranges as arguments, checks that the
 //   given ranges do not overlap.
 //
+// - `_LIBCPP_ASSERT_VALID_DEALLOCATION` -- checks that an attempt to 
deallocate memory is valid (e.g. the given object
+//   was allocated by the given allocator). Violating this category typically 
results in a memory leak.
+//
+// - `_LIBCPP_ASSERT_VALID_EXTERNAL_API_CALL` -- checks that a call to an 
external API (e.g. a syscall) doesn't fail in
+//   an unexpected manner. This includes triggering documented cases of 
undefined behavior in an external library (like
+//   attempting to unlock an unlocked mutex in pthreads). We generally don't 
expect these failures to compromize memory
+//   safety or otherwise create an immediate security issue.
+//
 // - `_LIBCPP_ASSERT_COMPATIBLE_ALLOCATOR` -- checks any operations that 
exchange nodes between containers to make sure
 //   the containers have compatible allocators.
 //
@@ -327,6 +335,8 @@ _LIBCPP_HARDENING_MODE_DEBUG
 // Overlapping ranges will make algorithms produce incorrect results but don't 
directly lead to a security
 // vulnerability.
 #define _LIBCPP_ASSERT_NON_OVERLAPPING_RANGES(expression, message)   
_LIBCPP_ASSUME(expression)
+#define _LIBCPP_ASSERT_VALID_DEALLOCATION(expression, message)   
_LIBCPP_ASSUME(expression)
+#define _LIBCPP_ASSERT_VALID_EXTERNAL_API_CALL(expression, message)  
_LIBCPP_ASSUME(expression)
 #define _LIBCPP_ASSERT_COMPATIBLE_ALLOCATOR(expression, message) 
_LIBCPP_ASSUME(expression)
 #define _LIBCPP_ASSERT_PEDANTIC(expression, message) 
_LIBCPP_ASSUME(expression)
 #define _LIBCPP_ASSERT_INTERNAL(expression, message) 
_LIBCPP_ASSUME(expression)
@@ -341,6 +351,8 @@ _LIBCPP_HARDENING_MODE_DEBUG
 #define _LIBCPP_ASSERT_VALID_ELEMENT_ACCESS(expression, message) 
_LIBCPP_ASSERT(expression, message)
 #define _LIBCPP_ASSERT_NON_NULL(expression, message) 
_LIBCPP_ASSERT(expression, message)
 #define _LIBCPP_ASSERT_NON_OVERLAPPING_RANGES(expression, message)   
_LIBCPP_ASSERT(expression, message)
+#define _LIBCPP_ASSERT_VALID_DEALLOCATION(expression, message)   
_LIBCPP_ASSERT(expression, message)
+#define _LIBCPP_ASSERT_VALID_EXTERNAL_API_CALL(expression, message)  
_LIBCPP_ASSERT(expression, message)
 #define _LIBCPP_ASSERT_COMPATIBLE_ALLOCATOR(expression, message) 
_LIBCPP_ASSERT(expression, message)
 #define _LIBCPP_ASSERT_UNCATEGORIZED(expression, message)
_LIBCPP_ASSERT(expression, message)
 #define _LIBCPP_ASSERT_PEDANTIC(expression, message) 
_LIBCPP_ASSERT(expression, message)
@@ -356,6 +368,8 @@ _LIBCPP_HARDENING_MODE_DEBUG
 #define _LIBCPP_ASSERT_VALID_ELEMENT_ACCESS(expression, message)  
_LIBCPP_ASSERT(expression, message)
 #define _LIBCPP_ASSERT_NON_NULL(expression, message)  
_LIBCPP_ASSERT(expression, message)
 #define _LIBCPP_ASSERT_NON_OVERLAPPING_RANGES(expression, message)
_LIBCPP_ASSERT(expression, message)
+#define _LIBCPP_ASSERT_VALID_DEALLOCATION(expression, message)
_LIBCPP_ASSERT(expression, message)
+#define _LIBCPP_ASSERT_VALID_EXTERNAL_API_CALL(expression, message)   
_LIBCPP_ASSERT(expression, message)
 #define _LIBCPP_ASSERT_COMPATIBLE_ALLOCATOR(expression, message)  
_LIBCPP_ASSERT(expression, message)
 #define _LIBCPP_ASSERT_PEDANTIC(expression, message)  
_LIBCPP_ASSERT(expression, message)
 #define _LIBCPP_ASSERT_INTERNAL(expression, message)  
_LIBCPP_ASSERT(expression, message)
@@ -370,6 +384,8 @@ _LIBCPP_HARDENING_MODE_DEBUG
 #define _LIBCPP_ASSERT_VALID_ELEMENT_ACCESS(expression, message)  
_LIBCPP_ASSUME(expression)
 #define _LIBCPP_ASSERT_NON_NULL(expression, message)  
_LIBCPP_ASSUME(expression)
 #def

[libcxx] [llvm] [clang] [clang-tools-extra] [libc++][hardening] Don't trigger redundant checks in the fast mode. (PR #77176)

2024-01-19 Thread Konstantin Varlamov via cfe-commits

https://github.com/var-const updated 
https://github.com/llvm/llvm-project/pull/77176

>From f86839d0bfc8b2070127dc3b2c609c2b3f7239ad Mon Sep 17 00:00:00 2001
From: Konstantin Varlamov 
Date: Fri, 5 Jan 2024 20:08:27 -0800
Subject: [PATCH 1/2] [libc++][hardening] Don't trigger redundant checks in the
 fast mode.

Sometimes we essentially check the same condition twice -- for example,
a class might check that an index into its vector member variable is
valid before accessing it, but `vector::operator[]` contains the same
check. These "redundant" checks allow catching errors closer to the
source and providing a better error message, but they also impose
additional overhead. Marking the "early" checks as redundant allows
ignoring them in the fast mode (while still getting a guaranteed trap)
while still getting better error messages in the extensive mode and
above. Introducing a separate wrapper macro allows making the concept of
redundant assertions orthogonal to assertion categories and retaining
the actual category of a check.

This is a follow-up to https://github.com/llvm/llvm-project/pull/75918,
specifically to [this 
discussion](https://github.com/llvm/llvm-project/pull/75918#discussion_r1434493455).
---
 libcxx/include/__config | 16 
 .../include/__filesystem/directory_iterator.h   |  3 ++-
 libcxx/include/__iterator/next.h|  5 +++--
 libcxx/include/__iterator/prev.h|  5 +++--
 libcxx/include/__mdspan/layout_left.h   |  5 +++--
 libcxx/include/__mdspan/layout_right.h  |  5 +++--
 libcxx/include/__mdspan/layout_stride.h |  5 +++--
 libcxx/include/__ranges/chunk_by_view.h | 17 +++--
 libcxx/include/__ranges/drop_while_view.h   |  9 +
 libcxx/include/__ranges/filter_view.h   |  5 +++--
 libcxx/include/regex|  3 ++-
 11 files changed, 54 insertions(+), 24 deletions(-)

diff --git a/libcxx/include/__config b/libcxx/include/__config
index 082c73e672c749..b20e8abed0939c 100644
--- a/libcxx/include/__config
+++ b/libcxx/include/__config
@@ -290,6 +290,18 @@
 //   user input.
 //
 // - `_LIBCPP_ASSERT_UNCATEGORIZED` -- for assertions that haven't been 
properly classified yet.
+//
+// In addition to these categories, `_LIBCPP_REDUNDANT_ASSERTION` should be 
used to wrap assertions that duplicate other
+// assertions (for example, a range view might check that its `optional` data 
member holds a value before dereferencing
+// it, but this is already checked by `optional` itself). Redundant assertions 
incur an additional performance overhead
+// and don't provide any extra security benefit, but catching an error earlier 
allows halting the program closer to the
+// root cause and giving the user an error message that contains more context. 
Due to these tradeoffs, redundant
+// assertions are disabled in the fast mode but are enabled in the extensive 
mode and above. Thus, going back to the
+// example above, if a view attempts to dereference an empty optional member 
variable:
+// - in the fast mode, the program will only perform one check and will trap 
inside the optional (with an error
+//   amounting to "Attempting to dereference an empty optional");
+// - in the extensive mode, the program will normally perform two checks (in 
the non-error case), and if the optional is
+//   empty, it will trap inside the view (with an error like "`foo_view` 
doesn't have a valid predicate").
 
 // clang-format off
 #  define _LIBCPP_HARDENING_MODE_NONE  (1 << 1)
@@ -331,6 +343,7 @@ _LIBCPP_HARDENING_MODE_DEBUG
 #define _LIBCPP_ASSERT_PEDANTIC(expression, message) 
_LIBCPP_ASSUME(expression)
 #define _LIBCPP_ASSERT_INTERNAL(expression, message) 
_LIBCPP_ASSUME(expression)
 #define _LIBCPP_ASSERT_UNCATEGORIZED(expression, message)
_LIBCPP_ASSUME(expression)
+#define _LIBCPP_REDUNDANT_ASSERTION(expression)  
_LIBCPP_ASSUME(expression)
 
 // Extensive hardening mode checks.
 
@@ -344,6 +357,7 @@ _LIBCPP_HARDENING_MODE_DEBUG
 #define _LIBCPP_ASSERT_COMPATIBLE_ALLOCATOR(expression, message) 
_LIBCPP_ASSERT(expression, message)
 #define _LIBCPP_ASSERT_UNCATEGORIZED(expression, message)
_LIBCPP_ASSERT(expression, message)
 #define _LIBCPP_ASSERT_PEDANTIC(expression, message) 
_LIBCPP_ASSERT(expression, message)
+#define _LIBCPP_REDUNDANT_ASSERTION(expression)  
expression
 // Disabled checks.
 #define _LIBCPP_ASSERT_INTERNAL(expression, message) 
_LIBCPP_ASSUME(expression)
 
@@ -360,6 +374,7 @@ _LIBCPP_HARDENING_MODE_DEBUG
 #define _LIBCPP_ASSERT_PEDANTIC(expression, message)  
_LIBCPP_ASSERT(expression, message)
 #define _LIBCPP_ASSERT_INTERNAL(expression, message)  
_LIBCPP_ASSERT(expression, message)
 #define _LIBCPP_ASSERT_UNCATEGORIZED(expression, me

[libcxx] [llvm] [clang] [clang-tools-extra] [libc++][hardening] Classify assertions related to leaks and syscalls. (PR #77164)

2024-01-19 Thread via cfe-commits

github-actions[bot] wrote:




:warning: C/C++ code formatter, clang-format found issues in your code. 
:warning:



You can test this locally with the following command:


``bash
git-clang-format --diff 4f215fdd62d3f014750339eab9a46946b6fb1c4a 
c6fb1dea762178e7b850c5f13da9aaa28723eb21 -- libcxx/include/__config 
libcxx/include/__coroutine/coroutine_handle.h 
libcxx/include/__memory_resource/polymorphic_allocator.h 
libcxx/src/filesystem/operations.cpp libcxx/src/memory_resource.cpp 
libcxx/src/mutex.cpp
``





View the diff from clang-format here.


``diff
diff --git a/libcxx/src/filesystem/operations.cpp 
b/libcxx/src/filesystem/operations.cpp
index 8a99347fe1..2b75df5a4d 100644
--- a/libcxx/src/filesystem/operations.cpp
+++ b/libcxx/src/filesystem/operations.cpp
@@ -460,13 +460,13 @@ path __current_path(error_code* ec) {
   typedef decltype(&::free) Deleter;
   Deleter deleter = &::free;
 #else
-  errno = 0; // Note: POSIX mandates that modifying `errno` is thread-safe.
+  errno = 0; // Note: POSIX mandates that modifying `errno` is thread-safe.
   auto size = ::pathconf(".", _PC_PATH_MAX);
   if (size == -1) {
 if (errno != 0) {
   return err.report(capture_errno(), "call to pathconf failed");
 
-// `pathconf` returns `-1` without an error to indicate no limit.
+  // `pathconf` returns `-1` without an error to indicate no limit.
 } else {
 #  if defined(__MVS__) && !defined(PATH_MAX)
   size = _XOPEN_PATH_MAX + 1;

``




https://github.com/llvm/llvm-project/pull/77164
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [libcxx] [llvm] [clang] [libc++][hardening] Classify assertions related to leaks and syscalls. (PR #77164)

2024-01-19 Thread Konstantin Varlamov via cfe-commits

https://github.com/var-const updated 
https://github.com/llvm/llvm-project/pull/77164

>From e28e7b3e1337cb960cdc8028a70a43740fa7d636 Mon Sep 17 00:00:00 2001
From: Konstantin Varlamov 
Date: Thu, 21 Dec 2023 14:36:47 -0800
Subject: [PATCH 1/2] [libc++][hardening] Classify assertions related to leaks
 and syscalls.

Introduce two new categories:
- `_LIBCPP_ASSERT_VALID_DEALLOCATION`;
- `_LIBCPP_ASSERT_VALID_EXTERNAL_API_CALL`.
---
 libcxx/include/__config  | 16 
 libcxx/include/__coroutine/coroutine_handle.h| 16 
 .../__memory_resource/polymorphic_allocator.h|  3 ++-
 libcxx/src/filesystem/operations.cpp |  8 +---
 libcxx/src/memory_resource.cpp   |  3 ++-
 libcxx/src/mutex.cpp |  8 +---
 6 files changed, 38 insertions(+), 16 deletions(-)

diff --git a/libcxx/include/__config b/libcxx/include/__config
index 082c73e672c749..4d74b564864272 100644
--- a/libcxx/include/__config
+++ b/libcxx/include/__config
@@ -280,6 +280,14 @@
 // - `_LIBCPP_ASSERT_NON_OVERLAPPING_RANGES` -- for functions that take 
several ranges as arguments, checks that the
 //   given ranges do not overlap.
 //
+// - `_LIBCPP_ASSERT_VALID_DEALLOCATION` -- checks that an attempt to 
deallocate memory is valid (e.g. the given object
+//   was allocated by the given allocator). Violating this category typically 
results in a memory leak.
+//
+// - `_LIBCPP_ASSERT_VALID_EXTERNAL_API_CALL` -- checks that a call to an 
external API (e.g. a syscall) doesn't fail in
+//   an unexpected manner. This includes triggering documented cases of 
undefined behavior in an external library (like
+//   attempting to unlock an unlocked mutex in pthreads). We generally don't 
expect these failures to compromize memory
+//   safety or otherwise create an immediate security issue.
+//
 // - `_LIBCPP_ASSERT_COMPATIBLE_ALLOCATOR` -- checks any operations that 
exchange nodes between containers to make sure
 //   the containers have compatible allocators.
 //
@@ -327,6 +335,8 @@ _LIBCPP_HARDENING_MODE_DEBUG
 // Overlapping ranges will make algorithms produce incorrect results but don't 
directly lead to a security
 // vulnerability.
 #define _LIBCPP_ASSERT_NON_OVERLAPPING_RANGES(expression, message)   
_LIBCPP_ASSUME(expression)
+#define _LIBCPP_ASSERT_VALID_DEALLOCATION(expression, message)   
_LIBCPP_ASSUME(expression)
+#define _LIBCPP_ASSERT_VALID_EXTERNAL_API_CALL(expression, message)  
_LIBCPP_ASSUME(expression)
 #define _LIBCPP_ASSERT_COMPATIBLE_ALLOCATOR(expression, message) 
_LIBCPP_ASSUME(expression)
 #define _LIBCPP_ASSERT_PEDANTIC(expression, message) 
_LIBCPP_ASSUME(expression)
 #define _LIBCPP_ASSERT_INTERNAL(expression, message) 
_LIBCPP_ASSUME(expression)
@@ -341,6 +351,8 @@ _LIBCPP_HARDENING_MODE_DEBUG
 #define _LIBCPP_ASSERT_VALID_ELEMENT_ACCESS(expression, message) 
_LIBCPP_ASSERT(expression, message)
 #define _LIBCPP_ASSERT_NON_NULL(expression, message) 
_LIBCPP_ASSERT(expression, message)
 #define _LIBCPP_ASSERT_NON_OVERLAPPING_RANGES(expression, message)   
_LIBCPP_ASSERT(expression, message)
+#define _LIBCPP_ASSERT_VALID_DEALLOCATION(expression, message)   
_LIBCPP_ASSERT(expression, message)
+#define _LIBCPP_ASSERT_VALID_EXTERNAL_API_CALL(expression, message)  
_LIBCPP_ASSERT(expression, message)
 #define _LIBCPP_ASSERT_COMPATIBLE_ALLOCATOR(expression, message) 
_LIBCPP_ASSERT(expression, message)
 #define _LIBCPP_ASSERT_UNCATEGORIZED(expression, message)
_LIBCPP_ASSERT(expression, message)
 #define _LIBCPP_ASSERT_PEDANTIC(expression, message) 
_LIBCPP_ASSERT(expression, message)
@@ -356,6 +368,8 @@ _LIBCPP_HARDENING_MODE_DEBUG
 #define _LIBCPP_ASSERT_VALID_ELEMENT_ACCESS(expression, message)  
_LIBCPP_ASSERT(expression, message)
 #define _LIBCPP_ASSERT_NON_NULL(expression, message)  
_LIBCPP_ASSERT(expression, message)
 #define _LIBCPP_ASSERT_NON_OVERLAPPING_RANGES(expression, message)
_LIBCPP_ASSERT(expression, message)
+#define _LIBCPP_ASSERT_VALID_DEALLOCATION(expression, message)
_LIBCPP_ASSERT(expression, message)
+#define _LIBCPP_ASSERT_VALID_EXTERNAL_API_CALL(expression, message)   
_LIBCPP_ASSERT(expression, message)
 #define _LIBCPP_ASSERT_COMPATIBLE_ALLOCATOR(expression, message)  
_LIBCPP_ASSERT(expression, message)
 #define _LIBCPP_ASSERT_PEDANTIC(expression, message)  
_LIBCPP_ASSERT(expression, message)
 #define _LIBCPP_ASSERT_INTERNAL(expression, message)  
_LIBCPP_ASSERT(expression, message)
@@ -370,6 +384,8 @@ _LIBCPP_HARDENING_MODE_DEBUG
 #define _LIBCPP_ASSERT_VALID_ELEMENT_ACCESS(expression, message)  
_LIBCPP_ASSUME(expression)
 #define _LIBCPP_ASSERT_NON_NULL(expression, message)  
_LIBCPP_ASSUME(expression)
 #def

[clang] [HLSL][SPIR-V] Add support -fspv-target-env opt (PR #78611)

2024-01-19 Thread Chris B via cfe-commits

https://github.com/llvm-beanz approved this pull request.


https://github.com/llvm/llvm-project/pull/78611
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [llvm] [MLGO] Upstream the corpus extraction tooling (PR #72319)

2024-01-19 Thread Aiden Grossman via cfe-commits

https://github.com/boomanaiden154 closed 
https://github.com/llvm/llvm-project/pull/72319
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] Add a "don't override" mapping for -fvisibility-from-dllstorageclass (PR #74629)

2024-01-19 Thread Tom Stellard via cfe-commits

tstellar wrote:

This commit broke the [ llvm-x86_64-debian-dylib 
bot](https://lab.llvm.org/buildbot/#/builders/196/builds/42821)

https://github.com/llvm/llvm-project/pull/74629
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Sema] Provide `-fvisibility-global-new-delete=` option (PR #75364)

2024-01-19 Thread via cfe-commits

https://github.com/bd1976bris updated 
https://github.com/llvm/llvm-project/pull/75364

>From 97efed8c73aed4fdca5510013c844e84953ec256 Mon Sep 17 00:00:00 2001
From: Ben Dunbobbin 
Date: Tue, 12 Dec 2023 08:07:17 +
Subject: [PATCH 1/7] [Sema] Provide `-fno-/-fvisibility-global-new-delete`
 option

By default the implicitly declared replaceable global new and delete
operators are given a `default` visibility attribute. Previous work,
see: https://reviews.llvm.org/D53787, added
`-fvisibility-global-new-delete-hidden` to change this to a `hidden`
visibility attribute.

This change adds: `-fno/-fvisibility-global-new-delete` which controls
whether or not to add a visibility attribute to the implicit
declarations for these functions. Without the attribute the replaceable
global new and delete operators behave normally (like other functions)
with respect to visibility attributes, pragmas and options.

The command line help for these options is rendered as:

  -fvisibility-global-new-delete
  Add a visibility attribute to the implicit
  global C++ operator new and delete declarations

  -fno-visibility-global-new-delete
  Do not add a visibility attribute to the implicit
  global C++ operator new and delete declarations

The motivation is to allow users to specify
`-fno-visibility-global-new-delete` when they intend to replace these
functions either for a single linkage unit or set of linkage units.

`-fno-visibility-global-new-delete` can be applied globally to the
compilations in a build where `-fvisibility-global-new-delete-hidden`
cannot; as it conflicts with a common pattern where these functions are
dynamically imported.

`-fno-visibility-global-new-delete` makes sense as the default for PS5.
Users that want the normal toolchain behaviour will be able to supply
`-fvisibility-global-new-delete`.
---
 clang/include/clang/Basic/LangOptions.def |  3 +-
 clang/include/clang/Driver/Options.td |  6 +++
 clang/lib/Driver/ToolChains/Clang.cpp | 12 +
 clang/lib/Driver/ToolChains/PS4CPU.cpp|  6 +++
 clang/lib/Sema/SemaExprCXX.cpp|  9 ++--
 .../visibility-global-new-delete.cpp  | 13 +
 .../Driver/visibility-global-new-delete.cl| 47 +++
 7 files changed, 91 insertions(+), 5 deletions(-)
 create mode 100644 clang/test/CodeGenCXX/visibility-global-new-delete.cpp
 create mode 100644 clang/test/Driver/visibility-global-new-delete.cl

diff --git a/clang/include/clang/Basic/LangOptions.def 
b/clang/include/clang/Basic/LangOptions.def
index c3d5399905a3fd..1471fc11e11663 100644
--- a/clang/include/clang/Basic/LangOptions.def
+++ b/clang/include/clang/Basic/LangOptions.def
@@ -306,7 +306,8 @@ BENIGN_LANGOPT(IgnoreXCOFFVisibility, 1, 0, "All the 
visibility attributes that
 BENIGN_LANGOPT(VisibilityInlinesHiddenStaticLocalVar, 1, 0,
"hidden visibility for static local variables in inline C++ "
"methods when -fvisibility-inlines hidden is enabled")
-LANGOPT(GlobalAllocationFunctionVisibilityHidden , 1, 0, "hidden visibility 
for global operator new and delete declaration")
+LANGOPT(GlobalAllocationFunctionVisibility, 1, 1, "add a visibility attribute 
to the implicit global operator new and delete declarations")
+LANGOPT(GlobalAllocationFunctionVisibilityHidden, 1, 0, "hidden visibility for 
global operator new and delete declarations")
 LANGOPT(NewInfallible , 1, 0, "Treats throwing global C++ operator new as 
always returning valid memory (annotates with __attribute__((returns_nonnull)) 
and throw()). This is detectable in source.")
 BENIGN_LANGOPT(ParseUnknownAnytype, 1, 0, "__unknown_anytype")
 BENIGN_LANGOPT(DebuggerSupport , 1, 0, "debugger support")
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index db2190318c931a..a9f43b18df6fbf 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -3863,6 +3863,12 @@ defm visibility_inlines_hidden_static_local_var : 
BoolFOption<"visibility-inline
 def fvisibility_ms_compat : Flag<["-"], "fvisibility-ms-compat">, 
Group,
   HelpText<"Give global types 'default' visibility and global functions and "
"variables 'hidden' visibility by default">;
+defm visibility_global_new_delete : BoolFOption<"visibility-global-new-delete",
+  LangOpts<"GlobalAllocationFunctionVisibility">, DefaultTrue,
+  PosFlag,
+  NegFlag,
+  BothFlags<[], [ClangOption, CC1Option],
+  " a visibility attribute to the implicit global C++ operator new and 
delete declarations">>;
 def fvisibility_global_new_delete_hidden : Flag<["-"], 
"fvisibility-global-new-delete-hidden">, Group,
   HelpText<"Give global C++ operator new and delete declarations hidden 
visibility">,
   Visibility<[ClangOption, CC1Option]>,
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
inde

[clang] [llvm] [Clang] Correct __builtin_dynamic_object_size for subobject types (PR #78526)

2024-01-19 Thread Bill Wendling via cfe-commits

bwendling wrote:

> > My answer for the question "what's the semantics of GCC's builtin X?" has 
> > always been "whatever GCC does." It's the best we can rely upon. But then 
> > we get into situations like this, where you and @nikic have one 
> > interpretation of their documentation and I have another. I can point to 
> > their behavior to back up my claim, but in the end it's probably not 
> > exactly clear even to GCC.
> 
> [@nikic 
> demonstrated](https://github.com/llvm/llvm-project/pull/78526#issuecomment-1900439850)
>  that our current behavior is already compatible with GCC's behavior. If 
> GCC's behavior is the spec, then we are allowed to return 48 rather than only 
> 40 or -1 (or presumably 0 if `argc` is out of bounds) for the original 
> example, because in some cases GCC does so.

No, he exposed a fluke in their implementation. I gave examples of where clang 
gets it wrong, and yet I apparently haven't "proven" anything according to this 
logic?

> > My concern is that we want to use this for code hardening. Without precise 
> > object sizes, we're hampered in our goal. The unfortunate reality is that 
> > we can only get that size via these `__builtin_[dynamic_]object_size` 
> > functions.
> 
> That's a totally understandable desire, but I think it's not realistic to 
> expect precise _sub_object sizes in the same cases that GCC can provide them, 
> due to the different architectural choices in the two compilers. If we had a 
> mid-level IR for Clang that still had frontend information, we could do 
> better by evaluating BOS there, so maybe that's one long term path forward to 
> consider. And in the short term, while there are cases where we won't be able 
> to match GCC, I think Clang should do better than it currently does in the 
> frontend, 

We're not talking about something like inline asm, where the internals of their 
register allocator is more-or-less exposed to the user, and therefore it's next 
to impossible for us to replicate all of it. This feature is far simpler, and 
should be something we can determine based on all of the information we're 
given.

> specifically in cases like the one in the bug report where there's an obvious 
> better answer that doesn't require any sophisticated analysis to discover.

What "obvious better answer" is that?

https://github.com/llvm/llvm-project/pull/78526
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [CMake][Release] Add option for enabling PGO to release cache file. (PR #78823)

2024-01-19 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Tom Stellard (tstellar)


Changes

The option is LLVM_RELEASE_ENABLE_PGO and it's turned on by default.

---
Full diff: https://github.com/llvm/llvm-project/pull/78823.diff


2 Files Affected:

- (modified) clang/cmake/caches/Release.cmake (+57-16) 
- (modified) llvm/utils/release/test-release.sh (+2-2) 


``diff
diff --git a/clang/cmake/caches/Release.cmake b/clang/cmake/caches/Release.cmake
index a7b9a8d0e29f88f..0d114c3734a82d3 100644
--- a/clang/cmake/caches/Release.cmake
+++ b/clang/cmake/caches/Release.cmake
@@ -4,27 +4,53 @@
 
 # General Options
 set(LLVM_RELEASE_ENABLE_LTO THIN CACHE STRING "")
+set(LLVM_RELEASE_ENABLE_PGO ON CACHE BOOL "")
 
 set(CMAKE_BUILD_TYPE RELEASE CACHE STRING "")
 
 # Stage 1 Bootstrap Setup
 set(CLANG_ENABLE_BOOTSTRAP ON CACHE BOOL "")
-set(CLANG_BOOTSTRAP_TARGETS
-  clang
-  check-all
-  check-llvm
-  check-clang
-  test-suite
-  stage3
-  stage3-clang
-  stage3-check-all
-  stage3-check-llvm
-  stage3-check-clang
-  stage3-install
-  stage3-test-suite CACHE STRING "")
+if (LLVM_RELEASE_ENABLE_PGO)
+  set(CLANG_BOOTSTRAP_TARGETS
+generate-profdata
+stage2
+stage2-clang
+stage2-distribution
+stage2-install
+stage2-install-distribution
+stage2-install-distribution-toolchain
+stage2-check-all
+stage2-check-llvm
+stage2-check-clang
+stage2-test-suite CACHE STRING "")
+else()
+  set(CLANG_BOOTSTRAP_TARGETS
+clang
+check-all
+check-llvm
+check-clang
+test-suite
+stage3
+stage3-clang
+stage3-check-all
+stage3-check-llvm
+stage3-check-clang
+stage3-install
+stage3-test-suite CACHE STRING "")
+endif()
 
 # Stage 1 Options
-set(LLVM_ENABLE_PROJECTS "clang" CACHE STRING "")
+set(STAGE1_PROJECTS "clang")
+set(STAGE1_RUNTIMES "")
+
+if (LLVM_RELEASE_ENABLE_PGO)
+  list(APPEND STAGE1_PROJECTS "lld")
+  list(APPEND STAGE1_RUNTIMES "compiler-rt")
+endif()
+
+set(LLVM_ENABLE_RUNTIMES ${STAGE1_RUNTIMES} CACHE STRING "")
+set(LLVM_ENABLE_PROJECTS ${STAGE1_PROJECTS} CACHE STRING "")
+
 set(LLVM_TARGETS_TO_BUILD Native CACHE STRING "")
 
 # Stage 2 Bootstrap Setup
@@ -37,11 +63,26 @@ set(BOOTSTRAP_CLANG_BOOTSTRAP_TARGETS
 
 # Stage 2 Options
 set(STAGE2_PROJECTS "clang")
-if (LLVM_RELEASE_ENABLE_LTO)
+set(STAGE2_RUNTIMES "")
+
+if (LLVM_RELEASE_ENABLE_LTO OR LLVM_RELEASE_ENABLE_PGO)
  list(APPEND STAGE2_PROJECTS "lld")
 endif()
+
+if (LLVM_RELEASE_ENABLE_PGO)
+  set(BOOTSTRAP_LLVM_BUILD_INSTRUMENTED ON CACHE BOOL "")
+  list(APPEND STAGE2_RUNTIMES "compiler-rt")
+  set(BOOTSTRAP_LLVM_ENABLE_LTO ${LLVM_RELEASE_ENABLE_LTO})
+  if (LLVM_RELEASE_ENABLE_LTO)
+set(BOOTSTRAP_LLVM_ENABLE_LLD ON CACHE BOOL "")
+  endif()
+endif()
+
 set(BOOTSTRAP_LLVM_ENABLE_PROJECTS ${STAGE2_PROJECTS} CACHE STRING "")
-set(BOOTSTRAP_LLVM_TARGETS_TO_BUILD Native CACHE STRING "")
+set(BOOTSTRAP_LLVM_ENABLE_RUNTIMES ${STAGE2_RUNTIMES} CACHE STRING "")
+if (NOT LLVM_RELEASE_ENABLE_PGO)
+  set(BOOTSTRAP_LLVM_TARGETS_TO_BUILD Native CACHE STRING "")
+endif()
 
 # Stage 3 Options
 set(BOOTSTRAP_BOOTSTRAP_LLVM_ENABLE_RUNTIMES 
"compiler-rt;libcxx;libcxxabi;libunwind" CACHE STRING "")
diff --git a/llvm/utils/release/test-release.sh 
b/llvm/utils/release/test-release.sh
index 544d4bfdd799ce8..5b1945df47d24a7 100755
--- a/llvm/utils/release/test-release.sh
+++ b/llvm/utils/release/test-release.sh
@@ -359,11 +359,11 @@ function build_with_cmake_cache() {
 $ExtraConfigureFlags
 2>&1 | tee $LogDir/llvm.configure-$Flavor.log
 
-  ${MAKE} $J_ARG $Verbose -C $CMakeBuildDir stage3-check-all \
+  ${MAKE} $J_ARG $Verbose -C $CMakeBuildDir stage2-check-all \
   2>&1 | tee $LogDir/llvm.make-$Flavor.log > $redir
 
   DESTDIR="${InstallDir}" \
-  ${MAKE} -C $CMakeBuildDir stage3-install \
+  ${MAKE} -C $CMakeBuildDir stage2-install \
   2>&1 | tee $LogDir/llvm.install-$Flavor.log > $redir
 
  mkdir -p $BuildDir/Release

``




https://github.com/llvm/llvm-project/pull/78823
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [CMake][Release] Add option for enabling PGO to release cache file. (PR #78823)

2024-01-19 Thread Tom Stellard via cfe-commits

https://github.com/tstellar created 
https://github.com/llvm/llvm-project/pull/78823

The option is LLVM_RELEASE_ENABLE_PGO and it's turned on by default.

>From b23e23f862bec32e42fa7aa96da1fe0c4ed38a54 Mon Sep 17 00:00:00 2001
From: Tom Stellard 
Date: Sat, 6 Jan 2024 06:44:32 +
Subject: [PATCH] [CMake][Release] Add option for enabling PGO to release cache
 file.

The option is LLVM_RELEASE_ENABLE_PGO and it's turned on by default.
---
 clang/cmake/caches/Release.cmake   | 73 +++---
 llvm/utils/release/test-release.sh |  4 +-
 2 files changed, 59 insertions(+), 18 deletions(-)

diff --git a/clang/cmake/caches/Release.cmake b/clang/cmake/caches/Release.cmake
index a7b9a8d0e29f88f..0d114c3734a82d3 100644
--- a/clang/cmake/caches/Release.cmake
+++ b/clang/cmake/caches/Release.cmake
@@ -4,27 +4,53 @@
 
 # General Options
 set(LLVM_RELEASE_ENABLE_LTO THIN CACHE STRING "")
+set(LLVM_RELEASE_ENABLE_PGO ON CACHE BOOL "")
 
 set(CMAKE_BUILD_TYPE RELEASE CACHE STRING "")
 
 # Stage 1 Bootstrap Setup
 set(CLANG_ENABLE_BOOTSTRAP ON CACHE BOOL "")
-set(CLANG_BOOTSTRAP_TARGETS
-  clang
-  check-all
-  check-llvm
-  check-clang
-  test-suite
-  stage3
-  stage3-clang
-  stage3-check-all
-  stage3-check-llvm
-  stage3-check-clang
-  stage3-install
-  stage3-test-suite CACHE STRING "")
+if (LLVM_RELEASE_ENABLE_PGO)
+  set(CLANG_BOOTSTRAP_TARGETS
+generate-profdata
+stage2
+stage2-clang
+stage2-distribution
+stage2-install
+stage2-install-distribution
+stage2-install-distribution-toolchain
+stage2-check-all
+stage2-check-llvm
+stage2-check-clang
+stage2-test-suite CACHE STRING "")
+else()
+  set(CLANG_BOOTSTRAP_TARGETS
+clang
+check-all
+check-llvm
+check-clang
+test-suite
+stage3
+stage3-clang
+stage3-check-all
+stage3-check-llvm
+stage3-check-clang
+stage3-install
+stage3-test-suite CACHE STRING "")
+endif()
 
 # Stage 1 Options
-set(LLVM_ENABLE_PROJECTS "clang" CACHE STRING "")
+set(STAGE1_PROJECTS "clang")
+set(STAGE1_RUNTIMES "")
+
+if (LLVM_RELEASE_ENABLE_PGO)
+  list(APPEND STAGE1_PROJECTS "lld")
+  list(APPEND STAGE1_RUNTIMES "compiler-rt")
+endif()
+
+set(LLVM_ENABLE_RUNTIMES ${STAGE1_RUNTIMES} CACHE STRING "")
+set(LLVM_ENABLE_PROJECTS ${STAGE1_PROJECTS} CACHE STRING "")
+
 set(LLVM_TARGETS_TO_BUILD Native CACHE STRING "")
 
 # Stage 2 Bootstrap Setup
@@ -37,11 +63,26 @@ set(BOOTSTRAP_CLANG_BOOTSTRAP_TARGETS
 
 # Stage 2 Options
 set(STAGE2_PROJECTS "clang")
-if (LLVM_RELEASE_ENABLE_LTO)
+set(STAGE2_RUNTIMES "")
+
+if (LLVM_RELEASE_ENABLE_LTO OR LLVM_RELEASE_ENABLE_PGO)
  list(APPEND STAGE2_PROJECTS "lld")
 endif()
+
+if (LLVM_RELEASE_ENABLE_PGO)
+  set(BOOTSTRAP_LLVM_BUILD_INSTRUMENTED ON CACHE BOOL "")
+  list(APPEND STAGE2_RUNTIMES "compiler-rt")
+  set(BOOTSTRAP_LLVM_ENABLE_LTO ${LLVM_RELEASE_ENABLE_LTO})
+  if (LLVM_RELEASE_ENABLE_LTO)
+set(BOOTSTRAP_LLVM_ENABLE_LLD ON CACHE BOOL "")
+  endif()
+endif()
+
 set(BOOTSTRAP_LLVM_ENABLE_PROJECTS ${STAGE2_PROJECTS} CACHE STRING "")
-set(BOOTSTRAP_LLVM_TARGETS_TO_BUILD Native CACHE STRING "")
+set(BOOTSTRAP_LLVM_ENABLE_RUNTIMES ${STAGE2_RUNTIMES} CACHE STRING "")
+if (NOT LLVM_RELEASE_ENABLE_PGO)
+  set(BOOTSTRAP_LLVM_TARGETS_TO_BUILD Native CACHE STRING "")
+endif()
 
 # Stage 3 Options
 set(BOOTSTRAP_BOOTSTRAP_LLVM_ENABLE_RUNTIMES 
"compiler-rt;libcxx;libcxxabi;libunwind" CACHE STRING "")
diff --git a/llvm/utils/release/test-release.sh 
b/llvm/utils/release/test-release.sh
index 544d4bfdd799ce8..5b1945df47d24a7 100755
--- a/llvm/utils/release/test-release.sh
+++ b/llvm/utils/release/test-release.sh
@@ -359,11 +359,11 @@ function build_with_cmake_cache() {
 $ExtraConfigureFlags
 2>&1 | tee $LogDir/llvm.configure-$Flavor.log
 
-  ${MAKE} $J_ARG $Verbose -C $CMakeBuildDir stage3-check-all \
+  ${MAKE} $J_ARG $Verbose -C $CMakeBuildDir stage2-check-all \
   2>&1 | tee $LogDir/llvm.make-$Flavor.log > $redir
 
   DESTDIR="${InstallDir}" \
-  ${MAKE} -C $CMakeBuildDir stage3-install \
+  ${MAKE} -C $CMakeBuildDir stage2-install \
   2>&1 | tee $LogDir/llvm.install-$Flavor.log > $redir
 
  mkdir -p $BuildDir/Release

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [-Wunsafe-buffer-usage] Fix the crash introduced by the unsafe invocation of span::data warning (PR #78815)

2024-01-19 Thread Ziqing Luo via cfe-commits


@@ -2263,15 +2263,27 @@ class UnsafeBufferUsageReporter : public 
UnsafeBufferUsageHandler {
 MsgParam = 3;
   } else if (const auto *ECE = dyn_cast(Operation)) {
 QualType destType = ECE->getType();
-const uint64_t dSize =
-Ctx.getTypeSize(destType.getTypePtr()->getPointeeType());
-if (const auto *CE = dyn_cast(ECE->getSubExpr())) {
-  QualType srcType = CE->getType();
-  const uint64_t sSize =
-  Ctx.getTypeSize(srcType.getTypePtr()->getPointeeType());
-  if (sSize >= dSize)
+if (!isa(destType))
+  return;
+
+const Expr *subExpr = ECE->getSubExpr();
+// Check if related to DataInvocation warning gadget.

ziqingluo-90 wrote:

nitpick: not sure if we need this check.  `DataInvocation` warning gadget is 
the only possible explicit-cast kind `Operation` here.This is completely my 
personal taste: this function sort of implies unique correspondence between 
warning gadgets and `Operation` kinds if without the check.

https://github.com/llvm/llvm-project/pull/78815
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [-Wunsafe-buffer-usage] Fix the crash introduced by the unsafe invocation of span::data warning (PR #78815)

2024-01-19 Thread Ziqing Luo via cfe-commits

https://github.com/ziqingluo-90 approved this pull request.

LGTM!   Feel free to ignore my comment if it doesn't make sense to you.

https://github.com/llvm/llvm-project/pull/78815
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [-Wunsafe-buffer-usage] Fix the crash introduced by the unsafe invocation of span::data warning (PR #78815)

2024-01-19 Thread Ziqing Luo via cfe-commits

https://github.com/ziqingluo-90 edited 
https://github.com/llvm/llvm-project/pull/78815
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[llvm] [clang-tools-extra] [MLGO] Upstream the corpus extraction tooling (PR #72319)

2024-01-19 Thread Mircea Trofin via cfe-commits

https://github.com/mtrofin approved this pull request.

Thanks for adding license info!

https://github.com/llvm/llvm-project/pull/72319
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[llvm] [clang] [Clang] Correct __builtin_dynamic_object_size for subobject types (PR #78526)

2024-01-19 Thread Richard Smith via cfe-commits

zygoloid wrote:

> My answer for the question "what's the semantics of GCC's builtin X?" has 
> always been "whatever GCC does." It's the best we can rely upon. But then we 
> get into situations like this, where you and @nikic have one interpretation 
> of their documentation and I have another. I can point to their behavior to 
> back up my claim, but in the end it's probably not exactly clear even to GCC.

[@nikic 
demonstrated](https://github.com/llvm/llvm-project/pull/78526#issuecomment-1900439850)
 that our current behavior is already compatible with GCC's behavior. If GCC's 
behavior is the spec, then we are allowed to return 48 rather than only 40 or 
-1 (or presumably 0 if `argc` is out of bounds) for the original example, 
because in some cases GCC does so.

> My concern is that we want to use this for code hardening. Without precise 
> object sizes, we're hampered in our goal. The unfortunate reality is that we 
> can only get that size via these `__builtin_[dynamic_]object_size` functions.

That's a totally understandable desire, but I think it's not realistic to 
expect precise *sub*object sizes in the same cases that GCC can provide them, 
due to the different architectural choices in the two compilers. If we had a 
mid-level IR for Clang that still had frontend information, we could do better 
by evaluating BOS there, so maybe that's one long term path forward to 
consider. And in the short term, while there are cases where we won't be able 
to match GCC, I think Clang should do better than it currently does in the 
frontend, specifically in cases like the one in the bug report where there's an 
obvious better answer that doesn't require any sophisticated analysis to 
discover.

> > Here, `f` ideally would return 4, but at the LLVM IR level, `p` and `q` are 
> > identical values and the `&p->a` operation is a no-op. In cases like this, 
> > the best we can realistically do is to return 8.
> 
> The sub-object for `&p->a` and even `&p->b` is `struct X`, not the integers 
> themselves. If you want that, you'll have to use casts: `&((char 
> *)p->b)[2];`. (I had to take care to get that correct.) So `f` should return 
> `8` (note it's likely to get `8` from the `alloc_size` attribute on `malloc` 
> in your example).

GCC disagrees with you: https://godbolt.org/z/s4P74oEqx

https://github.com/llvm/llvm-project/pull/78526
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [clang, SystemZ] Pass HasDef flag to getMinGlobalAlign(). (PR #73511)

2024-01-19 Thread Jonas Paulsson via cfe-commits


@@ -11,6 +11,7 @@
 
//===--===//
 
 #include "SystemZ.h"
+#include "clang/AST/Decl.h"

JonPsson1 wrote:

Ah, one more #include to remove that I missed - thanks :)

https://github.com/llvm/llvm-project/pull/73511
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [clang, SystemZ] Pass HasDef flag to getMinGlobalAlign(). (PR #73511)

2024-01-19 Thread Jonas Paulsson via cfe-commits

https://github.com/JonPsson1 updated 
https://github.com/llvm/llvm-project/pull/73511

>From 5c1c5d401775089bc600b85227f5e7bd974d4bd0 Mon Sep 17 00:00:00 2001
From: Jonas Paulsson 
Date: Thu, 23 Nov 2023 17:22:32 +0100
Subject: [PATCH 1/3] Initial Also handle weak symbols Fix test for -emit-llvm
 clang-format

---
 clang/include/clang/AST/ASTContext.h  |   4 +-
 clang/include/clang/Basic/TargetInfo.h|   6 +-
 clang/include/clang/Driver/Options.td |   4 +
 clang/lib/AST/ASTContext.cpp  |  12 +-
 clang/lib/Basic/Targets/AArch64.cpp   |   5 +-
 clang/lib/Basic/Targets/AArch64.h |   3 +-
 clang/lib/Basic/Targets/CSKY.cpp  |   3 +-
 clang/lib/Basic/Targets/CSKY.h|   2 +-
 clang/lib/Basic/Targets/NVPTX.cpp |   3 +-
 clang/lib/Basic/Targets/SPIR.h|   3 +-
 clang/lib/Basic/Targets/SystemZ.cpp   |  11 ++
 clang/lib/Basic/Targets/SystemZ.h |   9 +-
 clang/lib/CodeGen/CodeGenModule.cpp   |   7 +-
 clang/lib/Driver/ToolChains/Arch/SystemZ.cpp  |   8 ++
 clang/lib/Sema/SemaOpenMP.cpp |   2 +-
 .../test/CodeGen/SystemZ/unaligned-symbols.c  | 113 ++
 llvm/lib/Target/SystemZ/SystemZFeatures.td|   5 +
 17 files changed, 179 insertions(+), 21 deletions(-)
 create mode 100644 clang/test/CodeGen/SystemZ/unaligned-symbols.c

diff --git a/clang/include/clang/AST/ASTContext.h 
b/clang/include/clang/AST/ASTContext.h
index 3e46a5da3fc043f..2c42602bef5a6f3 100644
--- a/clang/include/clang/AST/ASTContext.h
+++ b/clang/include/clang/AST/ASTContext.h
@@ -2406,11 +2406,11 @@ class ASTContext : public RefCountedBase {
 
   /// Return the alignment in bits that should be given to a
   /// global variable with type \p T.
-  unsigned getAlignOfGlobalVar(QualType T) const;
+  unsigned getAlignOfGlobalVar(QualType T, const VarDecl *VD) const;
 
   /// Return the alignment in characters that should be given to a
   /// global variable with type \p T.
-  CharUnits getAlignOfGlobalVarInChars(QualType T) const;
+  CharUnits getAlignOfGlobalVarInChars(QualType T, const VarDecl *VD) const;
 
   /// Return a conservative estimate of the alignment of the specified
   /// decl \p D.
diff --git a/clang/include/clang/Basic/TargetInfo.h 
b/clang/include/clang/Basic/TargetInfo.h
index 3eb23ebdacf0edd..7ac6bf24124cdda 100644
--- a/clang/include/clang/Basic/TargetInfo.h
+++ b/clang/include/clang/Basic/TargetInfo.h
@@ -50,6 +50,7 @@ class DiagnosticsEngine;
 class LangOptions;
 class CodeGenOptions;
 class MacroBuilder;
+class VarDecl;
 
 /// Contains information gathered from parsing the contents of TargetAttr.
 struct ParsedTargetAttr {
@@ -704,8 +705,9 @@ class TargetInfo : public TransferrableTargetInfo,
   }
 
   /// getMinGlobalAlign - Return the minimum alignment of a global variable,
-  /// unless its alignment is explicitly reduced via attributes.
-  virtual unsigned getMinGlobalAlign (uint64_t) const {
+  /// unless its alignment is explicitly reduced via attributes. If \param VD
+  /// is non-null, it may be used to examine the specific variable's 
attributes.
+  virtual unsigned getMinGlobalAlign(uint64_t Size, const VarDecl *VD) const {
 return MinGlobalAlign;
   }
 
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index d2e6c3ff721c27e..29f2b5c8b005120 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -4601,6 +4601,10 @@ def munaligned_access : Flag<["-"], 
"munaligned-access">, Group,
   HelpText<"Allow memory accesses to be unaligned 
(AArch32/AArch64/LoongArch/RISC-V only)">;
 def mno_unaligned_access : Flag<["-"], "mno-unaligned-access">, Group,
   HelpText<"Force all memory accesses to be aligned 
(AArch32/AArch64/LoongArch/RISC-V only)">;
+def munaligned_symbols : Flag<["-"], "munaligned-symbols">, Group,
+  HelpText<"Expect external char-aligned symbols to be without ABI alignment 
(SystemZ only)">;
+def mno_unaligned_symbols : Flag<["-"], "mno-unaligned-symbols">, 
Group,
+  HelpText<"Expect external char-aligned symbols to be without ABI alignment 
(SystemZ only)">;
 } // let Flags = [TargetSpecific]
 def mstrict_align : Flag<["-"], "mstrict-align">, Alias,
   Flags<[HelpHidden]>, Visibility<[ClangOption, CC1Option]>,
diff --git a/clang/lib/AST/ASTContext.cpp b/clang/lib/AST/ASTContext.cpp
index 0fc0831b221aab3..a6314c83f06ca73 100644
--- a/clang/lib/AST/ASTContext.cpp
+++ b/clang/lib/AST/ASTContext.cpp
@@ -1688,7 +1688,8 @@ CharUnits ASTContext::getDeclAlign(const Decl *D, bool 
ForAlignof) const {
   if (VD->hasGlobalStorage() && !ForAlignof) {
 uint64_t TypeSize =
 !BaseT->isIncompleteType() ? getTypeSize(T.getTypePtr()) : 0;
-Align = std::max(Align, getTargetInfo().getMinGlobalAlign(TypeSize));
+Align =
+std::max(Align, getTargetInfo().getMinGlobalAlign(TypeSize, VD));
   }
 
 // Fields can be subject

[clang] [clang][modules] Fix CodeGen options that can affect the AST. (PR #78816)

2024-01-19 Thread Juergen Ributzka via cfe-commits

https://github.com/ributzka updated 
https://github.com/llvm/llvm-project/pull/78816

>From ba6eac97038a8fbd24d288ffa88a4dcf508e66b8 Mon Sep 17 00:00:00 2001
From: Juergen Ributzka 
Date: Fri, 19 Jan 2024 16:10:03 -0800
Subject: [PATCH 1/2] [clang][modules] Fix CodeGen options that can affect the
 AST.

`OptimizationLevel` and `OptimizeSize` can affect the generated AST. They
indirectly affect the `Optimize` and `OptimizeSize` frontend options, which in
turn set predefined macro definitions.

This fixes rdar://121228252.
---
 clang/include/clang/Basic/CodeGenOptions.def  | 14 --
 clang/lib/Basic/CodeGenOptions.cpp|  2 ++
 clang/test/ClangScanDeps/strip-codegen-args.m | 11 +++
 3 files changed, 21 insertions(+), 6 deletions(-)

diff --git a/clang/include/clang/Basic/CodeGenOptions.def 
b/clang/include/clang/Basic/CodeGenOptions.def
index 2c4fb6745bc172..f535291b6ba4ee 100644
--- a/clang/include/clang/Basic/CodeGenOptions.def
+++ b/clang/include/clang/Basic/CodeGenOptions.def
@@ -12,6 +12,9 @@
 // that have enumeration type and VALUE_CODEGENOPT is a code
 // generation option that describes a value rather than a flag.
 //
+// AFFECTING_VALUE_CODEGENOPT is used for code generation options that can
+// affect the AST.
+//
 
//===--===//
 #ifndef CODEGENOPT
 #  error Define the CODEGENOPT macro to handle language options
@@ -27,6 +30,11 @@ CODEGENOPT(Name, Bits, Default)
 CODEGENOPT(Name, Bits, Default)
 #endif
 
+#ifndef AFFECTING_VALUE_CODEGENOPT
+#  define AFFECTING_VALUE_CODEGENOPT(Name, Bits, Default) \
+VALUE_CODEGENOPT(Name, Bits, Default)
+#endif
+
 CODEGENOPT(DisableIntegratedAS, 1, 0) ///< -no-integrated-as
 CODEGENOPT(RelaxELFRelocations, 1, 1) ///< -Wa,-mrelax-relocations={yes,no}
 CODEGENOPT(AsmVerbose, 1, 0) ///< -dA, -fverbose-asm.
@@ -193,8 +201,10 @@ ENUM_CODEGENOPT(ObjCDispatchMethod, 
ObjCDispatchMethodKind, 2, Legacy)
 CODEGENOPT(ObjCConvertMessagesToRuntimeCalls , 1, 1)
 CODEGENOPT(ObjCAvoidHeapifyLocalBlocks, 1, 0)
 
-VALUE_CODEGENOPT(OptimizationLevel, 2, 0) ///< The -O[0-3] option specified.
-VALUE_CODEGENOPT(OptimizeSize, 2, 0) ///< If -Os (==1) or -Oz (==2) is 
specified.
+
+// The optimization options affect frontend options, whicn in turn do affect 
the AST.
+AFFECTING_VALUE_CODEGENOPT(OptimizationLevel, 2, 0) ///< The -O[0-3] option 
specified.
+AFFECTING_VALUE_CODEGENOPT(OptimizeSize, 2, 0) ///< If -Os (==1) or -Oz (==2) 
is specified.
 
 CODEGENOPT(AtomicProfileUpdate , 1, 0) ///< Set -fprofile-update=atomic
 /// Choose profile instrumenation kind or no instrumentation.
diff --git a/clang/lib/Basic/CodeGenOptions.cpp 
b/clang/lib/Basic/CodeGenOptions.cpp
index 182d0a2fa4d88f..79d715305ef20b 100644
--- a/clang/lib/Basic/CodeGenOptions.cpp
+++ b/clang/lib/Basic/CodeGenOptions.cpp
@@ -27,6 +27,8 @@ void CodeGenOptions::resetNonModularOptions(StringRef 
ModuleFormat) {
 #define ENUM_DEBUGOPT(Name, Type, Bits, Default)
 #define CODEGENOPT(Name, Bits, Default) Name = Default;
 #define ENUM_CODEGENOPT(Name, Type, Bits, Default) set##Name(Default);
+// Do not reset AST affecting code generation options.
+#define AFFECTING_VALUE_CODEGENOPT(Name, Bits, Default)
 #include "clang/Basic/CodeGenOptions.def"
 
   // Next reset all debug options that can always be reset, because they never
diff --git a/clang/test/ClangScanDeps/strip-codegen-args.m 
b/clang/test/ClangScanDeps/strip-codegen-args.m
index bb7e76e86aa2f9..71171f4983386d 100644
--- a/clang/test/ClangScanDeps/strip-codegen-args.m
+++ b/clang/test/ClangScanDeps/strip-codegen-args.m
@@ -5,11 +5,14 @@
 // RUN: clang-scan-deps -compilation-database %t/cdb1.json -format 
experimental-full > %t/result1.txt
 // RUN: FileCheck %s -input-file %t/result1.txt
 
-// This tests that codegen option that do not affect the AST or generation of 
a module are removed. 
+// This tests that codegen option that do not affect the AST or generation of a
+// module are removed. It also tests that the optimization options that affect
+// the AST are not reset to -O0.
 
 // CHECK:"modules": [
 // CHECK-NEXT: {
 // CHECK:"command-line": [
+// CHECK-NOT:  "-O0"
 // CHECK-NOT:  "-flto"
 // CHECK-NOT:  "-fno-autolink"
 // CHECK-NOT:  "-mrelax-relocations=no"
@@ -23,17 +26,17 @@
 [
   {
 "directory": "DIR",
-"command": "clang -Imodules/A -fmodules 
-fmodules-cache-path=DIR/module-cache -fimplicit-modules -flto -fno-autolink 
-Xclang -mrelax-relocations=no -fsyntax-only DIR/t1.m",
+"command": "clang -Imodules/A -fmodules 
-fmodules-cache-path=DIR/module-cache -fimplicit-modules -O2 -flto 
-fno-autolink -Xclang -mrelax-relocations=no -fsyntax-only DIR/t1.m",
 "file": "DIR/t1.m"
   },
   {
 "directory": "DIR",
-"command": "clang -Imodules/A -fmodules 
-fmodules-cache-path=DIR/module-cache -fimplicit-modules -flto=thin -fautolink 
-fsyntax-only DIR/t2.m",
+"command": "clang -Imodul

[clang] [llvm] [clang-tools-extra] [msan] Unpoison indirect outputs for userspace when -msan-handle-asm-conservative is specified (PR #77393)

2024-01-19 Thread Fangrui Song via cfe-commits

https://github.com/MaskRay closed 
https://github.com/llvm/llvm-project/pull/77393
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [-Wunsafe-buffer-usage] Fix the crash introduced by the unsafe invocation of span::data warning (PR #78815)

2024-01-19 Thread Malavika Samak via cfe-commits

https://github.com/malavikasamak edited 
https://github.com/llvm/llvm-project/pull/78815
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [-Wunsafe-buffer-usage] Fix the crash introduced by the unsafe invocation of span::data warning (PR #78815)

2024-01-19 Thread Malavika Samak via cfe-commits

https://github.com/malavikasamak edited 
https://github.com/llvm/llvm-project/pull/78815
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][modules] Fix CodeGen options that can affect the AST. (PR #78816)

2024-01-19 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Juergen Ributzka (ributzka)


Changes

`OptimizationLevel` and `OptimizeSize` can affect the generated AST. They
indirectly affect the `Optimize` and `OptimizeSize` frontend options, which in
turn set predefined macro definitions.

This fixes rdar://121228252.


---
Full diff: https://github.com/llvm/llvm-project/pull/78816.diff


3 Files Affected:

- (modified) clang/include/clang/Basic/CodeGenOptions.def (+12-2) 
- (modified) clang/lib/Basic/CodeGenOptions.cpp (+2) 
- (modified) clang/test/ClangScanDeps/strip-codegen-args.m (+7-4) 


``diff
diff --git a/clang/include/clang/Basic/CodeGenOptions.def 
b/clang/include/clang/Basic/CodeGenOptions.def
index 2c4fb6745bc172..f535291b6ba4ee 100644
--- a/clang/include/clang/Basic/CodeGenOptions.def
+++ b/clang/include/clang/Basic/CodeGenOptions.def
@@ -12,6 +12,9 @@
 // that have enumeration type and VALUE_CODEGENOPT is a code
 // generation option that describes a value rather than a flag.
 //
+// AFFECTING_VALUE_CODEGENOPT is used for code generation options that can
+// affect the AST.
+//
 
//===--===//
 #ifndef CODEGENOPT
 #  error Define the CODEGENOPT macro to handle language options
@@ -27,6 +30,11 @@ CODEGENOPT(Name, Bits, Default)
 CODEGENOPT(Name, Bits, Default)
 #endif
 
+#ifndef AFFECTING_VALUE_CODEGENOPT
+#  define AFFECTING_VALUE_CODEGENOPT(Name, Bits, Default) \
+VALUE_CODEGENOPT(Name, Bits, Default)
+#endif
+
 CODEGENOPT(DisableIntegratedAS, 1, 0) ///< -no-integrated-as
 CODEGENOPT(RelaxELFRelocations, 1, 1) ///< -Wa,-mrelax-relocations={yes,no}
 CODEGENOPT(AsmVerbose, 1, 0) ///< -dA, -fverbose-asm.
@@ -193,8 +201,10 @@ ENUM_CODEGENOPT(ObjCDispatchMethod, 
ObjCDispatchMethodKind, 2, Legacy)
 CODEGENOPT(ObjCConvertMessagesToRuntimeCalls , 1, 1)
 CODEGENOPT(ObjCAvoidHeapifyLocalBlocks, 1, 0)
 
-VALUE_CODEGENOPT(OptimizationLevel, 2, 0) ///< The -O[0-3] option specified.
-VALUE_CODEGENOPT(OptimizeSize, 2, 0) ///< If -Os (==1) or -Oz (==2) is 
specified.
+
+// The optimization options affect frontend options, whicn in turn do affect 
the AST.
+AFFECTING_VALUE_CODEGENOPT(OptimizationLevel, 2, 0) ///< The -O[0-3] option 
specified.
+AFFECTING_VALUE_CODEGENOPT(OptimizeSize, 2, 0) ///< If -Os (==1) or -Oz (==2) 
is specified.
 
 CODEGENOPT(AtomicProfileUpdate , 1, 0) ///< Set -fprofile-update=atomic
 /// Choose profile instrumenation kind or no instrumentation.
diff --git a/clang/lib/Basic/CodeGenOptions.cpp 
b/clang/lib/Basic/CodeGenOptions.cpp
index 182d0a2fa4d88f..79d715305ef20b 100644
--- a/clang/lib/Basic/CodeGenOptions.cpp
+++ b/clang/lib/Basic/CodeGenOptions.cpp
@@ -27,6 +27,8 @@ void CodeGenOptions::resetNonModularOptions(StringRef 
ModuleFormat) {
 #define ENUM_DEBUGOPT(Name, Type, Bits, Default)
 #define CODEGENOPT(Name, Bits, Default) Name = Default;
 #define ENUM_CODEGENOPT(Name, Type, Bits, Default) set##Name(Default);
+// Do not reset AST affecting code generation options.
+#define AFFECTING_VALUE_CODEGENOPT(Name, Bits, Default)
 #include "clang/Basic/CodeGenOptions.def"
 
   // Next reset all debug options that can always be reset, because they never
diff --git a/clang/test/ClangScanDeps/strip-codegen-args.m 
b/clang/test/ClangScanDeps/strip-codegen-args.m
index bb7e76e86aa2f9..71171f4983386d 100644
--- a/clang/test/ClangScanDeps/strip-codegen-args.m
+++ b/clang/test/ClangScanDeps/strip-codegen-args.m
@@ -5,11 +5,14 @@
 // RUN: clang-scan-deps -compilation-database %t/cdb1.json -format 
experimental-full > %t/result1.txt
 // RUN: FileCheck %s -input-file %t/result1.txt
 
-// This tests that codegen option that do not affect the AST or generation of 
a module are removed. 
+// This tests that codegen option that do not affect the AST or generation of a
+// module are removed. It also tests that the optimization options that affect
+// the AST are not reset to -O0.
 
 // CHECK:"modules": [
 // CHECK-NEXT: {
 // CHECK:"command-line": [
+// CHECK-NOT:  "-O0"
 // CHECK-NOT:  "-flto"
 // CHECK-NOT:  "-fno-autolink"
 // CHECK-NOT:  "-mrelax-relocations=no"
@@ -23,17 +26,17 @@
 [
   {
 "directory": "DIR",
-"command": "clang -Imodules/A -fmodules 
-fmodules-cache-path=DIR/module-cache -fimplicit-modules -flto -fno-autolink 
-Xclang -mrelax-relocations=no -fsyntax-only DIR/t1.m",
+"command": "clang -Imodules/A -fmodules 
-fmodules-cache-path=DIR/module-cache -fimplicit-modules -O2 -flto 
-fno-autolink -Xclang -mrelax-relocations=no -fsyntax-only DIR/t1.m",
 "file": "DIR/t1.m"
   },
   {
 "directory": "DIR",
-"command": "clang -Imodules/A -fmodules 
-fmodules-cache-path=DIR/module-cache -fimplicit-modules -flto=thin -fautolink 
-fsyntax-only DIR/t2.m",
+"command": "clang -Imodules/A -fmodules 
-fmodules-cache-path=DIR/module-cache -fimplicit-modules -O2 -flto=thin 
-fautolink -fsyntax-only DIR/t2.m",
 "file": "DIR/t2.m"
   },
  

[clang] [-Wunsafe-buffer-usage] Fix the crash introduced by the unsafe invocation of span::data warning (PR #78815)

2024-01-19 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Malavika Samak (malavikasamak)


Changes

The patch fixes the crash introduced by the DataInvocation warning gadget 
designed to warn against unsafe invocations of span::data method.

Radar: 121223051

---
Full diff: https://github.com/llvm/llvm-project/pull/78815.diff


3 Files Affected:

- (modified) clang/lib/Analysis/UnsafeBufferUsage.cpp (+3-2) 
- (modified) clang/lib/Sema/AnalysisBasedWarnings.cpp (+19-7) 
- (modified) 
clang/test/SemaCXX/warn-unsafe-buffer-usage-warning-data-invocation.cpp (+16-8) 


``diff
diff --git a/clang/lib/Analysis/UnsafeBufferUsage.cpp 
b/clang/lib/Analysis/UnsafeBufferUsage.cpp
index 724c4304a072420..7df706beb22662c 100644
--- a/clang/lib/Analysis/UnsafeBufferUsage.cpp
+++ b/clang/lib/Analysis/UnsafeBufferUsage.cpp
@@ -739,9 +739,10 @@ class DataInvocationGadget : public WarningGadget {
   }
 
   static Matcher matcher() {
+Matcher callExpr = cxxMemberCallExpr(
+callee(cxxMethodDecl(hasName("data"), ofClass(hasName("std::span");
 return stmt(
-explicitCastExpr(has(cxxMemberCallExpr(callee(cxxMethodDecl(
- hasName("data"), 
ofClass(hasName("std::span")))
+explicitCastExpr(anyOf(has(callExpr), has(parenExpr(has(callExpr)
 .bind(OpTag));
   }
   const Stmt *getBaseStmt() const override { return Op; }
diff --git a/clang/lib/Sema/AnalysisBasedWarnings.cpp 
b/clang/lib/Sema/AnalysisBasedWarnings.cpp
index 9eb1df5f0240596..749655d03342cca 100644
--- a/clang/lib/Sema/AnalysisBasedWarnings.cpp
+++ b/clang/lib/Sema/AnalysisBasedWarnings.cpp
@@ -2263,15 +2263,27 @@ class UnsafeBufferUsageReporter : public 
UnsafeBufferUsageHandler {
 MsgParam = 3;
   } else if (const auto *ECE = dyn_cast(Operation)) {
 QualType destType = ECE->getType();
-const uint64_t dSize =
-Ctx.getTypeSize(destType.getTypePtr()->getPointeeType());
-if (const auto *CE = dyn_cast(ECE->getSubExpr())) {
-  QualType srcType = CE->getType();
-  const uint64_t sSize =
-  Ctx.getTypeSize(srcType.getTypePtr()->getPointeeType());
-  if (sSize >= dSize)
+if (!isa(destType))
+  return;
+
+const Expr *subExpr = ECE->getSubExpr();
+// Check if related to DataInvocation warning gadget.
+if (!isa(subExpr)) {
+  if (const auto *SE = dyn_cast(subExpr)) {
+if (!isa(SE->getSubExpr()))
+  return;
+  } else
 return;
 }
+const uint64_t dSize =
+Ctx.getTypeSize(destType.getTypePtr()->getPointeeType());
+
+QualType srcType = ECE->getSubExpr()->getType();
+const uint64_t sSize =
+Ctx.getTypeSize(srcType.getTypePtr()->getPointeeType());
+if (sSize >= dSize)
+  return;
+
 MsgParam = 4;
   }
   Loc = Operation->getBeginLoc();
diff --git 
a/clang/test/SemaCXX/warn-unsafe-buffer-usage-warning-data-invocation.cpp 
b/clang/test/SemaCXX/warn-unsafe-buffer-usage-warning-data-invocation.cpp
index 79eb3bb4bacc6e7..7b39bef04114236 100644
--- a/clang/test/SemaCXX/warn-unsafe-buffer-usage-warning-data-invocation.cpp
+++ b/clang/test/SemaCXX/warn-unsafe-buffer-usage-warning-data-invocation.cpp
@@ -22,6 +22,8 @@ namespace std {
 using size_t = __typeof(sizeof(int));
 void *malloc(size_t);
 
+typedef long int  intptr_t;
+
 void foo(int v) {
 }
 
@@ -90,15 +92,18 @@ void cast_without_data(int *ptr) {
 void warned_patterns(std::span span_ptr, std::span base_span, 
span span_without_qual) {
 A *a1 = (A*)span_ptr.data(); // expected-warning{{unsafe invocation of 
span::data}}
 a1 = (A*)span_ptr.data(); // expected-warning{{unsafe invocation of 
span::data}}
-  
-A *a2 = (A*) span_without_qual.data(); // expected-warning{{unsafe 
invocation of span::data}}
-   
-// TODO:: Should we warn when we cast from base to derived type?
-Derived *b = dynamic_cast (base_span.data());// 
expected-warning{{unsafe invocation of span::data}}
 
-   // TODO:: This pattern is safe. We can add special handling for it, if we 
decide this
-   // is the recommended fixit for the unsafe invocations.
-   A *a3 = (A*)span_ptr.subspan(0, sizeof(A)).data(); // 
expected-warning{{unsafe invocation of span::data}}
+a1 = (A*)(span_ptr.data()); // expected-warning{{unsafe invocation of 
span::data}}
+A *a2 = (A*) (span_without_qual.data()); // expected-warning{{unsafe 
invocation of span::data}}
+
+a2 = (A*) span_without_qual.data(); // expected-warning{{unsafe invocation 
of span::data}}
+
+ // TODO:: Should we warn when we cast from base to derived type?
+ Derived *b = dynamic_cast (base_span.data());// 
expected-warning{{unsafe invocation of span::data}}
+
+// TODO:: This pattern is safe. We can add special handling for it, if we 
decide this
+// is the recommended fixit for the unsafe invocations.
+A *a3 = (A*)span_ptr.subspan(0, si

[clang] [clang][modules] Fix CodeGen options that can affect the AST. (PR #78816)

2024-01-19 Thread Juergen Ributzka via cfe-commits

https://github.com/ributzka created 
https://github.com/llvm/llvm-project/pull/78816

`OptimizationLevel` and `OptimizeSize` can affect the generated AST. They
indirectly affect the `Optimize` and `OptimizeSize` frontend options, which in
turn set predefined macro definitions.

This fixes rdar://121228252.


>From ba6eac97038a8fbd24d288ffa88a4dcf508e66b8 Mon Sep 17 00:00:00 2001
From: Juergen Ributzka 
Date: Fri, 19 Jan 2024 16:10:03 -0800
Subject: [PATCH] [clang][modules] Fix CodeGen options that can affect the AST.

`OptimizationLevel` and `OptimizeSize` can affect the generated AST. They
indirectly affect the `Optimize` and `OptimizeSize` frontend options, which in
turn set predefined macro definitions.

This fixes rdar://121228252.
---
 clang/include/clang/Basic/CodeGenOptions.def  | 14 --
 clang/lib/Basic/CodeGenOptions.cpp|  2 ++
 clang/test/ClangScanDeps/strip-codegen-args.m | 11 +++
 3 files changed, 21 insertions(+), 6 deletions(-)

diff --git a/clang/include/clang/Basic/CodeGenOptions.def 
b/clang/include/clang/Basic/CodeGenOptions.def
index 2c4fb6745bc172f..f535291b6ba4ee0 100644
--- a/clang/include/clang/Basic/CodeGenOptions.def
+++ b/clang/include/clang/Basic/CodeGenOptions.def
@@ -12,6 +12,9 @@
 // that have enumeration type and VALUE_CODEGENOPT is a code
 // generation option that describes a value rather than a flag.
 //
+// AFFECTING_VALUE_CODEGENOPT is used for code generation options that can
+// affect the AST.
+//
 
//===--===//
 #ifndef CODEGENOPT
 #  error Define the CODEGENOPT macro to handle language options
@@ -27,6 +30,11 @@ CODEGENOPT(Name, Bits, Default)
 CODEGENOPT(Name, Bits, Default)
 #endif
 
+#ifndef AFFECTING_VALUE_CODEGENOPT
+#  define AFFECTING_VALUE_CODEGENOPT(Name, Bits, Default) \
+VALUE_CODEGENOPT(Name, Bits, Default)
+#endif
+
 CODEGENOPT(DisableIntegratedAS, 1, 0) ///< -no-integrated-as
 CODEGENOPT(RelaxELFRelocations, 1, 1) ///< -Wa,-mrelax-relocations={yes,no}
 CODEGENOPT(AsmVerbose, 1, 0) ///< -dA, -fverbose-asm.
@@ -193,8 +201,10 @@ ENUM_CODEGENOPT(ObjCDispatchMethod, 
ObjCDispatchMethodKind, 2, Legacy)
 CODEGENOPT(ObjCConvertMessagesToRuntimeCalls , 1, 1)
 CODEGENOPT(ObjCAvoidHeapifyLocalBlocks, 1, 0)
 
-VALUE_CODEGENOPT(OptimizationLevel, 2, 0) ///< The -O[0-3] option specified.
-VALUE_CODEGENOPT(OptimizeSize, 2, 0) ///< If -Os (==1) or -Oz (==2) is 
specified.
+
+// The optimization options affect frontend options, whicn in turn do affect 
the AST.
+AFFECTING_VALUE_CODEGENOPT(OptimizationLevel, 2, 0) ///< The -O[0-3] option 
specified.
+AFFECTING_VALUE_CODEGENOPT(OptimizeSize, 2, 0) ///< If -Os (==1) or -Oz (==2) 
is specified.
 
 CODEGENOPT(AtomicProfileUpdate , 1, 0) ///< Set -fprofile-update=atomic
 /// Choose profile instrumenation kind or no instrumentation.
diff --git a/clang/lib/Basic/CodeGenOptions.cpp 
b/clang/lib/Basic/CodeGenOptions.cpp
index 182d0a2fa4d88f2..79d715305ef20b7 100644
--- a/clang/lib/Basic/CodeGenOptions.cpp
+++ b/clang/lib/Basic/CodeGenOptions.cpp
@@ -27,6 +27,8 @@ void CodeGenOptions::resetNonModularOptions(StringRef 
ModuleFormat) {
 #define ENUM_DEBUGOPT(Name, Type, Bits, Default)
 #define CODEGENOPT(Name, Bits, Default) Name = Default;
 #define ENUM_CODEGENOPT(Name, Type, Bits, Default) set##Name(Default);
+// Do not reset AST affecting code generation options.
+#define AFFECTING_VALUE_CODEGENOPT(Name, Bits, Default)
 #include "clang/Basic/CodeGenOptions.def"
 
   // Next reset all debug options that can always be reset, because they never
diff --git a/clang/test/ClangScanDeps/strip-codegen-args.m 
b/clang/test/ClangScanDeps/strip-codegen-args.m
index bb7e76e86aa2f92..71171f4983386dc 100644
--- a/clang/test/ClangScanDeps/strip-codegen-args.m
+++ b/clang/test/ClangScanDeps/strip-codegen-args.m
@@ -5,11 +5,14 @@
 // RUN: clang-scan-deps -compilation-database %t/cdb1.json -format 
experimental-full > %t/result1.txt
 // RUN: FileCheck %s -input-file %t/result1.txt
 
-// This tests that codegen option that do not affect the AST or generation of 
a module are removed. 
+// This tests that codegen option that do not affect the AST or generation of a
+// module are removed. It also tests that the optimization options that affect
+// the AST are not reset to -O0.
 
 // CHECK:"modules": [
 // CHECK-NEXT: {
 // CHECK:"command-line": [
+// CHECK-NOT:  "-O0"
 // CHECK-NOT:  "-flto"
 // CHECK-NOT:  "-fno-autolink"
 // CHECK-NOT:  "-mrelax-relocations=no"
@@ -23,17 +26,17 @@
 [
   {
 "directory": "DIR",
-"command": "clang -Imodules/A -fmodules 
-fmodules-cache-path=DIR/module-cache -fimplicit-modules -flto -fno-autolink 
-Xclang -mrelax-relocations=no -fsyntax-only DIR/t1.m",
+"command": "clang -Imodules/A -fmodules 
-fmodules-cache-path=DIR/module-cache -fimplicit-modules -O2 -flto 
-fno-autolink -Xclang -mrelax-relocations=no -fsyntax-only DIR/t1.m",
 "file": "DI

[clang] [-Wunsafe-buffer-usage] Fix the crash introduced by the unsafe invocation of span::data warning (PR #78815)

2024-01-19 Thread Malavika Samak via cfe-commits

https://github.com/malavikasamak created 
https://github.com/llvm/llvm-project/pull/78815

The patch fixes the crash introduced by the DataInvocation warning gadget 
designed to warn against unsafe invocations of span::data method.

Radar: 121223051

>From 6334cd361f79fc79f32b8ca95c6f31a083704332 Mon Sep 17 00:00:00 2001
From: MalavikaSamak 
Date: Fri, 19 Jan 2024 15:16:12 -0800
Subject: [PATCH] [-Wunsafe-buffer-usage] Fix the crash introduced by the
 unsafe invocation of span::data warning

Radar: 121223051
---
 clang/lib/Analysis/UnsafeBufferUsage.cpp  |  5 ++--
 clang/lib/Sema/AnalysisBasedWarnings.cpp  | 26 ++-
 ...e-buffer-usage-warning-data-invocation.cpp | 24 +++--
 3 files changed, 38 insertions(+), 17 deletions(-)

diff --git a/clang/lib/Analysis/UnsafeBufferUsage.cpp 
b/clang/lib/Analysis/UnsafeBufferUsage.cpp
index 724c4304a07242..7df706beb22662 100644
--- a/clang/lib/Analysis/UnsafeBufferUsage.cpp
+++ b/clang/lib/Analysis/UnsafeBufferUsage.cpp
@@ -739,9 +739,10 @@ class DataInvocationGadget : public WarningGadget {
   }
 
   static Matcher matcher() {
+Matcher callExpr = cxxMemberCallExpr(
+callee(cxxMethodDecl(hasName("data"), ofClass(hasName("std::span");
 return stmt(
-explicitCastExpr(has(cxxMemberCallExpr(callee(cxxMethodDecl(
- hasName("data"), 
ofClass(hasName("std::span")))
+explicitCastExpr(anyOf(has(callExpr), has(parenExpr(has(callExpr)
 .bind(OpTag));
   }
   const Stmt *getBaseStmt() const override { return Op; }
diff --git a/clang/lib/Sema/AnalysisBasedWarnings.cpp 
b/clang/lib/Sema/AnalysisBasedWarnings.cpp
index 9eb1df5f024059..749655d03342cc 100644
--- a/clang/lib/Sema/AnalysisBasedWarnings.cpp
+++ b/clang/lib/Sema/AnalysisBasedWarnings.cpp
@@ -2263,15 +2263,27 @@ class UnsafeBufferUsageReporter : public 
UnsafeBufferUsageHandler {
 MsgParam = 3;
   } else if (const auto *ECE = dyn_cast(Operation)) {
 QualType destType = ECE->getType();
-const uint64_t dSize =
-Ctx.getTypeSize(destType.getTypePtr()->getPointeeType());
-if (const auto *CE = dyn_cast(ECE->getSubExpr())) {
-  QualType srcType = CE->getType();
-  const uint64_t sSize =
-  Ctx.getTypeSize(srcType.getTypePtr()->getPointeeType());
-  if (sSize >= dSize)
+if (!isa(destType))
+  return;
+
+const Expr *subExpr = ECE->getSubExpr();
+// Check if related to DataInvocation warning gadget.
+if (!isa(subExpr)) {
+  if (const auto *SE = dyn_cast(subExpr)) {
+if (!isa(SE->getSubExpr()))
+  return;
+  } else
 return;
 }
+const uint64_t dSize =
+Ctx.getTypeSize(destType.getTypePtr()->getPointeeType());
+
+QualType srcType = ECE->getSubExpr()->getType();
+const uint64_t sSize =
+Ctx.getTypeSize(srcType.getTypePtr()->getPointeeType());
+if (sSize >= dSize)
+  return;
+
 MsgParam = 4;
   }
   Loc = Operation->getBeginLoc();
diff --git 
a/clang/test/SemaCXX/warn-unsafe-buffer-usage-warning-data-invocation.cpp 
b/clang/test/SemaCXX/warn-unsafe-buffer-usage-warning-data-invocation.cpp
index 79eb3bb4bacc6e..7b39bef0411423 100644
--- a/clang/test/SemaCXX/warn-unsafe-buffer-usage-warning-data-invocation.cpp
+++ b/clang/test/SemaCXX/warn-unsafe-buffer-usage-warning-data-invocation.cpp
@@ -22,6 +22,8 @@ namespace std {
 using size_t = __typeof(sizeof(int));
 void *malloc(size_t);
 
+typedef long int  intptr_t;
+
 void foo(int v) {
 }
 
@@ -90,15 +92,18 @@ void cast_without_data(int *ptr) {
 void warned_patterns(std::span span_ptr, std::span base_span, 
span span_without_qual) {
 A *a1 = (A*)span_ptr.data(); // expected-warning{{unsafe invocation of 
span::data}}
 a1 = (A*)span_ptr.data(); // expected-warning{{unsafe invocation of 
span::data}}
-  
-A *a2 = (A*) span_without_qual.data(); // expected-warning{{unsafe 
invocation of span::data}}
-   
-// TODO:: Should we warn when we cast from base to derived type?
-Derived *b = dynamic_cast (base_span.data());// 
expected-warning{{unsafe invocation of span::data}}
 
-   // TODO:: This pattern is safe. We can add special handling for it, if we 
decide this
-   // is the recommended fixit for the unsafe invocations.
-   A *a3 = (A*)span_ptr.subspan(0, sizeof(A)).data(); // 
expected-warning{{unsafe invocation of span::data}}
+a1 = (A*)(span_ptr.data()); // expected-warning{{unsafe invocation of 
span::data}}
+A *a2 = (A*) (span_without_qual.data()); // expected-warning{{unsafe 
invocation of span::data}}
+
+a2 = (A*) span_without_qual.data(); // expected-warning{{unsafe invocation 
of span::data}}
+
+ // TODO:: Should we warn when we cast from base to derived type?
+ Derived *b = dynamic_cast (base_span.data());// 
expected-warning{{unsafe invocation of span::data}}
+
+// TOD

[clang] Try on bot patch from #76218 (PR #78813)

2024-01-19 Thread Vitaly Buka via cfe-commits

https://github.com/vitalybuka converted_to_draft 
https://github.com/llvm/llvm-project/pull/78813
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] Try on bot patch from #76218 (PR #78813)

2024-01-19 Thread Vitaly Buka via cfe-commits

https://github.com/vitalybuka edited 
https://github.com/llvm/llvm-project/pull/78813
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] Try patch from #76218 (PR #78813)

2024-01-19 Thread Vitaly Buka via cfe-commits

https://github.com/vitalybuka edited 
https://github.com/llvm/llvm-project/pull/78813
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] Ensure bitmap for ternary condition is updated before visiting children (PR #78814)

2024-01-19 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-codegen

Author: Alan Phipps (evodius96)


Changes

This is a fix for MC/DC issue https://github.com/llvm/llvm-project/issues/78453 
in which a ConditionalOperator that evaluates a complex condition was 
incorrectly updating its global bitmap after visiting its LHS and RHS children. 
 This was wrong because if the LHS or RHS also evaluate a complex condition, 
the MCDC temporary bitmap value will get corrupted.  The fix is to ensure that 
the bitmap is updated prior to visiting the LHS and RHS.

---
Full diff: https://github.com/llvm/llvm-project/pull/78814.diff


2 Files Affected:

- (modified) clang/lib/CodeGen/CGExprScalar.cpp (+14-4) 
- (added) clang/test/Profile/c-mcdc-logicalop-ternary.c (+81) 


``diff
diff --git a/clang/lib/CodeGen/CGExprScalar.cpp 
b/clang/lib/CodeGen/CGExprScalar.cpp
index 9ec185153d12b1..181b15e9c7d0a7 100644
--- a/clang/lib/CodeGen/CGExprScalar.cpp
+++ b/clang/lib/CodeGen/CGExprScalar.cpp
@@ -4960,6 +4960,13 @@ VisitAbstractConditionalOperator(const 
AbstractConditionalOperator *E) {
CGF.getProfileCount(lhsExpr));
 
   CGF.EmitBlock(LHSBlock);
+
+  // If the top of the logical operator nest, update the MCDC bitmap for the
+  // ConditionalOperator prior to visiting its LHS and RHS blocks, since they
+  // may also contain a boolean expression.
+  if (CGF.MCDCLogOpStack.empty())
+CGF.maybeUpdateMCDCTestVectorBitmap(condExpr);
+
   CGF.incrementProfileCounter(E);
   eval.begin(CGF);
   Value *LHS = Visit(lhsExpr);
@@ -4969,6 +4976,13 @@ VisitAbstractConditionalOperator(const 
AbstractConditionalOperator *E) {
   Builder.CreateBr(ContBlock);
 
   CGF.EmitBlock(RHSBlock);
+
+  // If the top of the logical operator nest, update the MCDC bitmap for the
+  // ConditionalOperator prior to visiting its LHS and RHS blocks, since they
+  // may also contain a boolean expression.
+  if (CGF.MCDCLogOpStack.empty())
+CGF.maybeUpdateMCDCTestVectorBitmap(condExpr);
+
   eval.begin(CGF);
   Value *RHS = Visit(rhsExpr);
   eval.end(CGF);
@@ -4987,10 +5001,6 @@ VisitAbstractConditionalOperator(const 
AbstractConditionalOperator *E) {
   PN->addIncoming(LHS, LHSBlock);
   PN->addIncoming(RHS, RHSBlock);
 
-  // If the top of the logical operator nest, update the MCDC bitmap.
-  if (CGF.MCDCLogOpStack.empty())
-CGF.maybeUpdateMCDCTestVectorBitmap(condExpr);
-
   return PN;
 }
 
diff --git a/clang/test/Profile/c-mcdc-logicalop-ternary.c 
b/clang/test/Profile/c-mcdc-logicalop-ternary.c
new file mode 100644
index 00..558643f422021c
--- /dev/null
+++ b/clang/test/Profile/c-mcdc-logicalop-ternary.c
@@ -0,0 +1,81 @@
+// RUN: %clang_cc1 -triple %itanium_abi_triple %s -o - -emit-llvm 
-fprofile-instrument=clang -fcoverage-mapping -fcoverage-mcdc | FileCheck %s 
-check-prefix=MCDC
+// RUN: %clang_cc1 -triple %itanium_abi_triple %s -o - -emit-llvm 
-fprofile-instrument=clang -fcoverage-mapping | FileCheck %s 
-check-prefix=NOMCDC
+
+int test(int a, int b, int c, int d, int e, int f) {
+  return ((a || b) ? (c && d) : (e || f));
+}
+
+// NOMCDC-NOT: %mcdc.addr
+// NOMCDC-NOT: __profbm_test
+
+// MCDC BOOKKEEPING.
+// MCDC: @__profbm_test = private global [3 x i8] zeroinitializer
+
+// ALLOCATE MCDC TEMP AND ZERO IT.
+// MCDC-LABEL: @test(
+// MCDC: %mcdc.addr = alloca i32, align 4
+// MCDC: store i32 0, ptr %mcdc.addr, align 4
+
+// TERNARY TRUE SHOULD UPDATE THE BITMAP WITH RESULT AT ELEMENT 0.
+// MCDC-LABEL: cond.true:
+// MCDC-DAG:  %[[TEMP:mcdc.temp[0-9]*]] = load i32, ptr %mcdc.addr, align 4
+// MCDC:  %[[LAB1:[0-9]+]] = lshr i32 %[[TEMP]], 3
+// MCDC:  %[[LAB2:[0-9]+]] = zext i32 %[[LAB1]] to i64
+// MCDC:  %[[LAB3:[0-9]+]] = add i64 ptrtoint (ptr @__profbm_test to i64), 
%[[LAB2]]
+// MCDC:  %[[LAB4:[0-9]+]] = inttoptr i64 %[[LAB3]] to ptr
+// MCDC:  %[[LAB5:[0-9]+]] = and i32 %[[TEMP]], 7
+// MCDC:  %[[LAB6:[0-9]+]] = trunc i32 %[[LAB5]] to i8
+// MCDC:  %[[LAB7:[0-9]+]] = shl i8 1, %[[LAB6]]
+// MCDC:  %[[LAB8:mcdc.bits[0-9]*]] = load i8, ptr %[[LAB4]], align 1
+// MCDC:  %[[LAB9:[0-9]+]] = or i8 %[[LAB8]], %[[LAB7]]
+// MCDC:  store i8 %[[LAB9]], ptr %[[LAB4]], align 1
+
+// CHECK FOR ZERO OF MCDC TEMP
+// MCDC: store i32 0, ptr %mcdc.addr, align 4
+
+// TERNARY TRUE YIELDS TERNARY LHS LOGICAL-AND.
+// TERNARY LHS LOGICAL-AND SHOULD UPDATE THE BITMAP WITH RESULT AT ELEMENT 1.
+// MCDC-LABEL: land.end:
+// MCDC-DAG:  %[[TEMP:mcdc.temp[0-9]*]] = load i32, ptr %mcdc.addr, align 4
+// MCDC:  %[[LAB1:[0-9]+]] = lshr i32 %[[TEMP]], 3
+// MCDC:  %[[LAB2:[0-9]+]] = zext i32 %[[LAB1]] to i64
+// MCDC:  %[[LAB3:[0-9]+]] = add i64 ptrtoint (ptr getelementptr inbounds ([3 
x i8], ptr @__profbm_test, i32 0, i32 1) to i64), %[[LAB2]]
+// MCDC:  %[[LAB4:[0-9]+]] = inttoptr i64 %[[LAB3]] to ptr
+// MCDC:  %[[LAB5:[0-9]+]] = and i32 %[[TEMP]], 7
+// MCDC:  %[[LAB6:[0-9]+]] = trunc i32 %[[LAB5]] to i8
+// MCDC:  %[[LAB7:[0-9]+]] = shl i8 1, %[[LAB6]]
+// MCDC:  %[[LAB8:mcdc.bits[0-9]*]] = load i8, ptr %[[LAB4]]

[clang] Ensure bitmap for ternary condition is updated before visiting children (PR #78814)

2024-01-19 Thread Alan Phipps via cfe-commits

https://github.com/evodius96 created 
https://github.com/llvm/llvm-project/pull/78814

This is a fix for MC/DC issue https://github.com/llvm/llvm-project/issues/78453 
in which a ConditionalOperator that evaluates a complex condition was 
incorrectly updating its global bitmap after visiting its LHS and RHS children. 
 This was wrong because if the LHS or RHS also evaluate a complex condition, 
the MCDC temporary bitmap value will get corrupted.  The fix is to ensure that 
the bitmap is updated prior to visiting the LHS and RHS.

>From cbd5a8caaac0fd3d1dc9d4090d00e5bece6a41cf Mon Sep 17 00:00:00 2001
From: Alan Phipps 
Date: Fri, 19 Jan 2024 17:54:25 -0600
Subject: [PATCH] Ensure bitmap for ternary condition is updated prior to visit
 of LHS and RHS

This is a fix for MC/DC issue https://github.com/llvm/llvm-project/issues/78453 
in
which a ConditionalOperator that evaluates a complex condition was incorrectly
updating its global bitmap after visiting its LHS and RHS children.  This was
wrong because if the LHS or RHS also evaluate a complex condition, the MCDC
temporary bitmap value will get corrupted.  The fix is to ensure that the
bitmap is updated prior to visiting the LHS and RHS.
---
 clang/lib/CodeGen/CGExprScalar.cpp| 18 -
 clang/test/Profile/c-mcdc-logicalop-ternary.c | 81 +++
 2 files changed, 95 insertions(+), 4 deletions(-)
 create mode 100644 clang/test/Profile/c-mcdc-logicalop-ternary.c

diff --git a/clang/lib/CodeGen/CGExprScalar.cpp 
b/clang/lib/CodeGen/CGExprScalar.cpp
index 9ec185153d12b1..181b15e9c7d0a7 100644
--- a/clang/lib/CodeGen/CGExprScalar.cpp
+++ b/clang/lib/CodeGen/CGExprScalar.cpp
@@ -4960,6 +4960,13 @@ VisitAbstractConditionalOperator(const 
AbstractConditionalOperator *E) {
CGF.getProfileCount(lhsExpr));
 
   CGF.EmitBlock(LHSBlock);
+
+  // If the top of the logical operator nest, update the MCDC bitmap for the
+  // ConditionalOperator prior to visiting its LHS and RHS blocks, since they
+  // may also contain a boolean expression.
+  if (CGF.MCDCLogOpStack.empty())
+CGF.maybeUpdateMCDCTestVectorBitmap(condExpr);
+
   CGF.incrementProfileCounter(E);
   eval.begin(CGF);
   Value *LHS = Visit(lhsExpr);
@@ -4969,6 +4976,13 @@ VisitAbstractConditionalOperator(const 
AbstractConditionalOperator *E) {
   Builder.CreateBr(ContBlock);
 
   CGF.EmitBlock(RHSBlock);
+
+  // If the top of the logical operator nest, update the MCDC bitmap for the
+  // ConditionalOperator prior to visiting its LHS and RHS blocks, since they
+  // may also contain a boolean expression.
+  if (CGF.MCDCLogOpStack.empty())
+CGF.maybeUpdateMCDCTestVectorBitmap(condExpr);
+
   eval.begin(CGF);
   Value *RHS = Visit(rhsExpr);
   eval.end(CGF);
@@ -4987,10 +5001,6 @@ VisitAbstractConditionalOperator(const 
AbstractConditionalOperator *E) {
   PN->addIncoming(LHS, LHSBlock);
   PN->addIncoming(RHS, RHSBlock);
 
-  // If the top of the logical operator nest, update the MCDC bitmap.
-  if (CGF.MCDCLogOpStack.empty())
-CGF.maybeUpdateMCDCTestVectorBitmap(condExpr);
-
   return PN;
 }
 
diff --git a/clang/test/Profile/c-mcdc-logicalop-ternary.c 
b/clang/test/Profile/c-mcdc-logicalop-ternary.c
new file mode 100644
index 00..558643f422021c
--- /dev/null
+++ b/clang/test/Profile/c-mcdc-logicalop-ternary.c
@@ -0,0 +1,81 @@
+// RUN: %clang_cc1 -triple %itanium_abi_triple %s -o - -emit-llvm 
-fprofile-instrument=clang -fcoverage-mapping -fcoverage-mcdc | FileCheck %s 
-check-prefix=MCDC
+// RUN: %clang_cc1 -triple %itanium_abi_triple %s -o - -emit-llvm 
-fprofile-instrument=clang -fcoverage-mapping | FileCheck %s 
-check-prefix=NOMCDC
+
+int test(int a, int b, int c, int d, int e, int f) {
+  return ((a || b) ? (c && d) : (e || f));
+}
+
+// NOMCDC-NOT: %mcdc.addr
+// NOMCDC-NOT: __profbm_test
+
+// MCDC BOOKKEEPING.
+// MCDC: @__profbm_test = private global [3 x i8] zeroinitializer
+
+// ALLOCATE MCDC TEMP AND ZERO IT.
+// MCDC-LABEL: @test(
+// MCDC: %mcdc.addr = alloca i32, align 4
+// MCDC: store i32 0, ptr %mcdc.addr, align 4
+
+// TERNARY TRUE SHOULD UPDATE THE BITMAP WITH RESULT AT ELEMENT 0.
+// MCDC-LABEL: cond.true:
+// MCDC-DAG:  %[[TEMP:mcdc.temp[0-9]*]] = load i32, ptr %mcdc.addr, align 4
+// MCDC:  %[[LAB1:[0-9]+]] = lshr i32 %[[TEMP]], 3
+// MCDC:  %[[LAB2:[0-9]+]] = zext i32 %[[LAB1]] to i64
+// MCDC:  %[[LAB3:[0-9]+]] = add i64 ptrtoint (ptr @__profbm_test to i64), 
%[[LAB2]]
+// MCDC:  %[[LAB4:[0-9]+]] = inttoptr i64 %[[LAB3]] to ptr
+// MCDC:  %[[LAB5:[0-9]+]] = and i32 %[[TEMP]], 7
+// MCDC:  %[[LAB6:[0-9]+]] = trunc i32 %[[LAB5]] to i8
+// MCDC:  %[[LAB7:[0-9]+]] = shl i8 1, %[[LAB6]]
+// MCDC:  %[[LAB8:mcdc.bits[0-9]*]] = load i8, ptr %[[LAB4]], align 1
+// MCDC:  %[[LAB9:[0-9]+]] = or i8 %[[LAB8]], %[[LAB7]]
+// MCDC:  store i8 %[[LAB9]], ptr %[[LAB4]], align 1
+
+// CHECK FOR ZERO OF MCDC TEMP
+// MCDC: store i32 0, ptr %mcdc.addr, align 4
+
+// TERNARY TRUE YIELDS TERNARY LHS LOGICAL-AND.
+// TERNARY LHS LOGICAL-

[clang] Try patch from #76218 (PR #78813)

2024-01-19 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Vitaly Buka (vitalybuka)


Changes



---
Full diff: https://github.com/llvm/llvm-project/pull/78813.diff


1 Files Affected:

- (modified) clang/unittests/Interpreter/InterpreterTest.cpp (+3-8) 


``diff
diff --git a/clang/unittests/Interpreter/InterpreterTest.cpp 
b/clang/unittests/Interpreter/InterpreterTest.cpp
index d6eb0684ba49d8..406a4871dff5e8 100644
--- a/clang/unittests/Interpreter/InterpreterTest.cpp
+++ b/clang/unittests/Interpreter/InterpreterTest.cpp
@@ -34,12 +34,6 @@ using namespace clang;
 #define CLANG_INTERPRETER_NO_SUPPORT_EXEC
 #endif
 
-#if LLVM_ADDRESS_SANITIZER_BUILD || LLVM_HWADDRESS_SANITIZER_BUILD
-#include 
-#else
-extern "C" void __lsan_ignore_object(const void *p) {}
-#endif
-
 int Global = 42;
 // JIT reports symbol not found on Windows without the visibility attribute.
 REPL_EXTERNAL_VISIBILITY int getGlobal() { return Global; }
@@ -317,8 +311,9 @@ TEST(IncrementalProcessing, InstantiateTemplate) {
   auto fn =
   cantFail(Interp->getSymbolAddress(MangledName)).toPtr();
   EXPECT_EQ(42, fn(NewA.getPtr()));
-  // FIXME: release the memory.
-  __lsan_ignore_object(NewA.getPtr());
+  // FIXME: Consider providing an option in clang::Value to take ownership of
+  // the memory created from the interpreter.
+  free(NewA.getPtr());
 }
 
 #ifdef CLANG_INTERPRETER_NO_SUPPORT_EXEC

``




https://github.com/llvm/llvm-project/pull/78813
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] Try patch from #76218 (PR #78813)

2024-01-19 Thread Vitaly Buka via cfe-commits

https://github.com/vitalybuka created 
https://github.com/llvm/llvm-project/pull/78813

None

>From b2c13350471c50f75d7a32d118faf7b04a5fbede Mon Sep 17 00:00:00 2001
From: Vitaly Buka 
Date: Fri, 19 Jan 2024 16:07:34 -0800
Subject: [PATCH] =?UTF-8?q?[=F0=9D=98=80=F0=9D=97=BD=F0=9D=97=BF]=20initia?=
 =?UTF-8?q?l=20version?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Created using spr 1.3.4
---
 clang/unittests/Interpreter/InterpreterTest.cpp | 11 +++
 1 file changed, 3 insertions(+), 8 deletions(-)

diff --git a/clang/unittests/Interpreter/InterpreterTest.cpp 
b/clang/unittests/Interpreter/InterpreterTest.cpp
index d6eb0684ba49d8a..406a4871dff5e81 100644
--- a/clang/unittests/Interpreter/InterpreterTest.cpp
+++ b/clang/unittests/Interpreter/InterpreterTest.cpp
@@ -34,12 +34,6 @@ using namespace clang;
 #define CLANG_INTERPRETER_NO_SUPPORT_EXEC
 #endif
 
-#if LLVM_ADDRESS_SANITIZER_BUILD || LLVM_HWADDRESS_SANITIZER_BUILD
-#include 
-#else
-extern "C" void __lsan_ignore_object(const void *p) {}
-#endif
-
 int Global = 42;
 // JIT reports symbol not found on Windows without the visibility attribute.
 REPL_EXTERNAL_VISIBILITY int getGlobal() { return Global; }
@@ -317,8 +311,9 @@ TEST(IncrementalProcessing, InstantiateTemplate) {
   auto fn =
   cantFail(Interp->getSymbolAddress(MangledName)).toPtr();
   EXPECT_EQ(42, fn(NewA.getPtr()));
-  // FIXME: release the memory.
-  __lsan_ignore_object(NewA.getPtr());
+  // FIXME: Consider providing an option in clang::Value to take ownership of
+  // the memory created from the interpreter.
+  free(NewA.getPtr());
 }
 
 #ifdef CLANG_INTERPRETER_NO_SUPPORT_EXEC

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang-repl] Add a interpreter-specific overload of operator new for C++ (PR #76218)

2024-01-19 Thread Vitaly Buka via cfe-commits

vitalybuka wrote:

I suspect asan may complain on new/free mismatch


https://github.com/llvm/llvm-project/pull/76218
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang-tidy] Fix crash in modernize-loop-convert when int is used as iterator (PR #78796)

2024-01-19 Thread Julian Schmidt via cfe-commits

https://github.com/5chmidti approved this pull request.


https://github.com/llvm/llvm-project/pull/78796
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [clang-tools-extra] [msan] Unpoison indirect outputs for userspace when -msan-handle-asm-conservative is specified (PR #77393)

2024-01-19 Thread Vitaly Buka via cfe-commits

https://github.com/vitalybuka approved this pull request.


https://github.com/llvm/llvm-project/pull/77393
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang-tidy] Fix crash in modernize-loop-convert when int is used as iterator (PR #78796)

2024-01-19 Thread Congcong Cai via cfe-commits

https://github.com/HerrCai0907 approved this pull request.


https://github.com/llvm/llvm-project/pull/78796
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [clang-tools-extra] [msan] Unpoison indirect outputs for userspace when -msan-handle-asm-conservative is specified (PR #77393)

2024-01-19 Thread Fangrui Song via cfe-commits


@@ -4557,7 +4561,13 @@ struct MemorySanitizerVisitor : public 
InstVisitor {
   return;
 Value *SizeVal =
   IRB.CreateTypeSize(MS.IntptrTy, DL.getTypeStoreSize(ElemTy));
-IRB.CreateCall(MS.MsanInstrumentAsmStoreFn, {Operand, SizeVal});
+if (MS.CompileKernel) {
+  IRB.CreateCall(MS.MsanInstrumentAsmStoreFn, {Operand, SizeVal});
+} else {
+  auto [ShadowPtr, _] =
+  getShadowOriginPtrUserspace(Operand, IRB, IRB.getInt8Ty(), Align(1));
+  IRB.CreateAlignedStore(getCleanShadow(ElemTy), ShadowPtr, Align(1));

MaskRay wrote:

Done:)

https://github.com/llvm/llvm-project/pull/77393
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang] [llvm] [msan] Unpoison indirect outputs for userspace when -msan-handle-asm-conservative is specified (PR #77393)

2024-01-19 Thread Fangrui Song via cfe-commits

https://github.com/MaskRay updated 
https://github.com/llvm/llvm-project/pull/77393

>From 93ab63157297553fa678752995773db8b14642fe Mon Sep 17 00:00:00 2001
From: Fangrui Song 
Date: Mon, 8 Jan 2024 15:22:21 -0800
Subject: [PATCH] =?UTF-8?q?[=F0=9D=98=80=F0=9D=97=BD=F0=9D=97=BF]=20initia?=
 =?UTF-8?q?l=20version?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Created using spr 1.3.4
---
 .../Instrumentation/MemorySanitizer.cpp   |  14 ++-
 .../MemorySanitizer/msan_asm_conservative.ll  | 106 ++
 2 files changed, 71 insertions(+), 49 deletions(-)

diff --git a/llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp 
b/llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp
index 94af63da38c82c..38270716bc6996 100644
--- a/llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp
+++ b/llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp
@@ -4103,7 +4103,11 @@ struct MemorySanitizerVisitor : public 
InstVisitor {
   // do the usual thing: check argument shadow and mark all outputs as
   // clean. Note that any side effects of the inline asm that are not
   // immediately visible in its constraints are not handled.
-  if (ClHandleAsmConservative && MS.CompileKernel)
+  // For now, handle inline asm by default for KMSAN.
+  bool HandleAsm = ClHandleAsmConservative.getNumOccurrences()
+   ? ClHandleAsmConservative
+   : MS.CompileKernel;
+  if (HandleAsm)
 visitAsmInstruction(CB);
   else
 visitInstruction(CB);
@@ -4557,7 +4561,13 @@ struct MemorySanitizerVisitor : public 
InstVisitor {
   return;
 Value *SizeVal =
   IRB.CreateTypeSize(MS.IntptrTy, DL.getTypeStoreSize(ElemTy));
-IRB.CreateCall(MS.MsanInstrumentAsmStoreFn, {Operand, SizeVal});
+if (MS.CompileKernel) {
+  IRB.CreateCall(MS.MsanInstrumentAsmStoreFn, {Operand, SizeVal});
+} else {
+  auto [ShadowPtr, _] =
+  getShadowOriginPtrUserspace(Operand, IRB, IRB.getInt8Ty(), Align(1));
+  IRB.CreateAlignedStore(getCleanShadow(ElemTy), ShadowPtr, Align(1));
+}
   }
 
   /// Get the number of output arguments returned by pointers.
diff --git a/llvm/test/Instrumentation/MemorySanitizer/msan_asm_conservative.ll 
b/llvm/test/Instrumentation/MemorySanitizer/msan_asm_conservative.ll
index 1239698f3ac326..9a501ee6954c9c 100644
--- a/llvm/test/Instrumentation/MemorySanitizer/msan_asm_conservative.ll
+++ b/llvm/test/Instrumentation/MemorySanitizer/msan_asm_conservative.ll
@@ -1,10 +1,14 @@
 ; Test for handling of asm constraints in MSan instrumentation.
+; RUN: opt < %s -msan-check-access-address=0 -msan-handle-asm-conservative=0 
-S -passes=msan 2>&1 | \
+; RUN:   FileCheck %s
+; RUN: opt < %s -msan-check-access-address=0 -msan-handle-asm-conservative=1 
-S -passes=msan 2>&1 | \
+; RUN:   FileCheck --check-prefixes=CHECK,USER-CONS %s
 ; RUN: opt < %s -msan-kernel=1 -msan-check-access-address=0
\
-; RUN: -msan-handle-asm-conservative=0 -S -passes=msan 2>&1 | FileCheck
\
-; RUN: "-check-prefix=CHECK" %s
+; RUN:   -msan-handle-asm-conservative=0 -S -passes=msan 2>&1 | FileCheck  
\
+; RUN:   --check-prefixes=CHECK,KMSAN %s
 ; RUN: opt < %s -msan-kernel=1 -msan-check-access-address=0
\
-; RUN: -msan-handle-asm-conservative=1 -S -passes=msan 2>&1 | FileCheck
\
-; RUN: "-check-prefixes=CHECK,CHECK-CONS" %s
+; RUN:   -msan-handle-asm-conservative=1 -S -passes=msan 2>&1 | FileCheck  
\
+; RUN:   --check-prefixes=CHECK,KMSAN,CHECK-CONS %s
 
 target datalayout = "e-m:e-i64:64-f80:128-n8:16:32:64-S128"
 target triple = "x86_64-unknown-linux-gnu"
@@ -46,9 +50,9 @@ entry:
 ; CHECK: [[IS1_F1:%.*]] = load i32, ptr @is1, align 4
 ; CHECK: call void @__msan_warning
 ; CHECK: call i32 asm "",{{.*}}(i32 [[IS1_F1]])
-; CHECK: [[PACK1_F1:%.*]] = call {{.*}} 
@__msan_metadata_ptr_for_store_4({{.*}}@id1{{.*}})
-; CHECK: [[EXT1_F1:%.*]] = extractvalue { ptr, ptr } [[PACK1_F1]], 0
-; CHECK: store i32 0, ptr [[EXT1_F1]]
+; KMSAN: [[PACK1_F1:%.*]] = call {{.*}} 
@__msan_metadata_ptr_for_store_4({{.*}}@id1{{.*}})
+; KMSAN: [[EXT1_F1:%.*]] = extractvalue { ptr, ptr } [[PACK1_F1]], 0
+; KMSAN: store i32 0, ptr [[EXT1_F1]]
 
 
 ; Two input registers, two output registers:
@@ -69,14 +73,14 @@ entry:
 ; CHECK: [[IS1_F2:%.*]] = load i32, ptr @is1, align 4
 ; CHECK: [[IS2_F2:%.*]] = load i32, ptr @is2, align 4
 ; CHECK: call void @__msan_warning
-; CHECK: call void @__msan_warning
+; KMSAN: call void @__msan_warning
 ; CHECK: call { i32, i32 } asm "",{{.*}}(i32 [[IS1_F2]], i32 [[IS2_F2]])
-; CHECK: [[PACK1_F2:%.*]] = call {{.*}} 
@__msan_metadata_ptr_for_store_4({{.*}}@id1{{.*}})
-; CHECK: [[EXT1_F2:%.*]] = extractvalue { ptr, ptr } [[PACK1_F2]], 0
-; CHECK: store i32 0, ptr [[EXT1_F2]]
-; CHECK: [[PACK2_F2:%.*]] = call {{.*}} 
@__msan_metadata_ptr_for_store_4({{.*}}@id2{{.*}})
-; CHECK: [[EXT2_F2:%.*]] = extractvalue { ptr, ptr }

[clang-tools-extra] [llvm] [clang] Add clang-tidy check to suggest replacement of conditional statement with std::min/std::max (PR #77816)

2024-01-19 Thread Julian Schmidt via cfe-commits

https://github.com/5chmidti edited 
https://github.com/llvm/llvm-project/pull/77816
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [llvm] [clang] Add clang-tidy check to suggest replacement of conditional statement with std::min/std::max (PR #77816)

2024-01-19 Thread Julian Schmidt via cfe-commits


@@ -0,0 +1,139 @@
+//===--- UseStdMinMaxCheck.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 "UseStdMinMaxCheck.h"
+#include "../utils/ASTUtils.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Lex/Preprocessor.h"
+#include 
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::readability {
+
+UseStdMinMaxCheck::UseStdMinMaxCheck(StringRef Name, ClangTidyContext *Context)
+: ClangTidyCheck(Name, Context),
+  IncludeInserter(Options.getLocalOrGlobal("IncludeStyle",
+   utils::IncludeSorter::IS_LLVM),
+  areDiagsSelfContained()) {}
+
+void UseStdMinMaxCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
+  Options.store(Opts, "IncludeStyle", IncludeInserter.getStyle());
+  Options.store(Opts, "AlgorithmHeader",
+Options.get("AlgorithmHeader", ""));
+}
+
+void UseStdMinMaxCheck::registerMatchers(MatchFinder *Finder) {
+  Finder->addMatcher(
+  ifStmt(
+  hasCondition(binaryOperator(hasAnyOperatorName("<", ">", "<=", ">="),
+  hasLHS(expr().bind("CondLhs")),
+  hasRHS(expr().bind("CondRhs",
+  hasThen(anyOf(stmt(binaryOperator(hasOperatorName("="),
+hasLHS(expr().bind("AssignLhs")),
+hasRHS(expr().bind("AssignRhs",
+compoundStmt(has(binaryOperator(
+ hasOperatorName("="),
+ hasLHS(expr().bind("AssignLhs")),
+ hasRHS(expr().bind("AssignRhs")
+.bind("compound"
+  .bind("if"),
+  this);
+}
+
+void UseStdMinMaxCheck::registerPPCallbacks(const SourceManager &SM,
+Preprocessor *PP,
+Preprocessor *ModuleExpanderPP) {
+  IncludeInserter.registerPreprocessor(PP);
+}
+
+void UseStdMinMaxCheck::check(const MatchFinder::MatchResult &Result) {
+  const auto *CondLhs = Result.Nodes.getNodeAs("CondLhs");
+  const auto *CondRhs = Result.Nodes.getNodeAs("CondRhs");
+  const auto *AssignLhs = Result.Nodes.getNodeAs("AssignLhs");
+  const auto *AssignRhs = Result.Nodes.getNodeAs("AssignRhs");
+  const auto *If = Result.Nodes.getNodeAs("if");
+  const auto *Compound = Result.Nodes.getNodeAs("compound");
+  const auto &Context = *Result.Context;
+  const auto &LO = Context.getLangOpts();
+  const SourceManager &Source = Context.getSourceManager();
+
+  const auto *BinaryOp = dyn_cast(If->getCond());
+  if (!BinaryOp || If->hasElseStorage())
+return;
+
+  if (Compound) {
+if (Compound->size() > 1)
+  return;
+  }
+
+  const SourceLocation IfLocation = If->getIfLoc();
+  const SourceLocation ThenLocation = If->getEndLoc();
+
+  if (IfLocation.isMacroID() || ThenLocation.isMacroID())
+return;
+
+  const auto CreateString = [&](int index) -> llvm::StringRef {
+switch (index) {
+case 1:
+  return Lexer::getSourceText(
+  Source.getExpansionRange(CondLhs->getSourceRange()), Source, LO);
+case 2:
+  return Lexer::getSourceText(
+  Source.getExpansionRange(CondRhs->getSourceRange()), Source, LO);
+case 3:
+  return Lexer::getSourceText(
+  Source.getExpansionRange(AssignLhs->getSourceRange()), Source, LO);
+default:
+  return "Invalid index";
+}
+  };
+
+  const auto CreateReplacement = [&](bool useMax) {
+std::string functionName = useMax ? "std::max" : "std::min";
+return CreateString(/* AssignLhs */ 3).str() + " = " + functionName + "(" +
+   CreateString(/* CondLhs */ 1).str() + ", " +
+   CreateString(/* CondRhs */ 2).str() + ");";
+  };
+  const auto OperatorStr = BinaryOp->getOpcodeStr();
+  if (((BinaryOp->getOpcode() == BO_LT || BinaryOp->getOpcode() == BO_LE) &&
+   (tidy::utils::areStatementsIdentical(CondLhs, AssignRhs, Context) &&
+tidy::utils::areStatementsIdentical(CondRhs, AssignLhs, Context))) ||
+  ((BinaryOp->getOpcode() == BO_GT || BinaryOp->getOpcode() == BO_GE) &&
+   (tidy::utils::areStatementsIdentical(CondLhs, AssignLhs, Context) &&
+tidy::utils::areStatementsIdentical(CondRhs, AssignRhs, Context {
+diag(IfLocation, "use `std::min` instead of `%0`")
+<< OperatorStr
+<< FixItHint::CreateReplacement(SourceRange(IfLocation, ThenLocation),
+CreateReplacement(/*useMax = false*/ 
0))
+   

[clang] [llvm] [clang-tools-extra] Add clang-tidy check to suggest replacement of conditional statement with std::min/std::max (PR #77816)

2024-01-19 Thread Julian Schmidt via cfe-commits


@@ -0,0 +1,139 @@
+//===--- UseStdMinMaxCheck.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 "UseStdMinMaxCheck.h"
+#include "../utils/ASTUtils.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Lex/Preprocessor.h"
+#include 
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::readability {
+
+UseStdMinMaxCheck::UseStdMinMaxCheck(StringRef Name, ClangTidyContext *Context)
+: ClangTidyCheck(Name, Context),
+  IncludeInserter(Options.getLocalOrGlobal("IncludeStyle",
+   utils::IncludeSorter::IS_LLVM),
+  areDiagsSelfContained()) {}
+
+void UseStdMinMaxCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
+  Options.store(Opts, "IncludeStyle", IncludeInserter.getStyle());
+  Options.store(Opts, "AlgorithmHeader",
+Options.get("AlgorithmHeader", ""));
+}
+
+void UseStdMinMaxCheck::registerMatchers(MatchFinder *Finder) {
+  Finder->addMatcher(
+  ifStmt(
+  hasCondition(binaryOperator(hasAnyOperatorName("<", ">", "<=", ">="),
+  hasLHS(expr().bind("CondLhs")),
+  hasRHS(expr().bind("CondRhs",
+  hasThen(anyOf(stmt(binaryOperator(hasOperatorName("="),
+hasLHS(expr().bind("AssignLhs")),
+hasRHS(expr().bind("AssignRhs",
+compoundStmt(has(binaryOperator(
+ hasOperatorName("="),
+ hasLHS(expr().bind("AssignLhs")),
+ hasRHS(expr().bind("AssignRhs")
+.bind("compound"
+  .bind("if"),
+  this);
+}
+
+void UseStdMinMaxCheck::registerPPCallbacks(const SourceManager &SM,
+Preprocessor *PP,
+Preprocessor *ModuleExpanderPP) {
+  IncludeInserter.registerPreprocessor(PP);
+}
+
+void UseStdMinMaxCheck::check(const MatchFinder::MatchResult &Result) {
+  const auto *CondLhs = Result.Nodes.getNodeAs("CondLhs");
+  const auto *CondRhs = Result.Nodes.getNodeAs("CondRhs");
+  const auto *AssignLhs = Result.Nodes.getNodeAs("AssignLhs");
+  const auto *AssignRhs = Result.Nodes.getNodeAs("AssignRhs");
+  const auto *If = Result.Nodes.getNodeAs("if");
+  const auto *Compound = Result.Nodes.getNodeAs("compound");
+  const auto &Context = *Result.Context;
+  const auto &LO = Context.getLangOpts();
+  const SourceManager &Source = Context.getSourceManager();
+
+  const auto *BinaryOp = dyn_cast(If->getCond());
+  if (!BinaryOp || If->hasElseStorage())
+return;
+
+  if (Compound) {
+if (Compound->size() > 1)
+  return;
+  }

5chmidti wrote:

I noticed, that there is a `statementCountIs` matcher for `CompoundStmt`. You 
could use that instead, then you don't have to bind the compound statement. I 
should have thought about this earlier :)

https://github.com/llvm/llvm-project/pull/77816
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


  1   2   3   4   5   6   >