[clang] [llvm] [IR] Avoid creating icmp/fcmp constant expressions (PR #92885)

2024-05-22 Thread Nikita Popov via cfe-commits

nikic wrote:

@antmox Already fixed in 
https://github.com/llvm/llvm-project/commit/c609c04e32ef43f63a6ee54025fadf649c3247cc.

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


[clang] [ASTMatchers] forCallable should not erase binding on success (PR #89657)

2024-05-22 Thread Marco Borgeaud via cfe-commits

marco-antognini-sonarsource wrote:

Could someone review this PR, please? Any feedback you can give me is welcome.

The CI should be green and I've disabled keeping my email private.

Pinging some recent contributors/reviewers to AST Matchers. @danix800, 
@AaronBallman, @shafik, @PiotrZSL, @steakhal, @cor3ntin

Thanks

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


[clang] Reapply "[Clang][CWG1815] Support lifetime extension of temporary created by aggregate initialization using a default member initializer" (PR #92527)

2024-05-22 Thread via cfe-commits

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


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


[clang] [clang] Add /Zc:__STDC__ flag to clang-cl (PR #68690)

2024-05-22 Thread via cfe-commits


@@ -291,6 +291,7 @@ LANGOPT(HIPStdParInterposeAlloc, 1, 0, "Replace allocations 
/ deallocations with
 
 LANGOPT(OpenACC   , 1, 0, "OpenACC Enabled")
 
+LANGOPT(MSVCEnableStdcMacro , 1, 0, "Define __STDC__ with 
'-fms-compatability'")

xbjfk wrote:

Good catch!

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


[clang] [clang] Add /Zc:__STDC__ flag to clang-cl (PR #68690)

2024-05-22 Thread via cfe-commits


@@ -8065,6 +8069,9 @@ void Clang::AddClangCLArgs(const ArgList &Args, types::ID 
InputType,
CmdArgs.push_back("-fno-wchar");
  }
 
+ if (!types::isCXX(InputType) && Args.hasArg(options::OPT_fms_define_stdc))
+   CmdArgs.push_back("-fms-define-stdc");

xbjfk wrote:

Sounds good to me, thanks. 

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


[clang-tools-extra] [clang-tidy] Add new check bugprone-tagged-union-member-count (PR #89925)

2024-05-22 Thread via cfe-commits
=?utf-8?b?R8OhYm9yIFTDs3RodsOhcmk=?= 
Message-ID:
In-Reply-To: 


https://github.com/tigbr updated https://github.com/llvm/llvm-project/pull/89925

>From 0dff511a0f63480dea527b6e823dcf230755f312 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?G=C3=A1bor=20T=C3=B3thv=C3=A1ri?= 
Date: Sun, 3 Mar 2024 22:30:32 +0100
Subject: [PATCH 1/2] [clang-tidy] Add new check
 bugprone-tagged-union-member-count

This patch introduces a new check to find mismatches between the number
of data members in a union and the number enum values present in
variant-like structures.

Variant-like types can look something like this:

```c++
struct variant {
enum {
tag1,
tag2,
} kind;
union {
int i;
char c;
  } data;
};
```

The kind data member of the variant is supposed to tell which data
member of the union is valid, however if there are fewer enum values
than union members, then it is likely a mistake.

The opposite is not that obvious, because it might be fine to have more
enum values than union data members, but for the time being I am curious
how many real bugs can be caught if we give a warning regardless.

This patch also contains a heuristic where we try to guess whether the
last enum constant is actually supposed to be a tag value for the
variant or whether it is just holding how many enum constants have been
created.

I am still collecting data on how many bugs this check can catch on open
source software and I will update the pull-request with the results.
---
 .../bugprone/BugproneTidyModule.cpp   |   3 +
 .../clang-tidy/bugprone/CMakeLists.txt|   1 +
 .../bugprone/TaggedUnionMemberCountCheck.cpp  | 125 
 .../bugprone/TaggedUnionMemberCountCheck.h|  31 +++
 clang-tools-extra/docs/ReleaseNotes.rst   |   6 +
 .../bugprone/tagged-union-member-count.rst|  66 +++
 .../docs/clang-tidy/checks/list.rst   |   1 +
 .../bugprone/tagged-union-member-count.cpp| 181 ++
 8 files changed, 414 insertions(+)
 create mode 100644 
clang-tools-extra/clang-tidy/bugprone/TaggedUnionMemberCountCheck.cpp
 create mode 100644 
clang-tools-extra/clang-tidy/bugprone/TaggedUnionMemberCountCheck.h
 create mode 100644 
clang-tools-extra/docs/clang-tidy/checks/bugprone/tagged-union-member-count.rst
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/bugprone/tagged-union-member-count.cpp

diff --git a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp 
b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
index 2931325d8b579..d9e094e11bdf0 100644
--- a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
@@ -76,6 +76,7 @@
 #include "SuspiciousStringviewDataUsageCheck.h"
 #include "SwappedArgumentsCheck.h"
 #include "SwitchMissingDefaultCaseCheck.h"
+#include "TaggedUnionMemberCountCheck.h"
 #include "TerminatingContinueCheck.h"
 #include "ThrowKeywordMissingCheck.h"
 #include "TooSmallLoopVariableCheck.h"
@@ -223,6 +224,8 @@ class BugproneModule : public ClangTidyModule {
 "bugprone-suspicious-stringview-data-usage");
 CheckFactories.registerCheck(
 "bugprone-swapped-arguments");
+CheckFactories.registerCheck(
+"bugprone-tagged-union-member-count");
 CheckFactories.registerCheck(
 "bugprone-terminating-continue");
 CheckFactories.registerCheck(
diff --git a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
index 081ba67efe153..5e7fa08aece02 100644
--- a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
@@ -71,6 +71,7 @@ add_clang_library(clangTidyBugproneModule
   SuspiciousSemicolonCheck.cpp
   SuspiciousStringCompareCheck.cpp
   SwappedArgumentsCheck.cpp
+  TaggedUnionMemberCountCheck.cpp
   TerminatingContinueCheck.cpp
   ThrowKeywordMissingCheck.cpp
   TooSmallLoopVariableCheck.cpp
diff --git 
a/clang-tools-extra/clang-tidy/bugprone/TaggedUnionMemberCountCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/TaggedUnionMemberCountCheck.cpp
new file mode 100644
index 0..6a7b5a92902c8
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/bugprone/TaggedUnionMemberCountCheck.cpp
@@ -0,0 +1,125 @@
+//===--- TaggedUnionMemberCountCheck.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 "TaggedUnionMemberCountCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Expr.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+
+#include "clang/AST/PrettyPrinter.h"
+#include "llvm/ADT/STLExtras.h"
+#include "llvm/Support/Casting.h"
+#include 
+
+using namespace clang::ast_matchers

[clang] [Clang] Reuse tail-padding for more types that are not POD for the purpose of layout (PR #90462)

2024-05-22 Thread Mital Ashok via cfe-commits

https://github.com/MitalAshok updated 
https://github.com/llvm/llvm-project/pull/90462

>From 96ff21d5126ebb4b9a538b8eef11f8ac9e2194c5 Mon Sep 17 00:00:00 2001
From: Mital Ashok 
Date: Mon, 29 Apr 2024 12:27:04 +0100
Subject: [PATCH] [Clang] Reuse tail-padding for more types that are not POD
 for the purpose of layout

This will be done for types with over-large bitfields and 
potentially-overlapping ([[no_unique_address]]) members

Compatible with old Clang 18 semantics with -fclang-abi-compat

Fixes #50766
---
 clang/docs/ReleaseNotes.rst |   3 +
 clang/include/clang/Basic/LangOptions.h |   4 +-
 clang/include/clang/Basic/TargetCXXABI.h|  51 
 clang/lib/AST/RecordLayoutBuilder.cpp   | 134 +++-
 clang/test/CodeGenCXX/bitfield-layout.cpp   |  20 ++-
 clang/test/CodeGenCXX/no-unique-address.cpp |   9 +-
 clang/test/Layout/no-unique-address.cpp |  20 ++-
 7 files changed, 138 insertions(+), 103 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 604782ca43dd5..b5d76c95a24bd 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -63,6 +63,9 @@ ABI Changes in This Version
   MSVC uses a different mangling for these objects, compatibility is not 
affected.
   (#GH85423).
 
+- Fixed tail padding not being reused on types with oversized bit-fields and
+  potentially-overlapping members (#GH50766).
+
 AST Dumping Potentially Breaking Changes
 
 
diff --git a/clang/include/clang/Basic/LangOptions.h 
b/clang/include/clang/Basic/LangOptions.h
index e2a2aa71b880b..3fe1362a2d767 100644
--- a/clang/include/clang/Basic/LangOptions.h
+++ b/clang/include/clang/Basic/LangOptions.h
@@ -233,7 +233,9 @@ class LangOptionsBase {
 
 /// Attempt to be ABI-compatible with code generated by Clang 18.0.x.
 /// This causes clang to revert some fixes to the mangling of lambdas
-/// in the initializers of members of local classes.
+/// in the initializers of members of local classes and will not reuse
+/// tail padding on structs with potentially-overlapping members or
+/// oversized bit-fields under Itanium and some derived ABIs.
 Ver18,
 
 /// Conform to the underlying platform's C and C++ ABIs as closely
diff --git a/clang/include/clang/Basic/TargetCXXABI.h 
b/clang/include/clang/Basic/TargetCXXABI.h
index c113a6a048ad4..45d9dcc8f1b8a 100644
--- a/clang/include/clang/Basic/TargetCXXABI.h
+++ b/clang/include/clang/Basic/TargetCXXABI.h
@@ -255,57 +255,6 @@ class TargetCXXABI {
 llvm_unreachable("bad ABI kind");
   }
 
-  /// When is record layout allowed to allocate objects in the tail
-  /// padding of a base class?
-  ///
-  /// This decision cannot be changed without breaking platform ABI
-  /// compatibility. In ISO C++98, tail padding reuse was only permitted for
-  /// non-POD base classes, but that restriction was removed retroactively by
-  /// DR 43, and tail padding reuse is always permitted in all de facto C++
-  /// language modes. However, many platforms use a variant of the old C++98
-  /// rule for compatibility.
-  enum TailPaddingUseRules {
-/// The tail-padding of a base class is always theoretically
-/// available, even if it's POD.
-AlwaysUseTailPadding,
-
-/// Only allocate objects in the tail padding of a base class if
-/// the base class is not POD according to the rules of C++ TR1.
-UseTailPaddingUnlessPOD03,
-
-/// Only allocate objects in the tail padding of a base class if
-/// the base class is not POD according to the rules of C++11.
-UseTailPaddingUnlessPOD11
-  };
-  TailPaddingUseRules getTailPaddingUseRules() const {
-switch (getKind()) {
-// To preserve binary compatibility, the generic Itanium ABI has
-// permanently locked the definition of POD to the rules of C++ TR1,
-// and that trickles down to derived ABIs.
-case GenericItanium:
-case GenericAArch64:
-case GenericARM:
-case iOS:
-case GenericMIPS:
-case XL:
-  return UseTailPaddingUnlessPOD03;
-
-// AppleARM64 and WebAssembly use the C++11 POD rules.  They do not honor
-// the Itanium exception about classes with over-large bitfields.
-case AppleARM64:
-case Fuchsia:
-case WebAssembly:
-case WatchOS:
-  return UseTailPaddingUnlessPOD11;
-
-// MSVC always allocates fields in the tail-padding of a base class
-// subobject, even if they're POD.
-case Microsoft:
-  return AlwaysUseTailPadding;
-}
-llvm_unreachable("bad ABI kind");
-  }
-
   friend bool operator==(const TargetCXXABI &left, const TargetCXXABI &right) {
 return left.getKind() == right.getKind();
   }
diff --git a/clang/lib/AST/RecordLayoutBuilder.cpp 
b/clang/lib/AST/RecordLayoutBuilder.cpp
index d9bf62c2bbb04..0b6376381a53b 100644
--- a/clang/lib/AST/RecordLayoutBuilder.cpp
+++ b/clang/lib/AST/RecordLayoutBuilder.cpp
@@ -2415,46 +2415,112 @@ DiagnosticBuilder 

[clang] [openmp] [Clang][OpenMP] Fix tile/unroll on iterator- and foreach-loops. (PR #91459)

2024-05-22 Thread Michael Kruse via cfe-commits


@@ -156,9 +156,9 @@ extern "C" void body(...) {}
 // IR-EMPTY:
 // IR-NEXT:  [[FOR_INC]]:
 // IR-NEXT:%[[TMP34:.+]] = load i32, ptr %[[DOTTILE_0_IV_I]], align 4
-// IR-NEXT:%[[INC:.+]] = add nsw i32 %[[TMP34]], 1
+// IR-NEXT:%[[INC:.+]] = add i32 %[[TMP34]], 1

Meinersbur wrote:

This is due to the change of using the type of `LoopHelper.NumIterations` (an 
unsigned integer) as the new loop's induction variable (instead of the original 
loop's iteration variable type). In iterator-based loops that type would be 
incompatible with `LoopHelper.NumIterations` which remains an integer.

Even if the original loop variable is a signed integer (it could be a 
(`std::iota_view`)[https://en.cppreference.com/w/cpp/ranges/iota_view] over the 
same range), using and unsigned type is more correct as long as we start 
counting at 0. For instance, the loop
```
#pragma omp tile sizes(2)
for (int i = INT_MIN; i < INT_MAX; ++i)
```
would overflow the `nsw` flag.

The "most correct" fix would be to add the `nuw` flag. Unfortunately there is 
no AST expression we could create that would make CodeGen generate one. 
Alternatively, I could make generated loops start counting at `INT_MIN`.

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


[clang] [clang] [SemaCXX] Implement CWG2627 Bit-fields and narrowing conversions (PR #78112)

2024-05-22 Thread Mital Ashok via cfe-commits

https://github.com/MitalAshok updated 
https://github.com/llvm/llvm-project/pull/78112

>From 92f8720e3d21521b589d5291f086a2f32b87bfe0 Mon Sep 17 00:00:00 2001
From: Mital Ashok 
Date: Sun, 14 Jan 2024 19:52:31 +
Subject: [PATCH] [clang] [SemaCXX] Implement CWG2627 Bit-fields and narrowing
 conversions

---
 clang/docs/ReleaseNotes.rst   |   5 +
 .../clang/Basic/DiagnosticSemaKinds.td|   3 +
 clang/include/clang/Sema/Overload.h   |   7 +-
 clang/lib/Sema/SemaExpr.cpp   |  10 +-
 clang/lib/Sema/SemaInit.cpp   |  20 ++-
 clang/lib/Sema/SemaOverload.cpp   | 119 +--
 .../dcl.decl/dcl.init/dcl.init.list/p7-0x.cpp |  24 
 clang/test/CXX/drs/dr26xx.cpp | 136 ++
 clang/www/cxx_dr_status.html  |   2 +-
 9 files changed, 278 insertions(+), 48 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 92563262cc673..28202fc604e29 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -157,6 +157,11 @@ Resolutions to C++ Defect Reports
 - Clang now diagnoses declarative nested-name-specifiers with 
pack-index-specifiers.
   (`CWG2858: Declarative nested-name-specifiers and pack-index-specifiers 
`_).
 
+- Casts from a bit-field to an integral type is now not considered narrowing 
if the
+  width of the bit-field means that all potential values are in the range
+  of the target type, even if the type of the bit-field is larger.
+  (`CWG2627. Bit-fields and narrowing conversions  
`_).
+
 C Language Changes
 --
 
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index fdca82934cb4d..6cdb439be30ae 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -6253,6 +6253,9 @@ def ext_init_list_variable_narrowing_const_reference : 
ExtWarn<
 def ext_init_list_constant_narrowing : ExtWarn<
   "constant expression evaluates to %0 which cannot be narrowed to type %1">,
   InGroup, DefaultError, SFINAEFailure;
+def ext_bit_field_narrowing : Extension<
+  "narrowing non-constant-expression from %0 bit-field of width %2 to %1 is a 
C++23 extension">,
+  InGroup, SFINAEFailure;
 def ext_init_list_constant_narrowing_const_reference : ExtWarn<
   ext_init_list_constant_narrowing.Summary>,
   InGroup, DefaultError, SFINAEFailure;
diff --git a/clang/include/clang/Sema/Overload.h 
b/clang/include/clang/Sema/Overload.h
index 76311b00d2fc5..0d94045cc13f7 100644
--- a/clang/include/clang/Sema/Overload.h
+++ b/clang/include/clang/Sema/Overload.h
@@ -244,7 +244,11 @@ class Sema;
 /// Not a narrowing conversion.
 NK_Not_Narrowing,
 
-/// A narrowing conversion by virtue of the source and destination types.
+/// Not a narrowing conversion in C++23 because the source is a bit-field
+/// whose range can fit in the target type
+NK_BitField_Not_Narrowing,
+
+/// A narrowing conversion by virtue of the source and target types.
 NK_Type_Narrowing,
 
 /// A narrowing conversion, because a constant expression got narrowed.
@@ -387,6 +391,7 @@ class Sema;
 NarrowingKind
 getNarrowingKind(ASTContext &Context, const Expr *Converted,
  APValue &ConstantValue, QualType &ConstantType,
+ unsigned &BitFieldWidth,
  bool IgnoreFloatToIntegralConversion = false) const;
 bool isPointerConversionToBool() const;
 bool isPointerConversionToVoidPointer(ASTContext& Context) const;
diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index 50f92c496a539..4c16fcc60fc77 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -12361,8 +12361,9 @@ static bool checkThreeWayNarrowingConversion(Sema &S, 
QualType ToType, Expr *E,
 
   APValue PreNarrowingValue;
   QualType PreNarrowingType;
+  unsigned BitFieldWidth;
   switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
-   PreNarrowingType,
+   PreNarrowingType, BitFieldWidth,
/*IgnoreFloatToIntegralConversion*/ true)) {
   case NK_Dependent_Narrowing:
 // Implicit conversion to a narrower type, but the expression is
@@ -12370,6 +12371,13 @@ static bool checkThreeWayNarrowingConversion(Sema &S, 
QualType ToType, Expr *E,
   case NK_Not_Narrowing:
 return false;
 
+  case NK_BitField_Not_Narrowing:
+if (!S.getLangOpts().CPlusPlus23) {
+  return S.Diag(E->getBeginLoc(), diag::ext_bit_field_narrowing)
+ << FromType << ToType << BitFieldWidth;
+}
+return false;
+
   case NK_Constant_Narrowing:
 // Implicit conversion to a narrower type, and the value is not a constant
 // expression.
diff --git a/clang/li

[clang] [clang] [SemaCXX] Implement CWG2627 Bit-fields and narrowing conversions (PR #78112)

2024-05-22 Thread Mital Ashok via cfe-commits

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


[clang] [openmp] [Clang][OpenMP] Fix tile/unroll on iterator- and foreach-loops. (PR #91459)

2024-05-22 Thread Michael Kruse via cfe-commits


@@ -156,9 +156,9 @@ extern "C" void body(...) {}
 // IR-EMPTY:
 // IR-NEXT:  [[FOR_INC]]:
 // IR-NEXT:%[[TMP34:.+]] = load i32, ptr %[[DOTTILE_0_IV_I]], align 4
-// IR-NEXT:%[[INC:.+]] = add nsw i32 %[[TMP34]], 1
+// IR-NEXT:%[[INC:.+]] = add i32 %[[TMP34]], 1

Meinersbur wrote:

`nuw` would be an idea for a Clang extension in the footsteps of [vector 
extensions](https://releases.llvm.org/18.1.1/tools/clang/docs/LanguageExtensions.html#vectors-and-extended-vectors)
 or 
[`_ExtInt`](http://blog.llvm.org/2020/04/the-new-clang-extint-feature-provides.html)
 which also exposed a feature that LLVM always supported. E.g. 
```
typedef unsigned nowrap_unsigned_t __attribute__((ext_no_wrap));
for (nowrap_unsigned_t i = 0; i < n; ++i)
```
or
```
int [[clang::]]
```
However, the language consequences are immense.

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


[clang] [clang] Introduce `SemaRISCV` (PR #92682)

2024-05-22 Thread Vlad Serebrennikov via cfe-commits

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


[clang-tools-extra] [clangd] [C++20] [Modules] Introduce initial support for C++20 Modules (PR #66462)

2024-05-22 Thread kadir çetinkaya via cfe-commits


@@ -0,0 +1,106 @@
+//===-- ModuleDependencyScanner.h *- 
C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_MODULEDEPENDENCYSCANNER_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANGD_MODULEDEPENDENCYSCANNER_H
+
+#include "GlobalCompilationDatabase.h"
+#include "support/Path.h"
+#include "support/ThreadsafeFS.h"
+
+#include "clang/Tooling/DependencyScanning/DependencyScanningService.h"
+#include "clang/Tooling/DependencyScanning/DependencyScanningTool.h"
+
+#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/StringMap.h"
+
+namespace clang {
+namespace clangd {
+
+/// A scanner to query the dependency information for C++20 Modules.
+///
+/// The scanner can scan a single file with `scan(PathRef)` member function
+/// or scan the whole project with `globalScan(PathRef)` member function. See
+/// the comments of `globalScan` to see the details.
+///
+/// ModuleDependencyScanner should only be used via ScanningAllProjectModules.
+///
+/// The ModuleDependencyScanner can get the directly required module name for a
+/// specific source file. Also the ModuleDependencyScanner can get the source
+/// file declaring a specific module name.
+///
+/// IMPORTANT NOTE: we assume that every module unit is only declared once in a
+/// source file in the project. But the assumption is not strictly true even
+/// besides the invalid projects. The language specification requires that 
every
+/// module unit should be unique in a valid program. But a project can contain
+/// multiple programs. Then it is valid that we can have multiple source files
+/// declaring the same module in a project as long as these source files don't
+/// interere with each other.`
+class ModuleDependencyScanner {
+public:
+  ModuleDependencyScanner(const GlobalCompilationDatabase &CDB,
+  const ThreadsafeFS &TFS)
+  : CDB(CDB), TFS(TFS),
+Service(tooling::dependencies::ScanningMode::CanonicalPreprocessing,
+tooling::dependencies::ScanningOutputFormat::P1689) {}
+
+  // The scanned modules dependency information for a specific source file.

kadircet wrote:

3 slashes here and below

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


[clang-tools-extra] [clangd] [C++20] [Modules] Introduce initial support for C++20 Modules (PR #66462)

2024-05-22 Thread kadir çetinkaya via cfe-commits

https://github.com/kadircet requested changes to this pull request.

thanks a lot and sorry for taking so long.

i think this looks great at a high level, mostly asked for some changes in the 
implementation. the only layering-wise change is who should own 
`ModulesBuilder` (you can find details in the specific comment thread).

apart from that one, i think unittests can benefit from some "virtualizaiton", 
i believe things become a lot more simpler, if we ignore all the other module 
related flags that needs to be provided.

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


[clang-tools-extra] [clangd] [C++20] [Modules] Introduce initial support for C++20 Modules (PR #66462)

2024-05-22 Thread kadir çetinkaya via cfe-commits


@@ -0,0 +1,339 @@
+//===- ModulesBuilder.cpp *- 
C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "ModulesBuilder.h"
+#include "PrerequisiteModules.h"
+#include "support/Logger.h"
+
+#include "clang/Frontend/FrontendAction.h"
+#include "clang/Frontend/FrontendActions.h"
+
+namespace clang {
+namespace clangd {
+
+namespace {
+
+/// Get or create a path to store module files. Generally it should be:
+///
+///   project_root/.cache/clangd/module_files/{RequiredPrefixDir}/.

kadircet wrote:

as things stand today these are not really "cache" files, but rather 
"temporary" files, similar to clangd's preambles.

as a result, if clangd process dies unexpectedly, we'll just leak all of these 
pcms indefinitely, which is quite expensive for the user.

can you move this to `/tmp/` instead, until we start sharing pcms and have a 
reason to use a "persistent" storage?

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


[clang-tools-extra] [clangd] [C++20] [Modules] Introduce initial support for C++20 Modules (PR #66462)

2024-05-22 Thread kadir çetinkaya via cfe-commits


@@ -0,0 +1,71 @@
+//===- ModulesBuilder.h --*- 
C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+// Experimental support for C++20 Modules.
+//
+// Currently we simplify the implementations by preventing reusing module files
+// across different versions and different source files. But this is clearly a
+// waste of time and space in the end of the day.
+//
+// FIXME: Supporting reusing module files across different versions and
+// different source files.
+//
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_MODULES_BUILDER_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANGD_MODULES_BUILDER_H
+
+#include "GlobalCompilationDatabase.h"
+#include "ProjectModules.h"
+
+#include "support/Path.h"
+#include "support/ThreadsafeFS.h"
+
+#include "llvm/ADT/SmallString.h"
+
+#include 
+
+namespace clang {
+namespace clangd {
+
+class PrerequisiteModules;
+
+/// This class handles building module files for a given source file.
+///
+/// In the future, we want the class to manage the module files acorss
+/// different versions and different source files.
+class ModulesBuilder {
+public:
+  ModulesBuilder() = delete;
+
+  ModulesBuilder(const GlobalCompilationDatabase &CDB) : CDB(CDB) {}
+
+  ModulesBuilder(const ModulesBuilder &) = delete;
+  ModulesBuilder(ModulesBuilder &&) = delete;
+
+  ModulesBuilder &operator=(const ModulesBuilder &) = delete;
+  ModulesBuilder &operator=(ModulesBuilder &&) = delete;
+
+  ~ModulesBuilder() = default;

kadircet wrote:

again i don't think there's a difference between the implicit vs explicitly 
default'd destructor here

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


[clang-tools-extra] [clangd] [C++20] [Modules] Introduce initial support for C++20 Modules (PR #66462)

2024-05-22 Thread kadir çetinkaya via cfe-commits


@@ -0,0 +1,106 @@
+//===-- ModuleDependencyScanner.h *- 
C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_MODULEDEPENDENCYSCANNER_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANGD_MODULEDEPENDENCYSCANNER_H
+
+#include "GlobalCompilationDatabase.h"
+#include "support/Path.h"
+#include "support/ThreadsafeFS.h"
+
+#include "clang/Tooling/DependencyScanning/DependencyScanningService.h"
+#include "clang/Tooling/DependencyScanning/DependencyScanningTool.h"
+
+#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/StringMap.h"
+
+namespace clang {
+namespace clangd {
+
+/// A scanner to query the dependency information for C++20 Modules.
+///
+/// The scanner can scan a single file with `scan(PathRef)` member function
+/// or scan the whole project with `globalScan(PathRef)` member function. See
+/// the comments of `globalScan` to see the details.
+///
+/// ModuleDependencyScanner should only be used via ScanningAllProjectModules.
+///
+/// The ModuleDependencyScanner can get the directly required module name for a
+/// specific source file. Also the ModuleDependencyScanner can get the source
+/// file declaring a specific module name.
+///
+/// IMPORTANT NOTE: we assume that every module unit is only declared once in a
+/// source file in the project. But the assumption is not strictly true even
+/// besides the invalid projects. The language specification requires that 
every
+/// module unit should be unique in a valid program. But a project can contain
+/// multiple programs. Then it is valid that we can have multiple source files
+/// declaring the same module in a project as long as these source files don't
+/// interere with each other.`

kadircet wrote:

s/interere/interfere/

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


[clang-tools-extra] [clangd] [C++20] [Modules] Introduce initial support for C++20 Modules (PR #66462)

2024-05-22 Thread kadir çetinkaya via cfe-commits


@@ -0,0 +1,106 @@
+//===-- ModuleDependencyScanner.h *- 
C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_MODULEDEPENDENCYSCANNER_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANGD_MODULEDEPENDENCYSCANNER_H
+
+#include "GlobalCompilationDatabase.h"
+#include "support/Path.h"
+#include "support/ThreadsafeFS.h"
+
+#include "clang/Tooling/DependencyScanning/DependencyScanningService.h"
+#include "clang/Tooling/DependencyScanning/DependencyScanningTool.h"
+
+#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/StringMap.h"
+
+namespace clang {
+namespace clangd {
+
+/// A scanner to query the dependency information for C++20 Modules.
+///
+/// The scanner can scan a single file with `scan(PathRef)` member function
+/// or scan the whole project with `globalScan(PathRef)` member function. See
+/// the comments of `globalScan` to see the details.
+///
+/// ModuleDependencyScanner should only be used via ScanningAllProjectModules.

kadircet wrote:

not sure if this comment is helpful, possibly even distracting as it makes the 
author search for `ScanningAllProjectModules`.

I believe `ModuleDependencyScanner` as it stands here is pretty self-contained 
i don't see why we should be referring to others.

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


[clang-tools-extra] [clangd] [C++20] [Modules] Introduce initial support for C++20 Modules (PR #66462)

2024-05-22 Thread kadir çetinkaya via cfe-commits

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


[clang-tools-extra] [clangd] [C++20] [Modules] Introduce initial support for C++20 Modules (PR #66462)

2024-05-22 Thread kadir çetinkaya via cfe-commits


@@ -0,0 +1,106 @@
+//===-- ModuleDependencyScanner.h *- 
C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_MODULEDEPENDENCYSCANNER_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANGD_MODULEDEPENDENCYSCANNER_H
+
+#include "GlobalCompilationDatabase.h"
+#include "support/Path.h"
+#include "support/ThreadsafeFS.h"
+
+#include "clang/Tooling/DependencyScanning/DependencyScanningService.h"
+#include "clang/Tooling/DependencyScanning/DependencyScanningTool.h"
+
+#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/StringMap.h"
+
+namespace clang {
+namespace clangd {
+
+/// A scanner to query the dependency information for C++20 Modules.
+///
+/// The scanner can scan a single file with `scan(PathRef)` member function
+/// or scan the whole project with `globalScan(PathRef)` member function. See
+/// the comments of `globalScan` to see the details.
+///
+/// ModuleDependencyScanner should only be used via ScanningAllProjectModules.
+///
+/// The ModuleDependencyScanner can get the directly required module name for a
+/// specific source file. Also the ModuleDependencyScanner can get the source
+/// file declaring a specific module name.
+///
+/// IMPORTANT NOTE: we assume that every module unit is only declared once in a
+/// source file in the project. But the assumption is not strictly true even
+/// besides the invalid projects. The language specification requires that 
every
+/// module unit should be unique in a valid program. But a project can contain
+/// multiple programs. Then it is valid that we can have multiple source files
+/// declaring the same module in a project as long as these source files don't
+/// interere with each other.`
+class ModuleDependencyScanner {
+public:
+  ModuleDependencyScanner(const GlobalCompilationDatabase &CDB,
+  const ThreadsafeFS &TFS)
+  : CDB(CDB), TFS(TFS),
+Service(tooling::dependencies::ScanningMode::CanonicalPreprocessing,
+tooling::dependencies::ScanningOutputFormat::P1689) {}
+
+  // The scanned modules dependency information for a specific source file.
+  struct ModuleDependencyInfo {
+// The name of the module if the file is a module unit.
+std::optional ModuleName;
+// A list of names for the modules that the file directly depends.
+std::vector RequiredModules;
+  };
+
+  /// Scanning the single file specified by \param FilePath.
+  /// NOTE: This is only used by unittests for external uses.
+  std::optional scan(PathRef FilePath);
+
+  /// Scanning every source file in the current project to get the
+  ///  to  map.
+  /// It looks unefficiency to scan the whole project especially for
+  /// every version of every file!
+  /// TODO: We should find an efficient method to get the 
+  /// to  map. We can make it either by providing
+  /// a global module dependency scanner to monitor every file. Or we
+  /// can simply require the build systems (or even if the end users)
+  /// to provide the map.
+  void globalScan(const std::vector &AllFiles);

kadircet wrote:

nit: `llvm::ArrayRef`

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


[clang-tools-extra] [clangd] [C++20] [Modules] Introduce initial support for C++20 Modules (PR #66462)

2024-05-22 Thread kadir çetinkaya via cfe-commits


@@ -0,0 +1,71 @@
+//===- ModulesBuilder.h --*- 
C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+// Experimental support for C++20 Modules.
+//
+// Currently we simplify the implementations by preventing reusing module files
+// across different versions and different source files. But this is clearly a
+// waste of time and space in the end of the day.
+//
+// FIXME: Supporting reusing module files across different versions and
+// different source files.
+//
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_MODULES_BUILDER_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANGD_MODULES_BUILDER_H
+
+#include "GlobalCompilationDatabase.h"
+#include "ProjectModules.h"
+
+#include "support/Path.h"
+#include "support/ThreadsafeFS.h"
+
+#include "llvm/ADT/SmallString.h"
+
+#include 
+
+namespace clang {
+namespace clangd {
+
+class PrerequisiteModules;

kadircet wrote:

we avoid forward declarations in clangd, especially when they're for working 
around dependency cycles.

can you just include "PrerequisiteModules.h" here (see other header for ideas 
about breaking the cycle).

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


[clang-tools-extra] [clangd] [C++20] [Modules] Introduce initial support for C++20 Modules (PR #66462)

2024-05-22 Thread kadir çetinkaya via cfe-commits


@@ -0,0 +1,106 @@
+//===-- ModuleDependencyScanner.h *- 
C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_MODULEDEPENDENCYSCANNER_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANGD_MODULEDEPENDENCYSCANNER_H
+
+#include "GlobalCompilationDatabase.h"
+#include "support/Path.h"
+#include "support/ThreadsafeFS.h"
+
+#include "clang/Tooling/DependencyScanning/DependencyScanningService.h"
+#include "clang/Tooling/DependencyScanning/DependencyScanningTool.h"
+
+#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/StringMap.h"
+
+namespace clang {
+namespace clangd {
+
+/// A scanner to query the dependency information for C++20 Modules.
+///
+/// The scanner can scan a single file with `scan(PathRef)` member function
+/// or scan the whole project with `globalScan(PathRef)` member function. See

kadircet wrote:

`globalScan(vector)`

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


[clang-tools-extra] [clangd] [C++20] [Modules] Introduce initial support for C++20 Modules (PR #66462)

2024-05-22 Thread kadir çetinkaya via cfe-commits


@@ -0,0 +1,106 @@
+//===-- ModuleDependencyScanner.h *- 
C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_MODULEDEPENDENCYSCANNER_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANGD_MODULEDEPENDENCYSCANNER_H
+
+#include "GlobalCompilationDatabase.h"
+#include "support/Path.h"
+#include "support/ThreadsafeFS.h"
+
+#include "clang/Tooling/DependencyScanning/DependencyScanningService.h"
+#include "clang/Tooling/DependencyScanning/DependencyScanningTool.h"
+
+#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/StringMap.h"
+
+namespace clang {
+namespace clangd {
+
+/// A scanner to query the dependency information for C++20 Modules.
+///
+/// The scanner can scan a single file with `scan(PathRef)` member function
+/// or scan the whole project with `globalScan(PathRef)` member function. See
+/// the comments of `globalScan` to see the details.
+///
+/// ModuleDependencyScanner should only be used via ScanningAllProjectModules.
+///
+/// The ModuleDependencyScanner can get the directly required module name for a
+/// specific source file. Also the ModuleDependencyScanner can get the source
+/// file declaring a specific module name.
+///
+/// IMPORTANT NOTE: we assume that every module unit is only declared once in a
+/// source file in the project. But the assumption is not strictly true even
+/// besides the invalid projects. The language specification requires that 
every
+/// module unit should be unique in a valid program. But a project can contain
+/// multiple programs. Then it is valid that we can have multiple source files
+/// declaring the same module in a project as long as these source files don't
+/// interere with each other.`
+class ModuleDependencyScanner {
+public:
+  ModuleDependencyScanner(const GlobalCompilationDatabase &CDB,
+  const ThreadsafeFS &TFS)
+  : CDB(CDB), TFS(TFS),
+Service(tooling::dependencies::ScanningMode::CanonicalPreprocessing,
+tooling::dependencies::ScanningOutputFormat::P1689) {}
+
+  // The scanned modules dependency information for a specific source file.
+  struct ModuleDependencyInfo {
+// The name of the module if the file is a module unit.
+std::optional ModuleName;
+// A list of names for the modules that the file directly depends.
+std::vector RequiredModules;
+  };
+
+  /// Scanning the single file specified by \param FilePath.
+  /// NOTE: This is only used by unittests for external uses.
+  std::optional scan(PathRef FilePath);
+
+  /// Scanning every source file in the current project to get the
+  ///  to  map.
+  /// It looks unefficiency to scan the whole project especially for

kadircet wrote:

i think we can drop this sentence. following todo clearly says we need a more 
efficient way

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


[clang-tools-extra] [clangd] [C++20] [Modules] Introduce initial support for C++20 Modules (PR #66462)

2024-05-22 Thread kadir çetinkaya via cfe-commits


@@ -0,0 +1,106 @@
+//===-- ModuleDependencyScanner.h *- 
C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_MODULEDEPENDENCYSCANNER_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANGD_MODULEDEPENDENCYSCANNER_H
+
+#include "GlobalCompilationDatabase.h"
+#include "support/Path.h"
+#include "support/ThreadsafeFS.h"
+
+#include "clang/Tooling/DependencyScanning/DependencyScanningService.h"
+#include "clang/Tooling/DependencyScanning/DependencyScanningTool.h"
+
+#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/StringMap.h"
+
+namespace clang {
+namespace clangd {
+
+/// A scanner to query the dependency information for C++20 Modules.
+///
+/// The scanner can scan a single file with `scan(PathRef)` member function
+/// or scan the whole project with `globalScan(PathRef)` member function. See
+/// the comments of `globalScan` to see the details.
+///
+/// ModuleDependencyScanner should only be used via ScanningAllProjectModules.
+///
+/// The ModuleDependencyScanner can get the directly required module name for a
+/// specific source file. Also the ModuleDependencyScanner can get the source
+/// file declaring a specific module name.
+///
+/// IMPORTANT NOTE: we assume that every module unit is only declared once in a
+/// source file in the project. But the assumption is not strictly true even
+/// besides the invalid projects. The language specification requires that 
every
+/// module unit should be unique in a valid program. But a project can contain
+/// multiple programs. Then it is valid that we can have multiple source files
+/// declaring the same module in a project as long as these source files don't
+/// interere with each other.`
+class ModuleDependencyScanner {
+public:
+  ModuleDependencyScanner(const GlobalCompilationDatabase &CDB,
+  const ThreadsafeFS &TFS)
+  : CDB(CDB), TFS(TFS),
+Service(tooling::dependencies::ScanningMode::CanonicalPreprocessing,
+tooling::dependencies::ScanningOutputFormat::P1689) {}
+
+  // The scanned modules dependency information for a specific source file.
+  struct ModuleDependencyInfo {
+// The name of the module if the file is a module unit.
+std::optional ModuleName;
+// A list of names for the modules that the file directly depends.
+std::vector RequiredModules;
+  };
+
+  /// Scanning the single file specified by \param FilePath.
+  /// NOTE: This is only used by unittests for external uses.

kadircet wrote:

not sure what this `NOTE` serves. could you explain "why" this should be 
avoided (instead of documenting current state of the implementation)?

if you really intent this to be internal, i think you can just make it private, 
and use just the public interfaces in the tests (currently there's a single 
test that calls `scan` directly, it might as well call `globalScan` with a 
single file)

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


[clang-tools-extra] [clangd] [C++20] [Modules] Introduce initial support for C++20 Modules (PR #66462)

2024-05-22 Thread kadir çetinkaya via cfe-commits


@@ -0,0 +1,106 @@
+//===-- ModuleDependencyScanner.h *- 
C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_MODULEDEPENDENCYSCANNER_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANGD_MODULEDEPENDENCYSCANNER_H
+
+#include "GlobalCompilationDatabase.h"
+#include "support/Path.h"
+#include "support/ThreadsafeFS.h"
+
+#include "clang/Tooling/DependencyScanning/DependencyScanningService.h"
+#include "clang/Tooling/DependencyScanning/DependencyScanningTool.h"
+
+#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/StringMap.h"
+
+namespace clang {
+namespace clangd {
+
+/// A scanner to query the dependency information for C++20 Modules.
+///
+/// The scanner can scan a single file with `scan(PathRef)` member function
+/// or scan the whole project with `globalScan(PathRef)` member function. See
+/// the comments of `globalScan` to see the details.
+///
+/// ModuleDependencyScanner should only be used via ScanningAllProjectModules.
+///
+/// The ModuleDependencyScanner can get the directly required module name for a
+/// specific source file. Also the ModuleDependencyScanner can get the source
+/// file declaring a specific module name.
+///
+/// IMPORTANT NOTE: we assume that every module unit is only declared once in a
+/// source file in the project. But the assumption is not strictly true even
+/// besides the invalid projects. The language specification requires that 
every
+/// module unit should be unique in a valid program. But a project can contain
+/// multiple programs. Then it is valid that we can have multiple source files
+/// declaring the same module in a project as long as these source files don't
+/// interere with each other.`
+class ModuleDependencyScanner {
+public:
+  ModuleDependencyScanner(const GlobalCompilationDatabase &CDB,
+  const ThreadsafeFS &TFS)
+  : CDB(CDB), TFS(TFS),
+Service(tooling::dependencies::ScanningMode::CanonicalPreprocessing,
+tooling::dependencies::ScanningOutputFormat::P1689) {}
+
+  // The scanned modules dependency information for a specific source file.
+  struct ModuleDependencyInfo {
+// The name of the module if the file is a module unit.
+std::optional ModuleName;
+// A list of names for the modules that the file directly depends.
+std::vector RequiredModules;
+  };
+
+  /// Scanning the single file specified by \param FilePath.
+  /// NOTE: This is only used by unittests for external uses.
+  std::optional scan(PathRef FilePath);
+
+  /// Scanning every source file in the current project to get the
+  ///  to  map.
+  /// It looks unefficiency to scan the whole project especially for
+  /// every version of every file!
+  /// TODO: We should find an efficient method to get the 
+  /// to  map. We can make it either by providing
+  /// a global module dependency scanner to monitor every file. Or we
+  /// can simply require the build systems (or even if the end users)

kadircet wrote:

s/even if/even

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


[clang-tools-extra] [clangd] [C++20] [Modules] Introduce initial support for C++20 Modules (PR #66462)

2024-05-22 Thread kadir çetinkaya via cfe-commits


@@ -0,0 +1,106 @@
+//===-- ModuleDependencyScanner.h *- 
C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_MODULEDEPENDENCYSCANNER_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANGD_MODULEDEPENDENCYSCANNER_H
+
+#include "GlobalCompilationDatabase.h"
+#include "support/Path.h"
+#include "support/ThreadsafeFS.h"
+
+#include "clang/Tooling/DependencyScanning/DependencyScanningService.h"
+#include "clang/Tooling/DependencyScanning/DependencyScanningTool.h"
+
+#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/StringMap.h"
+
+namespace clang {
+namespace clangd {
+
+/// A scanner to query the dependency information for C++20 Modules.
+///
+/// The scanner can scan a single file with `scan(PathRef)` member function
+/// or scan the whole project with `globalScan(PathRef)` member function. See
+/// the comments of `globalScan` to see the details.
+///
+/// ModuleDependencyScanner should only be used via ScanningAllProjectModules.
+///
+/// The ModuleDependencyScanner can get the directly required module name for a
+/// specific source file. Also the ModuleDependencyScanner can get the source
+/// file declaring a specific module name.

kadircet wrote:

s/a specific module name/the primary module interface for a specific module 
name/

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


[clang-tools-extra] [clangd] [C++20] [Modules] Introduce initial support for C++20 Modules (PR #66462)

2024-05-22 Thread kadir çetinkaya via cfe-commits


@@ -0,0 +1,81 @@
+//=== ModuleDependencyScanner.cpp *- 
C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "ModuleDependencyScanner.h"
+#include "support/Logger.h"
+
+namespace clang {
+namespace clangd {
+
+std::optional
+ModuleDependencyScanner::scan(PathRef FilePath) {
+  std::optional Cmd = CDB.getCompileCommand(FilePath);
+
+  if (!Cmd)
+return std::nullopt;
+
+  using namespace clang::tooling::dependencies;
+
+  llvm::SmallString<128> FilePathDir(FilePath);
+  llvm::sys::path::remove_filename(FilePathDir);
+  DependencyScanningTool ScanningTool(Service, TFS.view(FilePathDir));
+
+  llvm::Expected ScanningResult =
+  ScanningTool.getP1689ModuleDependencyFile(*Cmd, Cmd->Directory);
+
+  if (auto E = ScanningResult.takeError()) {
+log("Scanning modules dependencies for {0} failed: {1}", FilePath,
+llvm::toString(std::move(E)));
+return std::nullopt;
+  }
+
+  ModuleDependencyInfo Result;
+
+  if (ScanningResult->Provides) {
+ModuleNameToSource[ScanningResult->Provides->ModuleName] = FilePath;

kadircet wrote:

nit: maybe move caching to `globalScan` and mark this function as `const` ? 
that way `getRequiredModules` can also become a `const` method.

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


[clang-tools-extra] [clangd] [C++20] [Modules] Introduce initial support for C++20 Modules (PR #66462)

2024-05-22 Thread kadir çetinkaya via cfe-commits


@@ -0,0 +1,71 @@
+//===- ModulesBuilder.h --*- 
C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+// Experimental support for C++20 Modules.
+//
+// Currently we simplify the implementations by preventing reusing module files
+// across different versions and different source files. But this is clearly a
+// waste of time and space in the end of the day.
+//
+// FIXME: Supporting reusing module files across different versions and
+// different source files.
+//
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_MODULES_BUILDER_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANGD_MODULES_BUILDER_H
+
+#include "GlobalCompilationDatabase.h"
+#include "ProjectModules.h"
+
+#include "support/Path.h"
+#include "support/ThreadsafeFS.h"
+
+#include "llvm/ADT/SmallString.h"
+
+#include 
+
+namespace clang {
+namespace clangd {
+
+class PrerequisiteModules;
+
+/// This class handles building module files for a given source file.
+///
+/// In the future, we want the class to manage the module files acorss
+/// different versions and different source files.
+class ModulesBuilder {
+public:
+  ModulesBuilder() = delete;

kadircet wrote:

this is already deleted.

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


[clang-tools-extra] [clangd] [C++20] [Modules] Introduce initial support for C++20 Modules (PR #66462)

2024-05-22 Thread kadir çetinkaya via cfe-commits


@@ -0,0 +1,81 @@
+//=== ModuleDependencyScanner.cpp *- 
C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "ModuleDependencyScanner.h"
+#include "support/Logger.h"
+
+namespace clang {
+namespace clangd {
+
+std::optional
+ModuleDependencyScanner::scan(PathRef FilePath) {
+  std::optional Cmd = CDB.getCompileCommand(FilePath);
+
+  if (!Cmd)
+return std::nullopt;
+
+  using namespace clang::tooling::dependencies;
+
+  llvm::SmallString<128> FilePathDir(FilePath);
+  llvm::sys::path::remove_filename(FilePathDir);
+  DependencyScanningTool ScanningTool(Service, TFS.view(FilePathDir));
+
+  llvm::Expected ScanningResult =
+  ScanningTool.getP1689ModuleDependencyFile(*Cmd, Cmd->Directory);
+
+  if (auto E = ScanningResult.takeError()) {
+log("Scanning modules dependencies for {0} failed: {1}", FilePath,

kadircet wrote:

`elog("...", FilePath, std::move(E))`

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


[clang-tools-extra] [clangd] [C++20] [Modules] Introduce initial support for C++20 Modules (PR #66462)

2024-05-22 Thread kadir çetinkaya via cfe-commits


@@ -0,0 +1,339 @@
+//===- ModulesBuilder.cpp *- 
C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "ModulesBuilder.h"
+#include "PrerequisiteModules.h"
+#include "support/Logger.h"
+
+#include "clang/Frontend/FrontendAction.h"
+#include "clang/Frontend/FrontendActions.h"
+
+namespace clang {
+namespace clangd {
+
+namespace {
+
+/// Get or create a path to store module files. Generally it should be:
+///
+///   project_root/.cache/clangd/module_files/{RequiredPrefixDir}/.
+///
+/// \param MainFile is used to get the root of the project from global
+/// compilation database. \param RequiredPrefixDir is used to get the user
+/// defined prefix for module files. This is useful when we want to seperate
+/// module files. e.g., we want to build module files for the same module unit
+/// `a.cppm` with 2 different users `b.cpp` and `c.cpp` and we don't want the
+/// module file for `b.cpp` be conflict with the module files for `c.cpp`. Then
+/// we can put the 2 module files into different dirs like:
+///
+///   project_root/.cache/clangd/module_files/b.cpp/a.pcm
+///   project_root/.cache/clangd/module_files/c.cpp/a.pcm
+llvm::SmallString<256> getModuleFilesPath(PathRef MainFile,
+  const GlobalCompilationDatabase &CDB,
+  StringRef RequiredPrefixDir) {
+  std::optional PI = CDB.getProjectInfo(MainFile);
+  if (!PI)
+return {};
+
+  // FIXME: PI->SourceRoot may be empty, depending on the CDB strategy.
+  llvm::SmallString<256> Result(PI->SourceRoot);
+
+  llvm::sys::path::append(Result, ".cache");
+  llvm::sys::path::append(Result, "clangd");
+  llvm::sys::path::append(Result, "module_files");
+
+  llvm::sys::path::append(Result, RequiredPrefixDir);
+
+  llvm::sys::fs::create_directories(Result, /*IgnoreExisting=*/true);
+
+  return Result;
+}
+
+/// Get the absolute path for the filename from the compile command.
+llvm::SmallString<128> getAbsolutePath(const tooling::CompileCommand &Cmd) {
+  llvm::SmallString<128> AbsolutePath;
+  if (llvm::sys::path::is_absolute(Cmd.Filename)) {
+AbsolutePath = Cmd.Filename;
+  } else {
+AbsolutePath = Cmd.Directory;
+llvm::sys::path::append(AbsolutePath, Cmd.Filename);
+llvm::sys::path::remove_dots(AbsolutePath, true);
+  }
+  return AbsolutePath;
+}
+
+/// Get a unique module file path under \param ModuleFilesPrefix.
+std::string getUniqueModuleFilePath(StringRef ModuleName,
+PathRef ModuleFilesPrefix) {
+  llvm::SmallString<256> ModuleFilePattern(ModuleFilesPrefix);
+  auto [PrimaryModuleName, PartitionName] = ModuleName.split(':');
+  llvm::sys::path::append(ModuleFilePattern, PrimaryModuleName);
+  if (!PartitionName.empty()) {
+ModuleFilePattern.append("-");
+ModuleFilePattern.append(PartitionName);
+  }
+
+  ModuleFilePattern.append("-%%-%%-%%-%%-%%-%%");

kadircet wrote:

i think we should generate a random prefix for the directory, rather than 
generating a random pcm name for each individual module under a preamble.

in the end we want to achieve uniqueness per-preamble (even if it's for the 
same file)

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


[clang-tools-extra] [clangd] [C++20] [Modules] Introduce initial support for C++20 Modules (PR #66462)

2024-05-22 Thread kadir çetinkaya via cfe-commits


@@ -48,6 +48,9 @@ Major New Features
 Improvements to clangd
 --
 
+- Introduced exmperimental support for C++20 Modules. The experimental support 
can
+  be enabled by `-experimental-modules-support` option.

kadircet wrote:

i think we should also document current limitations here (we can update them as 
we implement more).

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


[clang-tools-extra] [clangd] [C++20] [Modules] Introduce initial support for C++20 Modules (PR #66462)

2024-05-22 Thread kadir çetinkaya via cfe-commits


@@ -0,0 +1,339 @@
+//===- ModulesBuilder.cpp *- 
C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "ModulesBuilder.h"
+#include "PrerequisiteModules.h"
+#include "support/Logger.h"
+
+#include "clang/Frontend/FrontendAction.h"
+#include "clang/Frontend/FrontendActions.h"
+
+namespace clang {
+namespace clangd {
+
+namespace {
+
+/// Get or create a path to store module files. Generally it should be:
+///
+///   project_root/.cache/clangd/module_files/{RequiredPrefixDir}/.
+///
+/// \param MainFile is used to get the root of the project from global
+/// compilation database. \param RequiredPrefixDir is used to get the user
+/// defined prefix for module files. This is useful when we want to seperate
+/// module files. e.g., we want to build module files for the same module unit
+/// `a.cppm` with 2 different users `b.cpp` and `c.cpp` and we don't want the
+/// module file for `b.cpp` be conflict with the module files for `c.cpp`. Then
+/// we can put the 2 module files into different dirs like:
+///
+///   project_root/.cache/clangd/module_files/b.cpp/a.pcm
+///   project_root/.cache/clangd/module_files/c.cpp/a.pcm
+llvm::SmallString<256> getModuleFilesPath(PathRef MainFile,
+  const GlobalCompilationDatabase &CDB,
+  StringRef RequiredPrefixDir) {
+  std::optional PI = CDB.getProjectInfo(MainFile);
+  if (!PI)
+return {};
+
+  // FIXME: PI->SourceRoot may be empty, depending on the CDB strategy.
+  llvm::SmallString<256> Result(PI->SourceRoot);
+
+  llvm::sys::path::append(Result, ".cache");
+  llvm::sys::path::append(Result, "clangd");
+  llvm::sys::path::append(Result, "module_files");
+
+  llvm::sys::path::append(Result, RequiredPrefixDir);
+
+  llvm::sys::fs::create_directories(Result, /*IgnoreExisting=*/true);
+
+  return Result;
+}
+
+/// Get the absolute path for the filename from the compile command.
+llvm::SmallString<128> getAbsolutePath(const tooling::CompileCommand &Cmd) {
+  llvm::SmallString<128> AbsolutePath;
+  if (llvm::sys::path::is_absolute(Cmd.Filename)) {
+AbsolutePath = Cmd.Filename;
+  } else {
+AbsolutePath = Cmd.Directory;
+llvm::sys::path::append(AbsolutePath, Cmd.Filename);
+llvm::sys::path::remove_dots(AbsolutePath, true);
+  }
+  return AbsolutePath;
+}
+
+/// Get a unique module file path under \param ModuleFilesPrefix.
+std::string getUniqueModuleFilePath(StringRef ModuleName,
+PathRef ModuleFilesPrefix) {
+  llvm::SmallString<256> ModuleFilePattern(ModuleFilesPrefix);
+  auto [PrimaryModuleName, PartitionName] = ModuleName.split(':');
+  llvm::sys::path::append(ModuleFilePattern, PrimaryModuleName);
+  if (!PartitionName.empty()) {
+ModuleFilePattern.append("-");
+ModuleFilePattern.append(PartitionName);
+  }
+
+  ModuleFilePattern.append("-%%-%%-%%-%%-%%-%%");
+  ModuleFilePattern.append(".pcm");
+
+  llvm::SmallString<256> ModuleFilePath;
+  llvm::sys::fs::createUniquePath(ModuleFilePattern, ModuleFilePath,
+  /*MakeAbsolute=*/false);
+
+  return (std::string)ModuleFilePath;
+}
+} // namespace
+
+bool ModulesBuilder::buildModuleFile(StringRef ModuleName,
+ const ThreadsafeFS *TFS,
+ std::shared_ptr MDB,
+ PathRef ModuleFilesPrefix,
+ PrerequisiteModules &BuiltModuleFiles) {
+  if (BuiltModuleFiles.isModuleUnitBuilt(ModuleName))
+return true;
+
+  PathRef ModuleUnitFileName = MDB->getSourceForModuleName(ModuleName);
+  /// It is possible that we're meeting third party modules (modules whose
+  /// source are not in the project. e.g, the std module may be a third-party
+  /// module for most project) or something wrong with the implementation of
+  /// ProjectModules.
+  /// FIXME: How should we treat third party modules here? If we want to ignore
+  /// third party modules, we should return true instead of false here.
+  /// Currently we simply bail out.
+  if (ModuleUnitFileName.empty())
+return false;
+
+  for (auto &RequiredModuleName : MDB->getRequiredModules(ModuleUnitFileName)) 
{
+// Return early if there are errors building the module file.
+if (!buildModuleFile(RequiredModuleName, TFS, MDB, ModuleFilesPrefix,
+ BuiltModuleFiles)) {
+  log("Failed to build module {0}", RequiredModuleName);
+  return false;
+}
+  }
+
+  auto Cmd = CDB.getCompileCommand(ModuleUnitFileName);
+  if (!Cmd)
+return false;
+
+  std::string ModuleFileName =
+  getUniqueModuleFilePath(ModuleName, M

[clang-tools-extra] [clangd] [C++20] [Modules] Introduce initial support for C++20 Modules (PR #66462)

2024-05-22 Thread kadir çetinkaya via cfe-commits


@@ -0,0 +1,339 @@
+//===- ModulesBuilder.cpp *- 
C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "ModulesBuilder.h"
+#include "PrerequisiteModules.h"
+#include "support/Logger.h"
+
+#include "clang/Frontend/FrontendAction.h"
+#include "clang/Frontend/FrontendActions.h"
+
+namespace clang {
+namespace clangd {
+
+namespace {
+
+/// Get or create a path to store module files. Generally it should be:
+///
+///   project_root/.cache/clangd/module_files/{RequiredPrefixDir}/.
+///
+/// \param MainFile is used to get the root of the project from global
+/// compilation database. \param RequiredPrefixDir is used to get the user
+/// defined prefix for module files. This is useful when we want to seperate
+/// module files. e.g., we want to build module files for the same module unit
+/// `a.cppm` with 2 different users `b.cpp` and `c.cpp` and we don't want the
+/// module file for `b.cpp` be conflict with the module files for `c.cpp`. Then
+/// we can put the 2 module files into different dirs like:
+///
+///   project_root/.cache/clangd/module_files/b.cpp/a.pcm
+///   project_root/.cache/clangd/module_files/c.cpp/a.pcm
+llvm::SmallString<256> getModuleFilesPath(PathRef MainFile,
+  const GlobalCompilationDatabase &CDB,
+  StringRef RequiredPrefixDir) {
+  std::optional PI = CDB.getProjectInfo(MainFile);
+  if (!PI)
+return {};
+
+  // FIXME: PI->SourceRoot may be empty, depending on the CDB strategy.
+  llvm::SmallString<256> Result(PI->SourceRoot);
+
+  llvm::sys::path::append(Result, ".cache");
+  llvm::sys::path::append(Result, "clangd");
+  llvm::sys::path::append(Result, "module_files");
+
+  llvm::sys::path::append(Result, RequiredPrefixDir);
+
+  llvm::sys::fs::create_directories(Result, /*IgnoreExisting=*/true);
+
+  return Result;
+}
+
+/// Get the absolute path for the filename from the compile command.
+llvm::SmallString<128> getAbsolutePath(const tooling::CompileCommand &Cmd) {
+  llvm::SmallString<128> AbsolutePath;
+  if (llvm::sys::path::is_absolute(Cmd.Filename)) {
+AbsolutePath = Cmd.Filename;
+  } else {
+AbsolutePath = Cmd.Directory;
+llvm::sys::path::append(AbsolutePath, Cmd.Filename);
+llvm::sys::path::remove_dots(AbsolutePath, true);
+  }
+  return AbsolutePath;
+}
+
+/// Get a unique module file path under \param ModuleFilesPrefix.
+std::string getUniqueModuleFilePath(StringRef ModuleName,
+PathRef ModuleFilesPrefix) {
+  llvm::SmallString<256> ModuleFilePattern(ModuleFilesPrefix);
+  auto [PrimaryModuleName, PartitionName] = ModuleName.split(':');
+  llvm::sys::path::append(ModuleFilePattern, PrimaryModuleName);
+  if (!PartitionName.empty()) {
+ModuleFilePattern.append("-");
+ModuleFilePattern.append(PartitionName);
+  }
+
+  ModuleFilePattern.append("-%%-%%-%%-%%-%%-%%");
+  ModuleFilePattern.append(".pcm");
+
+  llvm::SmallString<256> ModuleFilePath;
+  llvm::sys::fs::createUniquePath(ModuleFilePattern, ModuleFilePath,
+  /*MakeAbsolute=*/false);
+
+  return (std::string)ModuleFilePath;
+}
+} // namespace
+
+bool ModulesBuilder::buildModuleFile(StringRef ModuleName,
+ const ThreadsafeFS *TFS,
+ std::shared_ptr MDB,
+ PathRef ModuleFilesPrefix,
+ PrerequisiteModules &BuiltModuleFiles) {
+  if (BuiltModuleFiles.isModuleUnitBuilt(ModuleName))
+return true;
+
+  PathRef ModuleUnitFileName = MDB->getSourceForModuleName(ModuleName);
+  /// It is possible that we're meeting third party modules (modules whose
+  /// source are not in the project. e.g, the std module may be a third-party
+  /// module for most project) or something wrong with the implementation of
+  /// ProjectModules.
+  /// FIXME: How should we treat third party modules here? If we want to ignore
+  /// third party modules, we should return true instead of false here.
+  /// Currently we simply bail out.
+  if (ModuleUnitFileName.empty())
+return false;
+
+  for (auto &RequiredModuleName : MDB->getRequiredModules(ModuleUnitFileName)) 
{
+// Return early if there are errors building the module file.
+if (!buildModuleFile(RequiredModuleName, TFS, MDB, ModuleFilesPrefix,
+ BuiltModuleFiles)) {
+  log("Failed to build module {0}", RequiredModuleName);
+  return false;
+}
+  }
+
+  auto Cmd = CDB.getCompileCommand(ModuleUnitFileName);
+  if (!Cmd)
+return false;
+
+  std::string ModuleFileName =
+  getUniqueModuleFilePath(ModuleName, M

[clang] [clang] Fix PS "selective" DLL import/export of vtable & typeinfo (PR #92579)

2024-05-22 Thread Andrew Ng via cfe-commits


@@ -1793,6 +1793,37 @@ void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction 
&CGF,
 ThisTy, VTT, VTTTy, nullptr);
 }
 
+// Check if any non-inline method has the specified attribute.
+template 
+static bool CXXRecordNonInlineHasAttr(const CXXRecordDecl *RD) {
+  for (const auto *D : RD->noload_decls()) {
+if (const auto *FD = dyn_cast(D)) {
+  if (FD->isInlineSpecified() || FD->doesThisDeclarationHaveABody() ||

nga888 wrote:

Yes, I understand that they are not equivalent but the original code has used 
`isInlineSpecified()` for quite some time (has been downstream at Sony since 
2015). Are you OK with this patch going in as is with a follow up to look into 
using `isInlined()`?

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


[clang] [llvm] [AMDGPU] Add amdgpu-as MMRA for fences (PR #78572)

2024-05-22 Thread Matt Arsenault via cfe-commits

arsenm wrote:

> Then I guess the MMRA should just have "global" and "local" for now, we can 
> always add more later if needed. What do you think?

Yes, we don't have specific image counters. They are just vcmnt 

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


[clang] [Clang][AArch64][SVE] Allow write to SVE vector elements using the subscript operator (PR #91965)

2024-05-22 Thread Momchil Velikov via cfe-commits

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


[clang] 91d415b - [Clang][AArch64][SVE] Allow write to SVE vector elements using the subscript operator (#91965)

2024-05-22 Thread via cfe-commits

Author: Momchil Velikov
Date: 2024-05-22T10:41:03+01:00
New Revision: 91d415b8d94b15023e6c39d5376274a2b21ee448

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

LOG: [Clang][AArch64][SVE] Allow write to SVE vector elements using the 
subscript operator (#91965)

The patch at https://reviews.llvm.org/D122732 introduced using the array
subscript operator for SVE vectors, however it also causes an ICE when
the subscripting expression is used as an lvalue.

This patches fixes the error. Lvalue subscripting expressions are
emitted as LLVM IR `insertelement`.

Added: 


Modified: 
clang/lib/CodeGen/CGExpr.cpp
clang/lib/Sema/SemaExpr.cpp
clang/test/CodeGen/aarch64-sve-vector-subscript-ops.c

Removed: 




diff  --git a/clang/lib/CodeGen/CGExpr.cpp b/clang/lib/CodeGen/CGExpr.cpp
index cd1c48b420382..6f9237e2067f5 100644
--- a/clang/lib/CodeGen/CGExpr.cpp
+++ b/clang/lib/CodeGen/CGExpr.cpp
@@ -4180,7 +4180,7 @@ LValue CodeGenFunction::EmitArraySubscriptExpr(const 
ArraySubscriptExpr *E,
 
   // If the base is a vector type, then we are forming a vector element lvalue
   // with this subscript.
-  if (E->getBase()->getType()->isVectorType() &&
+  if (E->getBase()->getType()->isSubscriptableVectorType() &&
   !isa(E->getBase())) {
 // Emit the vector as an lvalue to get its address.
 LValue LHS = EmitLValue(E->getBase());

diff  --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index f0ad3de311387..282508d489a5e 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -5185,7 +5185,7 @@ Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, 
SourceLocation LLoc,
   }
 
   // Perform default conversions.
-  if (!LHSExp->getType()->getAs()) {
+  if (!LHSExp->getType()->isSubscriptableVectorType()) {
 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
 if (Result.isInvalid())
   return ExprError();

diff  --git a/clang/test/CodeGen/aarch64-sve-vector-subscript-ops.c 
b/clang/test/CodeGen/aarch64-sve-vector-subscript-ops.c
index fb60c6d100ce6..52a05d010de9b 100644
--- a/clang/test/CodeGen/aarch64-sve-vector-subscript-ops.c
+++ b/clang/test/CodeGen/aarch64-sve-vector-subscript-ops.c
@@ -88,3 +88,25 @@ float subscript_float32(svfloat32_t a, size_t b) {
 double subscript_float64(svfloat64_t a, size_t b) {
   return a[b];
 }
+
+// CHECK-LABEL: @subscript_write_float32(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[VECINS:%.*]] = insertelement  
[[A:%.*]], float 1.00e+00, i64 [[B:%.*]]
+// CHECK-NEXT:ret  [[VECINS]]
+//
+svfloat32_t subscript_write_float32(svfloat32_t a, size_t b) {
+  a[b] = 1.0f;
+  return a;
+}
+
+// CHECK-LABEL: @subscript_read_write_float32(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[VECEXT:%.*]] = extractelement  
[[A:%.*]], i64 [[B:%.*]]
+// CHECK-NEXT:[[ADD:%.*]] = fadd float [[VECEXT]], 1.00e+00
+// CHECK-NEXT:[[VECINS:%.*]] = insertelement  [[A]], 
float [[ADD]], i64 [[B]]
+// CHECK-NEXT:ret  [[VECINS]]
+//
+svfloat32_t subscript_read_write_float32(svfloat32_t a, size_t b) {
+  a[b] += 1.0f;
+  return a;
+}



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


[clang] [lldb] [llvm] Remove some `try_compile` CMake checks for compiler flags (PR #92953)

2024-05-22 Thread Vlad Serebrennikov via cfe-commits

https://github.com/Endilll updated 
https://github.com/llvm/llvm-project/pull/92953

>From 66e05ac24613435dbe774d49684d8ff9d119c4c3 Mon Sep 17 00:00:00 2001
From: Vlad Serebrennikov 
Date: Tue, 21 May 2024 21:41:24 +0300
Subject: [PATCH 1/2] Remove some `try_compile` CMake checks for compiler flags

This patch remove 36 checks for compiler flags that are done via invoking the 
compiler across LLVM, Clang, and LLDB. It's was made possible by raising the 
bar for supported compilers that has been happening over the years since the 
checks were added.

This is going to improve CMake configuration times. This topic was highlighted 
in 
https://discourse.llvm.org/t/cmake-compiler-flag-checks-are-really-slow-ideas-to-speed-them-up/78882.
---
 clang/CMakeLists.txt  |   5 +-
 .../tests/functional/exec/CMakeLists.txt  |   6 +-
 lldb/cmake/modules/LLDBConfig.cmake   |  20 +--
 llvm/cmake/config-ix.cmake|  19 +--
 llvm/cmake/modules/AddLLVM.cmake  |   4 +-
 llvm/cmake/modules/HandleLLVMOptions.cmake| 142 --
 third-party/unittest/CMakeLists.txt   |   4 +-
 7 files changed, 80 insertions(+), 120 deletions(-)

diff --git a/clang/CMakeLists.txt b/clang/CMakeLists.txt
index c20ce47a12abb..a6bcb853a464c 100644
--- a/clang/CMakeLists.txt
+++ b/clang/CMakeLists.txt
@@ -349,10 +349,7 @@ if (LLVM_COMPILER_IS_GCC_COMPATIBLE)
 set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -pedantic -Wno-long-long")
   endif ()
 
-  check_cxx_compiler_flag("-Werror -Wnested-anon-types" 
CXX_SUPPORTS_NO_NESTED_ANON_TYPES_FLAG)
-  if( CXX_SUPPORTS_NO_NESTED_ANON_TYPES_FLAG )
-set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-nested-anon-types" )
-  endif()
+  set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-nested-anon-types" )
 endif ()
 
 # Determine HOST_LINK_VERSION on Darwin.
diff --git a/clang/tools/scan-build-py/tests/functional/exec/CMakeLists.txt 
b/clang/tools/scan-build-py/tests/functional/exec/CMakeLists.txt
index 95c6fdb610e0f..cb6ebda183725 100644
--- a/clang/tools/scan-build-py/tests/functional/exec/CMakeLists.txt
+++ b/clang/tools/scan-build-py/tests/functional/exec/CMakeLists.txt
@@ -2,11 +2,7 @@ project(exec C)
 
 cmake_minimum_required(VERSION 3.20.0)
 
-include(CheckCCompilerFlag)
-check_c_compiler_flag("-std=c99" C99_SUPPORTED)
-if (C99_SUPPORTED)
-set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=c99")
-endif()
+set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=c99")
 
 include(CheckFunctionExists)
 include(CheckSymbolExists)
diff --git a/lldb/cmake/modules/LLDBConfig.cmake 
b/lldb/cmake/modules/LLDBConfig.cmake
index 3c6223b015bb1..6458f2e174643 100644
--- a/lldb/cmake/modules/LLDBConfig.cmake
+++ b/lldb/cmake/modules/LLDBConfig.cmake
@@ -187,24 +187,18 @@ 
include_directories("${CMAKE_CURRENT_BINARY_DIR}/../clang/include")
 # form -W, and if supported, add the corresponding -Wno- option.
 
 # Disable GCC warnings
-check_cxx_compiler_flag("-Wdeprecated-declarations" 
CXX_SUPPORTS_DEPRECATED_DECLARATIONS)
-append_if(CXX_SUPPORTS_DEPRECATED_DECLARATIONS "-Wno-deprecated-declarations" 
CMAKE_CXX_FLAGS)
-
-check_cxx_compiler_flag("-Wunknown-pragmas" CXX_SUPPORTS_UNKNOWN_PRAGMAS)
-append_if(CXX_SUPPORTS_UNKNOWN_PRAGMAS "-Wno-unknown-pragmas" CMAKE_CXX_FLAGS)
-
-check_cxx_compiler_flag("-Wstrict-aliasing" CXX_SUPPORTS_STRICT_ALIASING)
-append_if(CXX_SUPPORTS_STRICT_ALIASING "-Wno-strict-aliasing" CMAKE_CXX_FLAGS)
+append("-Wno-deprecated-declarations" CMAKE_CXX_FLAGS)
+append("-Wno-unknown-pragmas" CMAKE_CXX_FLAGS)
+append("-Wno-strict-aliasing" CMAKE_CXX_FLAGS)
 
 check_cxx_compiler_flag("-Wstringop-truncation" 
CXX_SUPPORTS_STRINGOP_TRUNCATION)
 append_if(CXX_SUPPORTS_STRINGOP_TRUNCATION "-Wno-stringop-truncation" 
CMAKE_CXX_FLAGS)
 
 # Disable Clang warnings
-check_cxx_compiler_flag("-Wdeprecated-register" 
CXX_SUPPORTS_DEPRECATED_REGISTER)
-append_if(CXX_SUPPORTS_DEPRECATED_REGISTER "-Wno-deprecated-register" 
CMAKE_CXX_FLAGS)
-
-check_cxx_compiler_flag("-Wvla-extension" CXX_SUPPORTS_VLA_EXTENSION)
-append_if(CXX_SUPPORTS_VLA_EXTENSION "-Wno-vla-extension" CMAKE_CXX_FLAGS)
+if (CMAKE_CXX_COMPILER_ID MATCHES "Clang")
+  append("-Wno-deprecated-register" CMAKE_CXX_FLAGS)
+  append("-Wno-vla-extension" CMAKE_CXX_FLAGS)
+endif()
 
 # Disable MSVC warnings
 if( MSVC )
diff --git a/llvm/cmake/config-ix.cmake b/llvm/cmake/config-ix.cmake
index bf1b110245bb2..0900e1107076e 100644
--- a/llvm/cmake/config-ix.cmake
+++ b/llvm/cmake/config-ix.cmake
@@ -415,15 +415,14 @@ if( LLVM_ENABLE_PIC )
   set(ENABLE_PIC 1)
 else()
   set(ENABLE_PIC 0)
-  check_cxx_compiler_flag("-fno-pie" SUPPORTS_NO_PIE_FLAG)
-  if(SUPPORTS_NO_PIE_FLAG)
-set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -fno-pie")
-  endif()
+  set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -fno-pie")
 endif()
 
-check_cxx_compiler_flag("-Wvariadic-macros" SUPPORTS_VARIADIC_MACROS_FLAG)
-check_cxx_compiler_flag("-Wgnu-zero-variadic-macro-arguments"
-SUPPORTS_GNU_ZERO_VA

[clang] 775d7cc - [AArch64] Fix feature flags dependecies (#90612)

2024-05-22 Thread via cfe-commits

Author: Lukacma
Date: 2024-05-22T10:50:22+01:00
New Revision: 775d7ccc0fa1de4bb02e2f5cdf4ca38a021e873e

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

LOG: [AArch64] Fix feature flags dependecies (#90612)

This patch removes FEAT_FPMR from list of available of architecture
features, instead enabling FMPR register by default.
Additionally dependencies between architectural features are added and
fixed.

Added: 


Modified: 
clang/test/Driver/aarch64-v95a.c
llvm/lib/Target/AArch64/AArch64Features.td
llvm/lib/Target/AArch64/AArch64InstrInfo.td
llvm/lib/Target/AArch64/AArch64SystemOperands.td
llvm/lib/Target/AArch64/AsmParser/AArch64AsmParser.cpp
llvm/test/MC/AArch64/FP8/system-regs.s
llvm/unittests/TargetParser/TargetParserTest.cpp

Removed: 




diff  --git a/clang/test/Driver/aarch64-v95a.c 
b/clang/test/Driver/aarch64-v95a.c
index 1037da65c8cb5..62878f2127626 100644
--- a/clang/test/Driver/aarch64-v95a.c
+++ b/clang/test/Driver/aarch64-v95a.c
@@ -6,7 +6,7 @@
 // RUN: %clang -target aarch64 -mlittle-endian -march=armv9.5-a -### -c %s 
2>&1 | FileCheck -check-prefix=GENERICV95A %s
 // RUN: %clang -target aarch64_be -mlittle-endian -march=armv9.5a -### -c %s 
2>&1 | FileCheck -check-prefix=GENERICV95A %s
 // RUN: %clang -target aarch64_be -mlittle-endian -march=armv9.5-a -### -c %s 
2>&1 | FileCheck -check-prefix=GENERICV95A %s
-// GENERICV95A: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-cpu" "generic" 
"-target-feature" "+v9.5a"
+// GENERICV95A: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-cpu" "generic" 
"-target-feature" "+v9.5a"{{.*}}  "-target-feature" "+cpa"{{.*}} 
"-target-feature" "+faminmax"{{.*}}  "-target-feature" "+lut"
 
 // RUN: %clang -target aarch64_be -march=armv9.5a -### -c %s 2>&1 | FileCheck 
-check-prefix=GENERICV95A-BE %s
 // RUN: %clang -target aarch64_be -march=armv9.5-a -### -c %s 2>&1 | FileCheck 
-check-prefix=GENERICV95A-BE %s
@@ -14,14 +14,10 @@
 // RUN: %clang -target aarch64 -mbig-endian -march=armv9.5-a -### -c %s 2>&1 | 
FileCheck -check-prefix=GENERICV95A-BE %s
 // RUN: %clang -target aarch64_be -mbig-endian -march=armv9.5a -### -c %s 2>&1 
| FileCheck -check-prefix=GENERICV95A-BE %s
 // RUN: %clang -target aarch64_be -mbig-endian -march=armv9.5-a -### -c %s 
2>&1 | FileCheck -check-prefix=GENERICV95A-BE %s
-// GENERICV95A-BE: "-cc1"{{.*}} "-triple" "aarch64_be{{.*}}" "-target-cpu" 
"generic" "-target-feature" "+v9.5a"
+// GENERICV95A-BE: "-cc1"{{.*}} "-triple" "aarch64_be{{.*}}" "-target-cpu" 
"generic" "-target-feature" "+v9.5a"{{.*}}  "-target-feature" "+cpa"{{.*}} 
"-target-feature" "+faminmax"{{.*}}  "-target-feature" "+lut"
 
 // = Features supported on aarch64 =
 
-// RUN: %clang -target aarch64 -march=armv9.5a+cpa -### -c %s 2>&1 | FileCheck 
-check-prefix=V95A-CPA %s
-// RUN: %clang -target aarch64 -march=armv9.5-a+cpa -### -c %s 2>&1 | 
FileCheck -check-prefix=V95A-CPA %s
-// V95A-CPA: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-cpu" "generic" 
"-target-feature" "+v9.5a"{{.*}} "-target-feature" "+cpa"
-
 // RUN: %clang -target aarch64 -march=armv9.5a+pauth-lr -### -c %s 2>&1 | 
FileCheck -check-prefix=V95A-PAUTHLR %s
 // RUN: %clang -target aarch64 -march=armv9.5-a+pauth-lr -### -c %s 2>&1 | 
FileCheck -check-prefix=V95A-PAUTHLR %s
 // V95A-PAUTHLR: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-cpu" 
"generic" "-target-feature" "+v9.5a"{{.*}} "-target-feature" "+pauth-lr"

diff  --git a/llvm/lib/Target/AArch64/AArch64Features.td 
b/llvm/lib/Target/AArch64/AArch64Features.td
index ba0b760ce3d73..ffb899a301459 100644
--- a/llvm/lib/Target/AArch64/AArch64Features.td
+++ b/llvm/lib/Target/AArch64/AArch64Features.td
@@ -223,13 +223,6 @@ def FeatureSVE : Extension<"sve", "SVE",
   "Enable Scalable Vector Extension (SVE) instructions (FEAT_SVE)", 
[FeatureFullFP16],
   "FEAT_SVE", "+sve,+fullfp16,+fp-armv8,+neon", 310>;
 
-def FeatureFPMR : Extension<"fpmr", "FPMR",
-  "Enable FPMR Register (FEAT_FPMR)">;
-
-let FMVDependencies = "+fpmr" in
-def FeatureFP8 : Extension<"fp8", "FP8",
-  "Enable FP8 instructions (FEAT_FP8)">;
-
 // This flag is currently still labeled as Experimental, but when fully
 // implemented this should tell the compiler to use the zeroing pseudos to
 // benefit from the reverse instructions (e.g. SUB vs SUBR) if the inactive
@@ -667,41 +660,44 @@ def FeatureSME2p1 : Extension<"sme2p1", "SME2p1",
 def FeatureFAMINMAX: Extension<"faminmax", "FAMINMAX",
"Enable FAMIN and FAMAX instructions (FEAT_FAMINMAX)">;
 
-let FMVDependencies = "+fpmr" in
+def FeatureLUT: Extension<"lut", "LUT",
+   "Enable Lookup Table instructions (FEAT_LUT)">;
+   
+def FeatureFP8 : Extension<"fp8", "FP8",
+  "Enable FP8 instructions (FEAT_FP8)", [FeatureFAMINMAX, FeatureLUT, 
FeatureBF16]>;
+  
 def 

[clang] [llvm] [AArch64] Fix feature flags dependecies (PR #90612)

2024-05-22 Thread via cfe-commits

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


[clang] 1f5cd3a - [clang][Interp][NFC] Fix getType() of pointers pointing to vector elems

2024-05-22 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2024-05-22T11:58:46+02:00
New Revision: 1f5cd3accd7e98abbf31d45b1ed59fbda0c91d30

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

LOG: [clang][Interp][NFC] Fix getType() of pointers pointing to vector elems

Added: 


Modified: 
clang/lib/AST/Interp/Pointer.h

Removed: 




diff  --git a/clang/lib/AST/Interp/Pointer.h b/clang/lib/AST/Interp/Pointer.h
index 3ade5756e580e..9468bdbf00cc0 100644
--- a/clang/lib/AST/Interp/Pointer.h
+++ b/clang/lib/AST/Interp/Pointer.h
@@ -314,12 +314,14 @@ class Pointer {
   /// Returns the type of the innermost field.
   QualType getType() const {
 if (inPrimitiveArray() && Offset != asBlockPointer().Base) {
-  // Unfortunately, complex types are not array types in clang, but they 
are
-  // for us.
+  // Unfortunately, complex and vector types are not array types in clang,
+  // but they are for us.
   if (const auto *AT = getFieldDesc()->getType()->getAsArrayTypeUnsafe())
 return AT->getElementType();
   if (const auto *CT = getFieldDesc()->getType()->getAs())
 return CT->getElementType();
+  if (const auto *CT = getFieldDesc()->getType()->getAs())
+return CT->getElementType();
 }
 return getFieldDesc()->getType();
   }



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


[clang] [clang][analyzer] Add checker 'security.SetgidSetuidOrder' (PR #91445)

2024-05-22 Thread Balázs Kéri via cfe-commits

https://github.com/balazske updated 
https://github.com/llvm/llvm-project/pull/91445

From d839faf7a30851a172d812137b30635c741870f0 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Bal=C3=A1zs=20K=C3=A9ri?= 
Date: Wed, 8 May 2024 10:10:24 +0200
Subject: [PATCH 01/10] [clang][analyzer] Add checker
 'Security.SetgidSetuidOrder'.

---
 clang/docs/analyzer/checkers.rst  |  28 +++
 .../clang/StaticAnalyzer/Checkers/Checkers.td |   5 +
 .../StaticAnalyzer/Checkers/CMakeLists.txt|   1 +
 .../Checkers/SetgidSetuidOrderChecker.cpp | 196 ++
 .../system-header-simulator-setgid-setuid.h   |  15 ++
 clang/test/Analysis/setgid-setuid-order.c | 170 +++
 6 files changed, 415 insertions(+)
 create mode 100644 
clang/lib/StaticAnalyzer/Checkers/SetgidSetuidOrderChecker.cpp
 create mode 100644 
clang/test/Analysis/Inputs/system-header-simulator-setgid-setuid.h
 create mode 100644 clang/test/Analysis/setgid-setuid-order.c

diff --git a/clang/docs/analyzer/checkers.rst b/clang/docs/analyzer/checkers.rst
index 0d87df36ced0e..d0c0c7a535c62 100644
--- a/clang/docs/analyzer/checkers.rst
+++ b/clang/docs/analyzer/checkers.rst
@@ -1179,6 +1179,34 @@ security.insecureAPI.DeprecatedOrUnsafeBufferHandling (C)
strncpy(buf, "a", 1); // warn
  }
 
+security.SetgidSetuidOrder (C)
+""
+When dropping user-level and group-level privileges in a program by using
+``setuid`` and ``setgid`` calls, it is important to reset the group-level
+privileges (with ``setgid``) first. Function ``setgid`` will likely fail if
+the superuser privileges are already dropped.
+
+The checker checks for sequences of ``setuid(getuid())`` and
+``setgid(getgid())`` calls (in this order). If such a sequence is found and
+there is no other privilege-changing function call (``seteuid``, ``setreuid``,
+``setresuid`` and the GID versions of these) in between, a warning is
+generated. The checker finds only exactly ``setuid(getuid())`` calls (and the
+GID versions), not for example if the result of ``getuid()`` is stored in a
+variable.
+
+This check corresponds to SEI CERT Rule `POS36-C 
`_.
+
+.. code-block:: c
+
+ void test1() {
+   if (setuid(getuid()) == -1) {
+ /* handle error condition */
+   }
+   if (setgid(getgid()) == -1) { // warn
+ /* handle error condition */
+   }
+ }
+
 .. _unix-checkers:
 
 unix
diff --git a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td 
b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
index 520286b57c9fd..cc954828901af 100644
--- a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
+++ b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
@@ -1011,6 +1011,11 @@ def FloatLoopCounter : Checker<"FloatLoopCounter">,
   Dependencies<[SecuritySyntaxChecker]>,
   Documentation;
 
+def SetgidSetuidOrderChecker : Checker<"SetgidSetuidOrder">,
+  HelpText<"Warn on possible reversed order of 'setgid(getgid()))' and 
'setuid(getuid())' (CERT: "
+   "POS36-C)">,
+  Documentation;
+
 } // end "security"
 
 let ParentPackage = ENV in {
diff --git a/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt 
b/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
index 4443ffd092938..45d3788f105dc 100644
--- a/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
+++ b/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
@@ -103,6 +103,7 @@ add_clang_library(clangStaticAnalyzerCheckers
   ReturnUndefChecker.cpp
   ReturnValueChecker.cpp
   RunLoopAutoreleaseLeakChecker.cpp
+  SetgidSetuidOrderChecker.cpp
   SimpleStreamChecker.cpp
   SmartPtrChecker.cpp
   SmartPtrModeling.cpp
diff --git a/clang/lib/StaticAnalyzer/Checkers/SetgidSetuidOrderChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/SetgidSetuidOrderChecker.cpp
new file mode 100644
index 0..11cc748cb40b1
--- /dev/null
+++ b/clang/lib/StaticAnalyzer/Checkers/SetgidSetuidOrderChecker.cpp
@@ -0,0 +1,196 @@
+//===-- ChrootChecker.cpp - chroot usage checks 
---===//
+//
+// 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
+//
+//===--===//
+//
+//  This file defines chroot checker, which checks improper use of chroot.
+//
+//===--===//
+
+#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
+#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
+#include "clang/StaticAnalyzer/Core/Checker.h"
+#include "clang/StaticAnalyzer/Core/CheckerManager.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
+#includ

[clang] 5d833c6 - [clang][Interp][NFC] Remove unneeded CheckRange call

2024-05-22 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2024-05-22T12:09:12+02:00
New Revision: 5d833c65da74d83a9b5df19da52d67ea1c0ecc10

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

LOG: [clang][Interp][NFC] Remove unneeded CheckRange call

This doesn't do anything with the current tests and is unnecessary in
general.

Added: 


Modified: 
clang/lib/AST/Interp/Interp.h

Removed: 




diff  --git a/clang/lib/AST/Interp/Interp.h b/clang/lib/AST/Interp/Interp.h
index bc2ca126ce364..c5607169b25f1 100644
--- a/clang/lib/AST/Interp/Interp.h
+++ b/clang/lib/AST/Interp/Interp.h
@@ -1538,9 +1538,6 @@ inline bool Memcpy(InterpState &S, CodePtr OpPC) {
 template 
 bool OffsetHelper(InterpState &S, CodePtr OpPC, const T &Offset,
   const Pointer &Ptr) {
-  if (!CheckRange(S, OpPC, Ptr, CSK_ArrayToPointer))
-return false;
-
   // A zero offset does not change the pointer.
   if (Offset.isZero()) {
 S.Stk.push(Ptr);



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


[clang] 11b97da - [clang][analyzer] Add checker 'security.SetgidSetuidOrder' (#91445)

2024-05-22 Thread via cfe-commits

Author: Balázs Kéri
Date: 2024-05-22T12:11:18+02:00
New Revision: 11b97da83141db857361ec9535dcd637ffcd0439

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

LOG: [clang][analyzer] Add checker 'security.SetgidSetuidOrder' (#91445)

Added: 
clang/lib/StaticAnalyzer/Checkers/SetgidSetuidOrderChecker.cpp
clang/test/Analysis/setgid-setuid-order-notes.c
clang/test/Analysis/setgid-setuid-order.c

Modified: 
clang/docs/analyzer/checkers.rst
clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt

Removed: 




diff  --git a/clang/docs/analyzer/checkers.rst 
b/clang/docs/analyzer/checkers.rst
index eb8b58323da4d..b4bd9dac1cbc2 100644
--- a/clang/docs/analyzer/checkers.rst
+++ b/clang/docs/analyzer/checkers.rst
@@ -1179,6 +1179,47 @@ security.insecureAPI.DeprecatedOrUnsafeBufferHandling (C)
strncpy(buf, "a", 1); // warn
  }
 
+security.SetgidSetuidOrder (C)
+""
+When dropping user-level and group-level privileges in a program by using
+``setuid`` and ``setgid`` calls, it is important to reset the group-level
+privileges (with ``setgid``) first. Function ``setgid`` will likely fail if
+the superuser privileges are already dropped.
+
+The checker checks for sequences of ``setuid(getuid())`` and
+``setgid(getgid())`` calls (in this order). If such a sequence is found and
+there is no other privilege-changing function call (``seteuid``, ``setreuid``,
+``setresuid`` and the GID versions of these) in between, a warning is
+generated. The checker finds only exactly ``setuid(getuid())`` calls (and the
+GID versions), not for example if the result of ``getuid()`` is stored in a
+variable.
+
+.. code-block:: c
+
+ void test1() {
+   // ...
+   // end of section with elevated privileges
+   // reset privileges (user and group) to normal user
+   if (setuid(getuid()) != 0) {
+ handle_error();
+ return;
+   }
+   if (setgid(getgid()) != 0) { // warning: A 'setgid(getgid())' call 
following a 'setuid(getuid())' call is likely to fail
+ handle_error();
+ return;
+   }
+   // user-ID and group-ID are reset to normal user now
+   // ...
+ }
+
+In the code above the problem is that ``setuid(getuid())`` removes superuser
+privileges before ``setgid(getgid())`` is called. To fix the problem the
+``setgid(getgid())`` should be called first. Further attention is needed to
+avoid code like ``setgid(getuid())`` (this checker does not detect bugs like
+this) and always check the return value of these calls.
+
+This check corresponds to SEI CERT Rule `POS36-C 
`_.
+
 .. _unix-checkers:
 
 unix

diff  --git a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td 
b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
index 64414e3d37f75..d0ba1ce548403 100644
--- a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
+++ b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
@@ -1011,6 +1011,11 @@ def FloatLoopCounter : Checker<"FloatLoopCounter">,
   Dependencies<[SecuritySyntaxChecker]>,
   Documentation;
 
+def SetgidSetuidOrderChecker : Checker<"SetgidSetuidOrder">,
+  HelpText<"Warn on possible reversed order of 'setgid(getgid()))' and "
+   "'setuid(getuid())' (CERT: POS36-C)">,
+  Documentation;
+
 } // end "security"
 
 let ParentPackage = ENV in {

diff  --git a/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt 
b/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
index 4443ffd092938..45d3788f105dc 100644
--- a/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
+++ b/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
@@ -103,6 +103,7 @@ add_clang_library(clangStaticAnalyzerCheckers
   ReturnUndefChecker.cpp
   ReturnValueChecker.cpp
   RunLoopAutoreleaseLeakChecker.cpp
+  SetgidSetuidOrderChecker.cpp
   SimpleStreamChecker.cpp
   SmartPtrChecker.cpp
   SmartPtrModeling.cpp

diff  --git a/clang/lib/StaticAnalyzer/Checkers/SetgidSetuidOrderChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/SetgidSetuidOrderChecker.cpp
new file mode 100644
index 0..dbe3fd33a6b43
--- /dev/null
+++ b/clang/lib/StaticAnalyzer/Checkers/SetgidSetuidOrderChecker.cpp
@@ -0,0 +1,196 @@
+//===-- SetgidSetuidOrderChecker.cpp - check privilege revocation calls 
---===//
+//
+// 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
+//
+//===--===//
+//
+//  This file defines a checker to detect possible reversed order of privilege
+//  revocations when 'setgid' and 'setuid' i

[clang] [clang][analyzer] Add checker 'security.SetgidSetuidOrder' (PR #91445)

2024-05-22 Thread Balázs Kéri via cfe-commits

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


[clang] 5cb2ea5 - [clang][Interp][NFC] Remove VarDecl requirement in diagnoseUnknownDecl()

2024-05-22 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2024-05-22T12:14:56+02:00
New Revision: 5cb2ea5704c733102ae93a50b10b80c1ae06112e

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

LOG: [clang][Interp][NFC] Remove VarDecl requirement in diagnoseUnknownDecl()

We can call diagnoseNonConstVariable() for all ValueDecls just fine.

Added: 


Modified: 
clang/lib/AST/Interp/Interp.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/Interp.cpp b/clang/lib/AST/Interp/Interp.cpp
index 3e4da487e43c3..1ed2ff30bdd05 100644
--- a/clang/lib/AST/Interp/Interp.cpp
+++ b/clang/lib/AST/Interp/Interp.cpp
@@ -76,18 +76,15 @@ static bool diagnoseUnknownDecl(InterpState &S, CodePtr 
OpPC,
 } else {
   S.FFDiag(E);
 }
-  } else if (const auto *VD = dyn_cast(D)) {
-if (!VD->getType().isConstQualified()) {
-  diagnoseNonConstVariable(S, OpPC, VD);
-  return false;
-}
-
-// const, but no initializer.
-if (!VD->getAnyInitializer()) {
-  diagnoseMissingInitializer(S, OpPC, VD);
-  return false;
-}
+return false;
   }
+
+  if (!D->getType().isConstQualified())
+diagnoseNonConstVariable(S, OpPC, D);
+  else if (const auto *VD = dyn_cast(D);
+   VD && !VD->getAnyInitializer())
+diagnoseMissingInitializer(S, OpPC, VD);
+
   return false;
 }
 



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


[libunwind] Use relative includes to allow source-based dependencies without `-I` (PR #80443)

2024-05-22 Thread Yuriy Chernyshov via cfe-commits

georgthegreat wrote:

@ldionne, gentle ping

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


[clang] [llvm] wip: Move instrumentation passes (PR #92171)

2024-05-22 Thread Egor Pasko via cfe-commits


@@ -0,0 +1,29 @@
+; RUN: llc -mtriple=x86_64-- -O0 < %s | FileCheck %s
+; RUN: llc -mtriple=x86_64-- -O1 < %s | FileCheck %s
+; RUN: llc -mtriple=x86_64-- -O2 < %s | FileCheck %s
+
+; The codegen should insert post-inlining instrumentation calls and should not
+; insert pre-inlining instrumentation.
+
+; CHECK-NOT:   callq __cyg_profile_func_enter
+
+define void @leaf_function() #0 {
+; CHECK-LABEL: leaf_function:
+; CHECK:   callq __cyg_profile_func_enter_bare
+; CHECK:   movqleaf_function@GOTPCREL(%rip), %rdi

pasko wrote:

Yeah, I was also thinking that the use of a particular relocation makes it more 
brittle. I think it is nice to check that func_exit is used without an argument 
(unlike `__cyg_profile_func_enter_bare`). This can be done with the 
`CHECK-NEXT` on the line that follows. Though I did not notice this kind of 
parameter passing is already checked in 
`llvm/test/Transforms/EntryExitInstrumenter/mcount.ll`, hence now I am not sure 
how much value there is in this check.

I would not probably regret removing the line, but I'd like to try one more 
thing:
```
; CHECK:   {{.*}} %rdi
; CHECK-NEXT:  callq  __cyg_profile_func_exit
```

Will it blend?

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


[clang] e5936b2 - [clang][Interp][NFC] Fix toAPValue() for array root pointers

2024-05-22 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2024-05-22T12:14:56+02:00
New Revision: e5936b245e9af0cea69a7e4eae22a05b7ffcf5a3

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

LOG: [clang][Interp][NFC] Fix toAPValue() for array root pointers

isArrayElement() returns false for them, so we used to add the decl
to the path, causing wrong APValues to be generated.

Added: 


Modified: 
clang/lib/AST/Interp/Pointer.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/Pointer.cpp 
b/clang/lib/AST/Interp/Pointer.cpp
index ee8cedccb8d4b..e45c291668caf 100644
--- a/clang/lib/AST/Interp/Pointer.cpp
+++ b/clang/lib/AST/Interp/Pointer.cpp
@@ -144,13 +144,18 @@ APValue Pointer::toAPValue() const {
 
   // TODO: compute the offset into the object.
   CharUnits Offset = CharUnits::Zero();
-  bool IsOnePastEnd = isOnePastEnd();
 
   // Build the path into the object.
   Pointer Ptr = *this;
   while (Ptr.isField() || Ptr.isArrayElement()) {
-if (Ptr.isArrayElement()) {
-  Path.push_back(APValue::LValuePathEntry::ArrayIndex(Ptr.getIndex()));
+if (Ptr.isArrayRoot()) {
+Path.push_back(APValue::LValuePathEntry::ArrayIndex(0));
+Ptr = Ptr.getBase();
+} else if (Ptr.isArrayElement()) {
+  if (Ptr.isOnePastEnd())
+
Path.push_back(APValue::LValuePathEntry::ArrayIndex(Ptr.getArray().getNumElems()));
+  else
+Path.push_back(APValue::LValuePathEntry::ArrayIndex(Ptr.getIndex()));
   Ptr = Ptr.getArray();
 } else {
   // TODO: figure out if base is virtual
@@ -173,7 +178,7 @@ APValue Pointer::toAPValue() const {
   // Just invert the order of the elements.
   std::reverse(Path.begin(), Path.end());
 
-  return APValue(Base, Offset, Path, IsOnePastEnd, /*IsNullPtr=*/false);
+  return APValue(Base, Offset, Path, /*IsOnePastEnd=*/false, 
/*IsNullPtr=*/false);
 }
 
 void Pointer::print(llvm::raw_ostream &OS) const {



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


[clang] [llvm] [AMDGPU] Add amdgpu-as MMRA for fences (PR #78572)

2024-05-22 Thread Pierre van Houtryve via cfe-commits

Pierre-vh wrote:

> > Then I guess the MMRA should just have "global" and "local" for now, we can 
> > always add more later if needed. What do you think?
> 
> Yes, we don't have specific image counters. They are just vcmnt

Diff has been updated with those changes

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


[clang] 9604e5c - [clang][Interp] Allow stepping back from a one-past-the-end pointer

2024-05-22 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2024-05-22T12:45:17+02:00
New Revision: 9604e5ce8b5607cd88ba130314fc7ae8545542e1

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

LOG: [clang][Interp] Allow stepping back from a one-past-the-end pointer

... back into range of the array.

Added: 


Modified: 
clang/lib/AST/Interp/Interp.h
clang/lib/AST/Interp/Pointer.h
clang/test/AST/Interp/arrays.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/Interp.h b/clang/lib/AST/Interp/Interp.h
index c5607169b25f1..7ef963c810c82 100644
--- a/clang/lib/AST/Interp/Interp.h
+++ b/clang/lib/AST/Interp/Interp.h
@@ -1555,8 +1555,12 @@ bool OffsetHelper(InterpState &S, CodePtr OpPC, const T 
&Offset,
   if (!CheckArray(S, OpPC, Ptr))
 return false;
 
-  uint64_t Index = Ptr.getIndex();
   uint64_t MaxIndex = static_cast(Ptr.getNumElems());
+  uint64_t Index;
+  if (Ptr.isOnePastEnd())
+Index = MaxIndex;
+  else
+Index = Ptr.getIndex();
 
   bool Invalid = false;
   // Helper to report an invalid offset, computed as APSInt.

diff  --git a/clang/lib/AST/Interp/Pointer.h b/clang/lib/AST/Interp/Pointer.h
index 9468bdbf00cc0..93ca754d04a64 100644
--- a/clang/lib/AST/Interp/Pointer.h
+++ b/clang/lib/AST/Interp/Pointer.h
@@ -537,9 +537,6 @@ class Pointer {
 if (isZero())
   return 0;
 
-if (isElementPastEnd())
-  return 1;
-
 // narrow()ed element in a composite array.
 if (asBlockPointer().Base > sizeof(InlineDescriptor) &&
 asBlockPointer().Base == Offset)

diff  --git a/clang/test/AST/Interp/arrays.cpp 
b/clang/test/AST/Interp/arrays.cpp
index e936ec6dc894b..dd5064d993e66 100644
--- a/clang/test/AST/Interp/arrays.cpp
+++ b/clang/test/AST/Interp/arrays.cpp
@@ -54,6 +54,10 @@ constexpr int derefPtr(const int *d) {
 }
 static_assert(derefPtr(data) == 5, "");
 
+/// Make sure we can refer to the one-past-the-end element
+/// and then return back to the end of the array.
+static_assert((&data[5])[-1] == 1, "");
+
 constexpr int storePtr() {
   int b[] = {1,2,3,4};
   int *c = b;



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


[clang] [llvm] [polly] [X86] Remove knl/knm specific ISAs supports (PR #92883)

2024-05-22 Thread Simon Pilgrim via cfe-commits

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


[clang] [llvm] [polly] [X86] Remove knl/knm specific ISAs supports (PR #92883)

2024-05-22 Thread Simon Pilgrim via cfe-commits


@@ -139,6 +139,9 @@ Changes to the Windows Target
 Changes to the X86 Backend
 --
 
+- Removed knl/knm specific ISA lowerings: AVX512PF, AVX512ER, PREFETCHWT1,

RKSimon wrote:

"ISA intrinsics" instead?

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


[clang] [llvm] [polly] [X86] Remove knl/knm specific ISAs supports (PR #92883)

2024-05-22 Thread Simon Pilgrim via cfe-commits

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

LGTM with one minor

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


[clang] f685481 - [clang][Interp] Fix checking unions for initialization

2024-05-22 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2024-05-22T13:12:48+02:00
New Revision: f68548135b8f9a02beac842646ab89bcaad9d400

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

LOG: [clang][Interp] Fix checking unions for initialization

Added: 
clang/test/AST/Interp/unions.cpp

Modified: 
clang/lib/AST/Interp/EvaluationResult.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/EvaluationResult.cpp 
b/clang/lib/AST/Interp/EvaluationResult.cpp
index e92d686c724cc..79f222ce2b30c 100644
--- a/clang/lib/AST/Interp/EvaluationResult.cpp
+++ b/clang/lib/AST/Interp/EvaluationResult.cpp
@@ -115,6 +115,10 @@ static bool CheckFieldsInitialized(InterpState &S, 
SourceLocation Loc,
   DiagnoseUninitializedSubobject(S, Loc, F.Decl);
   Result = false;
 }
+
+// Only the first member of a union needs to be initialized.
+if (R->isUnion())
+  break;
   }
 
   // Check Fields in all bases

diff  --git a/clang/test/AST/Interp/unions.cpp 
b/clang/test/AST/Interp/unions.cpp
new file mode 100644
index 0..08ca39c3cb089
--- /dev/null
+++ b/clang/test/AST/Interp/unions.cpp
@@ -0,0 +1,14 @@
+// RUN: %clang_cc1 -fexperimental-new-constant-interpreter 
-verify=expected,both %s
+// RUN: %clang_cc1 -verify=ref,both %s
+
+// both-no-diagnostics
+
+union U {
+  int a;
+  int b;
+};
+
+constexpr U a = {12};
+static_assert(a.a == 12, "");
+
+



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


[clang-tools-extra] [clang-tidy] Correcting issues in `readability-implicit-bool-conversion` on C23 (PR #92241)

2024-05-22 Thread Björn Svensson via cfe-commits

https://github.com/bjosv updated https://github.com/llvm/llvm-project/pull/92241

From 44ae41f00064dc477db0eb00b45fceff811cadec Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Bj=C3=B6rn=20Svensson?= 
Date: Mon, 29 Apr 2024 12:49:59 +0200
Subject: [PATCH 1/5] [clang-tidy] Use C-style casts on C23 in
 readability-implicit-bool-conversion

readability-implicit-bool-conversion supports language-versions which has
LangOpts.Bool and that includes C23. The problem is that the fixer suggests
`static_cast<>()` which is not available in C23.

Update checker to provide C-style casts when running on other than C++.
---
 .../ImplicitBoolConversionCheck.cpp   |   6 +
 clang-tools-extra/docs/ReleaseNotes.rst   |   3 +-
 .../readability/implicit-bool-conversion.rst  |   4 +-
 .../readability/implicit-bool-conversion.c| 333 ++
 4 files changed, 343 insertions(+), 3 deletions(-)
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/readability/implicit-bool-conversion.c

diff --git 
a/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp 
b/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp
index 74152c6034510..c2d1bc691d58a 100644
--- a/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp
+++ b/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp
@@ -165,6 +165,12 @@ bool needsSpacePrefix(SourceLocation Loc, ASTContext 
&Context) {
 void fixGenericExprCastFromBool(DiagnosticBuilder &Diag,
 const ImplicitCastExpr *Cast,
 ASTContext &Context, StringRef OtherType) {
+  if (!Context.getLangOpts().CPlusPlus) {
+Diag << FixItHint::CreateInsertion(Cast->getBeginLoc(),
+   (Twine("(") + OtherType + ")").str());
+return;
+  }
+
   const Expr *SubExpr = Cast->getSubExpr();
   const bool NeedParens = !isa(SubExpr->IgnoreImplicit());
   const bool NeedSpace = needsSpacePrefix(Cast->getBeginLoc(), Context);
diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 19f8307412956..d19f83793a6c4 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -368,7 +368,8 @@ Changes in existing checks
 - Improved :doc:`readability-implicit-bool-conversion
   ` check to provide
   valid fix suggestions for ``static_cast`` without a preceding space and
-  fixed problem with duplicate parentheses in double implicit casts.
+  fixed problem with duplicate parentheses in double implicit casts. Corrected
+  the fix suggestions for C23 by using C-style casts instead of 
``static_cast``.
 
 - Improved :doc:`readability-redundant-inline-specifier
   ` check to properly
diff --git 
a/clang-tools-extra/docs/clang-tidy/checks/readability/implicit-bool-conversion.rst
 
b/clang-tools-extra/docs/clang-tidy/checks/readability/implicit-bool-conversion.rst
index 1ea67a0b55e96..643af488ae3df 100644
--- 
a/clang-tools-extra/docs/clang-tidy/checks/readability/implicit-bool-conversion.rst
+++ 
b/clang-tools-extra/docs/clang-tidy/checks/readability/implicit-bool-conversion.rst
@@ -96,8 +96,8 @@ The rules for generating fix-it hints are:
   - ``if (!pointer)`` is changed to ``if (pointer == nullptr)``,
 
 - in case of conversions from bool to other built-in types, an explicit
-  ``static_cast`` is proposed to make it clear that a conversion is taking
-  place:
+  ``static_cast`` (or a C-style cast for C23) is proposed to make it clear that
+  a conversion is taking place:
 
   - ``int integer = boolean;`` is changed to
 ``int integer = static_cast(boolean);``,
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/readability/implicit-bool-conversion.c
 
b/clang-tools-extra/test/clang-tidy/checkers/readability/implicit-bool-conversion.c
new file mode 100644
index 0..c264372efaf25
--- /dev/null
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/readability/implicit-bool-conversion.c
@@ -0,0 +1,333 @@
+// RUN: %check_clang_tidy %s readability-implicit-bool-conversion %t -- -- 
-std=c23
+
+#undef NULL
+#define NULL 0L
+
+void functionTakingBool(bool);
+void functionTakingInt(int);
+void functionTakingUnsignedLong(unsigned long);
+void functionTakingChar(char);
+void functionTakingFloat(float);
+void functionTakingDouble(double);
+void functionTakingSignedChar(signed char);
+
+
+// Implicit conversion from bool.
+
+void implicitConversionFromBoolSimpleCases() {
+  bool boolean = true;
+
+  functionTakingBool(boolean);
+
+  functionTakingInt(boolean);
+  // CHECK-MESSAGES: :[[@LINE-1]]:21: warning: implicit conversion 'bool' -> 
'int' [readability-implicit-bool-conversion]
+  // CHECK-FIXES: functionTakingInt((int)boolean);
+
+  functionTakingUnsignedLong(boolean);
+  // CHECK-MESSAGES: :[[@LINE-1]]:30: warning: implicit conversion 'bool' -> 
'unsigned long'
+  // CHECK-FIXES: functionTakingUnsignedLong((unsigned long)boolean);
+
+  function

[clang] [openmp] [Clang][OpenMP] Fix tile/unroll on iterator- and foreach-loops. (PR #91459)

2024-05-22 Thread Alexey Bataev via cfe-commits

https://github.com/alexey-bataev approved this pull request.

LG

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


[clang] [llvm] [AMDGPU] Add amdgpu-as MMRA for fences (PR #78572)

2024-05-22 Thread Matt Arsenault via cfe-commits

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


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


[clang] [llvm] [AMDGPU] Add amdgpu-as MMRA for fences (PR #78572)

2024-05-22 Thread Matt Arsenault via cfe-commits

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


[clang] [llvm] [AMDGPU] Add amdgpu-as MMRA for fences (PR #78572)

2024-05-22 Thread Matt Arsenault via cfe-commits


@@ -678,6 +680,49 @@ class SIMemoryLegalizer final : public MachineFunctionPass 
{
   bool runOnMachineFunction(MachineFunction &MF) override;
 };
 
+static const StringMap ASNames = {{
+{"global", SIAtomicAddrSpace::GLOBAL},
+{"local", SIAtomicAddrSpace::LDS},
+}};
+
+void diagnoseUnknownMMRAASName(const MachineInstr &MI, StringRef AS) {
+  const MachineFunction *MF = MI.getMF();
+  const Function &Fn = MF->getFunction();
+  std::string Str;
+  raw_string_ostream OS(Str);

arsenm wrote:

SmallString + raw_svector_ostream? 

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


[clang] [C] Disallow declarations where a statement is required (PR #92908)

2024-05-22 Thread Aaron Ballman via cfe-commits

AaronBallman wrote:

It gets set a few lines down for `Compound`:

`Compound = AllowDeclarationsInC | AllowStandaloneOpenMPDirectives`

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


[clang] [clang] Distinguish unresolved templates in UnresolvedLookupExpr (PR #89019)

2024-05-22 Thread Krystian Stasiowski via cfe-commits

sdkrystian wrote:

@zyn0217 Yes, both examples are of uninstantiable templates & are intended to 
be diagnosed by #90152.

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


[clang] [llvm] [AArch64] set AppleA14 architecture version to v8.4-a (PR #92600)

2024-05-22 Thread Tomas Matheson via cfe-commits


@@ -718,12 +718,16 @@ def ProcessorFeatures {
   list AppleA13 = [HasV8_4aOps, FeatureCrypto, 
FeatureFPARMv8,
  FeatureNEON, FeaturePerfMon, 
FeatureFullFP16,
  FeatureFP16FML, FeatureSHA3];
+  // Apple A14 and M1 chips are based on Armv8.5-a but without BTI. Since there

tmatheson-arm wrote:

Is there a problem with emphasising it? The main motivation is to avoid people 
repeating the mistake that I made, i.e. seeing 8.4 here and 8.5 in publicly 
available documentation and "correcting" it.

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


[clang] [clang-tools-extra] [libcxx] Reland "[clang] Enable sized deallocation by default in C++14 onwards" (PR #90373)

2024-05-22 Thread Vitaly Buka via cfe-commits

vitalybuka wrote:

This one is broken https://lab.llvm.org/buildbot/#/builders/168/builds/20461

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


[clang] [Clang] Implement resolution for CWG1835 (PR #92957)

2024-05-22 Thread Krystian Stasiowski via cfe-commits


@@ -55,15 +55,21 @@ namespace PR11856 {
 
   template T *end(T*);
 
-  class X { };
+  struct X { };
+  struct Y {
+int end;
+  };
   template 
   void Foo2() {
 T it1;
-if (it1->end < it1->end) {
-}
+if (it1->end < it1->end) { }
 
 X *x;
-if (x->end < 7) {  // expected-error{{no member named 'end' in 
'PR11856::X'}}
-}
+if (x->end < 7) { } // expected-error{{expected '>'}}
+// expected-note@-1{{to match this '<'}}
+// expected-error@-2{{expected unqualified-id}}

sdkrystian wrote:

This actually is expected -- see the final note in the comments of the PR. 
Since we didn't find anything via qualified lookup, we "lock into" the 
nested-name-specifier interpretation (because it would otherwise be an invalid 
class member access since such a member doesn't exist). So, we do unqualified 
lookup, find the template, and try parse `<` as a template argument list. 

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


[clang-tools-extra] [clang-tidy][NFCI] Simplify bugprone-sizeof-expression (PR #93024)

2024-05-22 Thread Donát Nagy via cfe-commits

https://github.com/NagyDonat created 
https://github.com/llvm/llvm-project/pull/93024

This commit eliminates a redundant matcher subexpression from the 
implementation of the "sizeof-pointer-to-aggregate" part of the clang-tidy 
check `bugprone-sizeof-expression`.

I'm fairly certain that anything that was previously matched by the deleted 
matcher `StructAddrOfExpr` is also covered by the more general 
`PointerToStructExpr` (which remains in the same `anyOf`).

This commit is made to "prepare the ground" for a followup change that would 
merge the functionality of the Clang Static Analyzer checker 
`alpha.core.SizeofPtr` into this clang-tidy check.

From b7fb1707601c73bd53b6ac810cd39a94f5b3cd53 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Don=C3=A1t=20Nagy?= 
Date: Wed, 22 May 2024 13:45:13 +0200
Subject: [PATCH] [clang-tidy][NFCI] Simplify bugprone-sizeof-expression

This commit eliminates a redundant matcher subexpression from the
implementation of the "sizeof-pointer-to-aggregate" part of the
clang-tidy check `bugprone-sizeof-expression`.

I'm fairly certain that anything that was previously matched by the
deleted matcher `StructAddrOfExpr` is also covered by the more general
`PointerToStructExpr` (which remains in the same `anyOf`).

This commit is made to "prepare the ground" for a followup change that
would merge the functionality of the Clang Static Analyzer checker
`alpha.core.SizeofPtr` into this clang-tidy check.
---
 .../clang-tidy/bugprone/SizeofExpressionCheck.cpp| 9 +++--
 1 file changed, 3 insertions(+), 6 deletions(-)

diff --git a/clang-tools-extra/clang-tidy/bugprone/SizeofExpressionCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/SizeofExpressionCheck.cpp
index a1cffbc666199..f119711638111 100644
--- a/clang-tools-extra/clang-tidy/bugprone/SizeofExpressionCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/SizeofExpressionCheck.cpp
@@ -147,9 +147,6 @@ void SizeofExpressionCheck::registerMatchers(MatchFinder 
*Finder) {
 const auto PointerToArrayExpr = ignoringParenImpCasts(
 hasType(hasCanonicalType(pointerType(pointee(arrayType());
 
-const auto StructAddrOfExpr = unaryOperator(
-hasOperatorName("&"), hasUnaryOperand(ignoringParenImpCasts(
-  hasType(hasCanonicalType(recordType());
 const auto PointerToStructType =
 hasUnqualifiedDesugaredType(pointerType(pointee(recordType(;
 const auto PointerToStructExpr = ignoringParenImpCasts(expr(
@@ -171,9 +168,9 @@ void SizeofExpressionCheck::registerMatchers(MatchFinder 
*Finder) {
has(ArrayOfPointersExpr,
  sizeOfExpr(has(ArrayOfSamePointersZeroSubscriptExpr)));
 
-Finder->addMatcher(expr(anyOf(sizeOfExpr(has(ignoringParenImpCasts(anyOf(
-  ArrayCastExpr, PointerToArrayExpr,
-  StructAddrOfExpr, 
PointerToStructExpr,
+Finder->addMatcher(expr(anyOf(sizeOfExpr(has(ignoringParenImpCasts(
+  anyOf(ArrayCastExpr, PointerToArrayExpr,
+PointerToStructExpr,
   sizeOfExpr(has(PointerToStructType))),
 unless(ArrayLengthExprDenom))
.bind("sizeof-pointer-to-aggregate"),

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


[clang-tools-extra] [clang-tidy][NFCI] Simplify bugprone-sizeof-expression (PR #93024)

2024-05-22 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-clang-tidy

@llvm/pr-subscribers-clang-tools-extra

Author: Donát Nagy (NagyDonat)


Changes

This commit eliminates a redundant matcher subexpression from the 
implementation of the "sizeof-pointer-to-aggregate" part of the clang-tidy 
check `bugprone-sizeof-expression`.

I'm fairly certain that anything that was previously matched by the deleted 
matcher `StructAddrOfExpr` is also covered by the more general 
`PointerToStructExpr` (which remains in the same `anyOf`).

This commit is made to "prepare the ground" for a followup change that would 
merge the functionality of the Clang Static Analyzer checker 
`alpha.core.SizeofPtr` into this clang-tidy check.

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


1 Files Affected:

- (modified) clang-tools-extra/clang-tidy/bugprone/SizeofExpressionCheck.cpp 
(+3-6) 


``diff
diff --git a/clang-tools-extra/clang-tidy/bugprone/SizeofExpressionCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/SizeofExpressionCheck.cpp
index a1cffbc666199..f119711638111 100644
--- a/clang-tools-extra/clang-tidy/bugprone/SizeofExpressionCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/SizeofExpressionCheck.cpp
@@ -147,9 +147,6 @@ void SizeofExpressionCheck::registerMatchers(MatchFinder 
*Finder) {
 const auto PointerToArrayExpr = ignoringParenImpCasts(
 hasType(hasCanonicalType(pointerType(pointee(arrayType());
 
-const auto StructAddrOfExpr = unaryOperator(
-hasOperatorName("&"), hasUnaryOperand(ignoringParenImpCasts(
-  hasType(hasCanonicalType(recordType());
 const auto PointerToStructType =
 hasUnqualifiedDesugaredType(pointerType(pointee(recordType(;
 const auto PointerToStructExpr = ignoringParenImpCasts(expr(
@@ -171,9 +168,9 @@ void SizeofExpressionCheck::registerMatchers(MatchFinder 
*Finder) {
has(ArrayOfPointersExpr,
  sizeOfExpr(has(ArrayOfSamePointersZeroSubscriptExpr)));
 
-Finder->addMatcher(expr(anyOf(sizeOfExpr(has(ignoringParenImpCasts(anyOf(
-  ArrayCastExpr, PointerToArrayExpr,
-  StructAddrOfExpr, 
PointerToStructExpr,
+Finder->addMatcher(expr(anyOf(sizeOfExpr(has(ignoringParenImpCasts(
+  anyOf(ArrayCastExpr, PointerToArrayExpr,
+PointerToStructExpr,
   sizeOfExpr(has(PointerToStructType))),
 unless(ArrayLengthExprDenom))
.bind("sizeof-pointer-to-aggregate"),

``




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


[clang] [openmp] [Clang][OpenMP] Fix tile/unroll on iterator- and foreach-loops. (PR #91459)

2024-05-22 Thread Michael Kruse via cfe-commits

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


[clang] [openmp] [Clang][OpenMP] Fix tile/unroll on iterator- and foreach-loops. (PR #91459)

2024-05-22 Thread Michael Kruse via cfe-commits

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


[clang] [clang] Catch missing format attributes (PR #70024)

2024-05-22 Thread Budimir Aranđelović via cfe-commits

https://github.com/budimirarandjelovicsyrmia updated 
https://github.com/llvm/llvm-project/pull/70024

From 0fc447dabd674597bbff456f638ee52a49ef5b0c Mon Sep 17 00:00:00 2001
From: budimirarandjelovicsyrmia 
Date: Fri, 5 Apr 2024 15:20:37 +0200
Subject: [PATCH] [clang] Catch missing format attributes

---
 clang/docs/ReleaseNotes.rst   |   3 +
 clang/include/clang/Basic/DiagnosticGroups.td |   1 -
 .../clang/Basic/DiagnosticSemaKinds.td|   3 +
 clang/include/clang/Sema/Sema.h   |   4 +
 clang/lib/Sema/SemaChecking.cpp   |   4 +-
 clang/lib/Sema/SemaDeclAttr.cpp   | 120 ++-
 clang/test/Sema/attr-format-missing.c | 277 
 clang/test/Sema/attr-format-missing.cpp   | 303 ++
 8 files changed, 710 insertions(+), 5 deletions(-)
 create mode 100644 clang/test/Sema/attr-format-missing.c
 create mode 100644 clang/test/Sema/attr-format-missing.cpp

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 5a123b0b86dda..b6851374fdccc 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -501,6 +501,9 @@ Improvements to Clang's diagnostics
 - Clang emits a ``-Wparentheses`` warning for expressions with consecutive 
comparisons like ``x < y < z``.
   Fixes #GH20456.
 
+- Clang now diagnoses missing format attributes for non-template functions and
+  class/struct/union members. Fixes #GH70024
+
 Improvements to Clang's time-trace
 --
 
diff --git a/clang/include/clang/Basic/DiagnosticGroups.td 
b/clang/include/clang/Basic/DiagnosticGroups.td
index 4cb4f3d999f7a..1bd826eb715f9 100644
--- a/clang/include/clang/Basic/DiagnosticGroups.td
+++ b/clang/include/clang/Basic/DiagnosticGroups.td
@@ -507,7 +507,6 @@ def MainReturnType : DiagGroup<"main-return-type">;
 def MaxUnsignedZero : DiagGroup<"max-unsigned-zero">;
 def MissingBraces : DiagGroup<"missing-braces">;
 def MissingDeclarations: DiagGroup<"missing-declarations">;
-def : DiagGroup<"missing-format-attribute">;
 def : DiagGroup<"missing-include-dirs">;
 def MissingNoreturn : DiagGroup<"missing-noreturn">;
 def MultiChar : DiagGroup<"multichar">;
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index e3b4186f1b06f..493791854a856 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -1010,6 +1010,9 @@ def err_opencl_invalid_param : Error<
 def err_opencl_invalid_return : Error<
   "declaring function return value of type %0 is not allowed %select{; did you 
forget * ?|}1">;
 def warn_enum_value_overflow : Warning<"overflow in enumeration value">;
+def warn_missing_format_attribute : Warning<
+  "diagnostic behavior may be improved by adding the %0 format attribute to 
the declaration of %1">,
+  InGroup>, DefaultIgnore;
 def warn_pragma_options_align_reset_failed : Warning<
   "#pragma options align=reset failed: %0">,
   InGroup;
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 6c89d275215de..f149419ac6a66 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -3688,6 +3688,10 @@ class Sema final : public SemaBase {
   bool DiagnoseSwiftName(Decl *D, StringRef Name, SourceLocation Loc,
  const ParsedAttr &AL, bool IsAsync);
 
+  void DiagnoseMissingFormatAttributes(const FunctionDecl *FDecl,
+   ArrayRef Args,
+   SourceLocation Loc);
+
   UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
   StringRef UuidAsWritten, MSGuidDecl *GuidDecl);
 
diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index f2dc8e9dd0050..0277375a7600a 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -8088,8 +8088,10 @@ void Sema::checkCall(NamedDecl *FDecl, const 
FunctionProtoType *Proto,
 }
   }
 
-  if (FD)
+  if (FD) {
 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
+DiagnoseMissingFormatAttributes(FD, Args, Range.getBegin());
+  }
 }
 
 void Sema::CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc) {
diff --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp
index ca5938083917f..24bb69d66c162 100644
--- a/clang/lib/Sema/SemaDeclAttr.cpp
+++ b/clang/lib/Sema/SemaDeclAttr.cpp
@@ -166,6 +166,13 @@ static bool isInstanceMethod(const Decl *D) {
   return false;
 }
 
+static bool checkIfMethodHasImplicitObjectParameter(const Decl *D) {
+  if (const auto *MethodDecl = dyn_cast(D))
+return MethodDecl->isInstance() &&
+   !MethodDecl->hasCXXExplicitFunctionObjectParameter();
+  return false;
+}
+
 static inline bool isNSStringType(QualType T, ASTContext &Ctx,
   bool AllowNSAttributedString = false) {
   const auto *PT = T->getAs()

[clang] [openmp] [Clang][OpenMP] Fix tile/unroll on iterator- and foreach-loops. (PR #91459)

2024-05-22 Thread Michael Kruse via cfe-commits

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


[clang] [openmp] [Clang][OpenMP] Fix tile/unroll on iterator- and foreach-loops. (PR #91459)

2024-05-22 Thread Michael Kruse via cfe-commits

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


[clang] [llvm] [openmp] [Clang][OpenMP] Add reverse directive (PR #92916)

2024-05-22 Thread Michael Kruse via cfe-commits

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


[clang-tools-extra] [clang-tidy][NFCI] Simplify bugprone-sizeof-expression (PR #93024)

2024-05-22 Thread Donát Nagy via cfe-commits

https://github.com/NagyDonat updated 
https://github.com/llvm/llvm-project/pull/93024

From b7fb1707601c73bd53b6ac810cd39a94f5b3cd53 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Don=C3=A1t=20Nagy?= 
Date: Wed, 22 May 2024 13:45:13 +0200
Subject: [PATCH 1/3] [clang-tidy][NFCI] Simplify bugprone-sizeof-expression

This commit eliminates a redundant matcher subexpression from the
implementation of the "sizeof-pointer-to-aggregate" part of the
clang-tidy check `bugprone-sizeof-expression`.

I'm fairly certain that anything that was previously matched by the
deleted matcher `StructAddrOfExpr` is also covered by the more general
`PointerToStructExpr` (which remains in the same `anyOf`).

This commit is made to "prepare the ground" for a followup change that
would merge the functionality of the Clang Static Analyzer checker
`alpha.core.SizeofPtr` into this clang-tidy check.
---
 .../clang-tidy/bugprone/SizeofExpressionCheck.cpp| 9 +++--
 1 file changed, 3 insertions(+), 6 deletions(-)

diff --git a/clang-tools-extra/clang-tidy/bugprone/SizeofExpressionCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/SizeofExpressionCheck.cpp
index a1cffbc666199..f119711638111 100644
--- a/clang-tools-extra/clang-tidy/bugprone/SizeofExpressionCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/SizeofExpressionCheck.cpp
@@ -147,9 +147,6 @@ void SizeofExpressionCheck::registerMatchers(MatchFinder 
*Finder) {
 const auto PointerToArrayExpr = ignoringParenImpCasts(
 hasType(hasCanonicalType(pointerType(pointee(arrayType());
 
-const auto StructAddrOfExpr = unaryOperator(
-hasOperatorName("&"), hasUnaryOperand(ignoringParenImpCasts(
-  hasType(hasCanonicalType(recordType());
 const auto PointerToStructType =
 hasUnqualifiedDesugaredType(pointerType(pointee(recordType(;
 const auto PointerToStructExpr = ignoringParenImpCasts(expr(
@@ -171,9 +168,9 @@ void SizeofExpressionCheck::registerMatchers(MatchFinder 
*Finder) {
has(ArrayOfPointersExpr,
  sizeOfExpr(has(ArrayOfSamePointersZeroSubscriptExpr)));
 
-Finder->addMatcher(expr(anyOf(sizeOfExpr(has(ignoringParenImpCasts(anyOf(
-  ArrayCastExpr, PointerToArrayExpr,
-  StructAddrOfExpr, 
PointerToStructExpr,
+Finder->addMatcher(expr(anyOf(sizeOfExpr(has(ignoringParenImpCasts(
+  anyOf(ArrayCastExpr, PointerToArrayExpr,
+PointerToStructExpr,
   sizeOfExpr(has(PointerToStructType))),
 unless(ArrayLengthExprDenom))
.bind("sizeof-pointer-to-aggregate"),

From 89552a0539b587e9fcbc431db0d9ad6511f36050 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Don=C3=A1t=20Nagy?= 
Date: Wed, 22 May 2024 14:10:31 +0200
Subject: [PATCH 2/3] Simplify some matcher expressions

Eliminate a few redundant `ignoreParenImpCasts` calls and simplify the
final matcher expression.
---
 .../bugprone/SizeofExpressionCheck.cpp| 23 ++-
 1 file changed, 12 insertions(+), 11 deletions(-)

diff --git a/clang-tools-extra/clang-tidy/bugprone/SizeofExpressionCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/SizeofExpressionCheck.cpp
index f119711638111..913be196a29b5 100644
--- a/clang-tools-extra/clang-tidy/bugprone/SizeofExpressionCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/SizeofExpressionCheck.cpp
@@ -144,13 +144,13 @@ void SizeofExpressionCheck::registerMatchers(MatchFinder 
*Finder) {
 unaryOperator(hasUnaryOperand(ArrayExpr), 
unless(hasOperatorName("*"))),
 binaryOperator(hasEitherOperand(ArrayExpr)),
 castExpr(hasSourceExpression(ArrayExpr;
-const auto PointerToArrayExpr = ignoringParenImpCasts(
-hasType(hasCanonicalType(pointerType(pointee(arrayType());
+const auto PointerToArrayExpr =
+hasType(hasCanonicalType(pointerType(pointee(arrayType();
 
 const auto PointerToStructType =
 hasUnqualifiedDesugaredType(pointerType(pointee(recordType(;
-const auto PointerToStructExpr = ignoringParenImpCasts(expr(
-hasType(hasCanonicalType(PointerToStructType)), 
unless(cxxThisExpr(;
+const auto PointerToStructExpr = expr(
+hasType(hasCanonicalType(PointerToStructType)), unless(cxxThisExpr()));
 
 const auto ArrayOfPointersExpr = ignoringParenImpCasts(
 hasType(hasCanonicalType(arrayType(hasElementType(pointerType()))
@@ -168,13 +168,14 @@ void SizeofExpressionCheck::registerMatchers(MatchFinder 
*Finder) {
has(ArrayOfPointersExpr,
  sizeOfExpr(has(ArrayOfSamePointersZeroSubscriptExpr)));
 
-Finder->addMatcher(expr(anyOf(sizeOfExpr(has(ignoringParenImpCasts(
-  anyOf(ArrayCastExpr, 

[clang-tools-extra] [clangd] Support go-to-definition on type hints. The core part (PR #86629)

2024-05-22 Thread Younan Zhang via cfe-commits

zyn0217 wrote:

@HighCommander4 No problem, I'm always delighted to receive responses! However 
it might take me some time to pick up my thoughts, as the patch has been a 
while. Anyway, I will try to revive this patch in the next few days and let's 
see if we can make it into clangd 19.

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


[clang] [llvm] wip: Move instrumentation passes (PR #92171)

2024-05-22 Thread Egor Pasko via cfe-commits


@@ -0,0 +1,31 @@
+; RUN: opt -passes="default" -S < %s | FileCheck %s
+; RUN: opt -passes="thinlto-pre-link" -S < %s | FileCheck %s
+; RUN: opt -passes="thinlto-pre-link,thinlto" -S < %s | FileCheck %s
+
+target triple = "x86_64-unknown-linux"
+
+define void @leaf_function() #0 {

pasko wrote:

Done.

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


[clang-tools-extra] [clang-tidy][NFCI] Simplify bugprone-sizeof-expression (PR #93024)

2024-05-22 Thread Piotr Zegar via cfe-commits
=?utf-8?q?Don=C3=A1t?= Nagy ,
=?utf-8?q?Don=C3=A1t?= Nagy 
Message-ID:
In-Reply-To: 


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

LGTM (if tests pass)

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


[clang-tools-extra] 5272768 - [clang-tidy][NFCI] Simplify bugprone-sizeof-expression (#93024)

2024-05-22 Thread via cfe-commits

Author: Donát Nagy
Date: 2024-05-22T15:04:22+02:00
New Revision: 527276832f7e8f109dbab8eb3b01631f68cfe50e

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

LOG: [clang-tidy][NFCI] Simplify bugprone-sizeof-expression (#93024)

This commit eliminates a redundant matcher subexpression from the
implementation of the "sizeof-pointer-to-aggregate" part of the
clang-tidy check `bugprone-sizeof-expression`.

I'm fairly certain that anything that was previously matched by the
deleted matcher `StructAddrOfExpr` is also covered by the more general
`PointerToStructExpr` (which remains in the same `anyOf`).

This commit is made to "prepare the ground" for a followup change that
would merge the functionality of the Clang Static Analyzer checker
`alpha.core.SizeofPtr` into this clang-tidy check.

Added: 


Modified: 
clang-tools-extra/clang-tidy/bugprone/SizeofExpressionCheck.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/bugprone/SizeofExpressionCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/SizeofExpressionCheck.cpp
index a1cffbc666199..5e64d23874ec1 100644
--- a/clang-tools-extra/clang-tidy/bugprone/SizeofExpressionCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/SizeofExpressionCheck.cpp
@@ -144,16 +144,13 @@ void SizeofExpressionCheck::registerMatchers(MatchFinder 
*Finder) {
 unaryOperator(hasUnaryOperand(ArrayExpr), 
unless(hasOperatorName("*"))),
 binaryOperator(hasEitherOperand(ArrayExpr)),
 castExpr(hasSourceExpression(ArrayExpr;
-const auto PointerToArrayExpr = ignoringParenImpCasts(
-hasType(hasCanonicalType(pointerType(pointee(arrayType());
+const auto PointerToArrayExpr =
+hasType(hasCanonicalType(pointerType(pointee(arrayType();
 
-const auto StructAddrOfExpr = unaryOperator(
-hasOperatorName("&"), hasUnaryOperand(ignoringParenImpCasts(
-  hasType(hasCanonicalType(recordType());
 const auto PointerToStructType =
 hasUnqualifiedDesugaredType(pointerType(pointee(recordType(;
-const auto PointerToStructExpr = ignoringParenImpCasts(expr(
-hasType(hasCanonicalType(PointerToStructType)), 
unless(cxxThisExpr(;
+const auto PointerToStructExpr = expr(
+hasType(hasCanonicalType(PointerToStructType)), unless(cxxThisExpr()));
 
 const auto ArrayOfPointersExpr = ignoringParenImpCasts(
 hasType(hasCanonicalType(arrayType(hasElementType(pointerType()))
@@ -166,18 +163,19 @@ void SizeofExpressionCheck::registerMatchers(MatchFinder 
*Finder) {
 ignoringParenImpCasts(arraySubscriptExpr(
 hasBase(ArrayOfSamePointersExpr), hasIndex(ZeroLiteral)));
 const auto ArrayLengthExprDenom =
-expr(hasParent(expr(ignoringParenImpCasts(binaryOperator(
- hasOperatorName("/"), hasLHS(ignoringParenImpCasts(sizeOfExpr(
-   has(ArrayOfPointersExpr,
+expr(hasParent(binaryOperator(hasOperatorName("/"),
+  hasLHS(ignoringParenImpCasts(sizeOfExpr(
+  has(ArrayOfPointersExpr)),
  sizeOfExpr(has(ArrayOfSamePointersZeroSubscriptExpr)));
 
-Finder->addMatcher(expr(anyOf(sizeOfExpr(has(ignoringParenImpCasts(anyOf(
-  ArrayCastExpr, PointerToArrayExpr,
-  StructAddrOfExpr, 
PointerToStructExpr,
-  sizeOfExpr(has(PointerToStructType))),
-unless(ArrayLengthExprDenom))
-   .bind("sizeof-pointer-to-aggregate"),
-   this);
+Finder->addMatcher(
+expr(sizeOfExpr(anyOf(
+ has(ignoringParenImpCasts(anyOf(
+ ArrayCastExpr, PointerToArrayExpr, PointerToStructExpr))),
+ has(PointerToStructType))),
+ unless(ArrayLengthExprDenom))
+.bind("sizeof-pointer-to-aggregate"),
+this);
   }
 
   // Detect expression like: sizeof(expr) <= k for a suspicious constant 'k'.



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


[clang-tools-extra] [clang-tidy][NFCI] Simplify bugprone-sizeof-expression (PR #93024)

2024-05-22 Thread Donát Nagy via cfe-commits

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


[clang] [clang][Driver] Fix enabling strict alising by default when the environment is MSVC (PR #91689)

2024-05-22 Thread via cfe-commits

zmodem wrote:

This seems right to me. I think adding a small release note under "Windows 
Support" would be good.

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


[clang] e3bd627 - [clang][Interp][NFC] Retrieve active union field in Pointer::toRValue()

2024-05-22 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2024-05-22T15:31:44+02:00
New Revision: e3bd627f53b6c7e1c16368803c3f119910cc5c84

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

LOG: [clang][Interp][NFC] Retrieve active union field in Pointer::toRValue()

Added: 


Modified: 
clang/lib/AST/Interp/Pointer.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/Pointer.cpp 
b/clang/lib/AST/Interp/Pointer.cpp
index e45c291668caf..252f7ea46086f 100644
--- a/clang/lib/AST/Interp/Pointer.cpp
+++ b/clang/lib/AST/Interp/Pointer.cpp
@@ -351,6 +351,7 @@ std::optional Pointer::toRValue(const Context 
&Ctx) const {
 } else {
   Ok &= Composite(FieldTy, FP, Value);
 }
+ActiveField = FP.getFieldDesc()->asFieldDecl();
 break;
   }
 }



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


[clang] [llvm] [IR] Add getelementptr nusw and nuw flags (PR #90824)

2024-05-22 Thread Nikita Popov via cfe-commits

nikic wrote:

There's already another approval from @aeubanks, so I plan to merge this next 
Monday if there's no more feedback.

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


[clang] [Coverage][Expansion] handle nested macros in scratch space (PR #89869)

2024-05-22 Thread Wentao Zhang via cfe-commits

https://github.com/whentojump updated 
https://github.com/llvm/llvm-project/pull/89869

>From 968ef430dd09ee4545323426d0c5b550c6a0f690 Mon Sep 17 00:00:00 2001
From: NAKAMURA Takumi 
Date: Fri, 19 Apr 2024 15:16:05 +0900
Subject: [PATCH 1/8] [MC/DC][Coverage] Workaround for `##` conditions

A synthesized identifier with `##` is emitted to ``.
`llvm-cov` cannot handle ` since it doesn't have actual files.

As a workaround, peel `` to the actual definition if the 
definition is present.

This affects predefined built-in macros, like __LINE__.

Fixes #87000
---
 clang/lib/CodeGen/CoverageMappingGen.cpp  | 12 +-
 clang/test/CoverageMapping/builtinmacro.c |  2 +-
 clang/test/CoverageMapping/macros.c   |  8 ++--
 .../test/CoverageMapping/mcdc-scratch-space.c | 39 +++
 4 files changed, 56 insertions(+), 5 deletions(-)
 create mode 100644 clang/test/CoverageMapping/mcdc-scratch-space.c

diff --git a/clang/lib/CodeGen/CoverageMappingGen.cpp 
b/clang/lib/CodeGen/CoverageMappingGen.cpp
index 733686d4946b3..f92706f579a7b 100644
--- a/clang/lib/CodeGen/CoverageMappingGen.cpp
+++ b/clang/lib/CodeGen/CoverageMappingGen.cpp
@@ -339,8 +339,18 @@ class CoverageMappingBuilder {
 
 llvm::SmallSet Visited;
 SmallVector, 8> FileLocs;
-for (const auto &Region : SourceRegions) {
+for (auto &Region : SourceRegions) {
   SourceLocation Loc = Region.getBeginLoc();
+
+  // Replace Region with its definition if it is in .
+  while (Loc.isMacroID() &&
+ SM.isWrittenInScratchSpace(SM.getSpellingLoc(Loc))) {
+auto ExpansionRange = SM.getImmediateExpansionRange(Loc);
+Loc = ExpansionRange.getBegin();
+Region.setStartLoc(Loc);
+Region.setEndLoc(ExpansionRange.getEnd());
+  }
+
   FileID File = SM.getFileID(Loc);
   if (!Visited.insert(File).second)
 continue;
diff --git a/clang/test/CoverageMapping/builtinmacro.c 
b/clang/test/CoverageMapping/builtinmacro.c
index abcdc191523a5..5d5a176aa7d87 100644
--- a/clang/test/CoverageMapping/builtinmacro.c
+++ b/clang/test/CoverageMapping/builtinmacro.c
@@ -4,7 +4,7 @@
 
 // CHECK: filename
 const char *filename (const char *name) { // CHECK-NEXT: File 0, [[@LINE]]:41 
-> [[@LINE+3]]:2 = #0
-  static const char this_file[] = __FILE__;
+  static const char this_file[] = __FILE__; // CHECK-NEXT: File 0, 
[[@LINE]]:35 -> [[@LINE]]:35 = #0
   return this_file;
 }
 
diff --git a/clang/test/CoverageMapping/macros.c 
b/clang/test/CoverageMapping/macros.c
index 6bd3be434139a..fcf21170ef135 100644
--- a/clang/test/CoverageMapping/macros.c
+++ b/clang/test/CoverageMapping/macros.c
@@ -80,12 +80,14 @@ void func7(void) { // CHECK-NEXT: File 0, [[@LINE]]:18 -> 
[[@LINE+6]]:2 = #0
   int kk,ll;   // CHECK-NEXT: File 0, [[@LINE+1]]:7 -> [[@LINE+1]]:8 = #0
   if (k)   // CHECK-NEXT: Branch,File 0, [[@LINE]]:7 -> [[@LINE]]:8 = 
#1
 m(k);  // CHECK-NEXT: Gap,File 0, [[@LINE-1]]:9 -> [[@LINE]]:5 = #1
-  else // CHECK-NEXT: Expansion,File 0, [[@LINE-1]]:5 -> 
[[@LINE-1]]:6 = #0
+  else // CHECK-NEXT: Expansion,File 0, [[@LINE-1]]:5 -> 
[[@LINE-1]]:6 = #1
 l = m(l);  // CHECK-NEXT: Gap,File 0, [[@LINE-2]]:7 -> [[@LINE]]:5 = 
(#0 - #1)
 }  // CHECK-NEXT: File 0, [[@LINE-1]]:5 -> [[@LINE-1]]:10 = 
(#0 - #1)
// CHECK-NEXT: Expansion,File 0, [[@LINE-2]]:9 -> 
[[@LINE-2]]:10 = (#0 - #1)
-   // CHECK-NEXT: File 1, [[@LINE-9]]:14 -> [[@LINE-9]]:18 = #0
-   // CHECK-NEXT: File 2, [[@LINE-10]]:14 -> [[@LINE-10]]:15 = 
(#0 - #1)
+   // CHECK-NEXT: File 1, [[@LINE-9]]:14 -> [[@LINE-9]]:17 = #1
+   // CHECK-NEXT: File 1, [[@LINE-10]]:14 -> [[@LINE-10]]:18 = 
#0
+   // CHECK-NEXT: File 2, [[@LINE-11]]:14 -> [[@LINE-11]]:17 = 
(#0 - #1)
+   // CHECK-NEXT: File 2, [[@LINE-12]]:14 -> [[@LINE-12]]:15 = 
(#0 - #1)
 
 int main(int argc, const char *argv[]) {
   func();
diff --git a/clang/test/CoverageMapping/mcdc-scratch-space.c 
b/clang/test/CoverageMapping/mcdc-scratch-space.c
new file mode 100644
index 0..1b8735cd27445
--- /dev/null
+++ b/clang/test/CoverageMapping/mcdc-scratch-space.c
@@ -0,0 +1,39 @@
+// RUN: %clang_cc1 -triple %itanium_abi_triple -std=c99 -fcoverage-mcdc 
-fprofile-instrument=clang -fcoverage-mapping -dump-coverage-mapping 
-emit-llvm-only %s | FileCheck %s
+
+// CHECK: builtin_macro0:
+int builtin_macro0(int a) {
+  // CHECK: Decision,File 0, [[@LINE+1]]:11 -> [[@LINE+2]]:15 = M:0, C:2
+  return (__LINE__ // CHECK: Branch,File 0, [[@LINE]]:11 -> [[@LINE]]:11 = 0, 
0 [1,2,0]
+  && a); //   CHECK: Branch,File 0, [[@LINE]]:14 -> [[@LINE]]:15 = #2, 
(#1 - #2) [2,0,0]
+}
+
+// CHECK: builtin_macro1:
+int builtin_macro1(int a) {
+  // CHECK: Decision,File 0, [[@LINE+1]]:11 -> [[@LINE+2]]:22 = M:0, C:2
+  return (a // CHECK: Branch,File 0, [[@LINE]]:11 -> [[@LINE]]:12 = (#0 - #1), 
#1 [1,0,2]

[clang] [Clang][AArch64] Use __clang_arm_builtin_alias for overloaded svreinterpret's (PR #92427)

2024-05-22 Thread Paul Walker via cfe-commits

https://github.com/paulwalker-arm approved this pull request.


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


[clang] [Coverage][Expansion] handle nested macros in scratch space (PR #89869)

2024-05-22 Thread Wentao Zhang via cfe-commits

whentojump wrote:

Sorry for getting back this late.

I reverted the latest commit (using `SourceRange`) and addressed the earlier 
comment about updating region sloc only when they are changed.

And yes if you have better ideas about `getNonScratchExpansion` implementation 
you can please post a new PR.

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


[clang] [SystemZ][z/OS] Implement z/OS XPLINK ABI (PR #91384)

2024-05-22 Thread Fanbo Meng via cfe-commits

https://github.com/fanbo-meng updated 
https://github.com/llvm/llvm-project/pull/91384

>From 6428b9603044031aa5c58b2d75a0e9310bc3af6a Mon Sep 17 00:00:00 2001
From: Fanbo Meng 
Date: Tue, 7 May 2024 13:36:38 -0400
Subject: [PATCH 1/7] [SystemZ][z/OS] Implement z/OS XPLINK ABI

The XPLINK calling convention is specified in the Language
Environment Vendor Interface, chapter 22,
(https://www.ibm.com/support/knowledgecenter/SSLTBW_2.4.0/com.ibm.zos.v2r4.cee/cee.htm)
and in Redbook XPLink: OS/390 Extra Performance Linkage
(http://www.redbooks.ibm.com/abstracts/sg245991.html?Open)
---
 clang/lib/CodeGen/CodeGenModule.cpp   |   2 +
 clang/lib/CodeGen/TargetInfo.h|   4 +
 clang/lib/CodeGen/Targets/SystemZ.cpp | 393 ++
 clang/test/CodeGen/zos-abi.c  | 162 +++
 4 files changed, 561 insertions(+)
 create mode 100644 clang/test/CodeGen/zos-abi.c

diff --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index 489c08a4d4819..c7305dede7123 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -242,6 +242,8 @@ createTargetCodeGenInfo(CodeGenModule &CGM) {
   case llvm::Triple::systemz: {
 bool SoftFloat = CodeGenOpts.FloatABI == "soft";
 bool HasVector = !SoftFloat && Target.getABI() == "vector";
+if (Triple.getOS() == llvm::Triple::ZOS)
+  return createSystemZ_ZOS_TargetCodeGenInfo(CGM, HasVector, SoftFloat);
 return createSystemZTargetCodeGenInfo(CGM, HasVector, SoftFloat);
   }
 
diff --git a/clang/lib/CodeGen/TargetInfo.h b/clang/lib/CodeGen/TargetInfo.h
index f242d9e36ed40..e15f9bdf39356 100644
--- a/clang/lib/CodeGen/TargetInfo.h
+++ b/clang/lib/CodeGen/TargetInfo.h
@@ -527,6 +527,10 @@ std::unique_ptr
 createSystemZTargetCodeGenInfo(CodeGenModule &CGM, bool HasVector,
bool SoftFloatABI);
 
+std::unique_ptr
+createSystemZ_ZOS_TargetCodeGenInfo(CodeGenModule &CGM, bool HasVector,
+bool SoftFloatABI);
+
 std::unique_ptr
 createTCETargetCodeGenInfo(CodeGenModule &CGM);
 
diff --git a/clang/lib/CodeGen/Targets/SystemZ.cpp 
b/clang/lib/CodeGen/Targets/SystemZ.cpp
index deaafc85a3157..d420286c71c16 100644
--- a/clang/lib/CodeGen/Targets/SystemZ.cpp
+++ b/clang/lib/CodeGen/Targets/SystemZ.cpp
@@ -10,6 +10,7 @@
 #include "TargetInfo.h"
 #include "clang/Basic/Builtins.h"
 #include "llvm/IR/IntrinsicsS390.h"
+#include 
 
 using namespace clang;
 using namespace clang::CodeGen;
@@ -529,9 +530,401 @@ bool SystemZTargetCodeGenInfo::isVectorTypeBased(const 
Type *Ty,
   return false;
 }
 
+//===--===//
+// z/OS XPLINK ABI Implementation
+//===--===//
+
+namespace {
+
+class ZOSXPLinkABIInfo : public ABIInfo {
+  const unsigned GPRBits = 64;
+  bool HasVector;
+
+public:
+  ZOSXPLinkABIInfo(CodeGenTypes &CGT, bool HV) : ABIInfo(CGT), HasVector(HV) {}
+
+  bool isPromotableIntegerType(QualType Ty) const;
+  bool isCompoundType(QualType Ty) const;
+  bool isVectorArgumentType(QualType Ty) const;
+  bool isFPArgumentType(QualType Ty) const;
+  QualType getSingleElementType(QualType Ty) const;
+  unsigned getMaxAlignFromTypeDefs(QualType Ty) const;
+  std::optional getFPTypeOfComplexLikeType(QualType Ty) const;
+
+  ABIArgInfo classifyReturnType(QualType RetTy,
+unsigned functionCallConv) const;
+  ABIArgInfo classifyArgumentType(QualType ArgTy, bool IsNamedArg,
+  unsigned functionCallConv) const;
+
+  void computeInfo(CGFunctionInfo &FI) const override {
+if (!getCXXABI().classifyReturnType(FI))
+  FI.getReturnInfo() =
+  classifyReturnType(FI.getReturnType(), FI.getCallingConvention());
+
+unsigned NumRequiredArgs = FI.getNumRequiredArgs();
+unsigned ArgNo = 0;
+
+for (auto &I : FI.arguments()) {
+  bool IsNamedArg = ArgNo < NumRequiredArgs;
+  I.info =
+  classifyArgumentType(I.type, IsNamedArg, FI.getCallingConvention());
+  ++ArgNo;
+}
+  }
+
+  Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
+QualType Ty) const override;
+};
+
+class ZOSXPLinkTargetCodeGenInfo : public TargetCodeGenInfo {
+public:
+  ZOSXPLinkTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector)
+  : TargetCodeGenInfo(std::make_unique(CGT, HasVector)) {
+SwiftInfo =
+std::make_unique(CGT, /*SwiftErrorInRegister=*/false);
+  }
+};
+
+} // namespace
+
+// Return true if the ABI requires Ty to be passed sign- or zero-
+// extended to 64 bits.
+bool ZOSXPLinkABIInfo::isPromotableIntegerType(QualType Ty) const {
+  // Treat an enum type as its underlying type.
+  if (const EnumType *EnumTy = Ty->getAs())
+Ty = EnumTy->getDecl()->getIntegerType();
+
+  // Promotable integer types are required to be promoted by the ABI.
+  if (getContext().isPromotableIntegerType(Ty

[clang] [Coverage][Expansion] handle nested macros in scratch space (PR #89869)

2024-05-22 Thread Wentao Zhang via cfe-commits


@@ -517,7 +552,7 @@ class CoverageMappingBuilder {
 SourceRegionFilter Filter;
 for (const auto &FM : FileIDMapping) {
   SourceLocation ExpandedLoc = FM.second.second;
-  SourceLocation ParentLoc = getIncludeOrExpansionLoc(ExpandedLoc);
+  SourceLocation ParentLoc = getIncludeOrExpansionLoc(ExpandedLoc, false);

whentojump wrote:

Hi, in the initial version we were actually using a separate function (but with 
some duplicate code). See this commit 
https://github.com/llvm/llvm-project/pull/89869/commits/145c807a177db8e649f7f3343d640a000e65cebb

Do you suggest that way is better?

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


[clang] [clang] Catch missing format attributes (PR #70024)

2024-05-22 Thread Budimir Aranđelović via cfe-commits

https://github.com/budimirarandjelovicsyrmia updated 
https://github.com/llvm/llvm-project/pull/70024

From 44e3593c8409a49d878d6a0b2eb97732c01cd7b3 Mon Sep 17 00:00:00 2001
From: budimirarandjelovicsyrmia 
Date: Fri, 5 Apr 2024 15:20:37 +0200
Subject: [PATCH] [clang] Catch missing format attributes

---
 clang/docs/ReleaseNotes.rst   |   3 +
 clang/include/clang/Basic/DiagnosticGroups.td |   1 -
 .../clang/Basic/DiagnosticSemaKinds.td|   3 +
 clang/include/clang/Sema/Sema.h   |   4 +
 clang/lib/Sema/SemaChecking.cpp   |   4 +-
 clang/lib/Sema/SemaDeclAttr.cpp   | 121 ++-
 clang/test/Sema/attr-format-missing.c | 277 
 clang/test/Sema/attr-format-missing.cpp   | 303 ++
 8 files changed, 711 insertions(+), 5 deletions(-)
 create mode 100644 clang/test/Sema/attr-format-missing.c
 create mode 100644 clang/test/Sema/attr-format-missing.cpp

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 5a123b0b86dda..b6851374fdccc 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -501,6 +501,9 @@ Improvements to Clang's diagnostics
 - Clang emits a ``-Wparentheses`` warning for expressions with consecutive 
comparisons like ``x < y < z``.
   Fixes #GH20456.
 
+- Clang now diagnoses missing format attributes for non-template functions and
+  class/struct/union members. Fixes #GH70024
+
 Improvements to Clang's time-trace
 --
 
diff --git a/clang/include/clang/Basic/DiagnosticGroups.td 
b/clang/include/clang/Basic/DiagnosticGroups.td
index 4cb4f3d999f7a..1bd826eb715f9 100644
--- a/clang/include/clang/Basic/DiagnosticGroups.td
+++ b/clang/include/clang/Basic/DiagnosticGroups.td
@@ -507,7 +507,6 @@ def MainReturnType : DiagGroup<"main-return-type">;
 def MaxUnsignedZero : DiagGroup<"max-unsigned-zero">;
 def MissingBraces : DiagGroup<"missing-braces">;
 def MissingDeclarations: DiagGroup<"missing-declarations">;
-def : DiagGroup<"missing-format-attribute">;
 def : DiagGroup<"missing-include-dirs">;
 def MissingNoreturn : DiagGroup<"missing-noreturn">;
 def MultiChar : DiagGroup<"multichar">;
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index e3b4186f1b06f..493791854a856 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -1010,6 +1010,9 @@ def err_opencl_invalid_param : Error<
 def err_opencl_invalid_return : Error<
   "declaring function return value of type %0 is not allowed %select{; did you 
forget * ?|}1">;
 def warn_enum_value_overflow : Warning<"overflow in enumeration value">;
+def warn_missing_format_attribute : Warning<
+  "diagnostic behavior may be improved by adding the %0 format attribute to 
the declaration of %1">,
+  InGroup>, DefaultIgnore;
 def warn_pragma_options_align_reset_failed : Warning<
   "#pragma options align=reset failed: %0">,
   InGroup;
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 6c89d275215de..f149419ac6a66 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -3688,6 +3688,10 @@ class Sema final : public SemaBase {
   bool DiagnoseSwiftName(Decl *D, StringRef Name, SourceLocation Loc,
  const ParsedAttr &AL, bool IsAsync);
 
+  void DiagnoseMissingFormatAttributes(const FunctionDecl *FDecl,
+   ArrayRef Args,
+   SourceLocation Loc);
+
   UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
   StringRef UuidAsWritten, MSGuidDecl *GuidDecl);
 
diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index f2dc8e9dd0050..0277375a7600a 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -8088,8 +8088,10 @@ void Sema::checkCall(NamedDecl *FDecl, const 
FunctionProtoType *Proto,
 }
   }
 
-  if (FD)
+  if (FD) {
 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
+DiagnoseMissingFormatAttributes(FD, Args, Range.getBegin());
+  }
 }
 
 void Sema::CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc) {
diff --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp
index ca5938083917f..57c301a7e0eef 100644
--- a/clang/lib/Sema/SemaDeclAttr.cpp
+++ b/clang/lib/Sema/SemaDeclAttr.cpp
@@ -166,6 +166,13 @@ static bool isInstanceMethod(const Decl *D) {
   return false;
 }
 
+static bool checkIfMethodHasImplicitObjectParameter(const Decl *D) {
+  if (const auto *MethodDecl = dyn_cast(D))
+return MethodDecl->isInstance() &&
+   !MethodDecl->hasCXXExplicitFunctionObjectParameter();
+  return false;
+}
+
 static inline bool isNSStringType(QualType T, ASTContext &Ctx,
   bool AllowNSAttributedString = false) {
   const auto *PT = T->getAs()

[clang] [SystemZ][z/OS] Implement z/OS XPLINK ABI (PR #91384)

2024-05-22 Thread Fanbo Meng via cfe-commits

https://github.com/fanbo-meng updated 
https://github.com/llvm/llvm-project/pull/91384

>From 6428b9603044031aa5c58b2d75a0e9310bc3af6a Mon Sep 17 00:00:00 2001
From: Fanbo Meng 
Date: Tue, 7 May 2024 13:36:38 -0400
Subject: [PATCH 1/7] [SystemZ][z/OS] Implement z/OS XPLINK ABI

The XPLINK calling convention is specified in the Language
Environment Vendor Interface, chapter 22,
(https://www.ibm.com/support/knowledgecenter/SSLTBW_2.4.0/com.ibm.zos.v2r4.cee/cee.htm)
and in Redbook XPLink: OS/390 Extra Performance Linkage
(http://www.redbooks.ibm.com/abstracts/sg245991.html?Open)
---
 clang/lib/CodeGen/CodeGenModule.cpp   |   2 +
 clang/lib/CodeGen/TargetInfo.h|   4 +
 clang/lib/CodeGen/Targets/SystemZ.cpp | 393 ++
 clang/test/CodeGen/zos-abi.c  | 162 +++
 4 files changed, 561 insertions(+)
 create mode 100644 clang/test/CodeGen/zos-abi.c

diff --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index 489c08a4d4819..c7305dede7123 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -242,6 +242,8 @@ createTargetCodeGenInfo(CodeGenModule &CGM) {
   case llvm::Triple::systemz: {
 bool SoftFloat = CodeGenOpts.FloatABI == "soft";
 bool HasVector = !SoftFloat && Target.getABI() == "vector";
+if (Triple.getOS() == llvm::Triple::ZOS)
+  return createSystemZ_ZOS_TargetCodeGenInfo(CGM, HasVector, SoftFloat);
 return createSystemZTargetCodeGenInfo(CGM, HasVector, SoftFloat);
   }
 
diff --git a/clang/lib/CodeGen/TargetInfo.h b/clang/lib/CodeGen/TargetInfo.h
index f242d9e36ed40..e15f9bdf39356 100644
--- a/clang/lib/CodeGen/TargetInfo.h
+++ b/clang/lib/CodeGen/TargetInfo.h
@@ -527,6 +527,10 @@ std::unique_ptr
 createSystemZTargetCodeGenInfo(CodeGenModule &CGM, bool HasVector,
bool SoftFloatABI);
 
+std::unique_ptr
+createSystemZ_ZOS_TargetCodeGenInfo(CodeGenModule &CGM, bool HasVector,
+bool SoftFloatABI);
+
 std::unique_ptr
 createTCETargetCodeGenInfo(CodeGenModule &CGM);
 
diff --git a/clang/lib/CodeGen/Targets/SystemZ.cpp 
b/clang/lib/CodeGen/Targets/SystemZ.cpp
index deaafc85a3157..d420286c71c16 100644
--- a/clang/lib/CodeGen/Targets/SystemZ.cpp
+++ b/clang/lib/CodeGen/Targets/SystemZ.cpp
@@ -10,6 +10,7 @@
 #include "TargetInfo.h"
 #include "clang/Basic/Builtins.h"
 #include "llvm/IR/IntrinsicsS390.h"
+#include 
 
 using namespace clang;
 using namespace clang::CodeGen;
@@ -529,9 +530,401 @@ bool SystemZTargetCodeGenInfo::isVectorTypeBased(const 
Type *Ty,
   return false;
 }
 
+//===--===//
+// z/OS XPLINK ABI Implementation
+//===--===//
+
+namespace {
+
+class ZOSXPLinkABIInfo : public ABIInfo {
+  const unsigned GPRBits = 64;
+  bool HasVector;
+
+public:
+  ZOSXPLinkABIInfo(CodeGenTypes &CGT, bool HV) : ABIInfo(CGT), HasVector(HV) {}
+
+  bool isPromotableIntegerType(QualType Ty) const;
+  bool isCompoundType(QualType Ty) const;
+  bool isVectorArgumentType(QualType Ty) const;
+  bool isFPArgumentType(QualType Ty) const;
+  QualType getSingleElementType(QualType Ty) const;
+  unsigned getMaxAlignFromTypeDefs(QualType Ty) const;
+  std::optional getFPTypeOfComplexLikeType(QualType Ty) const;
+
+  ABIArgInfo classifyReturnType(QualType RetTy,
+unsigned functionCallConv) const;
+  ABIArgInfo classifyArgumentType(QualType ArgTy, bool IsNamedArg,
+  unsigned functionCallConv) const;
+
+  void computeInfo(CGFunctionInfo &FI) const override {
+if (!getCXXABI().classifyReturnType(FI))
+  FI.getReturnInfo() =
+  classifyReturnType(FI.getReturnType(), FI.getCallingConvention());
+
+unsigned NumRequiredArgs = FI.getNumRequiredArgs();
+unsigned ArgNo = 0;
+
+for (auto &I : FI.arguments()) {
+  bool IsNamedArg = ArgNo < NumRequiredArgs;
+  I.info =
+  classifyArgumentType(I.type, IsNamedArg, FI.getCallingConvention());
+  ++ArgNo;
+}
+  }
+
+  Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
+QualType Ty) const override;
+};
+
+class ZOSXPLinkTargetCodeGenInfo : public TargetCodeGenInfo {
+public:
+  ZOSXPLinkTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector)
+  : TargetCodeGenInfo(std::make_unique(CGT, HasVector)) {
+SwiftInfo =
+std::make_unique(CGT, /*SwiftErrorInRegister=*/false);
+  }
+};
+
+} // namespace
+
+// Return true if the ABI requires Ty to be passed sign- or zero-
+// extended to 64 bits.
+bool ZOSXPLinkABIInfo::isPromotableIntegerType(QualType Ty) const {
+  // Treat an enum type as its underlying type.
+  if (const EnumType *EnumTy = Ty->getAs())
+Ty = EnumTy->getDecl()->getIntegerType();
+
+  // Promotable integer types are required to be promoted by the ABI.
+  if (getContext().isPromotableIntegerType(Ty

[clang] [clang] Fix PS "selective" DLL import/export of vtable & typeinfo (PR #92579)

2024-05-22 Thread Andrew Ng via cfe-commits


@@ -1793,6 +1793,37 @@ void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction 
&CGF,
 ThisTy, VTT, VTTTy, nullptr);
 }
 
+// Check if any non-inline method has the specified attribute.
+template 
+static bool CXXRecordNonInlineHasAttr(const CXXRecordDecl *RD) {
+  for (const auto *D : RD->noload_decls()) {
+if (const auto *FD = dyn_cast(D)) {
+  if (FD->isInlineSpecified() || FD->doesThisDeclarationHaveABody() ||

nga888 wrote:

@wjristow, I believe that you wrote the original code. Do you remember why 
`isInlineSpecified()` was used rather than `isInlined()`?

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


[clang] 7d9634e - [clang][Interp][NFC] Propagate IsActive state in unions properly

2024-05-22 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2024-05-22T15:31:44+02:00
New Revision: 7d9634e527fe52bf20a9036be6e5771f8fc4de17

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

LOG: [clang][Interp][NFC] Propagate IsActive state in unions properly

This resolves an older FIXME comment.

Added: 


Modified: 
clang/lib/AST/Interp/Descriptor.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/Descriptor.cpp 
b/clang/lib/AST/Interp/Descriptor.cpp
index d0466902247b4..746b765ca4216 100644
--- a/clang/lib/AST/Interp/Descriptor.cpp
+++ b/clang/lib/AST/Interp/Descriptor.cpp
@@ -137,9 +137,8 @@ static void moveArrayDesc(Block *B, const std::byte *Src, 
std::byte *Dst,
 }
 
 static void initField(Block *B, std::byte *Ptr, bool IsConst, bool IsMutable,
-  bool IsActive, const Descriptor *D,
+  bool IsActive, bool IsUnion, const Descriptor *D,
   unsigned FieldOffset) {
-  bool IsUnion = false; // FIXME
   auto *Desc = reinterpret_cast(Ptr + FieldOffset) - 1;
   Desc->Offset = FieldOffset;
   Desc->Desc = D;
@@ -174,7 +173,7 @@ static void initBase(Block *B, std::byte *Ptr, bool 
IsConst, bool IsMutable,
 initBase(B, Ptr + FieldOffset, IsConst, IsMutable, IsActive, V.Desc,
  V.Offset, false);
   for (const auto &F : D->ElemRecord->fields())
-initField(B, Ptr + FieldOffset, IsConst, IsMutable, IsActive, F.Desc,
+initField(B, Ptr + FieldOffset, IsConst, IsMutable, IsActive, IsUnion, 
F.Desc,
   F.Offset);
 
   // If this is initializing a virtual base, we do NOT want to consider its
@@ -193,7 +192,7 @@ static void ctorRecord(Block *B, std::byte *Ptr, bool 
IsConst, bool IsMutable,
   for (const auto &V : D->ElemRecord->bases())
 initBase(B, Ptr, IsConst, IsMutable, IsActive, V.Desc, V.Offset, false);
   for (const auto &F : D->ElemRecord->fields())
-initField(B, Ptr, IsConst, IsMutable, IsActive, F.Desc, F.Offset);
+initField(B, Ptr, IsConst, IsMutable, IsActive, D->ElemRecord->isUnion(), 
F.Desc, F.Offset);
   for (const auto &V : D->ElemRecord->virtual_bases())
 initBase(B, Ptr, IsConst, IsMutable, IsActive, V.Desc, V.Offset, true);
 }



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


[clang] [clang][ASTImporter] Fix possible crash "given incorrect InsertPos for specialization". (PR #89887)

2024-05-22 Thread Balázs Kéri via cfe-commits

balazske wrote:

I could reproduce this assertion (with CTU analysis on project "contour"):
```
clang-19: llvm-project/clang/lib/AST/DeclTemplate.cpp:370: void 
clang::RedeclarableTemplateDecl::addSpecializationImpl(llvm::FoldingSetVector&,
 EntryType*, void*) [with Derived = clang::VarTemplateDecl; EntryType = 
clang::VarTemplateSpeciali
zationDecl]: Assertion `!findSpecializationImpl(Specializations, 
CorrectInsertPos, SETraits::getTemplateArgs(Entry)) && InsertPos == 
CorrectInsertPos && "given incorrect InsertPos for specialization"' failed.
```
With the latest clang (debug or release) the assertion does not show up any 
more (when the same test is run). Still I think that this change is an 
improvement in the code and could be merged, even if no test can be found that 
triggers the assertion.

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


[clang-tools-extra] [include-cleaner] don't consider the associated header unused (PR #67228)

2024-05-22 Thread Mike Weller via cfe-commits

MikeWeller wrote:

Is it @sam-mccall who needs to address remaining comments? Or how can we move 
this along? I'd also be keen on getting this change merged.

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


[clang] [clang-tools-extra] [clang] NFCI: use TemplateArgumentLoc for NTTP DefaultArgument (PR #92852)

2024-05-22 Thread Erich Keane via cfe-commits

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


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


[clang] [clang][driver] Support `-x` for all languages in CL mode (PR #89772)

2024-05-22 Thread via cfe-commits

huangqinjin wrote:

CI still fails. No idea how to proceed.

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


[clang] [clang][ASTImporter] Fix possible crash "given incorrect InsertPos for specialization". (PR #89887)

2024-05-22 Thread Balázs Kéri via cfe-commits

balazske wrote:

The problem is that there is a distance between getting the "InsertPos" and the 
insetion into the list. Between getting the `InsertPos` 
(`VarTemplate->findSpecialization`) and the insertion further AST import 
statements can occur and probably it can cause the list of specializations to 
change. I have a test that can cause the same situation (change of list before 
the insertion) but still the assertion did not show up.

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


[clang] [llvm] wip: Move instrumentation passes (PR #92171)

2024-05-22 Thread Egor Pasko via cfe-commits


@@ -0,0 +1,31 @@
+; RUN: opt -passes="default" -S < %s | FileCheck %s
+; RUN: opt -passes="thinlto-pre-link" -S < %s | FileCheck %s
+; RUN: opt -passes="thinlto-pre-link,thinlto" -S < %s | FileCheck %s

pasko wrote:

Ah, good idea! I still went with O2 for lto/thinlto because even at O1 it does 
not inline the alwaysinline leaf, oops.

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


[clang] nonblocking/nonallocating attributes (was: nolock/noalloc) (PR #84983)

2024-05-22 Thread Doug Wyatt via cfe-commits


@@ -4912,3 +4922,279 @@ void AutoType::Profile(llvm::FoldingSetNodeID &ID, 
const ASTContext &Context) {
   Profile(ID, Context, getDeducedType(), getKeyword(), isDependentType(),
   getTypeConstraintConcept(), getTypeConstraintArguments());
 }
+
+FunctionEffect::~FunctionEffect() = default;
+
+bool FunctionEffect::diagnoseConversion(bool Adding, QualType OldType,
+FunctionEffectSet OldFX,
+QualType NewType,
+FunctionEffectSet NewFX) const {
+  return false;
+}
+
+bool FunctionEffect::diagnoseRedeclaration(bool Adding,
+   const FunctionDecl &OldFunction,
+   FunctionEffectSet OldFX,
+   const FunctionDecl &NewFunction,
+   FunctionEffectSet NewFX) const {
+  return false;
+}
+
+bool FunctionEffect::diagnoseMethodOverride(bool Adding,
+const CXXMethodDecl &OldMethod,
+FunctionEffectSet OldFX,
+const CXXMethodDecl &NewMethod,
+FunctionEffectSet NewFX) const {
+  return false;
+}
+
+bool FunctionEffect::canInferOnDecl(const Decl *Caller,
+FunctionEffectSet CallerFX) const {
+  return false;
+}
+
+bool FunctionEffect::diagnoseFunctionCall(bool Direct, const Decl *Caller,
+  FunctionEffectSet CallerFX,
+  CalleeDeclOrType Callee,
+  FunctionEffectSet CalleeFX) const {
+  return false;
+}
+
+const NoLockNoAllocEffect &NoLockNoAllocEffect::nolock_instance() {
+  static NoLockNoAllocEffect global(kNoLockTrue, "nolock");
+  return global;
+}
+
+const NoLockNoAllocEffect &NoLockNoAllocEffect::noalloc_instance() {
+  static NoLockNoAllocEffect global(kNoAllocTrue, "noalloc");
+  return global;
+}
+
+// TODO: Separate flags for noalloc
+NoLockNoAllocEffect::NoLockNoAllocEffect(EffectType Ty, const char *Name)
+: FunctionEffect(Ty,
+ kRequiresVerification | kVerifyCalls |
+ kInferrableOnCallees | kExcludeThrow | kExcludeCatch |
+ kExcludeObjCMessageSend | kExcludeStaticLocalVars |
+ kExcludeThreadLocalVars,
+ Name) {}
+
+NoLockNoAllocEffect::~NoLockNoAllocEffect() = default;
+
+std::string NoLockNoAllocEffect::attribute() const {
+  return std::string{"__attribute__((clang_"} + name().str() + "))";
+}
+
+bool NoLockNoAllocEffect::diagnoseConversion(bool Adding, QualType OldType,
+ FunctionEffectSet OldFX,
+ QualType NewType,
+ FunctionEffectSet NewFX) const {
+  // noalloc can't be added (spoofed) during a conversion, unless we have 
nolock
+  if (Adding) {
+if (!isNoLock()) {
+  for (const auto *Effect : OldFX) {
+if (Effect->type() == kNoLockTrue)
+  return false;
+  }
+}
+// nolock can't be added (spoofed) during a conversion.
+return true;
+  }
+  return false;
+}
+
+bool NoLockNoAllocEffect::diagnoseRedeclaration(bool Adding,
+const FunctionDecl 
&OldFunction,
+FunctionEffectSet OldFX,
+const FunctionDecl 
&NewFunction,
+FunctionEffectSet NewFX) const 
{
+  // nolock/noalloc can't be removed in a redeclaration
+  // adding -> false, removing -> true (diagnose)
+  return !Adding;
+}
+
+bool NoLockNoAllocEffect::diagnoseMethodOverride(
+bool Adding, const CXXMethodDecl &OldMethod, FunctionEffectSet OldFX,
+const CXXMethodDecl &NewMethod, FunctionEffectSet NewFX) const {
+  // nolock/noalloc can't be removed from an override
+  return !Adding;
+}
+
+bool NoLockNoAllocEffect::canInferOnDecl(const Decl *Caller,
+ FunctionEffectSet CallerFX) const {
+  // Does the Decl have nolock(false) / noalloc(false) ?
+  QualType QT;
+  if (isa(Caller)) {
+const auto *TSI = cast(Caller)->getSignatureAsWritten();
+QT = TSI->getType();
+  } else if (isa(Caller)) {
+QT = cast(Caller)->getType();
+  } else {
+return false;
+  }
+  if (QT->hasAttr(isNoLock() ? attr::Kind::NoLock : attr::Kind::NoAlloc)) {
+return false;
+  }
+
+  return true;
+}
+
+// TODO: Notice that we don't care about some of the parameters. Is the
+// interface overly general?
+bool NoLockNoAllocEffect::diagnoseFunctionCall(
+bool Direct, const Decl *Caller, FunctionEffectSet CallerFX,
+CalleeD

[clang] nonblocking/nonallocating attributes (was: nolock/noalloc) (PR #84983)

2024-05-22 Thread Doug Wyatt via cfe-commits


@@ -464,6 +466,16 @@ class ASTContext : public RefCountedBase {
   /// This is the top-level (C++20) Named module we are building.
   Module *CurrentCXXNamedModule = nullptr;
 
+  class FunctionEffectSetUniquing {
+llvm::DenseSet> Set;
+
+  public:
+FunctionEffectSet getUniqued(llvm::ArrayRef FX);
+
+~FunctionEffectSetUniquing();
+  };
+  FunctionEffectSetUniquing UniquedFunctionEffectSet;
+

dougsonos wrote:

The uniquing went away

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


[clang] 9276a03 - MIPS/Clang: Add more false option pairs into validateTarget (#91968)

2024-05-22 Thread via cfe-commits

Author: YunQiang Su
Date: 2024-05-22T22:54:45+08:00
New Revision: 9276a03b5492d0ac62c48c4313139dbf32d7b9e1

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

LOG: MIPS/Clang: Add more false option pairs into validateTarget (#91968)

The option pairs include:
-mfpxx -mips1
-msoft-float -mmsa
-mmsa -mabi=32 with 32bit pre-R2 CPUs
-mfpxx -mmsa
-mfp32 -mmsa

Added: 


Modified: 
clang/lib/Basic/Targets/Mips.cpp

Removed: 




diff  --git a/clang/lib/Basic/Targets/Mips.cpp 
b/clang/lib/Basic/Targets/Mips.cpp
index 3a65f53c52485..174bc9d2ab996 100644
--- a/clang/lib/Basic/Targets/Mips.cpp
+++ b/clang/lib/Basic/Targets/Mips.cpp
@@ -273,6 +273,34 @@ bool MipsTargetInfo::validateTarget(DiagnosticsEngine 
&Diags) const {
 Diags.Report(diag::err_mips_fp64_req) << "-mfp64";
 return false;
   }
+  // FPXX requires mips2+
+  if (FPMode == FPXX && CPU == "mips1") {
+Diags.Report(diag::err_opt_not_valid_with_opt) << "-mfpxx" << CPU;
+return false;
+  }
+  // -mmsa with -msoft-float makes nonsense
+  if (FloatABI == SoftFloat && HasMSA) {
+Diags.Report(diag::err_opt_not_valid_with_opt) << "-msoft-float"
+   << "-mmsa";
+return false;
+  }
+  // Option -mmsa permitted on Mips32 iff revision 2 or higher is present
+  if (HasMSA && (CPU == "mips1" || CPU == "mips2" || getISARev() < 2) &&
+  ABI == "o32") {
+Diags.Report(diag::err_mips_fp64_req) << "-mmsa";
+return false;
+  }
+  // MSA requires FP64
+  if (FPMode == FPXX && HasMSA) {
+Diags.Report(diag::err_opt_not_valid_with_opt) << "-mfpxx"
+   << "-mmsa";
+return false;
+  }
+  if (FPMode == FP32 && HasMSA) {
+Diags.Report(diag::err_opt_not_valid_with_opt) << "-mfp32"
+   << "-mmsa";
+return false;
+  }
 
   return true;
 }



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


  1   2   3   4   >