[PATCH] D137205: [clang-tidy] Add performance-unnecessary-copy-on-last-use check

2022-11-28 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added a comment.

In D137205#3951230 , @Febbe wrote:

> In D137205#3950722 , @kadircet 
> wrote:
>
>> another thing that i noticed is usage of east consts in the implementation 
>> files. no one seem to have brought it up so far (at least none that i can 
>> see).
>> in theory there are no explicit guidelines about it in LLVM coding style, 
>> but rest of the codebase uses west const convention. so i am not sure if 
>> straying away from it here will make much sense.
>
> I think this should be regulated / enforced via clang-format if it is 
> relevant at all to somebody.

surely, it would be nice to have a clang-tidy check or something (by design 
clang-format only performs white-space changes).

> In terms of consistency, the east-const I use is more consistent. Not to the 
> previous written code, but to the language.

not sure what you mean by it's consistent "to the language", but right now even 
in your header files you have both east and west consts. probably to keep 
public interfaces consistent across the codebase, as you've noticed.
another consequence of this is anyone modifying this code later on, will need 
to make a choice between sticking to the code inside this file vs code inside 
the rest of the codebase, which will create more discussions with every patch 
making people lose time and moreover bring the file into an inconsistent state, 
as some of those discussions will insert west consts.

> It is also completely irrelevant, because a new programmer will not 
> understand that `const T const *` is actually `T const*` and not `T const * 
> const`. An experienced programmer can understand it well either way.

not sure I follow the argument here, but surely I also agree that `east const`s 
are more readable and fool-proof. it's unfortunate that most of the C++ world 
is stuck with the `west const`s.

> In my eyes it should therefore always be east-const and also be taught in 
> such a way, since such irritations do not arise thereby at all.
>
> When it is ok for you to keep the east-const I would like to leave it as is, 
> because it is on top a lot of work to manually search and replace those 
> occurrences.

As mentioned above, I understand your opinion here and deep down wish that was 
the state. But as I explained before, in a code base where thousands of 
developers are contributing, I don't think we can afford everyone introducing 
code with their own opinions. Despite not explicitly having a style guide on 
east vs west consts, it's clear from the rest of the codebase that one should 
adhere to west consts.
So I'd be glad if you could take your time to replace east consts to west.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D137205/new/

https://reviews.llvm.org/D137205

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


[PATCH] D138678: [include-cleaner] Capture private headers in PragmaIncludes.

2022-11-28 Thread Haojian Wu via Phabricator via cfe-commits
hokein accepted this revision.
hokein added a comment.
This revision is now accepted and ready to land.

Thanks, looks good from my side, a few nits on the test.




Comment at: clang-tools-extra/include-cleaner/unittests/RecordTest.cpp:364
+
   EXPECT_EQ(PI.getPublic(PrivateFE.get()), "\"public2.h\"");
   auto PublicFE = Processed.fileManager().getFile("public.h");

nit: IIUC, we're using a blank line to separate the tests per FileEntry,  this 
`EXPECT_EQ` statement should belong to the above group (which is `PrivateFE`), 
right?



Comment at: clang-tools-extra/include-cleaner/unittests/RecordTest.cpp:367
   assert(PublicFE);
   EXPECT_EQ(PI.getPublic(PublicFE.get()), ""); // no mapping.
+

nit: add `EXPECT_FALSE(PI.isPrivate(PublicFE.get()));`


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D138678/new/

https://reviews.llvm.org/D138678

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


[PATCH] D138678: [include-cleaner] Capture private headers in PragmaIncludes.

2022-11-28 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo updated this revision to Diff 478145.
VitaNuo marked an inline comment as done.
VitaNuo added a comment.

Address the remaining comments.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D138678/new/

https://reviews.llvm.org/D138678

Files:
  clang-tools-extra/include-cleaner/include/clang-include-cleaner/Record.h
  clang-tools-extra/include-cleaner/lib/Record.cpp
  clang-tools-extra/include-cleaner/unittests/RecordTest.cpp

Index: clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
===
--- clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
+++ clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
@@ -8,7 +8,6 @@
 
 #include "clang-include-cleaner/Record.h"
 #include "clang/Basic/SourceLocation.h"
-#include "clang/Basic/SourceLocation.h"
 #include "clang/Frontend/FrontendAction.h"
 #include "clang/Frontend/FrontendActions.h"
 #include "clang/Testing/TestAST.h"
@@ -257,27 +256,6 @@
   EXPECT_THAT(RefOffsets, ElementsAreArray(MainFile.points()));
 }
 
-TEST_F(RecordPPTest, CapturesIfDefMacroRefs) {
-  llvm::Annotations MainFile(R"cpp(
-#define X 1
-#ifdef $def^X
- #define Y 2
-#endif
-  )cpp");
-
-  Inputs.Code = MainFile.code();
-  auto AST = build();
-  ASSERT_THAT(Recorded.MacroReferences, Not(IsEmpty()));
-
-  SourceManager &SM = AST.sourceManager();
-  SourceLocation Def = SM.getComposedLoc(SM.getMainFileID(), MainFile.point("def"));
-
-  SymbolReference XRef = Recorded.MacroReferences.front();
-  EXPECT_EQ(XRef.RT, RefType::Ambiguous);
-  EXPECT_EQ("X", XRef.Target.macro().Name->getName());
-  EXPECT_EQ(XRef.RefLocation, Def);
-}
-
 // Matches an Include* on the specified line;
 MATCHER_P(line, N, "") { return arg->Line == (unsigned)N; }
 
@@ -368,18 +346,30 @@
   Inputs.Code = R"cpp(
 #include "public.h"
   )cpp";
-  Inputs.ExtraFiles["public.h"] = "#include \"private.h\"";
+  Inputs.ExtraFiles["public.h"] = R"cpp(
+#include "private.h"
+#include "private2.h"
+  )cpp";
   Inputs.ExtraFiles["private.h"] = R"cpp(
 // IWYU pragma: private, include "public2.h"
-class Private {};
+  )cpp";
+  Inputs.ExtraFiles["private2.h"] = R"cpp(
+// IWYU pragma: private
   )cpp";
   TestAST Processed = build();
   auto PrivateFE = Processed.fileManager().getFile("private.h");
   assert(PrivateFE);
+  EXPECT_TRUE(PI.isPrivate(PrivateFE.get()));
   EXPECT_EQ(PI.getPublic(PrivateFE.get()), "\"public2.h\"");
+
   auto PublicFE = Processed.fileManager().getFile("public.h");
   assert(PublicFE);
   EXPECT_EQ(PI.getPublic(PublicFE.get()), ""); // no mapping.
+  EXPECT_FALSE(PI.isPrivate(PublicFE.get()));
+
+  auto Private2FE = Processed.fileManager().getFile("private2.h");
+  assert(Private2FE);
+  EXPECT_TRUE(PI.isPrivate(Private2FE.get()));
 }
 
 TEST_F(PragmaIncludeTest, IWYUExport) {
Index: clang-tools-extra/include-cleaner/lib/Record.cpp
===
--- clang-tools-extra/include-cleaner/lib/Record.cpp
+++ clang-tools-extra/include-cleaner/lib/Record.cpp
@@ -53,7 +53,7 @@
 SourceRange Range, const MacroArgs *Args) override {
 if (!Active)
   return;
-recordMacroRef(MacroName, *MD.getMacroInfo(), RefType::Explicit);
+recordMacroRef(MacroName, *MD.getMacroInfo());
   }
 
   void MacroDefined(const Token &MacroName, const MacroDirective *MD) override {
@@ -71,7 +71,7 @@
   llvm::is_contained(MI->params(), II))
 continue;
   if (const MacroInfo *MI = PP.getMacroInfo(II))
-recordMacroRef(Tok, *MI, RefType::Explicit);
+recordMacroRef(Tok, *MI);
 }
   }
 
@@ -80,11 +80,11 @@
 if (!Active)
   return;
 if (const auto *MI = MD.getMacroInfo())
-  recordMacroRef(MacroName, *MI, RefType::Explicit);
+  recordMacroRef(MacroName, *MI);
   }
 
   void Ifdef(SourceLocation Loc, const Token &MacroNameTok,
- const MacroDefinition &MD) override {
+ const MacroDefinition &MD) override {
 if (!Active)
   return;
 if (const auto *MI = MD.getMacroInfo())
@@ -124,13 +124,13 @@
   }
 
 private:
-  void recordMacroRef(const Token &Tok, const MacroInfo &MI, RefType RT) {
+  void recordMacroRef(const Token &Tok, const MacroInfo &MI,
+  RefType RT = RefType::Explicit) {
 if (MI.isBuiltinMacro())
   return; // __FILE__ is not a reference.
-Recorded.MacroReferences.push_back(
-SymbolReference{Tok.getLocation(),
-Macro{Tok.getIdentifierInfo(), MI.getDefinitionLoc()},
-RT});
+Recorded.MacroReferences.push_back(SymbolReference{
+Tok.getLocation(),
+Macro{Tok.getIdentifierInfo(), MI.getDefinitionLoc()}, RT});
   }
 
   bool Active = false;
@@ -233,14 +233,18 @@
 if (!Pragma)
   return false;
 
-if (Pragma->consume_front("private, include ")) {
-  // We always insert usi

[PATCH] D136594: [clangd] Add support for semantic token type "operator"

2022-11-28 Thread Christian Kandeler via Phabricator via cfe-commits
ckandeler updated this revision to Diff 478146.
ckandeler added a comment.

Using operators on expressions with dependent types now considered "complex",


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D136594/new/

https://reviews.llvm.org/D136594

Files:
  clang-tools-extra/clangd/SemanticHighlighting.cpp
  clang-tools-extra/clangd/SemanticHighlighting.h
  clang-tools-extra/clangd/test/initialize-params.test
  clang-tools-extra/clangd/test/semantic-tokens.test
  clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp

Index: clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
===
--- clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
+++ clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
@@ -113,9 +113,9 @@
   void $Function_def[[foo]](int $Parameter_def[[A]], $Class[[AS]] $Parameter_def[[As]]) {
 $Primitive_deduced_defaultLibrary[[auto]] $LocalVariable_def[[VeryLongVariableName]] = 12312;
 $Class[[AS]] $LocalVariable_def[[AA]];
-$Primitive_deduced_defaultLibrary[[auto]] $LocalVariable_def[[L]] = $LocalVariable[[AA]].$Field[[SomeMember]] + $Parameter[[A]];
+$Primitive_deduced_defaultLibrary[[auto]] $LocalVariable_def[[L]] = $LocalVariable[[AA]].$Field[[SomeMember]] $Operator[[+]] $Parameter[[A]];
 auto $LocalVariable_def[[FN]] = [ $LocalVariable[[AA]]](int $Parameter_def[[A]]) -> void {};
-$LocalVariable[[FN]](12312);
+$LocalVariable[[FN]]$Operator_userProvided[[(]]12312$Operator_userProvided[[)]];
   }
 )cpp",
   R"cpp(
@@ -144,7 +144,7 @@
   struct $Class_def[[B]] {
 $Class_decl_constrDestr[[B]]();
 ~$Class_decl_constrDestr[[B]]();
-void operator<<($Class[[B]]);
+void operator$Operator_decl[[<<]]($Class[[B]]);
 $Class[[AAA]] $Field_decl[[AA]];
   };
   $Class[[B]]::$Class_def_constrDestr[[B]]() {}
@@ -203,20 +203,20 @@
 static double $StaticField_decl_static[[S]];
 static void $StaticMethod_def_static[[bar]]() {}
 void $Method_def[[foo]]() {
-  $Field[[B]] = 123;
-  this->$Field[[B]] = 156;
+  $Field[[B]] $Operator[[=]] 123;
+  this->$Field[[B]] $Operator[[=]] 156;
   this->$Method[[foo]]();
   $Method[[foo]]();
   $StaticMethod_static[[bar]]();
-  $StaticField_static[[S]] = 90.1;
+  $StaticField_static[[S]] $Operator[[=]] 90.1;
 }
   };
   void $Function_def[[foo]]() {
 $Class[[A]] $LocalVariable_def[[AA]];
-$LocalVariable[[AA]].$Field[[B]] += 2;
+$LocalVariable[[AA]].$Field[[B]] $Operator[[+=]] 2;
 $LocalVariable[[AA]].$Method[[foo]]();
 $LocalVariable[[AA]].$Field[[E]].$Field[[C]];
-$Class[[A]]::$StaticField_static[[S]] = 90;
+$Class[[A]]::$StaticField_static[[S]] $Operator[[=]] 90;
   }
 )cpp",
   R"cpp(
@@ -295,10 +295,10 @@
   struct $Class_def[[B]] {};
   struct $Class_def[[A]] {
 $Class[[B]] $Field_decl[[BB]];
-$Class[[A]] &operator=($Class[[A]] &&$Parameter_def[[O]]);
+$Class[[A]] &operator$Operator_decl[[=]]($Class[[A]] &&$Parameter_def[[O]]);
   };
 
-  $Class[[A]] &$Class[[A]]::operator=($Class[[A]] &&$Parameter_def[[O]]) = default;
+  $Class[[A]] &$Class[[A]]::operator$Operator_def[[=]]($Class[[A]] &&$Parameter_def[[O]]) = default;
 )cpp",
   R"cpp(
   enum $Enum_decl[[En]] {
@@ -327,9 +327,9 @@
   $Enum_deduced[[auto]] $Variable_def[[AE]] = $Enum[[E]]::$EnumConstant_readonly[[E]];
   $Class_deduced[[auto]] $Variable_def[[AF]] = $Class[[Foo]]();
   $Class_deduced[[decltype]](auto) $Variable_def[[AF2]] = $Class[[Foo]]();
-  $Class_deduced[[auto]] *$Variable_def[[AFP]] = &$Variable[[AF]];
+  $Class_deduced[[auto]] *$Variable_def[[AFP]] = $Operator[[&]]$Variable[[AF]];
   $Enum_deduced[[auto]] &$Variable_def[[AER]] = $Variable[[AE]];
-  $Primitive_deduced_defaultLibrary[[auto]] $Variable_def[[Form]] = 10.2 + 2 * 4;
+  $Primitive_deduced_defaultLibrary[[auto]] $Variable_def[[Form]] = 10.2 $Operator[[+]] 2 $Operator[[*]] 4;
   $Primitive_deduced_defaultLibrary[[decltype]]($Variable[[Form]]) $Variable_def[[F]] = 10;
   auto $Variable_def[[Fun]] = []()->void{};
 )cpp",
@@ -342,21 +342,21 @@
   template
   class $Class_def[[IP]] {
 void $Method_def[[f]]() {
-  *$TemplateParameter_readonly[[U]] += 5;
+  $Operator[[*]]$TemplateParameter_readonly[[U]] $Operator[[+=]] 5;
 }
   };
   template
   class $Class_def[[Foo]] {
 void $Method_def[[f]]() {
   for(int $LocalVariable_def[[I]] = 0;
-$LocalVariable[[I]] < $TemplateParameter_readonly[[U]];) {}
+$LocalVariable[[I]] $Operator[[<]] $TemplateParameter_readonly[[U]];) {}
 }
   };
 
   $Class

[PATCH] D136594: [clangd] Add support for semantic token type "operator"

2022-11-28 Thread Christian Kandeler via Phabricator via cfe-commits
ckandeler added a comment.

Now seems to do what we want. Should I switch the modifier around?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D136594/new/

https://reviews.llvm.org/D136594

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


[PATCH] D138678: [include-cleaner] Capture private headers in PragmaIncludes.

2022-11-28 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo updated this revision to Diff 478148.
VitaNuo added a comment.

Rebase.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D138678/new/

https://reviews.llvm.org/D138678

Files:
  clang-tools-extra/include-cleaner/include/clang-include-cleaner/Record.h
  clang-tools-extra/include-cleaner/lib/Record.cpp
  clang-tools-extra/include-cleaner/unittests/RecordTest.cpp

Index: clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
===
--- clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
+++ clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
@@ -346,18 +346,30 @@
   Inputs.Code = R"cpp(
 #include "public.h"
   )cpp";
-  Inputs.ExtraFiles["public.h"] = "#include \"private.h\"";
+  Inputs.ExtraFiles["public.h"] = R"cpp(
+#include "private.h"
+#include "private2.h"
+  )cpp";
   Inputs.ExtraFiles["private.h"] = R"cpp(
 // IWYU pragma: private, include "public2.h"
-class Private {};
+  )cpp";
+  Inputs.ExtraFiles["private2.h"] = R"cpp(
+// IWYU pragma: private
   )cpp";
   TestAST Processed = build();
   auto PrivateFE = Processed.fileManager().getFile("private.h");
   assert(PrivateFE);
+  EXPECT_TRUE(PI.isPrivate(PrivateFE.get()));
   EXPECT_EQ(PI.getPublic(PrivateFE.get()), "\"public2.h\"");
+
   auto PublicFE = Processed.fileManager().getFile("public.h");
   assert(PublicFE);
   EXPECT_EQ(PI.getPublic(PublicFE.get()), ""); // no mapping.
+  EXPECT_FALSE(PI.isPrivate(PublicFE.get()));
+
+  auto Private2FE = Processed.fileManager().getFile("private2.h");
+  assert(Private2FE);
+  EXPECT_TRUE(PI.isPrivate(Private2FE.get()));
 }
 
 TEST_F(PragmaIncludeTest, IWYUExport) {
Index: clang-tools-extra/include-cleaner/lib/Record.cpp
===
--- clang-tools-extra/include-cleaner/lib/Record.cpp
+++ clang-tools-extra/include-cleaner/lib/Record.cpp
@@ -233,14 +233,18 @@
 if (!Pragma)
   return false;
 
-if (Pragma->consume_front("private, include ")) {
-  // We always insert using the spelling from the pragma.
-  if (auto *FE = SM.getFileEntryForID(SM.getFileID(Range.getBegin(
-Out->IWYUPublic.insert(
-{FE->getLastRef().getUniqueID(),
- save(Pragma->startswith("<") || Pragma->startswith("\"")
-  ? (*Pragma)
-  : ("\"" + *Pragma + "\"").str())});
+if (Pragma->consume_front("private")) {
+  auto *FE = SM.getFileEntryForID(SM.getFileID(Range.getBegin()));
+  if (!FE)
+return false;
+  StringRef PublicHeader;
+  if (Pragma->consume_front(", include ")) {
+// We always insert using the spelling from the pragma.
+PublicHeader = save(Pragma->startswith("<") || Pragma->startswith("\"")
+? (*Pragma)
+: ("\"" + *Pragma + "\"").str());
+  }
+  Out->IWYUPublic.insert({FE->getLastRef().getUniqueID(), PublicHeader});
   return false;
 }
 FileID CommentFID = SM.getFileID(Range.getBegin());
@@ -346,6 +350,10 @@
   return !NonSelfContainedFiles.contains(FE->getUniqueID());
 }
 
+bool PragmaIncludes::isPrivate(const FileEntry *FE) const {
+  return IWYUPublic.find(FE->getUniqueID()) != IWYUPublic.end();
+}
+
 std::unique_ptr RecordedAST::record() {
   class Recorder : public ASTConsumer {
 RecordedAST *Out;
Index: clang-tools-extra/include-cleaner/include/clang-include-cleaner/Record.h
===
--- clang-tools-extra/include-cleaner/include/clang-include-cleaner/Record.h
+++ clang-tools-extra/include-cleaner/include/clang-include-cleaner/Record.h
@@ -17,16 +17,15 @@
 #ifndef CLANG_INCLUDE_CLEANER_RECORD_H
 #define CLANG_INCLUDE_CLEANER_RECORD_H
 
+#include "clang-include-cleaner/Types.h"
+#include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/DenseSet.h"
 #include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Allocator.h"
 #include "llvm/Support/FileSystem/UniqueID.h"
-#include "clang-include-cleaner/Types.h"
-#include "llvm/ADT/ArrayRef.h"
-#include "llvm/ADT/DenseMap.h"
-#include "llvm/ADT/StringMap.h"
 #include 
 #include 
 
@@ -73,6 +72,9 @@
   /// Returns true if the given file is a self-contained file.
   bool isSelfContained(const FileEntry *File) const;
 
+  /// Returns true if the given file is marked with the IWYU private pragma.
+  bool isPrivate(const FileEntry *File) const;
+
 private:
   class RecordPragma;
   /// 1-based Line numbers for the #include directives of the main file that
@@ -80,7 +82,8 @@
   /// export` right after).
   llvm::DenseSet ShouldKeep;
 
-  /// The public header mapping by the IWYU private pragma.
+  /// The public header mapping by the IWYU private pragma. For private pragmas
+  //  without public mapping an empty St

[clang-tools-extra] 10d183b - [include-cleaner] Capture private headers in PragmaIncludes.

2022-11-28 Thread Haojian Wu via cfe-commits

Author: Viktoriia Bakalova
Date: 2022-11-28T10:02:02+01:00
New Revision: 10d183b889daab4512d476c1645d24d4e8946e8c

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

LOG: [include-cleaner] Capture private headers in PragmaIncludes.

Save file IDs of IWYU private headers and report them as private.

Reviewed By: hokein

Differential Revision: https://reviews.llvm.org/D138678

Added: 


Modified: 
clang-tools-extra/include-cleaner/include/clang-include-cleaner/Record.h
clang-tools-extra/include-cleaner/lib/Record.cpp
clang-tools-extra/include-cleaner/unittests/RecordTest.cpp

Removed: 




diff  --git 
a/clang-tools-extra/include-cleaner/include/clang-include-cleaner/Record.h 
b/clang-tools-extra/include-cleaner/include/clang-include-cleaner/Record.h
index a569f219939d..66fd0c7915fa 100644
--- a/clang-tools-extra/include-cleaner/include/clang-include-cleaner/Record.h
+++ b/clang-tools-extra/include-cleaner/include/clang-include-cleaner/Record.h
@@ -17,16 +17,15 @@
 #ifndef CLANG_INCLUDE_CLEANER_RECORD_H
 #define CLANG_INCLUDE_CLEANER_RECORD_H
 
+#include "clang-include-cleaner/Types.h"
+#include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/DenseSet.h"
 #include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Allocator.h"
 #include "llvm/Support/FileSystem/UniqueID.h"
-#include "clang-include-cleaner/Types.h"
-#include "llvm/ADT/ArrayRef.h"
-#include "llvm/ADT/DenseMap.h"
-#include "llvm/ADT/StringMap.h"
 #include 
 #include 
 
@@ -73,6 +72,9 @@ class PragmaIncludes {
   /// Returns true if the given file is a self-contained file.
   bool isSelfContained(const FileEntry *File) const;
 
+  /// Returns true if the given file is marked with the IWYU private pragma.
+  bool isPrivate(const FileEntry *File) const;
+
 private:
   class RecordPragma;
   /// 1-based Line numbers for the #include directives of the main file that
@@ -80,7 +82,8 @@ class PragmaIncludes {
   /// export` right after).
   llvm::DenseSet ShouldKeep;
 
-  /// The public header mapping by the IWYU private pragma.
+  /// The public header mapping by the IWYU private pragma. For private pragmas
+  //  without public mapping an empty StringRef is stored.
   //
   // !!NOTE: instead of using a FileEntry* to identify the physical file, we
   // deliberately use the UniqueID to ensure the result is stable across

diff  --git a/clang-tools-extra/include-cleaner/lib/Record.cpp 
b/clang-tools-extra/include-cleaner/lib/Record.cpp
index eb9f5c3e390b..e93bc14d4b46 100644
--- a/clang-tools-extra/include-cleaner/lib/Record.cpp
+++ b/clang-tools-extra/include-cleaner/lib/Record.cpp
@@ -233,14 +233,18 @@ class PragmaIncludes::RecordPragma : public PPCallbacks, 
public CommentHandler {
 if (!Pragma)
   return false;
 
-if (Pragma->consume_front("private, include ")) {
-  // We always insert using the spelling from the pragma.
-  if (auto *FE = SM.getFileEntryForID(SM.getFileID(Range.getBegin(
-Out->IWYUPublic.insert(
-{FE->getLastRef().getUniqueID(),
- save(Pragma->startswith("<") || Pragma->startswith("\"")
-  ? (*Pragma)
-  : ("\"" + *Pragma + "\"").str())});
+if (Pragma->consume_front("private")) {
+  auto *FE = SM.getFileEntryForID(SM.getFileID(Range.getBegin()));
+  if (!FE)
+return false;
+  StringRef PublicHeader;
+  if (Pragma->consume_front(", include ")) {
+// We always insert using the spelling from the pragma.
+PublicHeader = save(Pragma->startswith("<") || Pragma->startswith("\"")
+? (*Pragma)
+: ("\"" + *Pragma + "\"").str());
+  }
+  Out->IWYUPublic.insert({FE->getLastRef().getUniqueID(), PublicHeader});
   return false;
 }
 FileID CommentFID = SM.getFileID(Range.getBegin());
@@ -346,6 +350,10 @@ bool PragmaIncludes::isSelfContained(const FileEntry *FE) 
const {
   return !NonSelfContainedFiles.contains(FE->getUniqueID());
 }
 
+bool PragmaIncludes::isPrivate(const FileEntry *FE) const {
+  return IWYUPublic.find(FE->getUniqueID()) != IWYUPublic.end();
+}
+
 std::unique_ptr RecordedAST::record() {
   class Recorder : public ASTConsumer {
 RecordedAST *Out;

diff  --git a/clang-tools-extra/include-cleaner/unittests/RecordTest.cpp 
b/clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
index fb4e0632fd24..0cc163751fd7 100644
--- a/clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
+++ b/clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
@@ -346,18 +346,30 @@ TEST_F(PragmaIncludeTest, IWYUPrivate) {
   Inputs.Code = R"cpp(
 #include "public.h"
   )cpp";
-  Inputs.ExtraF

[PATCH] D138678: [include-cleaner] Capture private headers in PragmaIncludes.

2022-11-28 Thread Haojian Wu via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG10d183b889da: [include-cleaner] Capture private headers in 
PragmaIncludes. (authored by VitaNuo, committed by hokein).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D138678/new/

https://reviews.llvm.org/D138678

Files:
  clang-tools-extra/include-cleaner/include/clang-include-cleaner/Record.h
  clang-tools-extra/include-cleaner/lib/Record.cpp
  clang-tools-extra/include-cleaner/unittests/RecordTest.cpp

Index: clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
===
--- clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
+++ clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
@@ -346,18 +346,30 @@
   Inputs.Code = R"cpp(
 #include "public.h"
   )cpp";
-  Inputs.ExtraFiles["public.h"] = "#include \"private.h\"";
+  Inputs.ExtraFiles["public.h"] = R"cpp(
+#include "private.h"
+#include "private2.h"
+  )cpp";
   Inputs.ExtraFiles["private.h"] = R"cpp(
 // IWYU pragma: private, include "public2.h"
-class Private {};
+  )cpp";
+  Inputs.ExtraFiles["private2.h"] = R"cpp(
+// IWYU pragma: private
   )cpp";
   TestAST Processed = build();
   auto PrivateFE = Processed.fileManager().getFile("private.h");
   assert(PrivateFE);
+  EXPECT_TRUE(PI.isPrivate(PrivateFE.get()));
   EXPECT_EQ(PI.getPublic(PrivateFE.get()), "\"public2.h\"");
+
   auto PublicFE = Processed.fileManager().getFile("public.h");
   assert(PublicFE);
   EXPECT_EQ(PI.getPublic(PublicFE.get()), ""); // no mapping.
+  EXPECT_FALSE(PI.isPrivate(PublicFE.get()));
+
+  auto Private2FE = Processed.fileManager().getFile("private2.h");
+  assert(Private2FE);
+  EXPECT_TRUE(PI.isPrivate(Private2FE.get()));
 }
 
 TEST_F(PragmaIncludeTest, IWYUExport) {
Index: clang-tools-extra/include-cleaner/lib/Record.cpp
===
--- clang-tools-extra/include-cleaner/lib/Record.cpp
+++ clang-tools-extra/include-cleaner/lib/Record.cpp
@@ -233,14 +233,18 @@
 if (!Pragma)
   return false;
 
-if (Pragma->consume_front("private, include ")) {
-  // We always insert using the spelling from the pragma.
-  if (auto *FE = SM.getFileEntryForID(SM.getFileID(Range.getBegin(
-Out->IWYUPublic.insert(
-{FE->getLastRef().getUniqueID(),
- save(Pragma->startswith("<") || Pragma->startswith("\"")
-  ? (*Pragma)
-  : ("\"" + *Pragma + "\"").str())});
+if (Pragma->consume_front("private")) {
+  auto *FE = SM.getFileEntryForID(SM.getFileID(Range.getBegin()));
+  if (!FE)
+return false;
+  StringRef PublicHeader;
+  if (Pragma->consume_front(", include ")) {
+// We always insert using the spelling from the pragma.
+PublicHeader = save(Pragma->startswith("<") || Pragma->startswith("\"")
+? (*Pragma)
+: ("\"" + *Pragma + "\"").str());
+  }
+  Out->IWYUPublic.insert({FE->getLastRef().getUniqueID(), PublicHeader});
   return false;
 }
 FileID CommentFID = SM.getFileID(Range.getBegin());
@@ -346,6 +350,10 @@
   return !NonSelfContainedFiles.contains(FE->getUniqueID());
 }
 
+bool PragmaIncludes::isPrivate(const FileEntry *FE) const {
+  return IWYUPublic.find(FE->getUniqueID()) != IWYUPublic.end();
+}
+
 std::unique_ptr RecordedAST::record() {
   class Recorder : public ASTConsumer {
 RecordedAST *Out;
Index: clang-tools-extra/include-cleaner/include/clang-include-cleaner/Record.h
===
--- clang-tools-extra/include-cleaner/include/clang-include-cleaner/Record.h
+++ clang-tools-extra/include-cleaner/include/clang-include-cleaner/Record.h
@@ -17,16 +17,15 @@
 #ifndef CLANG_INCLUDE_CLEANER_RECORD_H
 #define CLANG_INCLUDE_CLEANER_RECORD_H
 
+#include "clang-include-cleaner/Types.h"
+#include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/DenseSet.h"
 #include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Allocator.h"
 #include "llvm/Support/FileSystem/UniqueID.h"
-#include "clang-include-cleaner/Types.h"
-#include "llvm/ADT/ArrayRef.h"
-#include "llvm/ADT/DenseMap.h"
-#include "llvm/ADT/StringMap.h"
 #include 
 #include 
 
@@ -73,6 +72,9 @@
   /// Returns true if the given file is a self-contained file.
   bool isSelfContained(const FileEntry *File) const;
 
+  /// Returns true if the given file is marked with the IWYU private pragma.
+  bool isPrivate(const FileEntry *File) const;
+
 private:
   class RecordPragma;
   /// 1-based Line numbers for the #include directives of the main file that
@@ -80,7 +82,8 @@
   /// export` right after).
   llvm::DenseSet ShouldKee

[PATCH] D138777: [clang-tidy] Add check bugprone-multiple-new-in-one-expression.

2022-11-28 Thread Balázs Kéri via Phabricator via cfe-commits
balazske created this revision.
Herald added subscribers: carlosgalvezp, steakhal, martong, gamesh411, 
Szelethus, dkrupp, xazax.hun.
Herald added a reviewer: njames93.
Herald added a project: All.
balazske requested review of this revision.
Herald added a project: clang-tools-extra.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D138777

Files:
  clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
  clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
  clang-tools-extra/clang-tidy/bugprone/MultipleNewInOneExpressionCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/MultipleNewInOneExpressionCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  
clang-tools-extra/docs/clang-tidy/checks/bugprone/multiple-new-in-one-expression.rst
  
clang-tools-extra/test/clang-tidy/checkers/bugprone/multiple-new-in-one-expression.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/bugprone/multiple-new-in-one-expression.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/bugprone/multiple-new-in-one-expression.cpp
@@ -0,0 +1,179 @@
+// RUN: %check_clang_tidy -std=c++11 -check-suffixes=ALL,CPP11 %s bugprone-multiple-new-in-one-expression %t
+// RUN: %check_clang_tidy -std=c++17 -check-suffixes=ALL,CPP17 %s bugprone-multiple-new-in-one-expression %t
+
+namespace std {
+typedef __typeof__(sizeof(0)) size_t;
+enum class align_val_t : std::size_t {};
+class exception {};
+class bad_alloc : public exception {};
+struct nothrow_t {};
+extern const nothrow_t nothrow;
+} // namespace std
+
+void *operator new(std::size_t, const std::nothrow_t &) noexcept;
+void *operator new(std::size_t, std::align_val_t, const std::nothrow_t &) noexcept;
+void *operator new(std::size_t, void *) noexcept;
+void *operator new(std::size_t, char);
+
+struct B;
+
+struct A { int VarI; int *PtrI; B *PtrB; };
+
+struct B { int VarI; };
+
+struct G {
+  G(A*, B*) {}
+};
+
+int f(int);
+int f(A*);
+int f(A*, B*);
+int f(int, B*);
+int f(G, G);
+int f(B*);
+void f1(void *, void *);
+A *g(A *);
+
+G operator+(const G&, const G&);
+
+void test_function_parameter(A *XA, B *XB) {
+  (void)f(new A, new B);
+  try {
+(void)f(new A, new B);
+  }
+  catch (A) {};
+  try {
+(void)f(new A, new B);
+ // CHECK-MESSAGES-ALL: :[[@LINE-1]]:13: warning: memory allocation may leak if an other allocation is sequenced after it and throws an exception; order of these allocations is undefined [
+(void)f(f(new A, new B));
+ // CHECK-MESSAGES-ALL: :[[@LINE-1]]:15: warning: memory allocation may leak if an other allocation is sequenced after it and throws an exception;
+int X = f(new A, new B);
+ // CHECK-MESSAGES-ALL: :[[@LINE-1]]:15: warning: memory allocation may leak if an other allocation is sequenced after it and throws an exception;
+X = f(new A, new B);
+ // CHECK-MESSAGES-ALL: :[[@LINE-1]]:11: warning: memory allocation may leak if an other allocation is sequenced after it and throws an exception;
+X = 1 + f(new A, new B);
+ // CHECK-MESSAGES-ALL: :[[@LINE-1]]:15: warning: memory allocation may leak if an other allocation is sequenced after it and throws an exception;
+
+(void)f(g(new A), new B);
+ // CHECK-MESSAGES-ALL: :[[@LINE-1]]:15: warning: memory allocation may leak if an other allocation is sequenced after it and throws an exception;
+
+(void)f(1 + f(new A), new B);
+ // CHECK-MESSAGES-ALL: :[[@LINE-1]]:19: warning: memory allocation may leak if an other allocation is sequenced after it and throws an exception;
+(void)f(XA = new A, new B);
+ // CHECK-MESSAGES-ALL: :[[@LINE-1]]:18: warning: memory allocation may leak if an other allocation is sequenced after it and throws an exception;
+(void)f(1 + f(new A), XB = new B);
+ // CHECK-MESSAGES-ALL: :[[@LINE-1]]:19: warning: memory allocation may leak if an other allocation is sequenced after it and throws an exception;
+  }
+  catch (std::exception) {}
+}
+
+void test_operator() {
+  (void)(f(new A) + f(new B));
+  try {
+(void)(f(new A) + f(new B));
+ // CHECK-MESSAGES-ALL: :[[@LINE-1]]:14: warning: memory allocation may leak if an other allocation is sequenced after it and throws an exception;
+(void)f(f(new A) + f(new B));
+ // CHECK-MESSAGES-ALL: :[[@LINE-1]]:15: warning: memory allocation may leak if an other allocation is sequenced after it and throws an exception;
+int X = f(new A) + f(new B);
+ // CHECK-MESSAGES-ALL: :[[@LINE-1]]:15: warning: memory allocation may leak if an other allocation is sequenced after it and throws an exception;
+X = f(new A) + f(new B);
+ // CHECK-MESSAGES-ALL: :[[@LINE-1]]:11: warning: memory allocation may leak if an other allocation is sequenced after it and throws an exception;
+X = 1 + f(new A) + 1 + f(new B);
+ // CHECK-MESSAGES-ALL: :[[@LINE-1]]:15: warning: memory allocation may leak if an other allocation is sequen

[PATCH] D138709: Reland "[Lex] Fix suggested spelling of /usr/bin/../include/foo"

2022-11-28 Thread Sam McCall via Phabricator via cfe-commits
sammccall marked an inline comment as done.
sammccall added inline comments.



Comment at: clang/unittests/Lex/HeaderSearchTest.cpp:155
+  addSearchDir("/x/../y/");
+  EXPECT_EQ(Search.suggestPathToFileForDiagnostics("/x/../y/z",
+   /*WorkingDir=*/"",

kadircet wrote:
> can you also add a new test that looks like:
> ```
> addSearchDir("x/");
> EXPECT(suggestForDiag("x\y\z.h"), "y/z.h");
> ```
> 
> as in theory that's the new behaviour we're adding.
That looks a lot like `TEST_F(HeaderSearchTest, BackSlash)` to me (relative vs 
absolute, but not relevant at least to this change)


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D138709/new/

https://reviews.llvm.org/D138709

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


[clang] 2c1fa73 - Reland "[Lex] Fix suggested spelling of /usr/bin/../include/foo"

2022-11-28 Thread Sam McCall via cfe-commits

Author: Sam McCall
Date: 2022-11-28T10:09:13+01:00
New Revision: 2c1fa734598c9470139720565fbf624a5156ec03

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

LOG: Reland "[Lex] Fix suggested spelling of /usr/bin/../include/foo"

This reverts commit 1dc0a1e5d220b83c1074204bd3afd54f3bac4270.

Failures were caused by unintentional conversion to native slashes by
remove_dots, so undo that: we always suggest posix slashes for includes.

This could potentially be a change in behavior on windows if people were
spelling headers with backslashes and headermaps contained backslashes,
but that's all underspecified and I don't think anyone uses headermaps
on windows.

Differential Revision: https://reviews.llvm.org/D138709

Added: 


Modified: 
clang/lib/Lex/HeaderSearch.cpp
clang/unittests/Lex/HeaderSearchTest.cpp

Removed: 




diff  --git a/clang/lib/Lex/HeaderSearch.cpp b/clang/lib/Lex/HeaderSearch.cpp
index e6af12294970..7bf278cc98da 100644
--- a/clang/lib/Lex/HeaderSearch.cpp
+++ b/clang/lib/Lex/HeaderSearch.cpp
@@ -1928,32 +1928,28 @@ std::string 
HeaderSearch::suggestPathToFileForDiagnostics(
 llvm::StringRef File, llvm::StringRef WorkingDir, llvm::StringRef MainFile,
 bool *IsSystem) {
   using namespace llvm::sys;
+  
+  llvm::SmallString<32> FilePath = File;
+  // remove_dots switches to backslashes on windows as a side-effect!
+  // We always want to suggest forward slashes for includes.
+  // (not remove_dots(..., posix) as that misparses windows paths).
+  path::remove_dots(FilePath, /*remove_dot_dot=*/true);
+  path::native(FilePath, path::Style::posix);
+  File = FilePath;
 
   unsigned BestPrefixLength = 0;
   // Checks whether `Dir` is a strict path prefix of `File`. If so and that's
   // the longest prefix we've seen so for it, returns true and updates the
   // `BestPrefixLength` accordingly.
-  auto CheckDir = [&](llvm::StringRef Dir) -> bool {
-llvm::SmallString<32> DirPath(Dir.begin(), Dir.end());
+  auto CheckDir = [&](llvm::SmallString<32> Dir) -> bool {
 if (!WorkingDir.empty() && !path::is_absolute(Dir))
-  fs::make_absolute(WorkingDir, DirPath);
-path::remove_dots(DirPath, /*remove_dot_dot=*/true);
-Dir = DirPath;
+  fs::make_absolute(WorkingDir, Dir);
+path::remove_dots(Dir, /*remove_dot_dot=*/true);
 for (auto NI = path::begin(File), NE = path::end(File),
   DI = path::begin(Dir), DE = path::end(Dir);
- /*termination condition in loop*/; ++NI, ++DI) {
-  // '.' components in File are ignored.
-  while (NI != NE && *NI == ".")
-++NI;
-  if (NI == NE)
-break;
-
-  // '.' components in Dir are ignored.
-  while (DI != DE && *DI == ".")
-++DI;
+ NI != NE; ++NI, ++DI) {
   if (DI == DE) {
-// Dir is a prefix of File, up to '.' components and choice of path
-// separators.
+// Dir is a prefix of File, up to choice of path separators.
 unsigned PrefixLength = NI - path::begin(File);
 if (PrefixLength > BestPrefixLength) {
   BestPrefixLength = PrefixLength;

diff  --git a/clang/unittests/Lex/HeaderSearchTest.cpp 
b/clang/unittests/Lex/HeaderSearchTest.cpp
index 5024f0d3d6b0..939f5a7210d8 100644
--- a/clang/unittests/Lex/HeaderSearchTest.cpp
+++ b/clang/unittests/Lex/HeaderSearchTest.cpp
@@ -150,6 +150,14 @@ TEST_F(HeaderSearchTest, DotDotsWithAbsPath) {
 "z");
 }
 
+TEST_F(HeaderSearchTest, BothDotDots) {
+  addSearchDir("/x/../y/");
+  EXPECT_EQ(Search.suggestPathToFileForDiagnostics("/x/../y/z",
+   /*WorkingDir=*/"",
+   /*MainFile=*/""),
+"z");
+}
+
 TEST_F(HeaderSearchTest, IncludeFromSameDirectory) {
   EXPECT_EQ(Search.suggestPathToFileForDiagnostics("/y/z/t.h",
/*WorkingDir=*/"",



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


[PATCH] D138709: Reland "[Lex] Fix suggested spelling of /usr/bin/../include/foo"

2022-11-28 Thread Sam McCall via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG2c1fa734598c: Reland "[Lex] Fix suggested spelling of 
/usr/bin/../include/foo" (authored by sammccall).

Changed prior to commit:
  https://reviews.llvm.org/D138709?vs=477937&id=478152#toc

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D138709/new/

https://reviews.llvm.org/D138709

Files:
  clang/lib/Lex/HeaderSearch.cpp
  clang/unittests/Lex/HeaderSearchTest.cpp


Index: clang/unittests/Lex/HeaderSearchTest.cpp
===
--- clang/unittests/Lex/HeaderSearchTest.cpp
+++ clang/unittests/Lex/HeaderSearchTest.cpp
@@ -150,6 +150,14 @@
 "z");
 }
 
+TEST_F(HeaderSearchTest, BothDotDots) {
+  addSearchDir("/x/../y/");
+  EXPECT_EQ(Search.suggestPathToFileForDiagnostics("/x/../y/z",
+   /*WorkingDir=*/"",
+   /*MainFile=*/""),
+"z");
+}
+
 TEST_F(HeaderSearchTest, IncludeFromSameDirectory) {
   EXPECT_EQ(Search.suggestPathToFileForDiagnostics("/y/z/t.h",
/*WorkingDir=*/"",
Index: clang/lib/Lex/HeaderSearch.cpp
===
--- clang/lib/Lex/HeaderSearch.cpp
+++ clang/lib/Lex/HeaderSearch.cpp
@@ -1928,32 +1928,28 @@
 llvm::StringRef File, llvm::StringRef WorkingDir, llvm::StringRef MainFile,
 bool *IsSystem) {
   using namespace llvm::sys;
+  
+  llvm::SmallString<32> FilePath = File;
+  // remove_dots switches to backslashes on windows as a side-effect!
+  // We always want to suggest forward slashes for includes.
+  // (not remove_dots(..., posix) as that misparses windows paths).
+  path::remove_dots(FilePath, /*remove_dot_dot=*/true);
+  path::native(FilePath, path::Style::posix);
+  File = FilePath;
 
   unsigned BestPrefixLength = 0;
   // Checks whether `Dir` is a strict path prefix of `File`. If so and that's
   // the longest prefix we've seen so for it, returns true and updates the
   // `BestPrefixLength` accordingly.
-  auto CheckDir = [&](llvm::StringRef Dir) -> bool {
-llvm::SmallString<32> DirPath(Dir.begin(), Dir.end());
+  auto CheckDir = [&](llvm::SmallString<32> Dir) -> bool {
 if (!WorkingDir.empty() && !path::is_absolute(Dir))
-  fs::make_absolute(WorkingDir, DirPath);
-path::remove_dots(DirPath, /*remove_dot_dot=*/true);
-Dir = DirPath;
+  fs::make_absolute(WorkingDir, Dir);
+path::remove_dots(Dir, /*remove_dot_dot=*/true);
 for (auto NI = path::begin(File), NE = path::end(File),
   DI = path::begin(Dir), DE = path::end(Dir);
- /*termination condition in loop*/; ++NI, ++DI) {
-  // '.' components in File are ignored.
-  while (NI != NE && *NI == ".")
-++NI;
-  if (NI == NE)
-break;
-
-  // '.' components in Dir are ignored.
-  while (DI != DE && *DI == ".")
-++DI;
+ NI != NE; ++NI, ++DI) {
   if (DI == DE) {
-// Dir is a prefix of File, up to '.' components and choice of path
-// separators.
+// Dir is a prefix of File, up to choice of path separators.
 unsigned PrefixLength = NI - path::begin(File);
 if (PrefixLength > BestPrefixLength) {
   BestPrefixLength = PrefixLength;


Index: clang/unittests/Lex/HeaderSearchTest.cpp
===
--- clang/unittests/Lex/HeaderSearchTest.cpp
+++ clang/unittests/Lex/HeaderSearchTest.cpp
@@ -150,6 +150,14 @@
 "z");
 }
 
+TEST_F(HeaderSearchTest, BothDotDots) {
+  addSearchDir("/x/../y/");
+  EXPECT_EQ(Search.suggestPathToFileForDiagnostics("/x/../y/z",
+   /*WorkingDir=*/"",
+   /*MainFile=*/""),
+"z");
+}
+
 TEST_F(HeaderSearchTest, IncludeFromSameDirectory) {
   EXPECT_EQ(Search.suggestPathToFileForDiagnostics("/y/z/t.h",
/*WorkingDir=*/"",
Index: clang/lib/Lex/HeaderSearch.cpp
===
--- clang/lib/Lex/HeaderSearch.cpp
+++ clang/lib/Lex/HeaderSearch.cpp
@@ -1928,32 +1928,28 @@
 llvm::StringRef File, llvm::StringRef WorkingDir, llvm::StringRef MainFile,
 bool *IsSystem) {
   using namespace llvm::sys;
+  
+  llvm::SmallString<32> FilePath = File;
+  // remove_dots switches to backslashes on windows as a side-effect!
+  // We always want to suggest forward slashes for includes.
+  // (not remove_dots(..., posix) as that misparses windows paths).
+  path::remove_dots(FilePath, /*remove_dot_dot=*/true);
+  path::native(FilePath, path::Style::posix);
+  File = FilePath;
 
   unsigned BestPrefixLength = 0;
   // Checks whether `Dir` is 

[clang-tools-extra] 962343a - [include-cleaner] Fix walkUsed only report a single macro ref.

2022-11-28 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2022-11-28T10:12:10+01:00
New Revision: 962343a979d51cea9363167e9121c446abbdfdbc

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

LOG: [include-cleaner] Fix walkUsed only report a single macro ref.

Added: 


Modified: 
clang-tools-extra/include-cleaner/lib/Analysis.cpp

Removed: 




diff  --git a/clang-tools-extra/include-cleaner/lib/Analysis.cpp 
b/clang-tools-extra/include-cleaner/lib/Analysis.cpp
index e2455e115de2..0f96ae26f51c 100644
--- a/clang-tools-extra/include-cleaner/lib/Analysis.cpp
+++ b/clang-tools-extra/include-cleaner/lib/Analysis.cpp
@@ -38,8 +38,7 @@ void walkUsed(llvm::ArrayRef ASTRoots,
   }
   for (const SymbolReference &MacroRef : MacroRefs) {
 assert(MacroRef.Target.kind() == Symbol::Macro);
-return CB(MacroRef,
-  findHeaders(MacroRef.Target.macro().Definition, SM, PI));
+CB(MacroRef, findHeaders(MacroRef.Target.macro().Definition, SM, PI));
   }
 }
 



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


[PATCH] D138753: [AArch64TargetParser] getArchFeatures -> getArchFeature

2022-11-28 Thread Lucas Prates via Phabricator via cfe-commits
pratlucas added inline comments.



Comment at: llvm/unittests/Support/TargetParserTest.cpp:1686
 
-TEST(TargetParserTest, AArch64ArchFeatures) {
-  std::vector Features;

Can you keep a unit test covering the new version of the function?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D138753/new/

https://reviews.llvm.org/D138753

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


[PATCH] D119138: [clang-format] Further improve support for requires expressions

2022-11-28 Thread Manuel Klimek via Phabricator via cfe-commits
klimek added a comment.

For non-functional clean-ups generally llvm doesn't require pre-commit review - 
I did communicate here so people involved in the original change wouldn't miss 
the clean-up. I do agree that what commits to pre-review is a fine line, and 
usually try to err on the side of pre-review; I'll take your feedback into 
consideration for future changes.

Regarding a better overview, you're 100% right. This is something we've 
definitely not been good enough and we need to get better at.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D119138/new/

https://reviews.llvm.org/D119138

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


[PATCH] D138777: [clang-tidy] Add check bugprone-multiple-new-in-one-expression.

2022-11-28 Thread Balázs Kéri via Phabricator via cfe-commits
balazske added a comment.

Some of the code is copied from `UnhandledExceptionAtNewCheck`. Probably these 
checks can be merged into one `NewExceptionHandlingCheck`?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D138777/new/

https://reviews.llvm.org/D138777

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


[PATCH] D138753: [AArch64TargetParser] getArchFeatures -> getArchFeature

2022-11-28 Thread Tomas Matheson via Phabricator via cfe-commits
tmatheson added inline comments.



Comment at: llvm/unittests/Support/TargetParserTest.cpp:1686
 
-TEST(TargetParserTest, AArch64ArchFeatures) {
-  std::vector Features;

pratlucas wrote:
> Can you keep a unit test covering the new version of the function?
The old version had special treatment for INVALID, but the new version is just 
returning the feature as written in AArch64TargetParser.def. A unit test would 
consist of a list of getArchFeature() calls with the same strings as in the 
.def. So I could certainly add it but I'm not sure that it adds any value as a 
unit test?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D138753/new/

https://reviews.llvm.org/D138753

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


[PATCH] D138779: [include-cleaner] Filter out references that not spelled in the main file.

2022-11-28 Thread Haojian Wu via Phabricator via cfe-commits
hokein created this revision.
hokein added reviewers: kadircet, sammccall.
Herald added a project: All.
hokein requested review of this revision.
Herald added a project: clang-tools-extra.

A HTML report of gtest after this patch:
https://gist.githubusercontent.com/hokein/73eee6f65a803e5702d8388c187524a6/raw/cf05a503519703a2fb87840bb0b270fe11a7a9fd/RecordTest.html


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D138779

Files:
  clang-tools-extra/include-cleaner/lib/Analysis.cpp
  clang-tools-extra/include-cleaner/lib/AnalysisInternal.h
  clang-tools-extra/include-cleaner/lib/FindHeaders.cpp
  clang-tools-extra/include-cleaner/lib/HTMLReport.cpp
  clang-tools-extra/include-cleaner/unittests/AnalysisTest.cpp

Index: clang-tools-extra/include-cleaner/unittests/AnalysisTest.cpp
===
--- clang-tools-extra/include-cleaner/unittests/AnalysisTest.cpp
+++ clang-tools-extra/include-cleaner/unittests/AnalysisTest.cpp
@@ -25,6 +25,8 @@
 
 namespace clang::include_cleaner {
 namespace {
+using testing::AllOf;
+using testing::Not;
 using testing::Pair;
 using testing::UnorderedElementsAre;
 
@@ -134,6 +136,118 @@
   UnorderedElementsAre(Pair(Main.point(), UnorderedElementsAre(HdrFile;
 }
 
+MATCHER(isMacroLoc, "") { return arg.isMacroID(); }
+MATCHER_P3(expandedAt, FileID, Offset, SM, "") {
+  auto [ExpanedFileID, ExpandedOffset] = SM->getDecomposedExpansionLoc(arg);
+  return ExpanedFileID == FileID && ExpandedOffset == Offset;
+}
+MATCHER_P3(spelledAt, FileID, Offset, SM, "") {
+  auto [SpelledFileID, SpelledOffset] = SM->getDecomposedSpellingLoc(arg);
+  return SpelledFileID == FileID && SpelledOffset == Offset;
+}
+TEST(WalkUsed, FilterRefsNotSpelledInMainFile) {
+  llvm::Annotations Main(R"cpp(
+#include "header.h"
+
+// Macros defined in main file.
+#define PLUS_ONE(X) X+1;
+#define CALL_FUN $func_spelled^func()
+
+#define M 1
+#define USE_M $M1^$M2_spelled^M
+
+void test(int a) {
+  // Tests for decl refs.
+  // The ref of `func()` is spelled in the main-file macro body.
+  $func_expanded^CALL_FUN;
+
+  // Refs of `a` are spelled in the main file (via macro arg).
+  $a1_expanded^PLUS_ONE($a1_spelled^a);
+  $a2_expanded^HDR_PLUS_ONE($a2_spelled^a);
+
+  // Refs of `func()` and `a` are from macro body which are spelled outside
+  // the main file, thus filtered out.
+  HDR_CALL_FUN;
+  HDR_A_PLUS_ONE;
+
+  // Tests for macro refs.
+  // 2 macro refs of `M`:
+  //   - M1 is a file loc, spelled in the macro body of USE_M
+  //   - M2 is a macro loc, expanded by the macro USE_M usage.
+  $M2_expanded^USE_M;
+  // Macro refs of `HDR_M` not spelled in main file, thus filtered out.
+  HDR_USE_M;
+}
+  )cpp");
+  TestInputs Inputs(Main.code());
+  Inputs.ExtraFiles["header.h"] = guard(R"cpp(
+#define HDR_PLUS_ONE(X) X + 1
+#define HDR_A_PLUS_ONE a + 1
+#define HDR_CALL_FUN func()
+
+void func();
+
+#define HDR_M 1
+#define HDR_USE_M HDR_M
+  )cpp");
+  RecordedPP Recorded;
+  Inputs.MakeAction = [&]() {
+struct RecordAction : public SyntaxOnlyAction {
+  RecordedPP &Out;
+  RecordAction(RecordedPP &Out) : Out(Out) {}
+  bool BeginSourceFileAction(clang::CompilerInstance &CI) override {
+auto &PP = CI.getPreprocessor();
+PP.addPPCallbacks(Out.record(PP));
+return true;
+  }
+};
+return std::make_unique(Recorded);
+  };
+  TestAST AST(Inputs);
+
+  llvm::SmallVector TopLevelDecls;
+  for (Decl *D : AST.context().getTranslationUnitDecl()->decls())
+TopLevelDecls.emplace_back(D);
+  auto &SM = AST.sourceManager();
+  FileID MainFID = SM.getMainFileID();
+  llvm::StringMap> SymbolRefs;
+  walkUsed(
+  TopLevelDecls, Recorded.MacroReferences, /*PragmaIncludes=*/nullptr, SM,
+  [&](const SymbolReference &Ref, llvm::ArrayRef) {
+switch (Ref.Target.kind()) {
+case Symbol::Declaration:
+  SymbolRefs[dyn_cast(&Ref.Target.declaration())->getName()]
+  .push_back(Ref.RefLocation);
+  break;
+case Symbol::Macro:
+  SymbolRefs[Ref.Target.macro().Name->getName()].push_back(
+  Ref.RefLocation);
+  break;
+}
+  });
+  EXPECT_THAT(SymbolRefs.lookup("func"),
+  UnorderedElementsAre(
+  AllOf(isMacroLoc(),
+expandedAt(MainFID, Main.point("func_expanded"), &SM),
+spelledAt(MainFID, Main.point("func_spelled"), &SM;
+  EXPECT_THAT(SymbolRefs.lookup("a"),
+  UnorderedElementsAre(
+  AllOf(isMacroLoc(),
+expandedAt(MainFID, Main.point("a1_expanded"), &SM),
+spelledAt(MainFID, Main.point("a1_spelled"), &SM)),
+  AllOf(isMacroLoc(),
+expandedAt(MainFID, Main.point("a2_expanded"), &SM),
+  

[PATCH] D138780: [include-cleaner] Minor fixes to parseIWYUPragma:

2022-11-28 Thread Sam McCall via Phabricator via cfe-commits
sammccall created this revision.
sammccall added a reviewer: hokein.
Herald added a subscriber: kadircet.
Herald added a project: All.
sammccall requested review of this revision.
Herald added a project: clang-tools-extra.
Herald added a subscriber: cfe-commits.

- remove assert that can fail for input `/\* */`
- assert was also checking the wrong condition: that the prefix *differed* from 
either `//` or from `/*`. Avoid use of strncmp where we can.
- add a comment that the brittleness of the text matching is intentional


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D138780

Files:
  clang-tools-extra/include-cleaner/lib/Record.cpp


Index: clang-tools-extra/include-cleaner/lib/Record.cpp
===
--- clang-tools-extra/include-cleaner/lib/Record.cpp
+++ clang-tools-extra/include-cleaner/lib/Record.cpp
@@ -144,9 +144,13 @@
 // FIXME: this is a mirror of clang::clangd::parseIWYUPragma, move to 
libTooling
 // to share the code?
 static llvm::Optional parseIWYUPragma(const char *Text) {
-  assert(strncmp(Text, "//", 2) || strncmp(Text, "/*", 2));
+  // Skip the comment start, // or /*.
+  if (Text[0] != '/' || (Text[1] != '/' && Text[1] != '*'))
+return llvm::None;
+  Text += 2;
+
+  // Per spec, direcitves are whitespace- and case-sensitive.
   constexpr llvm::StringLiteral IWYUPragma = " IWYU pragma: ";
-  Text += 2; // Skip the comment start, // or /*.
   if (strncmp(Text, IWYUPragma.data(), IWYUPragma.size()))
 return llvm::None;
   Text += IWYUPragma.size();


Index: clang-tools-extra/include-cleaner/lib/Record.cpp
===
--- clang-tools-extra/include-cleaner/lib/Record.cpp
+++ clang-tools-extra/include-cleaner/lib/Record.cpp
@@ -144,9 +144,13 @@
 // FIXME: this is a mirror of clang::clangd::parseIWYUPragma, move to libTooling
 // to share the code?
 static llvm::Optional parseIWYUPragma(const char *Text) {
-  assert(strncmp(Text, "//", 2) || strncmp(Text, "/*", 2));
+  // Skip the comment start, // or /*.
+  if (Text[0] != '/' || (Text[1] != '/' && Text[1] != '*'))
+return llvm::None;
+  Text += 2;
+
+  // Per spec, direcitves are whitespace- and case-sensitive.
   constexpr llvm::StringLiteral IWYUPragma = " IWYU pragma: ";
-  Text += 2; // Skip the comment start, // or /*.
   if (strncmp(Text, IWYUPragma.data(), IWYUPragma.size()))
 return llvm::None;
   Text += IWYUPragma.size();
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D137836: [Support] Move getHostNumPhysicalCores to Threading.h

2022-11-28 Thread Sam Elliott via Phabricator via cfe-commits
lenary marked 3 inline comments as done.
lenary added a comment.

Going to attempt to land this again today.




Comment at: llvm/lib/Support/Threading.cpp:59
   if (MaxThreadCount <= 0)
 MaxThreadCount = 1;
   if (ThreadsRequested == 0)

tmatheson wrote:
> It looks like this is the only place `get_physical_cores` is used, and if the 
> number is unknown or threading is disabled `MaxThreadCount` is just set to 1. 
> Would it not make sense to change `get_physical_cores` to return 1, like 
> `compute_thread_count`?
I'd rather keep the unknown semantic, so it's clearer why someone is getting 
the answer they are.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D137836/new/

https://reviews.llvm.org/D137836

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


[PATCH] D138780: [include-cleaner] Minor fixes to parseIWYUPragma:

2022-11-28 Thread Haojian Wu via Phabricator via cfe-commits
hokein added a comment.

Thanks! The change is LG, I think it would be great to have some tests.




Comment at: clang-tools-extra/include-cleaner/lib/Record.cpp:146
 // to share the code?
 static llvm::Optional parseIWYUPragma(const char *Text) {
+  // Skip the comment start, // or /*.

I'd like to have some unittests for this function (the cases you mentioned are 
really good, I don't want to lose them), but this function is not exposed. 
Maybe expose it or even address the FIXME?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D138780/new/

https://reviews.llvm.org/D138780

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


[PATCH] D138779: [include-cleaner] Filter out references that not spelled in the main file.

2022-11-28 Thread Sam McCall via Phabricator via cfe-commits
sammccall added inline comments.



Comment at: clang-tools-extra/include-cleaner/lib/FindHeaders.cpp:58
+bool isSpelledInMainFile(SourceLocation Loc, const SourceManager &SM) {
+  return SM.isWrittenInMainFile(Loc.isMacroID() ? SM.getSpellingLoc(Loc) : 
Loc);
+}

this seems like unneccesary indirection:
 - the argument is just SM.getSpellingLoc(Loc), no isMacroID check needed
 - and given this, maybe just inline?



Comment at: clang-tools-extra/include-cleaner/unittests/AnalysisTest.cpp:148
+}
+TEST(WalkUsed, FilterRefsNotSpelledInMainFile) {
+  llvm::Annotations Main(R"cpp(

I find this test very hard to follow because it combines a lot of complicated 
and separate test cases, fixtures etc.
Consider a table-based test.



Comment at: clang-tools-extra/include-cleaner/unittests/AnalysisTest.cpp:218
+switch (Ref.Target.kind()) {
+case Symbol::Declaration:
+  SymbolRefs[dyn_cast(&Ref.Target.declaration())->getName()]

all this stuff around name-based lookup can be much simpler if you make your 
tests narrower, and require the ref target to have a fixed name (use 
`llvm::to_string(Ref.Target)`)

```
int ^target = 1;
#define M target
#define USE_M M
int y = ^USE_M;
```


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D138779/new/

https://reviews.llvm.org/D138779

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


[PATCH] D137782: [clang-tidy]bugprone-fold-init-type

2022-11-28 Thread Clement Courbet via Phabricator via cfe-commits
courbet added a comment.

ping


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D137782/new/

https://reviews.llvm.org/D137782

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


[PATCH] D138780: [include-cleaner] Merge 2 parseIWYUPragma impls in libToolingInclusions

2022-11-28 Thread Sam McCall via Phabricator via cfe-commits
sammccall updated this revision to Diff 478162.
sammccall retitled this revision from "[include-cleaner] Minor fixes to 
parseIWYUPragma:" to "[include-cleaner] Merge 2 parseIWYUPragma impls in 
libToolingInclusions".
sammccall edited the summary of this revision.
sammccall added a comment.
Herald added a subscriber: arphaman.
Herald added a project: clang.

Move to libTooling, remove clangd impl, add tests


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D138780/new/

https://reviews.llvm.org/D138780

Files:
  clang-tools-extra/clangd/Headers.cpp
  clang-tools-extra/clangd/Headers.h
  clang-tools-extra/include-cleaner/lib/Record.cpp
  clang/include/clang/Tooling/Inclusions/HeaderAnalysis.h
  clang/lib/Tooling/Inclusions/HeaderAnalysis.cpp
  clang/unittests/Tooling/HeaderAnalysisTest.cpp

Index: clang/unittests/Tooling/HeaderAnalysisTest.cpp
===
--- clang/unittests/Tooling/HeaderAnalysisTest.cpp
+++ clang/unittests/Tooling/HeaderAnalysisTest.cpp
@@ -9,11 +9,14 @@
 #include "clang/Tooling/Inclusions/HeaderAnalysis.h"
 #include "clang/Lex/Preprocessor.h"
 #include "clang/Testing/TestAST.h"
+#include "llvm/Testing/Support/SupportHelpers.h"
 #include "gtest/gtest.h"
 
 namespace clang {
 namespace tooling {
 namespace {
+using llvm::ValueIs;
+using testing::Eq;
 
 TEST(HeaderAnalysisTest, IsSelfContained) {
   TestInputs Inputs;
@@ -58,6 +61,19 @@
   EXPECT_FALSE(isSelfContainedHeader(FM.getFile("bad.h").get(), SM, HI));
 }
 
+TEST(HeaderAnalysisTest, ParseIWYUPragma) {
+  EXPECT_THAT(parseIWYUPragma("// IWYU pragma: keep"), ValueIs(Eq("keep")));
+  EXPECT_THAT(parseIWYUPragma("// IWYU pragma: keep\netc"),
+  ValueIs(Eq("keep")));
+  EXPECT_THAT(parseIWYUPragma("/* IWYU pragma: keep */"), ValueIs(Eq("keep ")));
+  EXPECT_EQ(parseIWYUPragma("//  IWYU pragma: keep"), llvm::None)
+  << "Sensitive to whitespace";
+  EXPECT_EQ(parseIWYUPragma("// IWYU pragma:keep"), llvm::None)
+  << "Sensitive to whitespace";
+  EXPECT_EQ(parseIWYUPragma("/\n* IWYU pragma: keep */"), llvm::None)
+  << "Must start with /* or //";
+}
+
 } // namespace
 } // namespace tooling
 } // namespace clang
Index: clang/lib/Tooling/Inclusions/HeaderAnalysis.cpp
===
--- clang/lib/Tooling/Inclusions/HeaderAnalysis.cpp
+++ clang/lib/Tooling/Inclusions/HeaderAnalysis.cpp
@@ -64,4 +64,22 @@
   const_cast(SM).getMemoryBufferForFileOrNone(FE).value_or(
   llvm::MemoryBufferRef()));
 }
+
+llvm::Optional parseIWYUPragma(const char *Text) {
+  // Skip the comment start, // or /*.
+  if (Text[0] != '/' || (Text[1] != '/' && Text[1] != '*'))
+return llvm::None;
+  Text += 2;
+
+  // Per spec, direcitves are whitespace- and case-sensitive.
+  constexpr llvm::StringLiteral IWYUPragma = " IWYU pragma: ";
+  if (strncmp(Text, IWYUPragma.data(), IWYUPragma.size()))
+return llvm::None;
+  Text += IWYUPragma.size();
+  const char *End = Text;
+  while (*End != 0 && *End != '\n')
+++End;
+  return StringRef(Text, End - Text);
+}
+
 } // namespace clang::tooling
Index: clang/include/clang/Tooling/Inclusions/HeaderAnalysis.h
===
--- clang/include/clang/Tooling/Inclusions/HeaderAnalysis.h
+++ clang/include/clang/Tooling/Inclusions/HeaderAnalysis.h
@@ -9,6 +9,8 @@
 #ifndef LLVM_CLANG_TOOLING_INCLUSIONS_HEADER_ANALYSIS_H
 #define LLVM_CLANG_TOOLING_INCLUSIONS_HEADER_ANALYSIS_H
 
+#include "llvm/ADT/Optional.h"
+#include "llvm/ADT/StringRef.h"
 namespace clang {
 class FileEntry;
 class SourceManager;
@@ -27,6 +29,12 @@
 bool isSelfContainedHeader(const FileEntry *FE, const SourceManager &SM,
HeaderSearch &HeaderInfo);
 
+/// If Text begins an Include-What-You-Use directive, returns it.
+/// Given "// IWYU pragma: keep", returns "keep".
+/// Input is a null-terminated char* as provided by SM.getCharacterData().
+/// (This should not be StringRef as we do *not* want to scan for its length).
+llvm::Optional parseIWYUPragma(const char *Text);
+
 } // namespace tooling
 } // namespace clang
 
Index: clang-tools-extra/include-cleaner/lib/Record.cpp
===
--- clang-tools-extra/include-cleaner/lib/Record.cpp
+++ clang-tools-extra/include-cleaner/lib/Record.cpp
@@ -141,21 +141,6 @@
 
 } // namespace
 
-// FIXME: this is a mirror of clang::clangd::parseIWYUPragma, move to libTooling
-// to share the code?
-static llvm::Optional parseIWYUPragma(const char *Text) {
-  assert(strncmp(Text, "//", 2) || strncmp(Text, "/*", 2));
-  constexpr llvm::StringLiteral IWYUPragma = " IWYU pragma: ";
-  Text += 2; // Skip the comment start, // or /*.
-  if (strncmp(Text, IWYUPragma.data(), IWYUPragma.size()))
-return llvm::None;
-  Text += IWYUPragma.size();
-  const char *End = Text;
-  while (*End != 0 && *End != '\n')

[PATCH] D138780: [include-cleaner] Merge 2 parseIWYUPragma impls in libToolingInclusions

2022-11-28 Thread Sam McCall via Phabricator via cfe-commits
sammccall updated this revision to Diff 478163.
sammccall added a comment.

clean dead tests


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D138780/new/

https://reviews.llvm.org/D138780

Files:
  clang-tools-extra/clangd/Headers.cpp
  clang-tools-extra/clangd/Headers.h
  clang-tools-extra/clangd/unittests/HeadersTests.cpp
  clang-tools-extra/include-cleaner/lib/Record.cpp
  clang/include/clang/Tooling/Inclusions/HeaderAnalysis.h
  clang/lib/Tooling/Inclusions/HeaderAnalysis.cpp
  clang/unittests/Tooling/HeaderAnalysisTest.cpp

Index: clang/unittests/Tooling/HeaderAnalysisTest.cpp
===
--- clang/unittests/Tooling/HeaderAnalysisTest.cpp
+++ clang/unittests/Tooling/HeaderAnalysisTest.cpp
@@ -9,11 +9,14 @@
 #include "clang/Tooling/Inclusions/HeaderAnalysis.h"
 #include "clang/Lex/Preprocessor.h"
 #include "clang/Testing/TestAST.h"
+#include "llvm/Testing/Support/SupportHelpers.h"
 #include "gtest/gtest.h"
 
 namespace clang {
 namespace tooling {
 namespace {
+using llvm::ValueIs;
+using testing::Eq;
 
 TEST(HeaderAnalysisTest, IsSelfContained) {
   TestInputs Inputs;
@@ -58,6 +61,19 @@
   EXPECT_FALSE(isSelfContainedHeader(FM.getFile("bad.h").get(), SM, HI));
 }
 
+TEST(HeaderAnalysisTest, ParseIWYUPragma) {
+  EXPECT_THAT(parseIWYUPragma("// IWYU pragma: keep"), ValueIs(Eq("keep")));
+  EXPECT_THAT(parseIWYUPragma("// IWYU pragma: keep\netc"),
+  ValueIs(Eq("keep")));
+  EXPECT_THAT(parseIWYUPragma("/* IWYU pragma: keep */"), ValueIs(Eq("keep ")));
+  EXPECT_EQ(parseIWYUPragma("//  IWYU pragma: keep"), llvm::None)
+  << "Sensitive to whitespace";
+  EXPECT_EQ(parseIWYUPragma("// IWYU pragma:keep"), llvm::None)
+  << "Sensitive to whitespace";
+  EXPECT_EQ(parseIWYUPragma("/\n* IWYU pragma: keep */"), llvm::None)
+  << "Must start with /* or //";
+}
+
 } // namespace
 } // namespace tooling
 } // namespace clang
Index: clang/lib/Tooling/Inclusions/HeaderAnalysis.cpp
===
--- clang/lib/Tooling/Inclusions/HeaderAnalysis.cpp
+++ clang/lib/Tooling/Inclusions/HeaderAnalysis.cpp
@@ -64,4 +64,22 @@
   const_cast(SM).getMemoryBufferForFileOrNone(FE).value_or(
   llvm::MemoryBufferRef()));
 }
+
+llvm::Optional parseIWYUPragma(const char *Text) {
+  // Skip the comment start, // or /*.
+  if (Text[0] != '/' || (Text[1] != '/' && Text[1] != '*'))
+return llvm::None;
+  Text += 2;
+
+  // Per spec, direcitves are whitespace- and case-sensitive.
+  constexpr llvm::StringLiteral IWYUPragma = " IWYU pragma: ";
+  if (strncmp(Text, IWYUPragma.data(), IWYUPragma.size()))
+return llvm::None;
+  Text += IWYUPragma.size();
+  const char *End = Text;
+  while (*End != 0 && *End != '\n')
+++End;
+  return StringRef(Text, End - Text);
+}
+
 } // namespace clang::tooling
Index: clang/include/clang/Tooling/Inclusions/HeaderAnalysis.h
===
--- clang/include/clang/Tooling/Inclusions/HeaderAnalysis.h
+++ clang/include/clang/Tooling/Inclusions/HeaderAnalysis.h
@@ -9,6 +9,8 @@
 #ifndef LLVM_CLANG_TOOLING_INCLUSIONS_HEADER_ANALYSIS_H
 #define LLVM_CLANG_TOOLING_INCLUSIONS_HEADER_ANALYSIS_H
 
+#include "llvm/ADT/Optional.h"
+#include "llvm/ADT/StringRef.h"
 namespace clang {
 class FileEntry;
 class SourceManager;
@@ -27,6 +29,12 @@
 bool isSelfContainedHeader(const FileEntry *FE, const SourceManager &SM,
HeaderSearch &HeaderInfo);
 
+/// If Text begins an Include-What-You-Use directive, returns it.
+/// Given "// IWYU pragma: keep", returns "keep".
+/// Input is a null-terminated char* as provided by SM.getCharacterData().
+/// (This should not be StringRef as we do *not* want to scan for its length).
+llvm::Optional parseIWYUPragma(const char *Text);
+
 } // namespace tooling
 } // namespace clang
 
Index: clang-tools-extra/include-cleaner/lib/Record.cpp
===
--- clang-tools-extra/include-cleaner/lib/Record.cpp
+++ clang-tools-extra/include-cleaner/lib/Record.cpp
@@ -141,21 +141,6 @@
 
 } // namespace
 
-// FIXME: this is a mirror of clang::clangd::parseIWYUPragma, move to libTooling
-// to share the code?
-static llvm::Optional parseIWYUPragma(const char *Text) {
-  assert(strncmp(Text, "//", 2) || strncmp(Text, "/*", 2));
-  constexpr llvm::StringLiteral IWYUPragma = " IWYU pragma: ";
-  Text += 2; // Skip the comment start, // or /*.
-  if (strncmp(Text, IWYUPragma.data(), IWYUPragma.size()))
-return llvm::None;
-  Text += IWYUPragma.size();
-  const char *End = Text;
-  while (*End != 0 && *End != '\n')
-++End;
-  return StringRef(Text, End - Text);
-}
-
 class PragmaIncludes::RecordPragma : public PPCallbacks, public CommentHandler {
 public:
   RecordPragma(const CompilerInstance &CI, PragmaIncludes *Out)
@@ -229,7 +214,8 @@
 
   bool HandleComment(Preproc

[PATCH] D138780: [include-cleaner] Merge 2 parseIWYUPragma impls in libToolingInclusions

2022-11-28 Thread Sam McCall via Phabricator via cfe-commits
sammccall added inline comments.



Comment at: clang-tools-extra/include-cleaner/lib/Record.cpp:146
 // to share the code?
 static llvm::Optional parseIWYUPragma(const char *Text) {
+  // Skip the comment start, // or /*.

hokein wrote:
> I'd like to have some unittests for this function (the cases you mentioned 
> are really good, I don't want to lose them), but this function is not 
> exposed. Maybe expose it or even address the FIXME?
Done.

This stings a little as I'd recently done this in 5d2d527c32, after which 
D136071 copied the impl without any tests and added new bugs.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D138780/new/

https://reviews.llvm.org/D138780

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


[PATCH] D137838: [RFC][Support] Move TargetParsers to new component

2022-11-28 Thread Francesco Petrogalli via Phabricator via cfe-commits
fpetrogalli accepted this revision.
fpetrogalli added a comment.
This revision is now accepted and ready to land.

Thank you for working on this @lenary  - LGTM!


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D137838/new/

https://reviews.llvm.org/D137838

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


[PATCH] D138782: [include-cleaner] Implement IWYU begin_keep/end_keep pragma support.

2022-11-28 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo created this revision.
Herald added a subscriber: kadircet.
Herald added a project: All.
VitaNuo requested review of this revision.
Herald added a project: clang-tools-extra.
Herald added a subscriber: cfe-commits.

Keep the includes contained between IWYU begin_keep and end_keep pragmas.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D138782

Files:
  clang-tools-extra/include-cleaner/lib/Record.cpp
  clang-tools-extra/include-cleaner/unittests/RecordTest.cpp

Index: clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
===
--- clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
+++ clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
@@ -322,15 +322,36 @@
 // IWYU pragma: end_exports
 
 #include "normal.h" // Line 11
+
+// IWYU pragma: begin_keep
+#include "keep3.h" 
+#include "keep4.h" 
+// IWYU pragma: end_keep
+
+// IWYU pragma: begin_keep // Line 18
+// IWYU pragma: end_keep
+
+// IWYU pragma: begin_keep // Line 21
+#include "keep5.h" 
+// IWYU pragma: end_keep
   )cpp";
-  createEmptyFiles({"keep1.h", "keep2.h", "export1.h", "export2.h", "export3.h",
-"normal.h"});
+  createEmptyFiles({"keep1.h", "keep2.h", "keep3.h", "keep4.h", "keep5.h",
+"export1.h", "export2.h", "export3.h", "normal.h"});
 
   TestAST Processed = build();
   EXPECT_FALSE(PI.shouldKeep(1));
   // Keep
   EXPECT_TRUE(PI.shouldKeep(2));
   EXPECT_TRUE(PI.shouldKeep(3));
+  EXPECT_FALSE(PI.shouldKeep(13)); // line with "begin_keep" pragma
+  EXPECT_TRUE(PI.shouldKeep(14));
+  EXPECT_TRUE(PI.shouldKeep(15));
+  EXPECT_FALSE(PI.shouldKeep(16)); // line with "end_keep" pragma
+  EXPECT_FALSE(PI.shouldKeep(18)); // starts empty "begin_keep" block
+  EXPECT_FALSE(PI.shouldKeep(19)); // ends empty "begin_keep" block
+  EXPECT_FALSE(PI.shouldKeep(21)); // line with "begin_keep" pragma
+  EXPECT_TRUE(PI.shouldKeep(22));
+  EXPECT_FALSE(PI.shouldKeep(23)); // line with "end_keep" pragma
 
   // Exports
   EXPECT_TRUE(PI.shouldKeep(5));
Index: clang-tools-extra/include-cleaner/lib/Record.cpp
===
--- clang-tools-extra/include-cleaner/lib/Record.cpp
+++ clang-tools-extra/include-cleaner/lib/Record.cpp
@@ -202,8 +202,14 @@
 int HashLine = SM.getLineNumber(HashFID, SM.getFileOffset(HashLoc));
 checkForExport(HashFID, HashLine, File ? &File->getFileEntry() : nullptr);
 
+// one-line "IWYU pragma: keep" pragma handling.
 if (InMainFile && LastPragmaKeepInMainFileLine == HashLine)
   Out->ShouldKeep.insert(HashLine);
+
+// multiline "IWYU pragma: begin_keep"/"IWYU pragma: end_keep" handling.
+if (InMainFile && InsidePragmaKeepBlock) {
+  Out->ShouldKeep.insert(HashLine);
+}
   }
 
   void checkForExport(FileID IncludingFile, int HashLine,
@@ -227,6 +233,8 @@
   ExportStack.pop_back();
   }
 
+  void checkForKeep() {}
+
   bool HandleComment(Preprocessor &PP, SourceRange Range) override {
 auto &SM = PP.getSourceManager();
 auto Pragma = parseIWYUPragma(SM.getCharacterData(Range.getBegin()));
@@ -270,23 +278,28 @@
 }
 
 if (InMainFile) {
-  if (!Pragma->startswith("keep"))
-return false;
-  // Given:
-  //
-  // #include "foo.h"
-  // #include "bar.h" // IWYU pragma: keep
-  //
-  // The order in which the callbacks will be triggered:
-  //
-  // 1. InclusionDirective("foo.h")
-  // 2. handleCommentInMainFile("// IWYU pragma: keep")
-  // 3. InclusionDirective("bar.h")
-  //
-  // This code stores the last location of "IWYU pragma: keep" comment in
-  // the main file, so that when next InclusionDirective is called, it will
-  // know that the next inclusion is behind the IWYU pragma.
-  LastPragmaKeepInMainFileLine = CommentLine;
+  if (Pragma->startswith("keep"))
+// Given:
+//
+// #include "foo.h"
+// #include "bar.h" // IWYU pragma: keep
+//
+// The order in which the callbacks will be triggered:
+//
+// 1. InclusionDirective("foo.h")
+// 2. handleCommentInMainFile("// IWYU pragma: keep")
+// 3. InclusionDirective("bar.h")
+//
+// This code stores the last location of "IWYU pragma: keep" comment in
+// the main file, so that when next InclusionDirective is called, it
+// will know that the next inclusion is behind the IWYU pragma.
+LastPragmaKeepInMainFileLine = CommentLine;
+
+  if (Pragma->starts_with("begin_keep")) {
+InsidePragmaKeepBlock = true;
+  } else if (Pragma->starts_with("end_keep")) {
+InsidePragmaKeepBlock = false;
+  }
 }
 return false;
   }
@@ -301,8 +314,12 @@
   llvm::BumpPtrAllocator Arena;
   /// Intern table for strings. Contents are on the arena.
   llvm::StringSaver UniqueStrings;
-  // T

[PATCH] D138782: [include-cleaner] Implement IWYU begin_keep/end_keep pragma support.

2022-11-28 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo updated this revision to Diff 478166.
VitaNuo added a comment.

Remove unnecessary code.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D138782/new/

https://reviews.llvm.org/D138782

Files:
  clang-tools-extra/include-cleaner/lib/Record.cpp
  clang-tools-extra/include-cleaner/unittests/RecordTest.cpp

Index: clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
===
--- clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
+++ clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
@@ -322,15 +322,36 @@
 // IWYU pragma: end_exports
 
 #include "normal.h" // Line 11
+
+// IWYU pragma: begin_keep
+#include "keep3.h" 
+#include "keep4.h" 
+// IWYU pragma: end_keep
+
+// IWYU pragma: begin_keep // Line 18
+// IWYU pragma: end_keep
+
+// IWYU pragma: begin_keep // Line 21
+#include "keep5.h" 
+// IWYU pragma: end_keep
   )cpp";
-  createEmptyFiles({"keep1.h", "keep2.h", "export1.h", "export2.h", "export3.h",
-"normal.h"});
+  createEmptyFiles({"keep1.h", "keep2.h", "keep3.h", "keep4.h", "keep5.h",
+"export1.h", "export2.h", "export3.h", "normal.h"});
 
   TestAST Processed = build();
   EXPECT_FALSE(PI.shouldKeep(1));
   // Keep
   EXPECT_TRUE(PI.shouldKeep(2));
   EXPECT_TRUE(PI.shouldKeep(3));
+  EXPECT_FALSE(PI.shouldKeep(13)); // line with "begin_keep" pragma
+  EXPECT_TRUE(PI.shouldKeep(14));
+  EXPECT_TRUE(PI.shouldKeep(15));
+  EXPECT_FALSE(PI.shouldKeep(16)); // line with "end_keep" pragma
+  EXPECT_FALSE(PI.shouldKeep(18)); // starts empty "begin_keep" block
+  EXPECT_FALSE(PI.shouldKeep(19)); // ends empty "begin_keep" block
+  EXPECT_FALSE(PI.shouldKeep(21)); // line with "begin_keep" pragma
+  EXPECT_TRUE(PI.shouldKeep(22));
+  EXPECT_FALSE(PI.shouldKeep(23)); // line with "end_keep" pragma
 
   // Exports
   EXPECT_TRUE(PI.shouldKeep(5));
Index: clang-tools-extra/include-cleaner/lib/Record.cpp
===
--- clang-tools-extra/include-cleaner/lib/Record.cpp
+++ clang-tools-extra/include-cleaner/lib/Record.cpp
@@ -202,8 +202,14 @@
 int HashLine = SM.getLineNumber(HashFID, SM.getFileOffset(HashLoc));
 checkForExport(HashFID, HashLine, File ? &File->getFileEntry() : nullptr);
 
+// one-line "IWYU pragma: keep" pragma handling.
 if (InMainFile && LastPragmaKeepInMainFileLine == HashLine)
   Out->ShouldKeep.insert(HashLine);
+
+// multiline "IWYU pragma: begin_keep"/"IWYU pragma: end_keep" handling.
+if (InMainFile && InsidePragmaKeepBlock) {
+  Out->ShouldKeep.insert(HashLine);
+}
   }
 
   void checkForExport(FileID IncludingFile, int HashLine,
@@ -270,23 +276,28 @@
 }
 
 if (InMainFile) {
-  if (!Pragma->startswith("keep"))
-return false;
-  // Given:
-  //
-  // #include "foo.h"
-  // #include "bar.h" // IWYU pragma: keep
-  //
-  // The order in which the callbacks will be triggered:
-  //
-  // 1. InclusionDirective("foo.h")
-  // 2. handleCommentInMainFile("// IWYU pragma: keep")
-  // 3. InclusionDirective("bar.h")
-  //
-  // This code stores the last location of "IWYU pragma: keep" comment in
-  // the main file, so that when next InclusionDirective is called, it will
-  // know that the next inclusion is behind the IWYU pragma.
-  LastPragmaKeepInMainFileLine = CommentLine;
+  if (Pragma->startswith("keep"))
+// Given:
+//
+// #include "foo.h"
+// #include "bar.h" // IWYU pragma: keep
+//
+// The order in which the callbacks will be triggered:
+//
+// 1. InclusionDirective("foo.h")
+// 2. handleCommentInMainFile("// IWYU pragma: keep")
+// 3. InclusionDirective("bar.h")
+//
+// This code stores the last location of "IWYU pragma: keep" comment in
+// the main file, so that when next InclusionDirective is called, it
+// will know that the next inclusion is behind the IWYU pragma.
+LastPragmaKeepInMainFileLine = CommentLine;
+
+  if (Pragma->starts_with("begin_keep")) {
+InsidePragmaKeepBlock = true;
+  } else if (Pragma->starts_with("end_keep")) {
+InsidePragmaKeepBlock = false;
+  }
 }
 return false;
   }
@@ -301,8 +312,12 @@
   llvm::BumpPtrAllocator Arena;
   /// Intern table for strings. Contents are on the arena.
   llvm::StringSaver UniqueStrings;
-  // Track the last line "IWYU pragma: keep" was seen in the main file, 1-based.
+  // Track the last line "IWYU pragma: keep" or "IWYU pragma: begin_keep"
+  // was seen in the main file, 1-based.
   int LastPragmaKeepInMainFileLine = -1;
+  // true if the location is inside a keep block (i.e., between "IWYU pragma:
+  // begin_keep" and "IWYU pragma: end_keep").
+  bool InsidePragmaKeepBlock = false;
   s

[PATCH] D136078: [RFC] Use-after-return binary metadata.

2022-11-28 Thread Dmitry Vyukov via Phabricator via cfe-commits
dvyukov updated this revision to Diff 478168.
dvyukov marked 3 inline comments as done.
dvyukov added a comment.

rebase and adressed comments


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D136078/new/

https://reviews.llvm.org/D136078

Files:
  clang/include/clang/Basic/CodeGenOptions.def
  clang/include/clang/Basic/CodeGenOptions.h
  clang/include/clang/Driver/Options.td
  clang/lib/CodeGen/BackendUtil.cpp
  clang/lib/Driver/SanitizerArgs.cpp
  llvm/include/llvm/CodeGen/CodeGenPassBuilder.h
  llvm/include/llvm/CodeGen/MachinePassRegistry.def
  llvm/include/llvm/CodeGen/Passes.h
  llvm/include/llvm/InitializePasses.h
  llvm/include/llvm/Transforms/Instrumentation.h
  llvm/include/llvm/Transforms/Instrumentation/SanitizerBinaryMetadata.h
  llvm/lib/CodeGen/CMakeLists.txt
  llvm/lib/CodeGen/CodeGen.cpp
  llvm/lib/CodeGen/SanitizerBinaryMetadata.cpp
  llvm/lib/CodeGen/TargetPassConfig.cpp
  llvm/lib/Transforms/Instrumentation/SanitizerBinaryMetadata.cpp
  llvm/test/Instrumentation/SanitizerBinaryMetadata/lit.local.cfg
  llvm/test/Instrumentation/SanitizerBinaryMetadata/uar.cpp

Index: llvm/test/Instrumentation/SanitizerBinaryMetadata/uar.cpp
===
--- /dev/null
+++ llvm/test/Instrumentation/SanitizerBinaryMetadata/uar.cpp
@@ -0,0 +1,98 @@
+// We run the compiled binary + sizes of stack arguments depend on the arch.
+// REQUIRES: native && target-x86_64
+// RUN: clang++ %s -o %t -fexperimental-sanitize-metadata=covered,uar && %t | tee /dev/stderr | FileCheck %s
+
+#include 
+#include 
+#include 
+
+// CHECK: metadata add version 1
+
+// CHECK: main: features=2 stack_args=0
+int main() {
+}
+
+// CHECK: non_empty_function: features=2 stack_args=0
+void non_empty_function() {
+  // Completely empty functions don't get uar metadata.
+  volatile int x;
+  x = 1;
+}
+
+// CHECK: no_stack_args: features=2 stack_args=0
+void no_stack_args(long a0, long a1, long a2, long a3, long a4, long a5) {
+  volatile int x;
+  x = 1;
+}
+
+// CHECK: stack_args: features=2 stack_args=16
+void stack_args(long a0, long a1, long a2, long a3, long a4, long a5, long a6) {
+  volatile int x;
+  x = 1;
+}
+
+// CHECK: more_stack_args: features=2 stack_args=32
+void more_stack_args(long a0, long a1, long a2, long a3, long a4, long a5, long a6, long a7, long a8) {
+  volatile int x;
+  x = 1;
+}
+
+// CHECK: struct_stack_args: features=2 stack_args=144
+struct large { char x[131]; };
+void struct_stack_args(large a) {
+  volatile int x;
+  x = 1;
+}
+
+
+typedef unsigned long uptr;
+
+const char* function_name(uptr pc) {
+#define FN(X) if (pc == reinterpret_cast(X)) return #X
+  FN(main);
+  FN(non_empty_function);
+  FN(no_stack_args);
+  FN(stack_args);
+  FN(more_stack_args);
+  FN(struct_stack_args);
+#undef FN
+  return nullptr;
+}
+
+template
+T consume(const char*& pos, const char* end) {
+  T v = *reinterpret_cast(pos);
+  pos += sizeof(T);
+  assert(pos <= end);
+  return v;
+}
+
+const char* meta_start;
+const char* meta_end;
+
+extern "C" {
+void __sanitizer_metadata_covered_add(uint32_t version, const char* start, const char* end) {
+  printf("metadata add version %u\n", version);
+  for (const char* pos = start; pos < end;) {
+const uptr base = reinterpret_cast(pos);
+const long offset = (version & (1 << 16)) ?
+consume(pos, end) : consume(pos, end);
+const uint32_t size = consume(pos, end);
+const uint32_t features = consume(pos, end);
+uint32_t stack_args = 0;
+if (features & (1 << 1))
+  stack_args = consume(pos, end);
+if (const char* name = function_name(base + offset))
+  printf("%s: features=%x stack_args=%u\n", name, features, stack_args);
+  }
+  meta_start = start;
+  meta_end = end;
+}
+
+void __sanitizer_metadata_covered_del(uint32_t version, const char* start, const char* end) {
+  assert(start == meta_start);
+  assert(end == meta_end);
+  printf("metadata del version %u\n", version);
+}
+// CHECK: metadata del version 1
+}
Index: llvm/test/Instrumentation/SanitizerBinaryMetadata/lit.local.cfg
===
--- /dev/null
+++ llvm/test/Instrumentation/SanitizerBinaryMetadata/lit.local.cfg
@@ -0,0 +1 @@
+config.suffixes = ['.ll', '.cpp']
Index: llvm/lib/Transforms/Instrumentation/SanitizerBinaryMetadata.cpp
===
--- llvm/lib/Transforms/Instrumentation/SanitizerBinaryMetadata.cpp
+++ llvm/lib/Transforms/Instrumentation/SanitizerBinaryMetadata.cpp
@@ -67,14 +67,16 @@
 private:
   // Forbid construction elsewhere.
   explicit constexpr MetadataInfo(StringRef FunctionPrefix,
-  StringRef SectionSuffix, int Feature)
+  StringRef SectionSuffix, uint32_t Feature)
   : FunctionPrefix(FunctionPrefix), SectionSuffix(SectionSuffix),
-FeatureMask(Feature != -1 ? (1u << Feature) : 0) {

[PATCH] D137205: [clang-tidy] Add performance-unnecessary-copy-on-last-use check

2022-11-28 Thread Carlos Galvez via Phabricator via cfe-commits
carlosgalvezp added a comment.

> by design clang-format only performs white-space changes

clang-format does support east/west const enforcement with the 
`QualifierAlignment` option. From experience, I strongly encourage repo owners 
to enable it repo-wide to avoid these kinds of discussions. Until then, I 
believe developers should keep consistency with the existing style in the 
codebase, regardless of personal views. This goes in line with the LLVM Coding 
Standards:

"If you are extending, enhancing, or bug fixing already implemented code, use 
the style that is already being used so that the source is uniform and easy to 
follow."


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D137205/new/

https://reviews.llvm.org/D137205

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


[PATCH] D138780: [include-cleaner] Merge 2 parseIWYUPragma impls in libToolingInclusions

2022-11-28 Thread Sam McCall via Phabricator via cfe-commits
sammccall updated this revision to Diff 478170.
sammccall added a comment.

tweak whitespace and */ behavior


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D138780/new/

https://reviews.llvm.org/D138780

Files:
  clang-tools-extra/clangd/Headers.cpp
  clang-tools-extra/clangd/Headers.h
  clang-tools-extra/clangd/unittests/HeadersTests.cpp
  clang-tools-extra/include-cleaner/lib/Record.cpp
  clang/include/clang/Tooling/Inclusions/HeaderAnalysis.h
  clang/lib/Tooling/Inclusions/HeaderAnalysis.cpp
  clang/unittests/Tooling/HeaderAnalysisTest.cpp

Index: clang/unittests/Tooling/HeaderAnalysisTest.cpp
===
--- clang/unittests/Tooling/HeaderAnalysisTest.cpp
+++ clang/unittests/Tooling/HeaderAnalysisTest.cpp
@@ -9,11 +9,14 @@
 #include "clang/Tooling/Inclusions/HeaderAnalysis.h"
 #include "clang/Lex/Preprocessor.h"
 #include "clang/Testing/TestAST.h"
+#include "llvm/Testing/Support/SupportHelpers.h"
 #include "gtest/gtest.h"
 
 namespace clang {
 namespace tooling {
 namespace {
+using llvm::ValueIs;
+using testing::Eq;
 
 TEST(HeaderAnalysisTest, IsSelfContained) {
   TestInputs Inputs;
@@ -58,6 +61,19 @@
   EXPECT_FALSE(isSelfContainedHeader(FM.getFile("bad.h").get(), SM, HI));
 }
 
+TEST(HeaderAnalysisTest, ParseIWYUPragma) {
+  EXPECT_THAT(parseIWYUPragma("// IWYU pragma: keep"), ValueIs(Eq("keep")));
+  EXPECT_THAT(parseIWYUPragma("// IWYU pragma:   keep  me\netc"),
+  ValueIs(Eq("keep  me")));
+  EXPECT_THAT(parseIWYUPragma("/* IWYU pragma: keep */"), ValueIs(Eq("keep")));
+  EXPECT_EQ(parseIWYUPragma("//  IWYU pragma: keep"), llvm::None)
+  << "Prefix is sensitive to whitespace";
+  EXPECT_EQ(parseIWYUPragma("// IWYU pragma:keep"), llvm::None)
+  << "Prefix is sensitive to whitespace";
+  EXPECT_EQ(parseIWYUPragma("/\n* IWYU pragma: keep */"), llvm::None)
+  << "Must start with /* or //";
+}
+
 } // namespace
 } // namespace tooling
 } // namespace clang
Index: clang/lib/Tooling/Inclusions/HeaderAnalysis.cpp
===
--- clang/lib/Tooling/Inclusions/HeaderAnalysis.cpp
+++ clang/lib/Tooling/Inclusions/HeaderAnalysis.cpp
@@ -64,4 +64,28 @@
   const_cast(SM).getMemoryBufferForFileOrNone(FE).value_or(
   llvm::MemoryBufferRef()));
 }
+
+llvm::Optional parseIWYUPragma(const char *Text) {
+  // Skip the comment start, // or /*.
+  if (Text[0] != '/' || (Text[1] != '/' && Text[1] != '*'))
+return llvm::None;
+  bool BlockComment = Text[1] == '*';
+  Text += 2;
+
+  // Per spec, direcitves are whitespace- and case-sensitive.
+  constexpr llvm::StringLiteral IWYUPragma = " IWYU pragma: ";
+  if (strncmp(Text, IWYUPragma.data(), IWYUPragma.size()))
+return llvm::None;
+  Text += IWYUPragma.size();
+  const char *End = Text;
+  while (*End != 0 && *End != '\n')
+++End;
+  StringRef Rest(Text, End - Text);
+  // Strip off whitespace and comment markers to avoid confusion. This isn't
+  // fully-compatible with IWYU, which splits into whitespace-delimited tokens.
+  if (BlockComment)
+Rest.consume_back("*/");
+  return Rest.trim();
+}
+
 } // namespace clang::tooling
Index: clang/include/clang/Tooling/Inclusions/HeaderAnalysis.h
===
--- clang/include/clang/Tooling/Inclusions/HeaderAnalysis.h
+++ clang/include/clang/Tooling/Inclusions/HeaderAnalysis.h
@@ -9,6 +9,8 @@
 #ifndef LLVM_CLANG_TOOLING_INCLUSIONS_HEADER_ANALYSIS_H
 #define LLVM_CLANG_TOOLING_INCLUSIONS_HEADER_ANALYSIS_H
 
+#include "llvm/ADT/Optional.h"
+#include "llvm/ADT/StringRef.h"
 namespace clang {
 class FileEntry;
 class SourceManager;
@@ -27,6 +29,13 @@
 bool isSelfContainedHeader(const FileEntry *FE, const SourceManager &SM,
HeaderSearch &HeaderInfo);
 
+/// If Text begins an Include-What-You-Use directive, returns it.
+/// Given "// IWYU pragma: keep", returns "keep".
+/// Input is a null-terminated char* as provided by SM.getCharacterData().
+/// (This should not be StringRef as we do *not* want to scan for its length).
+/// For multi-line comments, we return only the first line.
+llvm::Optional parseIWYUPragma(const char *Text);
+
 } // namespace tooling
 } // namespace clang
 
Index: clang-tools-extra/include-cleaner/lib/Record.cpp
===
--- clang-tools-extra/include-cleaner/lib/Record.cpp
+++ clang-tools-extra/include-cleaner/lib/Record.cpp
@@ -141,21 +141,6 @@
 
 } // namespace
 
-// FIXME: this is a mirror of clang::clangd::parseIWYUPragma, move to libTooling
-// to share the code?
-static llvm::Optional parseIWYUPragma(const char *Text) {
-  assert(strncmp(Text, "//", 2) || strncmp(Text, "/*", 2));
-  constexpr llvm::StringLiteral IWYUPragma = " IWYU pragma: ";
-  Text += 2; // Skip the comment start, // or /*.
-  if (strncmp(Text, IWYUPragma.data(), IWYUPragma.size()))
-

[PATCH] D138777: [clang-tidy] Add check bugprone-multiple-new-in-one-expression.

2022-11-28 Thread Daniel Krupp via Phabricator via cfe-commits
dkrupp added a comment.

Thanks for this new check. Could you please link here results of this checker 
on som relevant open source projects?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D138777/new/

https://reviews.llvm.org/D138777

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


[PATCH] D137205: [clang-tidy] Add performance-unnecessary-copy-on-last-use check

2022-11-28 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

In D137205#3952864 , @carlosgalvezp 
wrote:

>> by design clang-format only performs white-space changes
>
> clang-format does support east/west const enforcement with the 
> `QualifierAlignment` option. From experience, I strongly encourage repo 
> owners to enable it repo-wide to avoid these kinds of discussions.

FWIW, one reason this isn't enabled is that it's relatively recent and also not 
completely safe  in principle.
It's not as simple as "if LLVM cares about const-alignment, this flag should be 
on".

(And I don't think @carlosgalvezp was saying it was that simple! I'm just 
saying we can't rehash the discussion here because it's too big - maybe we 
should elsewhere).

> Until then, I believe developers should keep consistency with the existing 
> style in the codebase, regardless of personal views. This goes in line with 
> the LLVM Coding Standards:

+1


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D137205/new/

https://reviews.llvm.org/D137205

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


[PATCH] D136078: [RFC] Use-after-return binary metadata.

2022-11-28 Thread Dmitry Vyukov via Phabricator via cfe-commits
dvyukov added a comment.

PTAL

I've named everything consistently as "SanitizeBinaryMetadata",
fixed interning of metadata, and added a test.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D136078/new/

https://reviews.llvm.org/D136078

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


[clang] 7940888 - [AMDGPU] Intrinsic to expose s_wait_event for export ready

2022-11-28 Thread David Stuttard via cfe-commits

Author: David Stuttard
Date: 2022-11-28T11:26:15Z
New Revision: 7940888c5987de2b5cbb4ec45b482df88e822f67

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

LOG: [AMDGPU] Intrinsic to expose s_wait_event for export ready

Differential Revision: https://reviews.llvm.org/D138216

Added: 
llvm/test/CodeGen/AMDGPU/llvm.amdgcn.s.wait.event.ll

Modified: 
clang/include/clang/Basic/BuiltinsAMDGPU.def
clang/test/CodeGenOpenCL/builtins-amdgcn-gfx11.cl
llvm/include/llvm/IR/IntrinsicsAMDGPU.td
llvm/lib/Target/AMDGPU/SOPInstructions.td

Removed: 




diff  --git a/clang/include/clang/Basic/BuiltinsAMDGPU.def 
b/clang/include/clang/Basic/BuiltinsAMDGPU.def
index d4d16d5a9563d..5e64f830fb850 100644
--- a/clang/include/clang/Basic/BuiltinsAMDGPU.def
+++ b/clang/include/clang/Basic/BuiltinsAMDGPU.def
@@ -261,6 +261,7 @@ TARGET_BUILTIN(__builtin_amdgcn_image_bvh_intersect_ray_lh, 
"V4UiWUifV4fV4hV4hV4
 
 // TODO: This is a no-op in wave32. Should the builtin require wavefrontsize64?
 TARGET_BUILTIN(__builtin_amdgcn_permlane64, "UiUi", "nc", "gfx11-insts")
+TARGET_BUILTIN(__builtin_amdgcn_s_wait_event_export_ready, "v", "n", 
"gfx11-insts")
 
 
//===--===//
 // WMMA builtins.

diff  --git a/clang/test/CodeGenOpenCL/builtins-amdgcn-gfx11.cl 
b/clang/test/CodeGenOpenCL/builtins-amdgcn-gfx11.cl
index a4f2d610afa83..59a16900fb1a4 100644
--- a/clang/test/CodeGenOpenCL/builtins-amdgcn-gfx11.cl
+++ b/clang/test/CodeGenOpenCL/builtins-amdgcn-gfx11.cl
@@ -37,3 +37,9 @@ void test_ds_bvh_stack_rtn(global uint2* out, uint addr, uint 
data, uint4 data1)
 void test_permlane64(global uint* out, uint a) {
   *out = __builtin_amdgcn_permlane64(a);
 }
+
+// CHECK-LABEL: @test_s_wait_event_export_ready
+// CHECK: call void @llvm.amdgcn.s.wait.event.export.ready
+void test_s_wait_event_export_ready() {
+  __builtin_amdgcn_s_wait_event_export_ready();
+}

diff  --git a/llvm/include/llvm/IR/IntrinsicsAMDGPU.td 
b/llvm/include/llvm/IR/IntrinsicsAMDGPU.td
index 8f05eb10920c7..3e9233b1f86f9 100644
--- a/llvm/include/llvm/IR/IntrinsicsAMDGPU.td
+++ b/llvm/include/llvm/IR/IntrinsicsAMDGPU.td
@@ -2067,6 +2067,10 @@ def int_amdgcn_wmma_bf16_16x16x16_bf16 : 
AMDGPUWmmaIntrinsicOPSEL;
 def int_amdgcn_wmma_i32_16x16x16_iu4   : AMDGPUWmmaIntrinsicIU;
 
+def int_amdgcn_s_wait_event_export_ready :
+  ClangBuiltin<"__builtin_amdgcn_s_wait_event_export_ready">,
+  Intrinsic<[], [], [IntrNoMem, IntrHasSideEffects, IntrWillReturn]
+>;
 
 
//===--===//
 // Deep learning intrinsics.

diff  --git a/llvm/lib/Target/AMDGPU/SOPInstructions.td 
b/llvm/lib/Target/AMDGPU/SOPInstructions.td
index 674da1f0ae4a5..ce0b0dfc48ced 100644
--- a/llvm/lib/Target/AMDGPU/SOPInstructions.td
+++ b/llvm/lib/Target/AMDGPU/SOPInstructions.td
@@ -1388,7 +1388,9 @@ let SubtargetPredicate = isGFX10Plus in {
 
 let SubtargetPredicate = isGFX11Plus in {
   def S_WAIT_EVENT : SOPP_Pseudo<"s_wait_event", (ins s16imm:$simm16),
- "$simm16">;
+ "$simm16"> {
+   let hasSideEffects = 1;
+ }
   def S_DELAY_ALU : SOPP_Pseudo<"s_delay_alu", (ins DELAY_FLAG:$simm16),
 "$simm16">;
 } // End SubtargetPredicate = isGFX11Plus
@@ -1430,6 +1432,10 @@ def : GCNPat<
   (S_SEXT_I32_I16 $src)
 >;
 
+def : GCNPat <
+  (int_amdgcn_s_wait_event_export_ready),
+(S_WAIT_EVENT (i16 0))
+>;
 
 
//===--===//
 // SOP2 Patterns

diff  --git a/llvm/test/CodeGen/AMDGPU/llvm.amdgcn.s.wait.event.ll 
b/llvm/test/CodeGen/AMDGPU/llvm.amdgcn.s.wait.event.ll
new file mode 100644
index 0..3e95e4dec67a2
--- /dev/null
+++ b/llvm/test/CodeGen/AMDGPU/llvm.amdgcn.s.wait.event.ll
@@ -0,0 +1,15 @@
+; RUN: llc -global-isel=0 -march=amdgcn -verify-machineinstrs -mcpu=gfx1100 < 
%s | FileCheck -check-prefix=GCN %s
+; RUN: llc -global-isel -march=amdgcn -verify-machineinstrs -mcpu=gfx1100 < %s 
| FileCheck -check-prefix=GCN %s
+
+; GCN-LABEL: {{^}}test_wait_event:
+; GCN: s_wait_event 0x0
+
+define amdgpu_ps void @test_wait_event() #0 {
+entry:
+  call void @llvm.amdgcn.s.wait.event.export.ready() #0
+  ret void
+}
+
+declare void @llvm.amdgcn.s.wait.event.export.ready() #0
+
+attributes #0 = { nounwind }



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


[PATCH] D138216: [AMDGPU] Intrinsic to expose s_wait_event for export ready

2022-11-28 Thread David Stuttard via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG7940888c5987: [AMDGPU] Intrinsic to expose s_wait_event for 
export ready (authored by dstuttard).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D138216/new/

https://reviews.llvm.org/D138216

Files:
  clang/include/clang/Basic/BuiltinsAMDGPU.def
  clang/test/CodeGenOpenCL/builtins-amdgcn-gfx11.cl
  llvm/include/llvm/IR/IntrinsicsAMDGPU.td
  llvm/lib/Target/AMDGPU/SOPInstructions.td
  llvm/test/CodeGen/AMDGPU/llvm.amdgcn.s.wait.event.ll


Index: llvm/test/CodeGen/AMDGPU/llvm.amdgcn.s.wait.event.ll
===
--- /dev/null
+++ llvm/test/CodeGen/AMDGPU/llvm.amdgcn.s.wait.event.ll
@@ -0,0 +1,15 @@
+; RUN: llc -global-isel=0 -march=amdgcn -verify-machineinstrs -mcpu=gfx1100 < 
%s | FileCheck -check-prefix=GCN %s
+; RUN: llc -global-isel -march=amdgcn -verify-machineinstrs -mcpu=gfx1100 < %s 
| FileCheck -check-prefix=GCN %s
+
+; GCN-LABEL: {{^}}test_wait_event:
+; GCN: s_wait_event 0x0
+
+define amdgpu_ps void @test_wait_event() #0 {
+entry:
+  call void @llvm.amdgcn.s.wait.event.export.ready() #0
+  ret void
+}
+
+declare void @llvm.amdgcn.s.wait.event.export.ready() #0
+
+attributes #0 = { nounwind }
Index: llvm/lib/Target/AMDGPU/SOPInstructions.td
===
--- llvm/lib/Target/AMDGPU/SOPInstructions.td
+++ llvm/lib/Target/AMDGPU/SOPInstructions.td
@@ -1388,7 +1388,9 @@
 
 let SubtargetPredicate = isGFX11Plus in {
   def S_WAIT_EVENT : SOPP_Pseudo<"s_wait_event", (ins s16imm:$simm16),
- "$simm16">;
+ "$simm16"> {
+   let hasSideEffects = 1;
+ }
   def S_DELAY_ALU : SOPP_Pseudo<"s_delay_alu", (ins DELAY_FLAG:$simm16),
 "$simm16">;
 } // End SubtargetPredicate = isGFX11Plus
@@ -1430,6 +1432,10 @@
   (S_SEXT_I32_I16 $src)
 >;
 
+def : GCNPat <
+  (int_amdgcn_s_wait_event_export_ready),
+(S_WAIT_EVENT (i16 0))
+>;
 
 
//===--===//
 // SOP2 Patterns
Index: llvm/include/llvm/IR/IntrinsicsAMDGPU.td
===
--- llvm/include/llvm/IR/IntrinsicsAMDGPU.td
+++ llvm/include/llvm/IR/IntrinsicsAMDGPU.td
@@ -2067,6 +2067,10 @@
 def int_amdgcn_wmma_i32_16x16x16_iu8   : AMDGPUWmmaIntrinsicIU;
 def int_amdgcn_wmma_i32_16x16x16_iu4   : AMDGPUWmmaIntrinsicIU;
 
+def int_amdgcn_s_wait_event_export_ready :
+  ClangBuiltin<"__builtin_amdgcn_s_wait_event_export_ready">,
+  Intrinsic<[], [], [IntrNoMem, IntrHasSideEffects, IntrWillReturn]
+>;
 
 
//===--===//
 // Deep learning intrinsics.
Index: clang/test/CodeGenOpenCL/builtins-amdgcn-gfx11.cl
===
--- clang/test/CodeGenOpenCL/builtins-amdgcn-gfx11.cl
+++ clang/test/CodeGenOpenCL/builtins-amdgcn-gfx11.cl
@@ -37,3 +37,9 @@
 void test_permlane64(global uint* out, uint a) {
   *out = __builtin_amdgcn_permlane64(a);
 }
+
+// CHECK-LABEL: @test_s_wait_event_export_ready
+// CHECK: call void @llvm.amdgcn.s.wait.event.export.ready
+void test_s_wait_event_export_ready() {
+  __builtin_amdgcn_s_wait_event_export_ready();
+}
Index: clang/include/clang/Basic/BuiltinsAMDGPU.def
===
--- clang/include/clang/Basic/BuiltinsAMDGPU.def
+++ clang/include/clang/Basic/BuiltinsAMDGPU.def
@@ -261,6 +261,7 @@
 
 // TODO: This is a no-op in wave32. Should the builtin require wavefrontsize64?
 TARGET_BUILTIN(__builtin_amdgcn_permlane64, "UiUi", "nc", "gfx11-insts")
+TARGET_BUILTIN(__builtin_amdgcn_s_wait_event_export_ready, "v", "n", 
"gfx11-insts")
 
 
//===--===//
 // WMMA builtins.


Index: llvm/test/CodeGen/AMDGPU/llvm.amdgcn.s.wait.event.ll
===
--- /dev/null
+++ llvm/test/CodeGen/AMDGPU/llvm.amdgcn.s.wait.event.ll
@@ -0,0 +1,15 @@
+; RUN: llc -global-isel=0 -march=amdgcn -verify-machineinstrs -mcpu=gfx1100 < %s | FileCheck -check-prefix=GCN %s
+; RUN: llc -global-isel -march=amdgcn -verify-machineinstrs -mcpu=gfx1100 < %s | FileCheck -check-prefix=GCN %s
+
+; GCN-LABEL: {{^}}test_wait_event:
+; GCN: s_wait_event 0x0
+
+define amdgpu_ps void @test_wait_event() #0 {
+entry:
+  call void @llvm.amdgcn.s.wait.event.export.ready() #0
+  ret void
+}
+
+declare void @llvm.amdgcn.s.wait.event.export.ready() #0
+
+attributes #0 = { nounwind }
Index: llvm/lib/Target/AMDGPU/SOPInstructions.td
===
--- llvm/lib/Target/AMDGPU/SOPInstructions.td
+++ llvm/lib/Target/AMDGPU/SOPInstructions.td
@@ -1388,

[PATCH] D138788: [SVE] Change some bfloat lane intrinsics to use i32 immediates

2022-11-28 Thread David Sherwood via Phabricator via cfe-commits
david-arm created this revision.
david-arm added reviewers: sdesmalen, paulwalker-arm, kmclaughlin.
Herald added subscribers: ctetreau, psnobl, hiraditya, tschuett.
Herald added a reviewer: efriedma.
Herald added a project: All.
david-arm requested review of this revision.
Herald added projects: clang, LLVM.
Herald added subscribers: llvm-commits, cfe-commits.

Almost all of the other SVE LLVM IR intrinsics take i32 values
for lane indices or other immediates. We should bring the bfloat
intrinsics in line with that. It will also make it easier to
add support for the SVE2.1 float intrinsics in future, since
they reuse the same underlying instruction classes.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D138788

Files:
  clang/include/clang/Basic/arm_sve.td
  clang/test/CodeGen/aarch64-sve-intrinsics/acle_sve_bfdot.c
  clang/test/CodeGen/aarch64-sve-intrinsics/acle_sve_bfmlalb.c
  clang/test/CodeGen/aarch64-sve-intrinsics/acle_sve_bfmlalt.c
  llvm/include/llvm/IR/IntrinsicsAArch64.td
  llvm/lib/Target/AArch64/AArch64SVEInstrInfo.td
  llvm/lib/Target/AArch64/SVEInstrFormats.td
  llvm/test/CodeGen/AArch64/sve-intrinsics-bfloat.ll

Index: llvm/test/CodeGen/AArch64/sve-intrinsics-bfloat.ll
===
--- llvm/test/CodeGen/AArch64/sve-intrinsics-bfloat.ll
+++ llvm/test/CodeGen/AArch64/sve-intrinsics-bfloat.ll
@@ -19,7 +19,7 @@
 ; CHECK:   // %bb.0:
 ; CHECK-NEXT:bfdot z0.s, z1.h, z2.h[0]
 ; CHECK-NEXT:ret
-  %out = call  @llvm.aarch64.sve.bfdot.lane( %a,  %b,  %c, i64 0)
+  %out = call  @llvm.aarch64.sve.bfdot.lane( %a,  %b,  %c, i32 0)
   ret  %out
 }
 
@@ -28,7 +28,7 @@
 ; CHECK:   // %bb.0:
 ; CHECK-NEXT:bfdot z0.s, z1.h, z2.h[1]
 ; CHECK-NEXT:ret
-  %out = call  @llvm.aarch64.sve.bfdot.lane( %a,  %b,  %c, i64 1)
+  %out = call  @llvm.aarch64.sve.bfdot.lane( %a,  %b,  %c, i32 1)
   ret  %out
 }
 
@@ -37,7 +37,7 @@
 ; CHECK:   // %bb.0:
 ; CHECK-NEXT:bfdot z0.s, z1.h, z2.h[2]
 ; CHECK-NEXT:ret
-  %out = call  @llvm.aarch64.sve.bfdot.lane( %a,  %b,  %c, i64 2)
+  %out = call  @llvm.aarch64.sve.bfdot.lane( %a,  %b,  %c, i32 2)
   ret  %out
 }
 
@@ -46,7 +46,7 @@
 ; CHECK:   // %bb.0:
 ; CHECK-NEXT:bfdot z0.s, z1.h, z2.h[3]
 ; CHECK-NEXT:ret
-  %out = call  @llvm.aarch64.sve.bfdot.lane( %a,  %b,  %c, i64 3)
+  %out = call  @llvm.aarch64.sve.bfdot.lane( %a,  %b,  %c, i32 3)
   ret  %out
 }
 
@@ -68,7 +68,7 @@
 ; CHECK:   // %bb.0:
 ; CHECK-NEXT:bfmlalb z0.s, z1.h, z2.h[0]
 ; CHECK-NEXT:ret
-  %out = call  @llvm.aarch64.sve.bfmlalb.lane( %a,  %b,  %c, i64 0)
+  %out = call  @llvm.aarch64.sve.bfmlalb.lane( %a,  %b,  %c, i32 0)
   ret  %out
 }
 
@@ -77,7 +77,7 @@
 ; CHECK:   // %bb.0:
 ; CHECK-NEXT:bfmlalb z0.s, z1.h, z2.h[1]
 ; CHECK-NEXT:ret
-  %out = call  @llvm.aarch64.sve.bfmlalb.lane( %a,  %b,  %c, i64 1)
+  %out = call  @llvm.aarch64.sve.bfmlalb.lane( %a,  %b,  %c, i32 1)
   ret  %out
 }
 
@@ -86,7 +86,7 @@
 ; CHECK:   // %bb.0:
 ; CHECK-NEXT:bfmlalb z0.s, z1.h, z2.h[2]
 ; CHECK-NEXT:ret
-  %out = call  @llvm.aarch64.sve.bfmlalb.lane( %a,  %b,  %c, i64 2)
+  %out = call  @llvm.aarch64.sve.bfmlalb.lane( %a,  %b,  %c, i32 2)
   ret  %out
 }
 
@@ -95,7 +95,7 @@
 ; CHECK:   // %bb.0:
 ; CHECK-NEXT:bfmlalb z0.s, z1.h, z2.h[3]
 ; CHECK-NEXT:ret
-  %out = call  @llvm.aarch64.sve.bfmlalb.lane( %a,  %b,  %c, i64 3)
+  %out = call  @llvm.aarch64.sve.bfmlalb.lane( %a,  %b,  %c, i32 3)
   ret  %out
 }
 
@@ -104,7 +104,7 @@
 ; CHECK:   // %bb.0:
 ; CHECK-NEXT:bfmlalb z0.s, z1.h, z2.h[4]
 ; CHECK-NEXT:ret
-  %out = call  @llvm.aarch64.sve.bfmlalb.lane( %a,  %b,  %c, i64 4)
+  %out = call  @llvm.aarch64.sve.bfmlalb.lane( %a,  %b,  %c, i32 4)
   ret  %out
 }
 
@@ -113,7 +113,7 @@
 ; CHECK:   // %bb.0:
 ; CHECK-NEXT:bfmlalb z0.s, z1.h, z2.h[5]
 ; CHECK-NEXT:ret
-  %out = call  @llvm.aarch64.sve.bfmlalb.lane( %a,  %b,  %c, i64 5)
+  %out = call  @llvm.aarch64.sve.bfmlalb.lane( %a,  %b,  %c, i32 5)
   ret  %out
 }
 
@@ -122,7 +122,7 @@
 ; CHECK:   // %bb.0:
 ; CHECK-NEXT:bfmlalb z0.s, z1.h, z2.h[6]
 ; CHECK-NEXT:ret
-  %out = call  @llvm.aarch64.sve.bfmlalb.lane( %a,  %b,  %c, i64 6)
+  %out = call  @llvm.aarch64.sve.bfmlalb.lane( %a,  %b,  %c, i32 6)
   ret  %out
 }
 
@@ -131,7 +131,7 @@
 ; CHECK:   // %bb.0:
 ; CHECK-NEXT:bfmlalb z0.s, z1.h, z2.h[7]
 ; CHECK-NEXT:ret
-  %out = call  @llvm.aarch64.sve.bfmlalb.lane( %a,  %b,  %c, i64 7)
+  %out = call  @llvm.aarch64.sve.bfmlalb.lane( %a,  %b,  %c, i32 7)
   ret  %out
 }
 
@@ -153,7 +153,7 @@
 ; CHECK:   // %bb.0:
 ; CHECK-NEXT:bfmlalt z0.s, z1.h, z2.h[0]
 ; CHECK-NEXT:ret
-  %out = call  @llvm.aarch64.sve.bfmlalt.lane( %a,  %b,  %c, i64 0)
+  %out = call  @llvm.aarch64.sve.bfmlalt.lane( %a,  %b,  %c, i32 0)
   ret  %out
 }
 
@@ -162,7 +162,7 @@
 ; CHECK:   // %bb.0:
 ; CHECK-NEXT:bfmlalt z0.s, z1.h, z2.h[1]
 ; CHECK-NEXT:ret
-  %out = cal

[clang] dbb94b4 - [analyzer] Remove the unused LocalCheckers.h header

2022-11-28 Thread Balazs Benics via cfe-commits

Author: Balazs Benics
Date: 2022-11-28T13:08:38+01:00
New Revision: dbb94b415a00c444d6f91809dfcbb989d970c63e

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

LOG: [analyzer] Remove the unused LocalCheckers.h header

Added: 


Modified: 
clang/docs/tools/clang-formatted-files.txt
clang/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp

Removed: 
clang/include/clang/StaticAnalyzer/Checkers/LocalCheckers.h



diff  --git a/clang/docs/tools/clang-formatted-files.txt 
b/clang/docs/tools/clang-formatted-files.txt
index 715e1731af86e..898e75118e015 100644
--- a/clang/docs/tools/clang-formatted-files.txt
+++ b/clang/docs/tools/clang-formatted-files.txt
@@ -230,7 +230,6 @@ clang/include/clang/Sema/TemplateInstCallback.h
 clang/include/clang/Serialization/ASTBitCodes.h
 clang/include/clang/Serialization/InMemoryModuleCache.h
 clang/include/clang/Serialization/SerializationDiagnostic.h
-clang/include/clang/StaticAnalyzer/Checkers/LocalCheckers.h
 clang/include/clang/StaticAnalyzer/Core/CheckerRegistryData.h
 clang/include/clang/StaticAnalyzer/Core/BugReporter/CommonBugCategories.h
 clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicCastInfo.h

diff  --git a/clang/include/clang/StaticAnalyzer/Checkers/LocalCheckers.h 
b/clang/include/clang/StaticAnalyzer/Checkers/LocalCheckers.h
deleted file mode 100644
index 8f7148fde19a0..0
--- a/clang/include/clang/StaticAnalyzer/Checkers/LocalCheckers.h
+++ /dev/null
@@ -1,27 +0,0 @@
-//==- LocalCheckers.h - Intra-Procedural+Flow-Sensitive Checkers -*- 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
-//
-//===--===//
-//
-//  This file defines the interface to call a set of intra-procedural (local)
-//  checkers that use flow/path-sensitive analyses to find bugs.
-//
-//===--===//
-
-#ifndef LLVM_CLANG_STATICANALYZER_CHECKERS_LOCALCHECKERS_H
-#define LLVM_CLANG_STATICANALYZER_CHECKERS_LOCALCHECKERS_H
-
-namespace clang {
-namespace ento {
-
-class ExprEngine;
-
-void RegisterCallInliner(ExprEngine &Eng);
-
-} // end namespace ento
-} // end namespace clang
-
-#endif

diff  --git a/clang/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp 
b/clang/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
index ca0a66f54cedc..54e0f4bee5eb6 100644
--- a/clang/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
+++ b/clang/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
@@ -27,7 +27,6 @@
 #include "clang/Frontend/CompilerInstance.h"
 #include "clang/Lex/Preprocessor.h"
 #include "clang/Rewrite/Core/Rewriter.h"
-#include "clang/StaticAnalyzer/Checkers/LocalCheckers.h"
 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
 #include "clang/StaticAnalyzer/Core/CheckerManager.h"



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


[PATCH] D137205: [clang-tidy] Add performance-unnecessary-copy-on-last-use check

2022-11-28 Thread Carlos Galvez via Phabricator via cfe-commits
carlosgalvezp added a comment.

> we can't rehash the discussion here because it's too big

Indeed, it's a major task to undertake so I don't mean to hijack this thread 
with that :) Just wanted to point out clang-format supports it in case it's of 
interest (it's a fairly new addition that not everyone might be aware of).


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D137205/new/

https://reviews.llvm.org/D137205

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


[PATCH] D138780: [include-cleaner] Merge 2 parseIWYUPragma impls in libToolingInclusions

2022-11-28 Thread Haojian Wu via Phabricator via cfe-commits
hokein accepted this revision.
hokein added a comment.
This revision is now accepted and ready to land.

Thanks!


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D138780/new/

https://reviews.llvm.org/D138780

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


[PATCH] D138782: [include-cleaner] Implement IWYU begin_keep/end_keep pragma support.

2022-11-28 Thread Haojian Wu via Phabricator via cfe-commits
hokein added inline comments.



Comment at: clang-tools-extra/include-cleaner/lib/Record.cpp:299
+  } else if (Pragma->starts_with("end_keep")) {
+InsidePragmaKeepBlock = false;
+  }

using a simple variable is not enough to handle the nested case like 

```
// IWYU pragma: begin_keep
#include "keep1.h" 
// IWYU pragma: begin_keep
#include "keep2.h" 
#include "keep3.h"
// IWYU pragma: end_keep
#include "keep4.h"
// IWYU pragma: end_keep
```

now `keep4.h` is marked as unkeeped. I think we need to maintain a stack for 
`Keep` here (we already have a similar pattern for `export`)


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D138782/new/

https://reviews.llvm.org/D138782

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


[clang] 99b5ec1 - [include-cleaner] Merge 2 parseIWYUPragma impls in libToolingInclusions

2022-11-28 Thread Sam McCall via cfe-commits

Author: Sam McCall
Date: 2022-11-28T13:20:09+01:00
New Revision: 99b5ec1fd1a70680a8483e5efb86807254e44e0e

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

LOG: [include-cleaner] Merge 2 parseIWYUPragma impls in libToolingInclusions

Based on include-cleaner's version, but:

- remove assert that can fail for input `/\* */`
- assert was also checking the wrong condition: that the prefix *differed* from
  either `//` or from `/*`. Avoid use of strncmp where we can.
- add a comment that the brittleness of the text matching is intentional

Differential Revision: https://reviews.llvm.org/D138780

Added: 


Modified: 
clang-tools-extra/clangd/Headers.cpp
clang-tools-extra/clangd/Headers.h
clang-tools-extra/clangd/unittests/HeadersTests.cpp
clang-tools-extra/include-cleaner/lib/Record.cpp
clang/include/clang/Tooling/Inclusions/HeaderAnalysis.h
clang/lib/Tooling/Inclusions/HeaderAnalysis.cpp
clang/unittests/Tooling/HeaderAnalysisTest.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/Headers.cpp 
b/clang-tools-extra/clangd/Headers.cpp
index f276f5bd8c6c1..c808c6f2bcc51 100644
--- a/clang-tools-extra/clangd/Headers.cpp
+++ b/clang-tools-extra/clangd/Headers.cpp
@@ -23,18 +23,6 @@
 namespace clang {
 namespace clangd {
 
-llvm::Optional parseIWYUPragma(const char *Text) {
-  // This gets called for every comment seen in the preamble, so it's quite 
hot.
-  constexpr llvm::StringLiteral IWYUPragma = "// IWYU pragma: ";
-  if (strncmp(Text, IWYUPragma.data(), IWYUPragma.size()))
-return llvm::None;
-  Text += IWYUPragma.size();
-  const char *End = Text;
-  while (*End != 0 && *End != '\n')
-++End;
-  return StringRef(Text, End - Text);
-}
-
 class IncludeStructure::RecordHeaders : public PPCallbacks,
 public CommentHandler {
 public:
@@ -136,7 +124,8 @@ class IncludeStructure::RecordHeaders : public PPCallbacks,
   }
 
   bool HandleComment(Preprocessor &PP, SourceRange Range) override {
-auto Pragma = parseIWYUPragma(SM.getCharacterData(Range.getBegin()));
+auto Pragma =
+tooling::parseIWYUPragma(SM.getCharacterData(Range.getBegin()));
 if (!Pragma)
   return false;
 

diff  --git a/clang-tools-extra/clangd/Headers.h 
b/clang-tools-extra/clangd/Headers.h
index ba72ad397bf8f..ff3f063168325 100644
--- a/clang-tools-extra/clangd/Headers.h
+++ b/clang-tools-extra/clangd/Headers.h
@@ -35,12 +35,6 @@ namespace clangd {
 /// Returns true if \p Include is literal include like "path" or .
 bool isLiteralInclude(llvm::StringRef Include);
 
-/// If Text begins an Include-What-You-Use directive, returns it.
-/// Given "// IWYU pragma: keep", returns "keep".
-/// Input is a null-terminated char* as provided by SM.getCharacterData().
-/// (This should not be StringRef as we do *not* want to scan for its length).
-llvm::Optional parseIWYUPragma(const char *Text);
-
 /// Represents a header file to be #include'd.
 struct HeaderFile {
   std::string File;

diff  --git a/clang-tools-extra/clangd/unittests/HeadersTests.cpp 
b/clang-tools-extra/clangd/unittests/HeadersTests.cpp
index 324d4b58a1ef1..cad81d40ffc81 100644
--- a/clang-tools-extra/clangd/unittests/HeadersTests.cpp
+++ b/clang-tools-extra/clangd/unittests/HeadersTests.cpp
@@ -447,18 +447,6 @@ TEST_F(HeadersTest, HasIWYUPragmas) {
   EXPECT_FALSE(Includes.hasIWYUExport(getID("none.h", Includes)));
 }
 
-TEST(Headers, ParseIWYUPragma) {
-  EXPECT_THAT(parseIWYUPragma("// IWYU pragma: keep"), HasValue(Eq("keep")));
-  EXPECT_THAT(parseIWYUPragma("// IWYU pragma: keep\netc"),
-  HasValue(Eq("keep")));
-  EXPECT_EQ(parseIWYUPragma("/* IWYU pragma: keep"), llvm::None)
-  << "Only // comments supported!";
-  EXPECT_EQ(parseIWYUPragma("//  IWYU pragma: keep"), llvm::None)
-  << "Sensitive to whitespace";
-  EXPECT_EQ(parseIWYUPragma("// IWYU pragma:keep"), llvm::None)
-  << "Sensitive to whitespace";
-}
-
 } // namespace
 } // namespace clangd
 } // namespace clang

diff  --git a/clang-tools-extra/include-cleaner/lib/Record.cpp 
b/clang-tools-extra/include-cleaner/lib/Record.cpp
index e93bc14d4b46a..a0aa1ad6845d2 100644
--- a/clang-tools-extra/include-cleaner/lib/Record.cpp
+++ b/clang-tools-extra/include-cleaner/lib/Record.cpp
@@ -141,21 +141,6 @@ class PPRecorder : public PPCallbacks {
 
 } // namespace
 
-// FIXME: this is a mirror of clang::clangd::parseIWYUPragma, move to 
libTooling
-// to share the code?
-static llvm::Optional parseIWYUPragma(const char *Text) {
-  assert(strncmp(Text, "//", 2) || strncmp(Text, "/*", 2));
-  constexpr llvm::StringLiteral IWYUPragma = " IWYU pragma: ";
-  Text += 2; // Skip the comment start, // or /*.
-  if (strncmp(Text, IWYUPragma.data(), IWYUPragma.size()))
-return llvm::None;
-  Te

[PATCH] D138780: [include-cleaner] Merge 2 parseIWYUPragma impls in libToolingInclusions

2022-11-28 Thread Sam McCall via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG99b5ec1fd1a7: [include-cleaner] Merge 2 parseIWYUPragma 
impls in libToolingInclusions (authored by sammccall).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D138780/new/

https://reviews.llvm.org/D138780

Files:
  clang-tools-extra/clangd/Headers.cpp
  clang-tools-extra/clangd/Headers.h
  clang-tools-extra/clangd/unittests/HeadersTests.cpp
  clang-tools-extra/include-cleaner/lib/Record.cpp
  clang/include/clang/Tooling/Inclusions/HeaderAnalysis.h
  clang/lib/Tooling/Inclusions/HeaderAnalysis.cpp
  clang/unittests/Tooling/HeaderAnalysisTest.cpp

Index: clang/unittests/Tooling/HeaderAnalysisTest.cpp
===
--- clang/unittests/Tooling/HeaderAnalysisTest.cpp
+++ clang/unittests/Tooling/HeaderAnalysisTest.cpp
@@ -9,11 +9,14 @@
 #include "clang/Tooling/Inclusions/HeaderAnalysis.h"
 #include "clang/Lex/Preprocessor.h"
 #include "clang/Testing/TestAST.h"
+#include "llvm/Testing/Support/SupportHelpers.h"
 #include "gtest/gtest.h"
 
 namespace clang {
 namespace tooling {
 namespace {
+using llvm::ValueIs;
+using testing::Eq;
 
 TEST(HeaderAnalysisTest, IsSelfContained) {
   TestInputs Inputs;
@@ -58,6 +61,19 @@
   EXPECT_FALSE(isSelfContainedHeader(FM.getFile("bad.h").get(), SM, HI));
 }
 
+TEST(HeaderAnalysisTest, ParseIWYUPragma) {
+  EXPECT_THAT(parseIWYUPragma("// IWYU pragma: keep"), ValueIs(Eq("keep")));
+  EXPECT_THAT(parseIWYUPragma("// IWYU pragma:   keep  me\netc"),
+  ValueIs(Eq("keep  me")));
+  EXPECT_THAT(parseIWYUPragma("/* IWYU pragma: keep */"), ValueIs(Eq("keep")));
+  EXPECT_EQ(parseIWYUPragma("//  IWYU pragma: keep"), llvm::None)
+  << "Prefix is sensitive to whitespace";
+  EXPECT_EQ(parseIWYUPragma("// IWYU pragma:keep"), llvm::None)
+  << "Prefix is sensitive to whitespace";
+  EXPECT_EQ(parseIWYUPragma("/\n* IWYU pragma: keep */"), llvm::None)
+  << "Must start with /* or //";
+}
+
 } // namespace
 } // namespace tooling
 } // namespace clang
Index: clang/lib/Tooling/Inclusions/HeaderAnalysis.cpp
===
--- clang/lib/Tooling/Inclusions/HeaderAnalysis.cpp
+++ clang/lib/Tooling/Inclusions/HeaderAnalysis.cpp
@@ -64,4 +64,28 @@
   const_cast(SM).getMemoryBufferForFileOrNone(FE).value_or(
   llvm::MemoryBufferRef()));
 }
+
+llvm::Optional parseIWYUPragma(const char *Text) {
+  // Skip the comment start, // or /*.
+  if (Text[0] != '/' || (Text[1] != '/' && Text[1] != '*'))
+return llvm::None;
+  bool BlockComment = Text[1] == '*';
+  Text += 2;
+
+  // Per spec, direcitves are whitespace- and case-sensitive.
+  constexpr llvm::StringLiteral IWYUPragma = " IWYU pragma: ";
+  if (strncmp(Text, IWYUPragma.data(), IWYUPragma.size()))
+return llvm::None;
+  Text += IWYUPragma.size();
+  const char *End = Text;
+  while (*End != 0 && *End != '\n')
+++End;
+  StringRef Rest(Text, End - Text);
+  // Strip off whitespace and comment markers to avoid confusion. This isn't
+  // fully-compatible with IWYU, which splits into whitespace-delimited tokens.
+  if (BlockComment)
+Rest.consume_back("*/");
+  return Rest.trim();
+}
+
 } // namespace clang::tooling
Index: clang/include/clang/Tooling/Inclusions/HeaderAnalysis.h
===
--- clang/include/clang/Tooling/Inclusions/HeaderAnalysis.h
+++ clang/include/clang/Tooling/Inclusions/HeaderAnalysis.h
@@ -9,6 +9,8 @@
 #ifndef LLVM_CLANG_TOOLING_INCLUSIONS_HEADER_ANALYSIS_H
 #define LLVM_CLANG_TOOLING_INCLUSIONS_HEADER_ANALYSIS_H
 
+#include "llvm/ADT/Optional.h"
+#include "llvm/ADT/StringRef.h"
 namespace clang {
 class FileEntry;
 class SourceManager;
@@ -27,6 +29,13 @@
 bool isSelfContainedHeader(const FileEntry *FE, const SourceManager &SM,
HeaderSearch &HeaderInfo);
 
+/// If Text begins an Include-What-You-Use directive, returns it.
+/// Given "// IWYU pragma: keep", returns "keep".
+/// Input is a null-terminated char* as provided by SM.getCharacterData().
+/// (This should not be StringRef as we do *not* want to scan for its length).
+/// For multi-line comments, we return only the first line.
+llvm::Optional parseIWYUPragma(const char *Text);
+
 } // namespace tooling
 } // namespace clang
 
Index: clang-tools-extra/include-cleaner/lib/Record.cpp
===
--- clang-tools-extra/include-cleaner/lib/Record.cpp
+++ clang-tools-extra/include-cleaner/lib/Record.cpp
@@ -141,21 +141,6 @@
 
 } // namespace
 
-// FIXME: this is a mirror of clang::clangd::parseIWYUPragma, move to libTooling
-// to share the code?
-static llvm::Optional parseIWYUPragma(const char *Text) {
-  assert(strncmp(Text, "//", 2) || strncmp(Text, "/*", 2));
-  constexpr llvm::StringLite

[PATCH] D138782: [include-cleaner] Implement IWYU begin_keep/end_keep pragma support.

2022-11-28 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo added inline comments.



Comment at: clang-tools-extra/include-cleaner/lib/Record.cpp:299
+  } else if (Pragma->starts_with("end_keep")) {
+InsidePragmaKeepBlock = false;
+  }

hokein wrote:
> using a simple variable is not enough to handle the nested case like 
> 
> ```
> // IWYU pragma: begin_keep
> #include "keep1.h" 
> // IWYU pragma: begin_keep
> #include "keep2.h" 
> #include "keep3.h"
> // IWYU pragma: end_keep
> #include "keep4.h"
> // IWYU pragma: end_keep
> ```
> 
> now `keep4.h` is marked as unkeeped. I think we need to maintain a stack for 
> `Keep` here (we already have a similar pattern for `export`)
Ok, I had no idea this was valid usage :(


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D138782/new/

https://reviews.llvm.org/D138782

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


[PATCH] D138520: [clangd] Make decision forest model optional

2022-11-28 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

Thanks for doing this!




Comment at: clang-tools-extra/clangd/CMakeLists.txt:52
+  list(APPEND COMPLETIONMODEL_SOURCES 
${CMAKE_CURRENT_BINARY_DIR}/CompletionModel.cpp)
+  add_definitions(-DCLANGD_DECISION_FOREST=1)
+endif()

Rather than `add_definitions`, could you instead add a line to 
`clangd/Features.inc.in`, and `#include Features.h` where needed?

There are probably tradeoffs between these approaches, but that's the one we're 
using for other optional features.

We also use `#if` rather than `#if defined()` which ensures we're not 
forgetting to include a definition and getting some default behavior.



Comment at: clang-tools-extra/clangd/CodeComplete.h:129
 
+#if defined(CLANGD_DECISION_FOREST)
+#  define DEFAULT_RANKING_MODEL DecisionForest

this approach feels a bit heavy on the preprocessor, especially for a header.
It makes the decision-forest-less version seem "complete" but at the cost of 
having to understand two variants of the code.

what about:
 - keeping all the existing APIs
 - using `#if` to change the default value of `RankingModel`, but otherwise 
leaving this struct unchanged
 - providing an alternate definition of `evaluateDecisionForest` that just 
calls `std::abort()`
 - having `ClangdMain` exit with an error if DecisionForest is selected and not 
enabled (or simply ignoring the flag)


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D138520/new/

https://reviews.llvm.org/D138520

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


[PATCH] D138792: [AArch64] Improve TargetParser API

2022-11-28 Thread Tomas Matheson via Phabricator via cfe-commits
tmatheson created this revision.
tmatheson added reviewers: lenary, pratlucas, dmgreen, tschuett, DavidSpickett, 
danielkiss.
Herald added subscribers: hiraditya, kristof.beyls.
Herald added a project: All.
tmatheson requested review of this revision.
Herald added subscribers: llvm-commits, cfe-commits, MaskRay.
Herald added projects: clang, LLVM.

The TargetParser depends heavily on a collection of macros and enums to tie
together information about architectures, CPUs and extensions. Over time this
has led to some pretty awkward API choices. For example, recently a custom
operator-- has been added to the enum, which effectively turns iteration into
a graph traversal and makes the ordering of the macro calls in the header
significant. More generally there is a lot of string <-> enum conversion
going on. I think this shows the extent to which the current data structures
are constraining us, and the need for a rethink.

I tried to split this into smaller commits, but couldn't find a way to do it
without requiring people to review a lot of code that would be deleted in the
next patch.

AArch64 only for now, but if it is accepted I will work on the same for ARM.

Key changes:

- Get rid of Arch enum, which is used to bind fields together. Instead of 
passing around ArchKind, use the named ArchInfo objects directly or via 
references.
- The list of all known ArchInfo becomes an array of pointers.
- ArchKind::operator-- is replaced with ArchInfo::operator< etc, which defines 
which architectures are predecessors to each other. This allows features from 
predecessor architectures to be added in a more intuitive way.
- Free functions of the form f(ArchKind) are converted to ArchInfo::f(). Some 
functions become unnecessary and are deleted.
- Version number and profile are added to the ArchInfo. This makes comparison 
of architectures easier and moves a couple of functions out of clang and into 
AArch64TargetParser.
- clang::AArch64TargetInfo ArchInfo is initialised to Armv8a not INVALID.
- AArch64::ArchProfile which is distinct from ARM::ArchProfile
- Give things sensible names and add some comments.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D138792

Files:
  clang/lib/Basic/Targets/AArch64.cpp
  clang/lib/Basic/Targets/AArch64.h
  clang/lib/Driver/ToolChains/Arch/AArch64.cpp
  llvm/include/llvm/Support/AArch64TargetParser.def
  llvm/include/llvm/Support/AArch64TargetParser.h
  llvm/include/llvm/Support/VersionTuple.h
  llvm/lib/Support/AArch64TargetParser.cpp
  llvm/lib/Target/AArch64/AsmParser/AArch64AsmParser.cpp
  llvm/unittests/Support/TargetParserTest.cpp

Index: llvm/unittests/Support/TargetParserTest.cpp
===
--- llvm/unittests/Support/TargetParserTest.cpp
+++ llvm/unittests/Support/TargetParserTest.cpp
@@ -952,11 +952,11 @@
 TEST_P(AArch64CPUTestFixture, testAArch64CPU) {
   ARMCPUTestParams params = GetParam();
 
-  AArch64::ArchKind AK = AArch64::parseCPUArch(params.CPUName);
-  EXPECT_EQ(params.ExpectedArch, AArch64::getArchName(AK));
+  const AArch64::ArchInfo &AI = AArch64::parseCpu(params.CPUName).Arch;
+  EXPECT_EQ(params.ExpectedArch, AI.Name);
 
   uint64_t default_extensions =
-  AArch64::getDefaultExtensions(params.CPUName, AK);
+  AArch64::getDefaultExtensions(params.CPUName, AI);
   EXPECT_PRED_FORMAT2(AssertSameExtensionFlags,
   params.ExpectedFlags, default_extensions);
 }
@@ -1402,14 +1402,14 @@
   // valid, and match the expected 'magic' count.
   EXPECT_EQ(List.size(), NumAArch64CPUArchs);
   for(StringRef CPU : List) {
-EXPECT_NE(AArch64::parseCPUArch(CPU), AArch64::ArchKind::INVALID);
+EXPECT_NE(AArch64::parseCpu(CPU).Arch, AArch64::INVALID);
   }
 }
 
 bool testAArch64Arch(StringRef Arch, StringRef DefaultCPU, StringRef SubArch,
  unsigned ArchAttr) {
-  AArch64::ArchKind AK = AArch64::parseArch(Arch);
-  return AK != AArch64::ArchKind::INVALID;
+  const AArch64::ArchInfo &AI = AArch64::parseArch(Arch);
+  return AI != AArch64::INVALID;
 }
 
 TEST(TargetParserTest, testAArch64Arch) {
@@ -1445,148 +1445,81 @@
   ARMBuildAttrs::CPUArch::v8_A));
 }
 
-bool testAArch64Extension(StringRef CPUName, AArch64::ArchKind AK,
+bool testAArch64Extension(StringRef CPUName, const AArch64::ArchInfo &AI,
   StringRef ArchExt) {
-  return AArch64::getDefaultExtensions(CPUName, AK) &
+  return AArch64::getDefaultExtensions(CPUName, AI) &
  AArch64::parseArchExt(ArchExt);
 }
 
 TEST(TargetParserTest, testAArch64Extension) {
-  EXPECT_FALSE(testAArch64Extension("cortex-a34",
-AArch64::ArchKind::INVALID, "ras"));
-  EXPECT_FALSE(testAArch64Extension("cortex-a35",
-AArch64::ArchKind::INVALID, "ras"));
-  EXPECT_FALSE(testAArch64Extension("cortex-a53",
-AArch64::ArchKind::INVALID, "ras"));
-  EXPECT_TR

[PATCH] D136078: Use-after-return sanitizer binary metadata

2022-11-28 Thread Dmitry Vyukov via Phabricator via cfe-commits
dvyukov added inline comments.



Comment at: llvm/lib/CodeGen/SanitizerBinaryMetadata.cpp:79
+  };
+  MD->replaceOperandWith(1, MDNode::get(F.getContext(), NewAuxMDs));
+  return false;

Should this be a new method on MDBuilder?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D136078/new/

https://reviews.llvm.org/D136078

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


[PATCH] D127462: [Clang] Begin implementing Plan 9 C extensions

2022-11-28 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D127462#3950108 , @ksaunders wrote:

>> Just to check -- do you think (some of) these features are something you 
>> wish to propose to WG14 for adoption into C? e.g., are you aiming to get 
>> multiple compilers to implement Plan 9 extensions to demonstrate to WG14 
>> that this is existing practice in C compilers?
>
> A lot of the Plan 9 extensions were actually adopted by C99 like compound 
> literals and anonymous structures. Although I find these additional 
> extensions interesting and useful, I don't think that they belong in C and 
> they should remain as non-standard extensions. My interests lie in compiling 
> existing code with Clang which utilizes these extensions, rather than 
> encouraging new code to utilize them.
>
> There was actually a proposal to add Plan 9 extensions into the Linux kernel, 
> but Linus rejected it. I personally share his opinion that the silent type 
> conversion that the Plan 9 compilers introduce can be problematic. But on the 
> other hand, they are also very powerful when used judiciously. It's on the 
> LKML here if you're interested: https://lkml.org/lkml/2019/1/9/1127

Thank you for the details (and the later technical explanations as well)! Then 
yes, I'm in agreement that we shouldn't add these extensions at this time. We 
can revisit should anything change in the future.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D127462/new/

https://reviews.llvm.org/D127462

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


[PATCH] D137381: [clang][compiler-rt] Exception escape out of an non-unwinding function is an undefined behaviour

2022-11-28 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri added a comment.

ping. We need to get this going, reminder, this was caught because it caused a 
visible miscompilation.
@rjmccall are you satisfied with the way we emit srcloc info?
@aaron.ballman thoughts on the docs changes?

One unanswered question i have, is if we can get the exception's underlying C++ 
type as a string,
and print it. Also, is it useful to pass `Exn` into the handler? Can we do 
anything useful with it?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D137381/new/

https://reviews.llvm.org/D137381

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


[PATCH] D138779: [include-cleaner] Filter out references that not spelled in the main file.

2022-11-28 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added a comment.

Maybe I am missing some context here, but why are we trying to filter out 
references outside of the main file?
ATM there's no concept of main file in neither walkUsed, it just receives some 
ast nodes for analyzing references to declarations inside these nodes, and the 
second use is directly figuring out what macro is referenced at particular 
locations, so I believe that filtering shouldn't happen for macros at all.
For decls, I can see some reasoning to filter out references that occur outside 
these AST nodes, rather than some notion of main file. Moreover we seem to be 
doing it in both users of walkAST, so maybe it would be better to do that there 
once instead?

This limiting the references to be under ast nodes behaviour has the nasty 
wrinkle of macros defined inside the main file, e.g:

  #define FOO foo()
  void bar() {
FOO;
  }

we should say that `bar` uses `foo` despite the reference location lying 
outside of the AST node.

so maybe we should change the mapping policy from "just use spelling locations" 
to "use spelling location if it is in the same file as the expansion location 
and ignore the reference otherwise"?




Comment at: clang-tools-extra/include-cleaner/lib/Analysis.cpp:20
 
 void walkUsed(llvm::ArrayRef ASTRoots,
   llvm::ArrayRef MacroRefs,

as discussed offline we're introducing this extra constraint on references 
being provided, so let's mention that in the documentation as well. apart from 
that I agree with rest of the comments from Sam


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D138779/new/

https://reviews.llvm.org/D138779

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


[clang-tools-extra] c7fc0ab - [clangd] Add script to maintain list of fast clang-tidy checks

2022-11-28 Thread Sam McCall via cfe-commits

Author: Sam McCall
Date: 2022-11-28T14:29:23+01:00
New Revision: c7fc0abf510fb066c8bf581a5668235b95d00242

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

LOG: [clangd] Add script to maintain list of fast clang-tidy checks

The plan is to intersect this list with the checks selected per config.
This is not yet done, but the initial list is checked in as a baseline.

https://github.com/clangd/clangd/issues/1337

Differential Revision: https://reviews.llvm.org/D138491

Added: 
clang-tools-extra/clangd/TidyFastChecks.inc
clang-tools-extra/clangd/TidyFastChecks.py

Modified: 
clang-tools-extra/clangd/tool/Check.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/TidyFastChecks.inc 
b/clang-tools-extra/clangd/TidyFastChecks.inc
new file mode 100644
index 0..9596ba4d725b6
--- /dev/null
+++ b/clang-tools-extra/clangd/TidyFastChecks.inc
@@ -0,0 +1,378 @@
+// This file is generated, do not edit it directly!
+// Deltas are percentage regression in parsing clang/lib/Sema/Sema.cpp
+#ifndef FAST
+#define FAST(CHECK, DELTA)
+#endif
+#ifndef SLOW
+#define SLOW(CHECK, DELTA)
+#endif
+
+FAST(abseil-cleanup-ctad, -1.0)
+FAST(abseil-duration-addition, 0.0)
+FAST(abseil-duration-comparison, 1.0)
+FAST(abseil-duration-conversion-cast, 3.0)
+FAST(abseil-duration-division, -0.0)
+FAST(abseil-duration-factory-float, 1.0)
+FAST(abseil-duration-factory-scale, -0.0)
+FAST(abseil-duration-subtraction, 1.0)
+FAST(abseil-duration-unnecessary-conversion, 4.0)
+FAST(abseil-faster-strsplit-delimiter, 2.0)
+FAST(abseil-no-internal-dependencies, -1.0)
+FAST(abseil-no-namespace, -1.0)
+FAST(abseil-redundant-strcat-calls, 2.0)
+FAST(abseil-str-cat-append, 1.0)
+FAST(abseil-string-find-startswith, 1.0)
+FAST(abseil-string-find-str-contains, 1.0)
+FAST(abseil-time-comparison, -0.0)
+FAST(abseil-time-subtraction, 0.0)
+FAST(abseil-upgrade-duration-conversions, 2.0)
+SLOW(altera-id-dependent-backward-branch, 13.0)
+FAST(altera-kernel-name-restriction, -1.0)
+FAST(altera-single-work-item-barrier, -1.0)
+FAST(altera-struct-pack-align, -1.0)
+FAST(altera-unroll-loops, 2.0)
+FAST(android-cloexec-accept, -1.0)
+FAST(android-cloexec-accept4, 3.0)
+FAST(android-cloexec-creat, 0.0)
+FAST(android-cloexec-dup, 3.0)
+FAST(android-cloexec-epoll-create, -2.0)
+FAST(android-cloexec-epoll-create1, -1.0)
+FAST(android-cloexec-fopen, -0.0)
+FAST(android-cloexec-inotify-init, 1.0)
+FAST(android-cloexec-inotify-init1, 2.0)
+FAST(android-cloexec-memfd-create, 2.0)
+FAST(android-cloexec-open, -1.0)
+FAST(android-cloexec-pipe, -1.0)
+FAST(android-cloexec-pipe2, 0.0)
+FAST(android-cloexec-socket, 1.0)
+FAST(android-comparison-in-temp-failure-retry, 0.0)
+FAST(boost-use-to-string, 1.0)
+FAST(bugprone-argument-comment, 2.0)
+FAST(bugprone-assert-side-effect, 1.0)
+FAST(bugprone-assignment-in-if-condition, -0.0)
+FAST(bugprone-bad-signal-to-kill-thread, -1.0)
+FAST(bugprone-bool-pointer-implicit-conversion, 0.0)
+FAST(bugprone-branch-clone, -0.0)
+FAST(bugprone-copy-constructor-init, 1.0)
+FAST(bugprone-dangling-handle, 0.0)
+FAST(bugprone-dynamic-static-initializers, 1.0)
+FAST(bugprone-easily-swappable-parameters, 2.0)
+FAST(bugprone-exception-escape, 1.0)
+FAST(bugprone-fold-init-type, 2.0)
+FAST(bugprone-forward-declaration-namespace, 0.0)
+FAST(bugprone-forwarding-reference-overload, -0.0)
+FAST(bugprone-implicit-widening-of-multiplication-result, 3.0)
+FAST(bugprone-inaccurate-erase, -0.0)
+FAST(bugprone-incorrect-roundings, 1.0)
+FAST(bugprone-infinite-loop, 4.0)
+FAST(bugprone-integer-division, -3.0)
+FAST(bugprone-lambda-function-name, 1.0)
+FAST(bugprone-macro-parentheses, 8.0)
+FAST(bugprone-macro-repeated-side-effects, 1.0)
+FAST(bugprone-misplaced-operator-in-strlen-in-alloc, -0.0)
+FAST(bugprone-misplaced-pointer-arithmetic-in-alloc, 2.0)
+FAST(bugprone-misplaced-widening-cast, -2.0)
+FAST(bugprone-move-forwarding-reference, -2.0)
+FAST(bugprone-multiple-statement-macro, 1.0)
+FAST(bugprone-narrowing-conversions, -1.0)
+FAST(bugprone-no-escape, 3.0)
+FAST(bugprone-not-null-terminated-result, 4.0)
+FAST(bugprone-parent-virtual-call, 2.0)
+FAST(bugprone-posix-return, 0.0)
+FAST(bugprone-redundant-branch-condition, 0.0)
+FAST(bugprone-reserved-identifier, 2.0)
+FAST(bugprone-shared-ptr-array-mismatch, 0.0)
+FAST(bugprone-signal-handler, -0.0)
+FAST(bugprone-signed-char-misuse, 1.0)
+FAST(bugprone-sizeof-container, -0.0)
+FAST(bugprone-sizeof-expression, 0.0)
+FAST(bugprone-spuriously-wake-up-functions, 3.0)
+FAST(bugprone-string-constructor, 1.0)
+FAST(bugprone-string-integer-assignment, 1.0)
+FAST(bugprone-string-literal-with-embedded-nul, 0.0)
+FAST(bugprone-stringview-nullptr, 2.0)
+FAST(bugprone-suspicious-enum-usage, -0.0)
+FAST(bugprone-suspicious-include, 1.0)
+FAST(bugprone-suspicious-memory-comparison

[PATCH] D138491: [clangd] Add script to maintain list of fast clang-tidy checks

2022-11-28 Thread Sam McCall via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGc7fc0abf510f: [clangd] Add script to maintain list of fast 
clang-tidy checks (authored by sammccall).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D138491/new/

https://reviews.llvm.org/D138491

Files:
  clang-tools-extra/clangd/TidyFastChecks.inc
  clang-tools-extra/clangd/TidyFastChecks.py
  clang-tools-extra/clangd/tool/Check.cpp

Index: clang-tools-extra/clangd/tool/Check.cpp
===
--- clang-tools-extra/clangd/tool/Check.cpp
+++ clang-tools-extra/clangd/tool/Check.cpp
@@ -241,6 +241,9 @@
 elog("-{0} requires -DCLANGD_TIDY_CHECKS!", CheckTidyTime.ArgStr);
 return false;
   }
+  #ifndef NDEBUG
+  elog("Timing clang-tidy checks in asserts-mode is not representative!");
+  #endif
   checkTidyTimes();
 }
 
Index: clang-tools-extra/clangd/TidyFastChecks.py
===
--- /dev/null
+++ clang-tools-extra/clangd/TidyFastChecks.py
@@ -0,0 +1,95 @@
+#!/usr/bin/env python3
+#
+# Determines which clang-tidy checks are "fast enough" to run in clangd.
+# This runs clangd --check --check-tidy-time and parses the output.
+# This program outputs a header fragment specifying which checks are fast:
+#   FAST(bugprone-argument-comment, 5)
+#   SLOW(misc-const-correctness, 200)
+# If given the old header fragment as input, we lean to preserve its choices.
+#
+# This is not deterministic or hermetic, but should be run occasionally to
+# update the list of allowed checks. From llvm-project:
+#   clang-tools-extra/clangd/TidyFastChecks.py --clangd=build-opt/bin/clangd
+# Be sure to use an optimized, no-asserts, tidy-enabled build of clangd!
+
+import argparse
+import os
+import re
+import subprocess
+import sys
+
+# Checks faster than FAST_THRESHOLD are fast, slower than SLOW_THRESHOLD slow.
+# If a check is in between, we stick with our previous decision. This avoids
+# enabling/disabling checks between releases due to random measurement jitter.
+FAST_THRESHOLD = 8 # percent
+SLOW_THRESHOLD = 15
+
+parser = argparse.ArgumentParser()
+parser.add_argument('--target', help='X-macro output file. '
+'If it exists, existing contents will be used for hysteresis',
+default='clang-tools-extra/clangd/TidyFastChecks.inc')
+parser.add_argument('--source', help='Source file to benchmark tidy checks',
+default='clang/lib/Sema/Sema.cpp')
+parser.add_argument('--clangd', help='clangd binary to invoke',
+default='build/bin/clangd')
+parser.add_argument('--checks', help='check glob to run', default='*')
+parser.add_argument('--verbose', help='log clangd output', action='store_true')
+args = parser.parse_args()
+
+# Use the preprocessor to extract the list of previously-fast checks.
+def read_old_fast(path):
+text = subprocess.check_output(["cpp",
+"-P",# Omit GNU line markers
+"-nostdinc", # Don't include stdc-predef.h
+"-DFAST(C,T)=C", # Print fast checks only
+path])
+for line in text.splitlines():
+if line.strip():
+yield line.strip().decode('utf-8')
+old_fast = list(read_old_fast(args.target)) if os.path.exists(args.target) else []
+print(f"Old fast checks: {old_fast}", file=sys.stderr)
+
+# Runs clangd --check --check-tidy-time.
+# Yields (check, percent-overhead) pairs.
+def measure():
+process = subprocess.Popen([args.clangd,
+"--check=" + args.source,
+"--check-locations=0", # Skip useless slow steps.
+"--check-tidy-time=" + args.checks],
+stderr=subprocess.PIPE)
+recording = False
+for line in iter(process.stderr.readline, b""):
+if args.verbose:
+print("clangd> ", line, file=sys.stderr)
+if not recording:
+if b'Timing AST build with individual clang-tidy checks' in line:  
+   recording = True
+continue
+if b'Finished individual clang-tidy checks' in line:
+return
+match = re.search(rb'(\S+) = (\S+)%', line)
+if match:
+yield (match.group(1).decode('utf-8'), float(match.group(2)))
+
+with open(args.target, 'w', buffering=1) as target:
+# Produce an includable X-macros fragment with our decisions.
+print(f"""// This file is generated, do not edit it directly!
+// Deltas are percentage regression in parsing {args.source}
+#ifndef FAST
+#define FAST(CHECK, DELTA)
+#endif
+#ifndef SLOW
+#define SLOW(CHECK, DELTA)
+#endif
+""", file=target)
+
+for check, time in measure():
+threshold = SLOW_THRESHOLD if check in old_fast else FAST_THRESHOLD
+decision = "FAST" if time <= threshold else "SLOW"
+print(f"{decision} {check} {time}% <= {threshold}%", file=sys.stderr)
+print(f"{decision}({check}, {time})", fi

[PATCH] D138797: [include-cleaner] Implement IWYU begin_keep/end_keep pragma support.

2022-11-28 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo created this revision.
Herald added a subscriber: kadircet.
Herald added a project: All.
VitaNuo requested review of this revision.
Herald added a project: clang-tools-extra.
Herald added a subscriber: cfe-commits.

Implement support for begin_keep/end_keep pragmas.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D138797

Files:
  clang-tools-extra/include-cleaner/lib/Record.cpp
  clang-tools-extra/include-cleaner/unittests/RecordTest.cpp

Index: clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
===
--- clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
+++ clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
@@ -322,15 +322,42 @@
 // IWYU pragma: end_exports
 
 #include "normal.h" // Line 11
+
+// IWYU pragma: begin_keep // Line 13
+#include "keep3.h"
+#include "keep4.h"
+// IWYU pragma: end_keep
+
+// IWYU pragma: begin_keep // Line 18
+#include "keep5.h" 
+// IWYU pragma: begin_keep
+#include "keep6.h" 
+#include "keep7.h"
+// IWYU pragma: end_keep
+#include "keep8.h"
+// IWYU pragma: end_keep
   )cpp";
-  createEmptyFiles({"keep1.h", "keep2.h", "export1.h", "export2.h", "export3.h",
-"normal.h"});
+  createEmptyFiles({"keep1.h", "keep2.h", "keep3.h", "keep4.h", "keep5.h",
+"keep6.h", "keep7.h", "keep8.h", "export1.h", "export2.h",
+"export3.h", "normal.h"});
 
   TestAST Processed = build();
   EXPECT_FALSE(PI.shouldKeep(1));
   // Keep
   EXPECT_TRUE(PI.shouldKeep(2));
   EXPECT_TRUE(PI.shouldKeep(3));
+  EXPECT_FALSE(PI.shouldKeep(13));
+  EXPECT_TRUE(PI.shouldKeep(14));
+  EXPECT_TRUE(PI.shouldKeep(15));
+  EXPECT_FALSE(PI.shouldKeep(16));
+  EXPECT_FALSE(PI.shouldKeep(18));
+  EXPECT_TRUE(PI.shouldKeep(19));
+  EXPECT_FALSE(PI.shouldKeep(20));
+  EXPECT_TRUE(PI.shouldKeep(21));
+  EXPECT_TRUE(PI.shouldKeep(22));
+  EXPECT_FALSE(PI.shouldKeep(23));
+  EXPECT_TRUE(PI.shouldKeep(24));
+  EXPECT_FALSE(PI.shouldKeep(25));
 
   // Exports
   EXPECT_TRUE(PI.shouldKeep(5));
Index: clang-tools-extra/include-cleaner/lib/Record.cpp
===
--- clang-tools-extra/include-cleaner/lib/Record.cpp
+++ clang-tools-extra/include-cleaner/lib/Record.cpp
@@ -186,9 +186,7 @@
 FileID HashFID = SM.getFileID(HashLoc);
 int HashLine = SM.getLineNumber(HashFID, SM.getFileOffset(HashLoc));
 checkForExport(HashFID, HashLine, File ? &File->getFileEntry() : nullptr);
-
-if (InMainFile && LastPragmaKeepInMainFileLine == HashLine)
-  Out->ShouldKeep.insert(HashLine);
+checkForKeep(HashLine);
   }
 
   void checkForExport(FileID IncludingFile, int HashLine,
@@ -212,6 +210,19 @@
   ExportStack.pop_back();
   }
 
+  void checkForKeep(int HashLine) {
+if (!InMainFile || KeepStack.empty())
+  return;
+KeepPragma &Top = KeepStack.back();
+if ((Top.Block && HashLine > Top.SeenAtLine) ||
+Top.SeenAtLine == HashLine) {
+  Out->ShouldKeep.insert(HashLine);
+}
+if (!Top.Block) {
+  KeepStack.pop_back(); // Pop immediately for single-line keep pragma.
+}
+  }
+
   bool HandleComment(Preprocessor &PP, SourceRange Range) override {
 auto &SM = PP.getSourceManager();
 auto Pragma =
@@ -256,23 +267,14 @@
 }
 
 if (InMainFile) {
-  if (!Pragma->startswith("keep"))
-return false;
-  // Given:
-  //
-  // #include "foo.h"
-  // #include "bar.h" // IWYU pragma: keep
-  //
-  // The order in which the callbacks will be triggered:
-  //
-  // 1. InclusionDirective("foo.h")
-  // 2. handleCommentInMainFile("// IWYU pragma: keep")
-  // 3. InclusionDirective("bar.h")
-  //
-  // This code stores the last location of "IWYU pragma: keep" comment in
-  // the main file, so that when next InclusionDirective is called, it will
-  // know that the next inclusion is behind the IWYU pragma.
-  LastPragmaKeepInMainFileLine = CommentLine;
+  if (Pragma->startswith("keep")) {
+KeepStack.push_back({CommentLine, false});
+  } else if (Pragma->starts_with("begin_keep")) {
+KeepStack.push_back({CommentLine, true});
+  } else if (Pragma->starts_with("end_keep") && !KeepStack.empty()) {
+assert(KeepStack.back().Block);
+KeepStack.pop_back();
+  }
 }
 return false;
   }
@@ -287,8 +289,7 @@
   llvm::BumpPtrAllocator Arena;
   /// Intern table for strings. Contents are on the arena.
   llvm::StringSaver UniqueStrings;
-  // Track the last line "IWYU pragma: keep" was seen in the main file, 1-based.
-  int LastPragmaKeepInMainFileLine = -1;
+
   struct ExportPragma {
 // The line number where we saw the begin_exports or export pragma.
 int SeenAtLine = 0; // 1-based line number.
@@ -302,6 +303,16 @@
   };
   // A stack for tracking all open begin_exports or single-line exp

[clang-tools-extra] 551c7e8 - [clangd] Fix broken call missed in D138780

2022-11-28 Thread Sam McCall via cfe-commits

Author: Sam McCall
Date: 2022-11-28T14:36:48+01:00
New Revision: 551c7e81891abcf49aff625187f348ff119c4618

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

LOG: [clangd] Fix broken call missed in D138780

Added: 


Modified: 
clang-tools-extra/clangd/index/CanonicalIncludes.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/index/CanonicalIncludes.cpp 
b/clang-tools-extra/clangd/index/CanonicalIncludes.cpp
index 8568079ca1adb..f123b029f9fb3 100644
--- a/clang-tools-extra/clangd/index/CanonicalIncludes.cpp
+++ b/clang-tools-extra/clangd/index/CanonicalIncludes.cpp
@@ -9,6 +9,7 @@
 #include "CanonicalIncludes.h"
 #include "Headers.h"
 #include "clang/Basic/FileEntry.h"
+#include "clang/Tooling/Inclusions/HeaderAnalysis.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/FileSystem/UniqueID.h"
 #include "llvm/Support/Path.h"
@@ -710,7 +711,7 @@ collectIWYUHeaderMaps(CanonicalIncludes *Includes) {
 PragmaCommentHandler(CanonicalIncludes *Includes) : Includes(Includes) {}
 
 bool HandleComment(Preprocessor &PP, SourceRange Range) override {
-  auto Pragma = parseIWYUPragma(
+  auto Pragma = tooling::parseIWYUPragma(
   PP.getSourceManager().getCharacterData(Range.getBegin()));
   if (!Pragma || !Pragma->consume_front("private, include "))
 return false;



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


[PATCH] D138780: [include-cleaner] Merge 2 parseIWYUPragma impls in libToolingInclusions

2022-11-28 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added a comment.

Looks like it breaks the build:

  llvm-project/clang-tools-extra/clangd/index/CanonicalIncludes.cpp: In member 
function ‘virtual bool 
clang::clangd::collectIWYUHeaderMaps(clang::clangd::CanonicalIncludes*)::PragmaCommentHandler::HandleComment(clang::Preprocessor&,
 clang::SourceRange)’:
  llvm-project/clang-tools-extra/clangd/index/CanonicalIncludes.cpp:713:21: 
error: ‘parseIWYUPragma’ was not declared in this scope
 auto Pragma = parseIWYUPragma(
   ^~~


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D138780/new/

https://reviews.llvm.org/D138780

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


[PATCH] D138520: [clangd] Make decision forest model optional

2022-11-28 Thread Michał Górny via Phabricator via cfe-commits
mgorny added inline comments.



Comment at: clang-tools-extra/clangd/CodeComplete.h:129
 
+#if defined(CLANGD_DECISION_FOREST)
+#  define DEFAULT_RANKING_MODEL DecisionForest

sammccall wrote:
> this approach feels a bit heavy on the preprocessor, especially for a header.
> It makes the decision-forest-less version seem "complete" but at the cost of 
> having to understand two variants of the code.
> 
> what about:
>  - keeping all the existing APIs
>  - using `#if` to change the default value of `RankingModel`, but otherwise 
> leaving this struct unchanged
>  - providing an alternate definition of `evaluateDecisionForest` that just 
> calls `std::abort()`
>  - having `ClangdMain` exit with an error if DecisionForest is selected and 
> not enabled (or simply ignoring the flag)
This is what I originally wanted to do. However, it doesn't seem that this code 
path is covered by the test suite and I have no clue how to use clangd (or at 
least the test suite didn't see it crash when I added fatal asserts to the 
decision forest paths), so I've decided that ensure compile-time failures is 
the safer approach.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D138520/new/

https://reviews.llvm.org/D138520

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


[PATCH] D138797: [include-cleaner] Implement IWYU begin_keep/end_keep pragma support.

2022-11-28 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo updated this revision to Diff 478203.
VitaNuo added a comment.

Add a comment.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D138797/new/

https://reviews.llvm.org/D138797

Files:
  clang-tools-extra/include-cleaner/lib/Record.cpp
  clang-tools-extra/include-cleaner/unittests/RecordTest.cpp

Index: clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
===
--- clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
+++ clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
@@ -322,15 +322,42 @@
 // IWYU pragma: end_exports
 
 #include "normal.h" // Line 11
+
+// IWYU pragma: begin_keep // Line 13
+#include "keep3.h"
+#include "keep4.h"
+// IWYU pragma: end_keep
+
+// IWYU pragma: begin_keep // Line 18
+#include "keep5.h" 
+// IWYU pragma: begin_keep
+#include "keep6.h" 
+#include "keep7.h"
+// IWYU pragma: end_keep
+#include "keep8.h"
+// IWYU pragma: end_keep
   )cpp";
-  createEmptyFiles({"keep1.h", "keep2.h", "export1.h", "export2.h", "export3.h",
-"normal.h"});
+  createEmptyFiles({"keep1.h", "keep2.h", "keep3.h", "keep4.h", "keep5.h",
+"keep6.h", "keep7.h", "keep8.h", "export1.h", "export2.h",
+"export3.h", "normal.h"});
 
   TestAST Processed = build();
   EXPECT_FALSE(PI.shouldKeep(1));
   // Keep
   EXPECT_TRUE(PI.shouldKeep(2));
   EXPECT_TRUE(PI.shouldKeep(3));
+  EXPECT_FALSE(PI.shouldKeep(13));
+  EXPECT_TRUE(PI.shouldKeep(14));
+  EXPECT_TRUE(PI.shouldKeep(15));
+  EXPECT_FALSE(PI.shouldKeep(16));
+  EXPECT_FALSE(PI.shouldKeep(18));
+  EXPECT_TRUE(PI.shouldKeep(19));
+  EXPECT_FALSE(PI.shouldKeep(20));
+  EXPECT_TRUE(PI.shouldKeep(21));
+  EXPECT_TRUE(PI.shouldKeep(22));
+  EXPECT_FALSE(PI.shouldKeep(23));
+  EXPECT_TRUE(PI.shouldKeep(24));
+  EXPECT_FALSE(PI.shouldKeep(25));
 
   // Exports
   EXPECT_TRUE(PI.shouldKeep(5));
Index: clang-tools-extra/include-cleaner/lib/Record.cpp
===
--- clang-tools-extra/include-cleaner/lib/Record.cpp
+++ clang-tools-extra/include-cleaner/lib/Record.cpp
@@ -186,9 +186,7 @@
 FileID HashFID = SM.getFileID(HashLoc);
 int HashLine = SM.getLineNumber(HashFID, SM.getFileOffset(HashLoc));
 checkForExport(HashFID, HashLine, File ? &File->getFileEntry() : nullptr);
-
-if (InMainFile && LastPragmaKeepInMainFileLine == HashLine)
-  Out->ShouldKeep.insert(HashLine);
+checkForKeep(HashLine);
   }
 
   void checkForExport(FileID IncludingFile, int HashLine,
@@ -212,6 +210,20 @@
   ExportStack.pop_back();
   }
 
+  void checkForKeep(int HashLine) {
+if (!InMainFile || KeepStack.empty())
+  return;
+KeepPragma &Top = KeepStack.back();
+// Check if the current include is covered by a keep pragma.
+if ((Top.Block && HashLine > Top.SeenAtLine) ||
+Top.SeenAtLine == HashLine) {
+  Out->ShouldKeep.insert(HashLine);
+}
+if (!Top.Block) {
+  KeepStack.pop_back(); // Pop immediately for single-line keep pragma.
+}
+  }
+
   bool HandleComment(Preprocessor &PP, SourceRange Range) override {
 auto &SM = PP.getSourceManager();
 auto Pragma =
@@ -256,23 +268,14 @@
 }
 
 if (InMainFile) {
-  if (!Pragma->startswith("keep"))
-return false;
-  // Given:
-  //
-  // #include "foo.h"
-  // #include "bar.h" // IWYU pragma: keep
-  //
-  // The order in which the callbacks will be triggered:
-  //
-  // 1. InclusionDirective("foo.h")
-  // 2. handleCommentInMainFile("// IWYU pragma: keep")
-  // 3. InclusionDirective("bar.h")
-  //
-  // This code stores the last location of "IWYU pragma: keep" comment in
-  // the main file, so that when next InclusionDirective is called, it will
-  // know that the next inclusion is behind the IWYU pragma.
-  LastPragmaKeepInMainFileLine = CommentLine;
+  if (Pragma->startswith("keep")) {
+KeepStack.push_back({CommentLine, false});
+  } else if (Pragma->starts_with("begin_keep")) {
+KeepStack.push_back({CommentLine, true});
+  } else if (Pragma->starts_with("end_keep") && !KeepStack.empty()) {
+assert(KeepStack.back().Block);
+KeepStack.pop_back();
+  }
 }
 return false;
   }
@@ -287,8 +290,7 @@
   llvm::BumpPtrAllocator Arena;
   /// Intern table for strings. Contents are on the arena.
   llvm::StringSaver UniqueStrings;
-  // Track the last line "IWYU pragma: keep" was seen in the main file, 1-based.
-  int LastPragmaKeepInMainFileLine = -1;
+
   struct ExportPragma {
 // The line number where we saw the begin_exports or export pragma.
 int SeenAtLine = 0; // 1-based line number.
@@ -302,6 +304,16 @@
   };
   // A stack for tracking all open begin_exports or single-line export.
   std::vector ExportStack;
+
+  struct KeepPragma

[PATCH] D137534: [C++20] [Modules] [ClangScanDeps] Allow clang-scan-deps to without specified compilation database in P1689 (3/3)

2022-11-28 Thread Ben Boeckel via Phabricator via cfe-commits
ben.boeckel added inline comments.



Comment at: clang/tools/clang-scan-deps/ClangScanDeps.cpp:197
+llvm::cl::opt P1689TargetedCommand(
+"p1689-targeted-command", llvm::cl::Optional,
+llvm::cl::desc("Only supported for P1689, the targeted command of which "

ChuanqiXu wrote:
> ben.boeckel wrote:
> > ChuanqiXu wrote:
> > > ben.boeckel wrote:
> > > > Can this be something like `--` so that I don't have to figure out how 
> > > > to quote the thing (for the shell and whatever parsing Clang does 
> > > > internally)?
> > > Yeah, it can. Both `-` and `--` are accepted. I've updated the test to 
> > > disambiguate.
> > I don't mean the flag using `--` as a prefix. I don't care about that. What 
> > I *do* care about is having to quote everything I'd give to `clang` here. 
> > I'd vastly prefer something like:
> > 
> > ```
> > clang-scan-deps -p1689-targeted-file-name=… -p1689-use-command -- -flags 
> > --for ---clang --go --here
> > ```
> I got your point. But I prefer the current style if it won't be a problem for 
> you to quote the options. In my imagination, it would be easier for the build 
> systems to quote the flags than we synthesis things here. I guess there 
> should already be one existing command line in the build system. And I feel 
> like the current style may be more convenient and friendly for other tools to 
> use. Could you try to use the current style?
I don't think CMake has a mechanism for that at all right now. The problem is 
knowing how to quote things. Is it specified how Clang will parse this string 
into arguments? Is it platform-dependent?


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D137534/new/

https://reviews.llvm.org/D137534

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


[PATCH] D138780: [include-cleaner] Merge 2 parseIWYUPragma impls in libToolingInclusions

2022-11-28 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

In D138780#3953229 , @ABataev wrote:

> Looks like it breaks the build:
>
>   llvm-project/clang-tools-extra/clangd/index/CanonicalIncludes.cpp: In 
> member function ‘virtual bool 
> clang::clangd::collectIWYUHeaderMaps(clang::clangd::CanonicalIncludes*)::PragmaCommentHandler::HandleComment(clang::Preprocessor&,
>  clang::SourceRange)’:
>   llvm-project/clang-tools-extra/clangd/index/CanonicalIncludes.cpp:713:21: 
> error: ‘parseIWYUPragma’ was not declared in this scope
>  auto Pragma = parseIWYUPragma(
>^~~

Sorry, this is fixed in 551c7e81891abcf49aff625187f348ff119c4618 
 (I was 
running tests in the wrong terminal...)


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D138780/new/

https://reviews.llvm.org/D138780

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


[PATCH] D138802: [clang][Interp] Implement DecompositionDecls

2022-11-28 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder created this revision.
tbaeder added reviewers: aaron.ballman, erichkeane, tahonermann, shafik.
Herald added a project: All.
tbaeder requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Factor out the actual variable allocation logic into a separate function, so we 
can call it multiple times from `visitVarDecl()` if the variable declaration is 
a `DecompositionDecl()`.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D138802

Files:
  clang/lib/AST/Interp/ByteCodeExprGen.cpp
  clang/lib/AST/Interp/ByteCodeExprGen.h
  clang/lib/AST/Interp/ByteCodeStmtGen.cpp
  clang/lib/AST/Interp/Program.h
  clang/test/AST/Interp/cxx17.cpp

Index: clang/test/AST/Interp/cxx17.cpp
===
--- /dev/null
+++ clang/test/AST/Interp/cxx17.cpp
@@ -0,0 +1,26 @@
+// RUN: %clang_cc1 -fexperimental-new-constant-interpreter -std=c++17 -verify %s
+// RUN: %clang_cc1 -std=c++17 -verify=ref %s
+
+// expected-no-diagnostics
+// ref-no-diagnostics
+
+struct F { int a; int b;};
+constexpr F getF() {
+  return {12, 3};
+}
+constexpr int f() {
+  auto [a1, b1] = getF();
+  auto [a2, b2] = getF();
+
+  return a1 + a2 + b1 + b2;
+}
+static_assert(f() == 30);
+
+
+constexpr int a() {
+  int a[2] = {5, 3};
+  auto [x, y] = a;
+  return x + y;
+}
+static_assert(a() == 8);
+
Index: clang/lib/AST/Interp/Program.h
===
--- clang/lib/AST/Interp/Program.h
+++ clang/lib/AST/Interp/Program.h
@@ -131,7 +131,9 @@
   /// Context to manage declaration lifetimes.
   class DeclScope {
   public:
-DeclScope(Program &P, const VarDecl *VD) : P(P) { P.startDeclaration(VD); }
+DeclScope(Program &P, const ValueDecl *VD) : P(P) {
+  P.startDeclaration(VD);
+}
 ~DeclScope() { P.endDeclaration(); }
 
   private:
@@ -222,7 +224,7 @@
   unsigned CurrentDeclaration = NoDeclaration;
 
   /// Starts evaluating a declaration.
-  void startDeclaration(const VarDecl *Decl) {
+  void startDeclaration(const ValueDecl *Decl) {
 LastDeclaration += 1;
 CurrentDeclaration = LastDeclaration;
   }
Index: clang/lib/AST/Interp/ByteCodeStmtGen.cpp
===
--- clang/lib/AST/Interp/ByteCodeStmtGen.cpp
+++ clang/lib/AST/Interp/ByteCodeStmtGen.cpp
@@ -211,17 +211,11 @@
 template 
 bool ByteCodeStmtGen::visitDeclStmt(const DeclStmt *DS) {
   for (auto *D : DS->decls()) {
-// Variable declarator.
-if (auto *VD = dyn_cast(D)) {
-  if (!this->visitVarDecl(VD))
-return false;
-  continue;
-}
-
-// Decomposition declarator.
-if (auto *DD = dyn_cast(D)) {
-  return this->bail(DD);
-}
+const auto *VD = dyn_cast(D);
+if (!VD)
+  return false;
+if (!this->visitVarDecl(VD))
+  return false;
   }
 
   return true;
Index: clang/lib/AST/Interp/ByteCodeExprGen.h
===
--- clang/lib/AST/Interp/ByteCodeExprGen.h
+++ clang/lib/AST/Interp/ByteCodeExprGen.h
@@ -97,6 +97,8 @@
   bool visitDecl(const VarDecl *VD) override;
   bool visitVarDecl(const VarDecl *VD);
 
+  bool allocateVariable(const ValueDecl *VD, const Expr *Init);
+
   /// Emits scope cleanup instructions.
   void emitCleanup();
 
@@ -287,8 +289,11 @@
 
   /// Returns whether we should create a global variable for the
   /// given VarDecl.
-  bool isGlobalDecl(const VarDecl *VD) const {
-return !VD->hasLocalStorage() || VD->isConstexpr();
+  bool isGlobalDecl(const ValueDecl *VD) const {
+if (const auto *V = dyn_cast(VD))
+  return !V->hasLocalStorage() || V->isConstexpr();
+
+return false;
   }
 };
 
Index: clang/lib/AST/Interp/ByteCodeExprGen.cpp
===
--- clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -29,7 +29,7 @@
 /// Scope used to handle temporaries in toplevel variable declarations.
 template  class DeclScope final : public VariableScope {
 public:
-  DeclScope(ByteCodeExprGen *Ctx, const VarDecl *VD)
+  DeclScope(ByteCodeExprGen *Ctx, const ValueDecl *VD)
   : VariableScope(Ctx), Scope(Ctx->P, VD) {}
 
   virtual ~DeclScope() override { this->emitDestruction(); }
@@ -796,14 +796,15 @@
 bool ByteCodeExprGen::dereference(
 const Expr *LV, DerefKind AK, llvm::function_ref Direct,
 llvm::function_ref Indirect) {
+
   if (Optional T = classify(LV->getType())) {
 if (!LV->refersToBitField()) {
   // Only primitive, non bit-field types can be dereferenced directly.
-  if (auto *DE = dyn_cast(LV)) {
+  if (const auto *DE = dyn_cast(LV)) {
 if (!DE->getDecl()->getType()->isReferenceType()) {
-  if (auto *PD = dyn_cast(DE->getDecl()))
+  if (const auto *PD = dyn_cast(DE->getDecl()))
 return dereferenceParam(LV, *T, PD, AK, Direct, Indirect);
-  if (auto

[PATCH] D137534: [C++20] [Modules] [ClangScanDeps] Allow clang-scan-deps to without specified compilation database in P1689 (3/3)

2022-11-28 Thread Ben Boeckel via Phabricator via cfe-commits
ben.boeckel added inline comments.



Comment at: clang/tools/clang-scan-deps/ClangScanDeps.cpp:197
+llvm::cl::opt P1689TargetedCommand(
+"p1689-targeted-command", llvm::cl::Optional,
+llvm::cl::desc("Only supported for P1689, the targeted command of which "

ben.boeckel wrote:
> ChuanqiXu wrote:
> > ben.boeckel wrote:
> > > ChuanqiXu wrote:
> > > > ben.boeckel wrote:
> > > > > Can this be something like `--` so that I don't have to figure out 
> > > > > how to quote the thing (for the shell and whatever parsing Clang does 
> > > > > internally)?
> > > > Yeah, it can. Both `-` and `--` are accepted. I've updated the test to 
> > > > disambiguate.
> > > I don't mean the flag using `--` as a prefix. I don't care about that. 
> > > What I *do* care about is having to quote everything I'd give to `clang` 
> > > here. I'd vastly prefer something like:
> > > 
> > > ```
> > > clang-scan-deps -p1689-targeted-file-name=… -p1689-use-command -- -flags 
> > > --for ---clang --go --here
> > > ```
> > I got your point. But I prefer the current style if it won't be a problem 
> > for you to quote the options. In my imagination, it would be easier for the 
> > build systems to quote the flags than we synthesis things here. I guess 
> > there should already be one existing command line in the build system. And 
> > I feel like the current style may be more convenient and friendly for other 
> > tools to use. Could you try to use the current style?
> I don't think CMake has a mechanism for that at all right now. The problem is 
> knowing how to quote things. Is it specified how Clang will parse this string 
> into arguments? Is it platform-dependent?
Ah, it is the same as the compilation database parsing.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D137534/new/

https://reviews.llvm.org/D137534

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


[PATCH] D138803: [RISCV] Support vector crypto extension C intrinsics

2022-11-28 Thread Brandon Wu via Phabricator via cfe-commits
4vtomat created this revision.
Herald added subscribers: sunshaoce, VincentWu, vkmr, frasercrmck, evandro, 
luismarques, apazos, sameer.abuasal, s.egerton, Jim, benna, psnobl, jocewei, 
PkmX, the_o, brucehoult, MartinMosbeck, rogfer01, edward-jones, zzheng, jrtc27, 
shiva0217, kito-cheng, niosHD, sabuasal, simoncook, johnrusso, rbar, asb, 
arichardson.
Herald added a project: All.
4vtomat requested review of this revision.
Herald added subscribers: cfe-commits, pcwang-thead, eopXD, MaskRay.
Herald added a project: clang.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D138803

Files:
  clang/include/clang/Basic/riscv_vector.td
  clang/test/CodeGen/RISCV/rvv-intrinsics/vaesdf.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vaesdm.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vaesef.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vaesem.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vaeskf1.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vaeskf2.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vaesz.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vandn.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vbrev8.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vclmul.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vclmulh.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vghmac.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vrev8.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vrol.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vror.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vsha2ch.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vsha2cl.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vsha2ms.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vsm3c.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vsm3me.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vsm4k.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vsm4r.c

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


[PATCH] D136554: Implement CWG2631

2022-11-28 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added reviewers: usaxena95, erichkeane, hubert.reinterpretcast.
aaron.ballman added a comment.

The changes generally LGTM, but I'd appreciate a second set of eyes on the 
changes just to double-check we're implementing the resolution properly.




Comment at: clang/include/clang/AST/ExprCXX.h:1274
+  *getTrailingObjects() = RewrittenExpr;
 setDependence(computeDependence(this));
   }

Do we need to update `computeDependence()` to account for the rewritten `Expr 
*`?



Comment at: clang/include/clang/Sema/Sema.h:1344
+assert(Decl && Context && "invalid initialization context");
+  };
+

It took me a moment to realize this wasn't the end of the structure 
declaration. :-D



Comment at: clang/include/clang/Sema/Sema.h:9654-9655
+return true;
+  if (Ctx.isConstantEvaluated() || Ctx.isImmediateFunctionContext() ||
+  Ctx.isUnevaluated())
+return false;

We repeat this pattern four times in this patch; perhaps we should make a 
helper function for this predicate? Not certain of the best name for it, but 
removing the duplication might not be a bad idea.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D136554/new/

https://reviews.llvm.org/D136554

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


[PATCH] D138749: [clang] Compare constraints before diagnosing mismatched ref qualifiers (GH58962)

2022-11-28 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added a comment.

I can't find any example that breaks and needs the 
`AreConstraintExpressionsEqual`, so feel free to do it if you'd like.




Comment at: clang/lib/Sema/SemaOverload.cpp:1324
+if ((NewRC != nullptr) != (OldRC != nullptr))
+  // RC are most certainly different - these are overloads.
+  return true;

cor3ntin wrote:
> I know it's preexisting but, I'm not sure that comment adds anything.
> If we want to keep it, "requires clauses are different, - these are 
> overloads."
The comment is definitely low quality here, I would probably prefer a little 
more elaboration if we're going to keep it.



Comment at: clang/lib/Sema/SemaOverload.cpp:1327
+
+if (NewRC) {
+  llvm::FoldingSetNodeID NewID, OldID;

I did some work that extracted these at one point, and it matters because we 
have to 'fix' the depths sometimes.  I suspect it wont' really come up here, 
since we have already checked that these are both the same 'type' of template 
parameter by now?  But at some point (perhaps not in this patch?) we might find 
calling ` Sema::AreConstraintExpressionsEqual` necessary.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D138749/new/

https://reviews.llvm.org/D138749

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


[PATCH] D138749: [clang] Compare constraints before diagnosing mismatched ref qualifiers (GH58962)

2022-11-28 Thread Erich Keane via Phabricator via cfe-commits
erichkeane accepted this revision.
erichkeane added a comment.
This revision is now accepted and ready to land.

Feel free to clarify the comment yourself.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D138749/new/

https://reviews.llvm.org/D138749

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


[PATCH] D138805: [RISCV] Support vector crypto extension C intrinsics

2022-11-28 Thread Brandon Wu via Phabricator via cfe-commits
4vtomat created this revision.
Herald added subscribers: sunshaoce, VincentWu, vkmr, frasercrmck, evandro, 
luismarques, apazos, sameer.abuasal, s.egerton, Jim, benna, psnobl, jocewei, 
PkmX, the_o, brucehoult, MartinMosbeck, rogfer01, edward-jones, zzheng, jrtc27, 
shiva0217, kito-cheng, niosHD, sabuasal, simoncook, johnrusso, rbar, asb, 
arichardson.
Herald added a project: All.
4vtomat requested review of this revision.
Herald added subscribers: cfe-commits, pcwang-thead, eopXD, MaskRay.
Herald added a project: clang.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D138805

Files:
  clang/include/clang/Basic/riscv_vector.td
  clang/test/CodeGen/RISCV/rvv-intrinsics/vaesdf.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vaesdm.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vaesef.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vaesem.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vaeskf1.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vaeskf2.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vaesz.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vandn.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vbrev8.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vclmul.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vclmulh.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vghmac.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vrev8.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vrol.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vror.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vsha2ch.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vsha2cl.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vsha2ms.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vsm3c.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vsm3me.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vsm4k.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vsm4r.c

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


[PATCH] D136554: Implement CWG2631

2022-11-28 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin updated this revision to Diff 478216.
cor3ntin added a comment.

Remove extra ;


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D136554/new/

https://reviews.llvm.org/D136554

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/AST/ExprCXX.h
  clang/include/clang/AST/Stmt.h
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Sema/Sema.h
  clang/lib/AST/ASTImporter.cpp
  clang/lib/AST/Decl.cpp
  clang/lib/AST/ExprCXX.cpp
  clang/lib/Parse/ParseCXXInlineMethods.cpp
  clang/lib/Parse/ParseDeclCXX.cpp
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaTemplateInstantiate.cpp
  clang/lib/Sema/TreeTransform.h
  clang/lib/Serialization/ASTReaderStmt.cpp
  clang/lib/Serialization/ASTWriterStmt.cpp
  clang/test/CXX/class/class.local/p1-0x.cpp
  clang/test/CodeGenCXX/builtin-source-location.cpp
  clang/test/CodeGenCXX/default-arguments-with-immediate.cpp
  clang/test/PCH/default-argument-with-immediate-calls.cpp
  clang/test/SemaCXX/cxx11-default-member-initializers.cpp
  clang/test/SemaCXX/cxx2a-consteval-default-params.cpp
  clang/test/SemaCXX/source_location.cpp

Index: clang/test/SemaCXX/source_location.cpp
===
--- clang/test/SemaCXX/source_location.cpp
+++ clang/test/SemaCXX/source_location.cpp
@@ -1,4 +1,5 @@
 // RUN: %clang_cc1 -std=c++1z -fcxx-exceptions -fexceptions -verify %s
+// RUN: %clang_cc1 -std=c++2a -fcxx-exceptions -DUSE_CONSTEVAL -fexceptions -verify %s
 // expected-no-diagnostics
 
 #define assert(...) ((__VA_ARGS__) ? ((void)0) : throw 42)
@@ -8,15 +9,22 @@
 template 
 struct Printer;
 
+#ifdef USE_CONSTEVAL
+#define SOURCE_LOC_EVAL_KIND consteval
+#else
+#define SOURCE_LOC_EVAL_KIND constexpr
+#endif
+
 namespace std {
 class source_location {
   struct __impl;
 
 public:
-  static constexpr source_location current(const __impl *__p = __builtin_source_location()) noexcept {
-source_location __loc;
-__loc.__m_impl = __p;
-return __loc;
+  static SOURCE_LOC_EVAL_KIND source_location
+current(const __impl *__p = __builtin_source_location()) noexcept {
+  source_location __loc;
+  __loc.__m_impl = __p;
+  return __loc;
   }
   constexpr source_location() = default;
   constexpr source_location(source_location const &) = default;
@@ -593,3 +601,51 @@
   }
   static_assert(test());
 }
+
+namespace Lambda {
+#line 8000 "TestLambda.cpp"
+constexpr int nested_lambda(int l = []{
+  return SL::current().line();
+}()) {
+  return l;
+}
+static_assert(nested_lambda() == __LINE__ - 4);
+
+constexpr int lambda_param(int l = [](int l = SL::current().line()) {
+  return l;
+}()) {
+  return l;
+}
+static_assert(lambda_param() == __LINE__);
+
+
+}
+
+constexpr int compound_literal_fun(int a =
+  (int){ SL::current().line() }
+) { return a ;}
+static_assert(compound_literal_fun() == __LINE__);
+
+struct CompoundLiteral {
+  int a = (int){ SL::current().line() };
+};
+static_assert(CompoundLiteral{}.a == __LINE__);
+
+
+// FIXME
+// Init captures are subexpressions of the lambda expression
+// so according to the standard immediate invocations in init captures
+// should be evaluated at the call site.
+// However Clang does not yet implement this as it would introduce
+// a fair bit of complexity.
+// We intend to implement that functionality once we find real world
+// use cases that require it.
+constexpr int test_init_capture(int a =
+[b = SL::current().line()] { return b; }()) {
+  return a;
+}
+#ifdef USE_CONSTEVAL
+static_assert(test_init_capture() == __LINE__ - 4);
+#else
+static_assert(test_init_capture() == __LINE__ );
+#endif
Index: clang/test/SemaCXX/cxx2a-consteval-default-params.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/cxx2a-consteval-default-params.cpp
@@ -0,0 +1,81 @@
+// RUN: %clang_cc1 -fsyntax-only -verify -std=c++20 %s
+// RUN: %clang_cc1 -fsyntax-only -verify -std=c++2b %s
+
+consteval int undefined();  // expected-note 4 {{declared here}}
+
+void check_lambdas_unused(
+int a = []
+{
+// The body of a lambda is not a subexpression of the lambda
+// so this is immediately evaluated even if the parameter
+// is never used.
+return undefined();  // expected-error {{not a constant expression}} \
+ // expected-note  {{undefined function 'undefined'}}
+}(),
+int b = [](int no_error = undefined()) {
+return no_error;
+}(0),
+int c = [](int defaulted = undefined()) {
+return defaulted;
+}()
+) {}
+
+int check_lambdas_used(
+int b = [](int no_error = undefined()) {
+return no_error;
+}(0),
+int c = [](int defaulted = undefined()) { // expected-error {{not a constant expression}} \
+  // expected-note  {{declared here}} \
+  

[PATCH] D136554: Implement CWG2631

2022-11-28 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin added inline comments.



Comment at: clang/include/clang/AST/ExprCXX.h:1274
+  *getTrailingObjects() = RewrittenExpr;
 setDependence(computeDependence(this));
   }

aaron.ballman wrote:
> Do we need to update `computeDependence()` to account for the rewritten `Expr 
> *`?
Looking at the code again, `computeDependence` do use the rewritten expr if 
there is one already (contracticting what I previously stated offline)



Comment at: clang/include/clang/Sema/Sema.h:9654-9655
+return true;
+  if (Ctx.isConstantEvaluated() || Ctx.isImmediateFunctionContext() ||
+  Ctx.isUnevaluated())
+return false;

aaron.ballman wrote:
> We repeat this pattern four times in this patch; perhaps we should make a 
> helper function for this predicate? Not certain of the best name for it, but 
> removing the duplication might not be a bad idea.
`isNotPotentiallyEvaluatedContext`? Something like that


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D136554/new/

https://reviews.llvm.org/D136554

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


[PATCH] D138807: [RISCV] Support vector crypto extension ISA string and assembly

2022-11-28 Thread Brandon Wu via Phabricator via cfe-commits
4vtomat created this revision.
Herald added subscribers: sunshaoce, VincentWu, vkmr, frasercrmck, jdoerfert, 
evandro, luismarques, apazos, sameer.abuasal, s.egerton, Jim, benna, psnobl, 
jocewei, PkmX, the_o, brucehoult, MartinMosbeck, rogfer01, edward-jones, 
zzheng, jrtc27, shiva0217, kito-cheng, niosHD, sabuasal, simoncook, johnrusso, 
rbar, asb, hiraditya, arichardson.
Herald added a project: All.
4vtomat requested review of this revision.
Herald added subscribers: llvm-commits, cfe-commits, pcwang-thead, eopXD, 
MaskRay.
Herald added projects: clang, LLVM.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D138807

Files:
  clang/test/Preprocessor/riscv-target-features.c
  llvm/lib/Support/RISCVISAInfo.cpp
  llvm/lib/Target/RISCV/RISCV.td
  llvm/lib/Target/RISCV/RISCVInstrInfoV.td
  llvm/lib/Target/RISCV/RISCVInstrInfoZvk.td
  llvm/lib/Target/RISCV/RISCVSubtarget.h
  llvm/test/CodeGen/RISCV/attributes.ll
  llvm/test/MC/RISCV/attribute-arch.s
  llvm/test/MC/RISCV/rvv/rv64zvkb.s
  llvm/test/MC/RISCV/rvv/rv64zvkg.s
  llvm/test/MC/RISCV/rvv/rv64zvknf.s
  llvm/test/MC/RISCV/rvv/rv64zvknha.s
  llvm/test/MC/RISCV/rvv/rv64zvknhb.s
  llvm/test/MC/RISCV/rvv/rv64zvkns.s
  llvm/test/MC/RISCV/rvv/rv64zvksed.s
  llvm/test/MC/RISCV/rvv/rv64zvksh.s

Index: llvm/test/MC/RISCV/rvv/rv64zvksh.s
===
--- /dev/null
+++ llvm/test/MC/RISCV/rvv/rv64zvksh.s
@@ -0,0 +1,21 @@
+# RUN: llvm-mc -triple=riscv64 -show-encoding --mattr=+zvksh %s \
+# RUN:| FileCheck %s --check-prefixes=CHECK-ENCODING,CHECK-INST
+# RUN: not llvm-mc -triple=riscv64 -show-encoding %s 2>&1 \
+# RUN:| FileCheck %s --check-prefix=CHECK-ERROR
+# RUN: llvm-mc -triple=riscv64 -filetype=obj --mattr=+zvksh %s \
+# RUN:| llvm-objdump -d --mattr=+zvksh  - \
+# RUN:| FileCheck %s --check-prefix=CHECK-INST
+# RUN: llvm-mc -triple=riscv64 -filetype=obj --mattr=+zvksh %s \
+# RUN:| llvm-objdump -d - | FileCheck %s --check-prefix=CHECK-UNKNOWN
+
+vsm3c.vi v10, v9, 7
+# CHECK-INST: vsm3c.vi v10, v9, 7
+# CHECK-ENCODING: [0x57,0xb5,0x93,0xd6]
+# CHECK-ERROR: instruction requires the following: 'Zvksh'
+# CHECK-UNKNOWN: 57 b5 93 d6   
+
+vsm3me.vv v10, v9, v8
+# CHECK-INST: vsm3me.vv v10, v9, v8
+# CHECK-ENCODING: [0x57,0x35,0x94,0xda]
+# CHECK-ERROR: instruction requires the following: 'Zvksh'
+# CHECK-UNKNOWN: 57 35 94 da   
Index: llvm/test/MC/RISCV/rvv/rv64zvksed.s
===
--- /dev/null
+++ llvm/test/MC/RISCV/rvv/rv64zvksed.s
@@ -0,0 +1,21 @@
+# RUN: llvm-mc -triple=riscv64 -show-encoding --mattr=+zvksed %s \
+# RUN:| FileCheck %s --check-prefixes=CHECK-ENCODING,CHECK-INST
+# RUN: not llvm-mc -triple=riscv64 -show-encoding %s 2>&1 \
+# RUN:| FileCheck %s --check-prefix=CHECK-ERROR
+# RUN: llvm-mc -triple=riscv64 -filetype=obj --mattr=+zvksed %s \
+# RUN:| llvm-objdump -d --mattr=+zvksed  - \
+# RUN:| FileCheck %s --check-prefix=CHECK-INST
+# RUN: llvm-mc -triple=riscv64 -filetype=obj --mattr=+zvksed %s \
+# RUN:| llvm-objdump -d - | FileCheck %s --check-prefix=CHECK-UNKNOWN
+
+vsm4k.vi v10, v9, 7
+# CHECK-INST: vsm4k.vi v10, v9, 7
+# CHECK-ENCODING: [0x57,0xb5,0x93,0xea]
+# CHECK-ERROR: instruction requires the following: 'Zvksed'
+# CHECK-UNKNOWN: 57 b5 93 ea   
+
+vsm4r.vv v10, v9
+# CHECK-INST: vsm4r.vv v10, v9
+# CHECK-ENCODING: [0x57,0x35,0x90,0xee]
+# CHECK-ERROR: instruction requires the following: 'Zvksed'
+# CHECK-UNKNOWN: 57 35 90 ee   
Index: llvm/test/MC/RISCV/rvv/rv64zvkns.s
===
--- /dev/null
+++ llvm/test/MC/RISCV/rvv/rv64zvkns.s
@@ -0,0 +1,87 @@
+# RUN: llvm-mc -triple=riscv64 -show-encoding --mattr=+zvkns %s \
+# RUN:| FileCheck %s --check-prefixes=CHECK-ENCODING,CHECK-INST
+# RUN: not llvm-mc -triple=riscv64 -show-encoding %s 2>&1 \
+# RUN:| FileCheck %s --check-prefix=CHECK-ERROR
+# RUN: llvm-mc -triple=riscv64 -filetype=obj --mattr=+zvkns %s \
+# RUN:| llvm-objdump -d --mattr=+zvkns  - \
+# RUN:| FileCheck %s --check-prefix=CHECK-INST
+# RUN: llvm-mc -triple=riscv64 -filetype=obj --mattr=+zvkns %s \
+# RUN:| llvm-objdump -d - | FileCheck %s --check-prefix=CHECK-UNKNOWN
+
+vaesdf.vv v10, v9
+# CHECK-INST: vaesdf.vv v10, v9
+# CHECK-ENCODING: [0x57,0x05,0x90,0xee]
+# CHECK-ERROR: instruction requires the following: 'Zvkns'
+# CHECK-UNKNOWN: 57 05 90 ee   
+
+vaesdf.vs v10, v9
+# CHECK-INST: vaesdf.vs v10, v9
+# CHECK-ENCODING: [0x57,0x65,0x90,0x66]
+# CHECK-ERROR: instruction requires the following: 'Zvkns'
+# CHECK-UNKNOWN: 57 65 90 66   
+
+vaesef.vv v10, v9
+# CHECK-INST: vaesef.vv v10, v9
+# CHECK-ENCODING: [0x57,0x05,0x90,0xf6]
+# CHECK-ERROR: instruction requires the following: 'Zvkns'
+# CHECK-UNKNOWN: 57 05 90 f6   
+   
+vaesef.vs v10, v9
+# CHECK-INST: vaesef.vs v10, v9
+# CHECK-ENCODING: [0x57,0x65,0x90,0

[PATCH] D138810: [RISCV] Support vector crypto extension C intrinsics

2022-11-28 Thread Brandon Wu via Phabricator via cfe-commits
4vtomat created this revision.
Herald added subscribers: sunshaoce, VincentWu, vkmr, frasercrmck, evandro, 
luismarques, apazos, sameer.abuasal, s.egerton, Jim, benna, psnobl, jocewei, 
PkmX, the_o, brucehoult, MartinMosbeck, rogfer01, edward-jones, zzheng, jrtc27, 
shiva0217, kito-cheng, niosHD, sabuasal, simoncook, johnrusso, rbar, asb, 
arichardson.
Herald added a project: All.
4vtomat requested review of this revision.
Herald added subscribers: cfe-commits, pcwang-thead, eopXD, MaskRay.
Herald added a project: clang.

Depends on D138807 , D138809 



Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D138810

Files:
  clang/include/clang/Basic/riscv_vector.td
  clang/test/CodeGen/RISCV/rvv-intrinsics/vaesdf.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vaesdm.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vaesef.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vaesem.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vaeskf1.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vaeskf2.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vaesz.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vandn.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vbrev8.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vclmul.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vclmulh.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vghmac.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vrev8.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vrol.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vror.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vsha2ch.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vsha2cl.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vsha2ms.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vsm3c.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vsm3me.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vsm4k.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vsm4r.c

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


[PATCH] D138797: [include-cleaner] Implement IWYU begin_keep/end_keep pragma support.

2022-11-28 Thread Haojian Wu via Phabricator via cfe-commits
hokein added inline comments.



Comment at: clang-tools-extra/include-cleaner/lib/Record.cpp:219
+if ((Top.Block && HashLine > Top.SeenAtLine) ||
+Top.SeenAtLine == HashLine) {
+  Out->ShouldKeep.insert(HashLine);

nit: remove the brace for the `if`, the same below.



Comment at: clang-tools-extra/include-cleaner/unittests/RecordTest.cpp:349
   EXPECT_TRUE(PI.shouldKeep(3));
+  EXPECT_FALSE(PI.shouldKeep(13));
+  EXPECT_TRUE(PI.shouldKeep(14));

with more tests being added, these line-number-inlined tests now are hard to 
follow, even with the line comment in the example.

I think we can polish these tests by using the annotation point `^`, something 
like. 
```
llvm::Annotation Code = R"cpp(
$keep1^#include "keep1.h" // IWYU pragma: keep

$normal^%include "normal.h"
)cpp";

EXPECT_TRUE(PI.shouldKeep(offsetToLine(Code.point("keep1";
EXPECT_FALSE(PI.shouldKeep(offsetToLine(Code.point("normal";
```

We need to implement an `offsetToLine` function, it should be trivial to add 
(basically calculate the number of `\n`s to the offset point).


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D138797/new/

https://reviews.llvm.org/D138797

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


[PATCH] D138727: [clang] Skip defaulted functions in zero-as-null-pointer-constant.

2022-11-28 Thread Jens Massberg via Phabricator via cfe-commits
massberg updated this revision to Diff 478227.
massberg added a comment.

Sync to head.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D138727/new/

https://reviews.llvm.org/D138727

Files:
  clang/lib/Sema/Sema.cpp
  clang/test/SemaCXX/warn-zero-nullptr-cxx20.cpp


Index: clang/test/SemaCXX/warn-zero-nullptr-cxx20.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/warn-zero-nullptr-cxx20.cpp
@@ -0,0 +1,53 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s -isystem %S/Inputs 
-Wzero-as-null-pointer-constant -std=c++20
+
+#include 
+
+namespace std {
+class strong_ordering;
+
+// Mock how STD defined unspecified parameters for the operators below.
+struct _CmpUnspecifiedParam {
+  consteval
+  _CmpUnspecifiedParam(int _CmpUnspecifiedParam::*) noexcept {}
+};
+
+struct strong_ordering {
+  signed char value;
+
+  friend constexpr bool operator==(strong_ordering v,
+   _CmpUnspecifiedParam) noexcept {
+return v.value == 0;
+  }
+  friend constexpr bool operator<(strong_ordering v,
+  _CmpUnspecifiedParam) noexcept {
+return v.value < 0;
+  }
+  friend constexpr bool operator>(strong_ordering v,
+  _CmpUnspecifiedParam) noexcept {
+return v.value > 0;
+  }
+  friend constexpr bool operator>=(strong_ordering v,
+   _CmpUnspecifiedParam) noexcept {
+return v.value >= 0;
+  }
+  static const strong_ordering equal, greater, less;
+};
+constexpr strong_ordering strong_ordering::equal = {0};
+constexpr strong_ordering strong_ordering::greater = {1};
+constexpr strong_ordering strong_ordering::less = {-1};
+} // namespace std
+
+struct A {
+  int a;
+  constexpr auto operator<=>(const A &other) const = default;
+};
+
+void test_cxx_rewritten_binary_ops() {
+  A a1, a2;
+  bool result;
+  result = (a1 < a2);
+  result = (a1 >= a2);
+  int *ptr = 0; // expected-warning{{zero as null pointer constant}}
+  result = (a1 > (ptr == 0 ? a1 : a2)); // expected-warning{{zero as null 
pointer constant}}
+  result = (a1 > ((a1 > (ptr == 0 ? a1 : a2)) ? a1 : a2)); // 
expected-warning{{zero as null pointer constant}}
+}
Index: clang/lib/Sema/Sema.cpp
===
--- clang/lib/Sema/Sema.cpp
+++ clang/lib/Sema/Sema.cpp
@@ -597,6 +597,13 @@
   CodeSynthesisContext::RewritingOperatorAsSpaceship)
 return;
 
+  // Ignore null pointers in defaulted functions, e.g. defaulted comparison
+  // operators.
+  FunctionDecl *FD =  getCurFunctionDecl();
+  if (FD && FD->isDefaulted()) {
+return;
+  }
+
   // If it is a macro from system header, and if the macro name is not "NULL",
   // do not warn.
   SourceLocation MaybeMacroLoc = E->getBeginLoc();


Index: clang/test/SemaCXX/warn-zero-nullptr-cxx20.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/warn-zero-nullptr-cxx20.cpp
@@ -0,0 +1,53 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s -isystem %S/Inputs -Wzero-as-null-pointer-constant -std=c++20
+
+#include 
+
+namespace std {
+class strong_ordering;
+
+// Mock how STD defined unspecified parameters for the operators below.
+struct _CmpUnspecifiedParam {
+  consteval
+  _CmpUnspecifiedParam(int _CmpUnspecifiedParam::*) noexcept {}
+};
+
+struct strong_ordering {
+  signed char value;
+
+  friend constexpr bool operator==(strong_ordering v,
+   _CmpUnspecifiedParam) noexcept {
+return v.value == 0;
+  }
+  friend constexpr bool operator<(strong_ordering v,
+  _CmpUnspecifiedParam) noexcept {
+return v.value < 0;
+  }
+  friend constexpr bool operator>(strong_ordering v,
+  _CmpUnspecifiedParam) noexcept {
+return v.value > 0;
+  }
+  friend constexpr bool operator>=(strong_ordering v,
+   _CmpUnspecifiedParam) noexcept {
+return v.value >= 0;
+  }
+  static const strong_ordering equal, greater, less;
+};
+constexpr strong_ordering strong_ordering::equal = {0};
+constexpr strong_ordering strong_ordering::greater = {1};
+constexpr strong_ordering strong_ordering::less = {-1};
+} // namespace std
+
+struct A {
+  int a;
+  constexpr auto operator<=>(const A &other) const = default;
+};
+
+void test_cxx_rewritten_binary_ops() {
+  A a1, a2;
+  bool result;
+  result = (a1 < a2);
+  result = (a1 >= a2);
+  int *ptr = 0; // expected-warning{{zero as null pointer constant}}
+  result = (a1 > (ptr == 0 ? a1 : a2)); // expected-warning{{zero as null pointer constant}}
+  result = (a1 > ((a1 > (ptr == 0 ? a1 : a2)) ? a1 : a2)); // expected-warning{{zero as null pointer constant}}
+}
Index: clang/lib/Sema/Sema.cpp
===
--- clang/lib/Sema/Sema.cpp
+++ clang/lib/Sema/Sema.cpp
@@ -5

[PATCH] D138779: [include-cleaner] Filter out references that not spelled in the main file.

2022-11-28 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 478228.
hokein marked 3 inline comments as done.
hokein added a comment.

address comments:

- polish and simplify the tests
- inline the spelling-loc-check logic
- add a comment for the walkUsed


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D138779/new/

https://reviews.llvm.org/D138779

Files:
  clang-tools-extra/include-cleaner/include/clang-include-cleaner/Analysis.h
  clang-tools-extra/include-cleaner/lib/Analysis.cpp
  clang-tools-extra/include-cleaner/lib/HTMLReport.cpp
  clang-tools-extra/include-cleaner/unittests/AnalysisTest.cpp

Index: clang-tools-extra/include-cleaner/unittests/AnalysisTest.cpp
===
--- clang-tools-extra/include-cleaner/unittests/AnalysisTest.cpp
+++ clang-tools-extra/include-cleaner/unittests/AnalysisTest.cpp
@@ -18,13 +18,16 @@
 #include "clang/Tooling/Inclusions/StandardLibrary.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/SmallVector.h"
+#include "llvm/Support/ScopedPrinter.h"
 #include "llvm/Testing/Support/Annotations.h"
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
 #include 
+#include 
 
 namespace clang::include_cleaner {
 namespace {
+using testing::AllOf;
 using testing::Pair;
 using testing::UnorderedElementsAre;
 
@@ -134,6 +137,127 @@
   UnorderedElementsAre(Pair(Main.point(), UnorderedElementsAre(HdrFile;
 }
 
+MATCHER_P3(expandedAt, FileID, Offset, SM, "") {
+  auto [ExpanedFileID, ExpandedOffset] = SM->getDecomposedExpansionLoc(arg);
+  return ExpanedFileID == FileID && ExpandedOffset == Offset;
+}
+MATCHER_P3(spelledAt, FileID, Offset, SM, "") {
+  auto [SpelledFileID, SpelledOffset] = SM->getDecomposedSpellingLoc(arg);
+  return SpelledFileID == FileID && SpelledOffset == Offset;
+}
+TEST(WalkUsed, FilterRefsNotSpelledInMainFile) {
+  // Each test is expected to have a single expected ref of `target` symbol
+  // (or have none).
+  // The location in the reported ref is a macro location. $expand points to
+  // the macro location, and $spell points to the spelled location.
+  struct {
+llvm::StringRef Header;
+llvm::StringRef Main;
+  } TestCases[] = {
+  // Tests for decl references.
+  {
+  /*Header=*/"",
+  R"cpp(
+int target();
+#define CALL_FUNC $spell^target()
+
+int b = $expand^CALL_FUNC;
+  )cpp",
+  },
+  {/*Header=*/R"cpp(
+int target();
+#define CALL_FUNC target()
+)cpp",
+   // No ref of `target` being reported, as it is not spelled in main file.
+   "int a = CALL_FUNC;"},
+  {
+  /*Header=*/"",
+  R"cpp(
+int target;
+#define PLUS_ONE(X) X + 1
+int a = $expand^PLUS_ONE($spell^target);
+  )cpp",
+  },
+  {
+  /*Header*/ R"cpp(
+int target;
+#define PLUS_ONE(X) X + 1
+  )cpp",
+  R"cpp(
+int a = $expand^PLUS_ONE($spell^target);
+  )cpp",
+  },
+  {
+  /*Header=*/"#define PLUS_ONE(X) X + 1",
+  R"cpp(
+int target;
+int a = $expand^PLUS_ONE($spell^target);
+  )cpp",
+  },
+  // Tests for macro references,
+  {/*Header=*/"",
+   R"cpp(
+  #define target 1
+  #define USE_target $spell^target
+  int b = $expand^USE_target;
+)cpp"},
+  {/*Header=*/R"cpp(
+  #define target 1
+  #define USE_target target
+)cpp",
+   // No ref of `target` being reported, it is not spelled in main file.
+   R"cpp(
+  int a = USE_target;
+)cpp"},
+  };
+
+  for (const auto &T : TestCases) {
+llvm::Annotations Main(T.Main);
+TestInputs Inputs(Main.code());
+Inputs.ExtraFiles["header.h"] = guard(T.Header);
+RecordedPP Recorded;
+Inputs.MakeAction = [&]() {
+  struct RecordAction : public SyntaxOnlyAction {
+RecordedPP &Out;
+RecordAction(RecordedPP &Out) : Out(Out) {}
+bool BeginSourceFileAction(clang::CompilerInstance &CI) override {
+  auto &PP = CI.getPreprocessor();
+  PP.addPPCallbacks(Out.record(PP));
+  return true;
+}
+  };
+  return std::make_unique(Recorded);
+};
+Inputs.ExtraArgs.push_back("-include");
+Inputs.ExtraArgs.push_back("header.h");
+TestAST AST(Inputs);
+llvm::SmallVector TopLevelDecls;
+for (Decl *D : AST.context().getTranslationUnitDecl()->decls())
+  TopLevelDecls.emplace_back(D);
+auto &SM = AST.sourceManager();
+
+std::optional RefLoc;
+walkUsed(TopLevelDecls, Recorded.MacroReferences,
+ /*PragmaIncludes=*/nullptr, SM,
+ [&](const SymbolReference &Ref, llvm::ArrayRef) {
+   if (!Ref.RefLocation.isMacroID())
+ return;
+   if (llvm::to_string(Ref.Target) == "target") {
+ ASSERT

[PATCH] D138792: [AArch64] Improve TargetParser API

2022-11-28 Thread David Spickett via Phabricator via cfe-commits
DavidSpickett accepted this revision.
DavidSpickett added a comment.
This revision is now accepted and ready to land.

Looks like a good direction to me. Plenty more bits in clang that should really 
live in the target parser, and this is a great start at moving those.

My only issue is the use of `AI` for ArchInfo. I see that ArchKind was also a 
type and a var name. If this new name is following the codestyle then fine but 
I'd go with ArchInfo (`arch_info` but that's against the style, sigh). Up to 
you, I know the acronym style is common elsewhere and IDE helpers mitigate it 
somewhat.




Comment at: llvm/include/llvm/Support/AArch64TargetParser.h:119
+  ArchInfo(const ArchInfo &) = delete;
+  ArchInfo &operator=(const ArchInfo &rhs) = delete;
+

Do you need to do anything to prevent moving from this?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D138792/new/

https://reviews.llvm.org/D138792

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


[PATCH] D138702: support for HIP non hostcall printf

2022-11-28 Thread Matt Arsenault via Phabricator via cfe-commits
arsenm requested changes to this revision.
arsenm added a comment.
Herald added a subscriber: wdng.

I have a few questions. First, why surface this to users? If we really need to, 
I don't think this is the right flag name/design. A named argument to some kind 
of printf lowering flag would be better. Second, I thought we were moving 
towards hostcall printf, not away from it.




Comment at: clang/include/clang/Basic/LangOptions.def:275
 LANGOPT(OffloadingNewDriver, 1, 0, "use the new driver for generating 
offloading code.")
+LANGOPT(DelayedPrintf, 1, 0, "version onf printf function to be used, hostcall 
or buffer based")
 

Typo 'onf'



Comment at: clang/include/clang/Driver/Options.td:985
+def fdelayed_printf : Flag<["-"], "fdelayed-printf">,
+  HelpText<"Specifies which version of printf is to be used while CodeGen">,
+  Flags<[CC1Option]>,

Help text reads weird



Comment at: clang/lib/Driver/ToolChains/Clang.cpp:4655-4667
+
+if (JA.isDeviceOffloading(Action::OFK_HIP)) {
+  // Device side compilation printf
+  if (Args.getLastArg(options::OPT_fdelayed_printf))
+CmdArgs.push_back("-fdelayed-printf");
+}
   }

Missing clang side tests



Comment at: llvm/lib/Target/AMDGPU/AMDGPUPrintfRuntimeBinding.cpp:135-136
 
-bool AMDGPUPrintfRuntimeBindingImpl::shouldPrintAsStr(char Specifier,
-  Type *OpType) const {
-  if (Specifier != 's')
-return false;
-  const PointerType *PT = dyn_cast(OpType);
-  if (!PT || PT->getAddressSpace() != AMDGPUAS::CONSTANT_ADDRESS)
-return false;
-  Type *ElemType = PT->getContainedType(0);
-  if (ElemType->getTypeID() != Type::IntegerTyID)
-return false;
-  IntegerType *ElemIType = cast(ElemType);
-  return ElemIType->getBitWidth() == 8;
+// This function is essentially a copy from the file
+// Transforms/Utils/AMDGPUEmitPrintf.cpp
+static Value *getStrlenWithNull(IRBuilder<> &Builder, Value *Str) {

Why not share these? They should be in the same place. This should also be a 
separate change from any flag changes



Comment at: llvm/lib/Target/AMDGPU/AMDGPUPrintfRuntimeBinding.cpp:141
+
+  auto CharZero = Builder.getInt8(0);
+  auto One = Builder.getInt64(1);

auto *



Comment at: llvm/lib/Target/AMDGPU/AMDGPUPrintfRuntimeBinding.cpp:150
+  BasicBlock *Join = nullptr;
+  if (Prev->getTerminator()) {
+Join = Prev->splitBasicBlock(Builder.GetInsertPoint(), "strlen.join");

Why would the block be missing a terminator here?



Comment at: llvm/lib/Target/AMDGPU/AMDGPUPrintfRuntimeBinding.cpp:183-185
+  auto Begin = Builder.CreatePtrToInt(Str, Int64Ty);
+  auto End = Builder.CreatePtrToInt(PtrPhi, Int64Ty);
+  auto Len = Builder.CreateSub(End, Begin);

Really should try hard to avoid introducing ptrtoint. Do you really need to do 
a pointer subtract?



Comment at: llvm/lib/Target/AMDGPU/AMDGPUPrintfRuntimeBinding.cpp:215
+  StringRef Str;
+  llvm::Value *RealSize;
+  llvm::Value *AlignedSize;

Don't need llvm::



Comment at: llvm/lib/Target/AMDGPU/AMDGPUPrintfRuntimeBinding.cpp:439
 
-  Type *idPointer = PointerType::get(I32Ty, AMDGPUAS::GLOBAL_ADDRESS);
+  Type *idPointer = PointerType::get(Int32Ty, AMDGPUAS::GLOBAL_ADDRESS);
   Value *id_gep_cast =

Broken for opaque pointers?



Comment at: llvm/lib/Target/AMDGPU/AMDGPUPrintfRuntimeBinding.cpp:443
 
-  new StoreInst(ConstantInt::get(I32Ty, UniqID), id_gep_cast, Brnch);
+  new StoreInst(ConstantInt::get(Int32Ty, UniqID), id_gep_cast, Brnch);
 

Why isn't this using the IRBuilder?



Comment at: llvm/lib/Target/AMDGPU/AMDGPUPrintfRuntimeBinding.cpp:491-492
+  if (S[0]) {
+char *MyNewStr = new char[NSizeStr]();
+strcpy(MyNewStr, S.str().c_str());
+int NumInts = NSizeStr / 4;

Why do we have raw new and strcpy here? We have better string classes



Comment at: llvm/test/CodeGen/AMDGPU/hip-delayed-printf.ll:1
+; RUN: opt -mtriple=amdgcn--amdhsa -passes=amdgpu-printf-runtime-binding -S < 
%s | FileCheck --check-prefix=FUNC --check-prefix=GCN --check-prefix=METADATA %s
+

Don't need these separate prefixes



Comment at: llvm/test/CodeGen/AMDGPU/hip-delayed-printf.ll:3
+
+; FUNC-LABEL: @test_kernel(
+; GCN-LABEL: entry

Should use generated checks



Comment at: llvm/test/CodeGen/AMDGPU/hip-delayed-printf.ll:39
+  store i32 25, ptr %p.ascast, align 4
+  %0 = load i32, ptr %p.ascast, align 4
+  %cmp = icmp sgt i32 %0, 30

Use named values in tests


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTI

[PATCH] D138777: [clang-tidy] Add check bugprone-multiple-new-in-one-expression.

2022-11-28 Thread Eugene Zelenko via Phabricator via cfe-commits
Eugene.Zelenko added inline comments.



Comment at: 
clang-tools-extra/clang-tidy/bugprone/MultipleNewInOneExpressionCheck.h:25
+  bool isLanguageVersionSupported(const LangOptions &LangOpts) const override {
+return LangOpts.CPlusPlus11;
+  }

I think check is applicable to early versions too.



Comment at: 
clang-tools-extra/docs/clang-tidy/checks/bugprone/multiple-new-in-one-expression.rst:9
+
+C++ does often not specify the exact order of evaluation of the operands of an 
operator or arguments of a function.
+Therefore if a first allocation succeeds and a second fails, in an exception 
handler it is not possible to tell which allocation has failed and free the 
memory.

Please follow 80 characters limit.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D138777/new/

https://reviews.llvm.org/D138777

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


[PATCH] D138821: Remove filtering from UsingDecl visit.

2022-11-28 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo created this revision.
Herald added a subscriber: kadircet.
Herald added a project: All.
VitaNuo requested review of this revision.
Herald added a project: clang-tools-extra.
Herald added a subscriber: cfe-commits.

Removes filtering from the VisitUsingDecl method for implementation files.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D138821

Files:
  clang-tools-extra/include-cleaner/lib/WalkAST.cpp
  clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp


Index: clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp
===
--- clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp
+++ clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp
@@ -88,12 +88,10 @@
 auto RTStr = llvm::to_string(RT);
 for (auto Expected : Target.points(RTStr))
   if (!llvm::is_contained(ReferencedOffsets[RT], Expected))
-DiagnosePoint("location not marked used with type " + RTStr,
-  Expected);
+DiagnosePoint("location not marked used with type " + RTStr, Expected);
 for (auto Actual : ReferencedOffsets[RT])
   if (!llvm::is_contained(Target.points(RTStr), Actual))
-DiagnosePoint("location unexpectedly used with type " + RTStr,
-  Actual);
+DiagnosePoint("location unexpectedly used with type " + RTStr, Actual);
   }
 
   // If there were any differences, we print the entire referencing code once.
@@ -132,7 +130,7 @@
   // Make sure we ignore unused overloads.
   testWalk(R"cpp(
 namespace ns {
-  void $explicit^x(); void x(int); void x(char);
+  void $explicit^x(); void $ambiguous^x(int); void $ambiguous^x(char);
 })cpp",
"using ns::^x; void foo() { x(); }");
   // We should report unused overloads if main file is a header.
@@ -142,6 +140,15 @@
 })cpp",
"// c++-header\n using ns::^x;");
   testWalk("namespace ns { struct S; } using ns::$explicit^S;", "^S *s;");
+  // We should report templates with at least one instantiation
+  testWalk(R"cpp(
+namespace ns {
+  template
+  class Y {};
+}
+using ns::$explicit^Y;
+)cpp",
+   "^Y x;");
 }
 
 TEST(WalkAST, Namespaces) {
Index: clang-tools-extra/include-cleaner/lib/WalkAST.cpp
===
--- clang-tools-extra/include-cleaner/lib/WalkAST.cpp
+++ clang-tools-extra/include-cleaner/lib/WalkAST.cpp
@@ -82,10 +82,6 @@
 for (const auto *Shadow : UD->shadows()) {
   auto *TD = Shadow->getTargetDecl();
   auto IsUsed = TD->isUsed() || TD->isReferenced();
-  // We ignore unused overloads inside implementation files, as the ones in
-  // headers might still be used by the dependents of the header.
-  if (!IsUsed && !IsHeader)
-continue;
   report(UD->getLocation(), TD,
  IsUsed ? RefType::Explicit : RefType::Ambiguous);
 }


Index: clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp
===
--- clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp
+++ clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp
@@ -88,12 +88,10 @@
 auto RTStr = llvm::to_string(RT);
 for (auto Expected : Target.points(RTStr))
   if (!llvm::is_contained(ReferencedOffsets[RT], Expected))
-DiagnosePoint("location not marked used with type " + RTStr,
-  Expected);
+DiagnosePoint("location not marked used with type " + RTStr, Expected);
 for (auto Actual : ReferencedOffsets[RT])
   if (!llvm::is_contained(Target.points(RTStr), Actual))
-DiagnosePoint("location unexpectedly used with type " + RTStr,
-  Actual);
+DiagnosePoint("location unexpectedly used with type " + RTStr, Actual);
   }
 
   // If there were any differences, we print the entire referencing code once.
@@ -132,7 +130,7 @@
   // Make sure we ignore unused overloads.
   testWalk(R"cpp(
 namespace ns {
-  void $explicit^x(); void x(int); void x(char);
+  void $explicit^x(); void $ambiguous^x(int); void $ambiguous^x(char);
 })cpp",
"using ns::^x; void foo() { x(); }");
   // We should report unused overloads if main file is a header.
@@ -142,6 +140,15 @@
 })cpp",
"// c++-header\n using ns::^x;");
   testWalk("namespace ns { struct S; } using ns::$explicit^S;", "^S *s;");
+  // We should report templates with at least one instantiation
+  testWalk(R"cpp(
+namespace ns {
+  template
+  class Y {};
+}
+using ns::$explicit^Y;
+)cpp",
+   "^Y x;");
 }
 
 TEST(WalkAST, Namespaces) {
Index: clang-tools-extra/include-cleaner/lib/WalkAST.cpp
===
--- clang-tools-extra/include-cleaner/lib/WalkAST.cpp
+++ clang-tools-extra/include-cleaner/lib/WalkAST.cpp
@@ -82,10 +82,6 @@
 for (cons

[PATCH] D129531: [clang][C++20] P0960R3 and P1975R0: Allow initializing aggregates from a parenthesized list of values

2022-11-28 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

Thanks for addressing the comments and sorry for a wait before the comments.
Please see the comment about syntactic form, I might be holding it wrong, but 
it looks like we actually loose the syntactic form completely in this case.




Comment at: clang/lib/AST/JSONNodeDumper.cpp:852
 case VarDecl::ListInit: JOS.attribute("init", "list"); break;
+case VarDecl::ParenListInit:
+  JOS.attribute("init", "paren-list");

ayzhao wrote:
> ilya-biryukov wrote:
> > NIT: maybe use the same formatting as other switch cases for constistency?
> Unfortunately clang-format insists that these be on separate lines.
Ah, that's unfortunate. I normally just revert the effect of `clang-format` for 
those lines, but up to you.
Also fine to keep as is or even format the other lines according to the style 
guide (it's just 3 more lines, so should not be a big deal).





Comment at: clang/lib/CodeGen/CGExprAgg.cpp:581
+  Expr *filler = nullptr;
+  if (auto *ILE = dyn_cast(ExprToVisit))
+filler = ILE->getArrayFiller();

ayzhao wrote:
> ilya-biryukov wrote:
> > - Should we have a filler for `CXXParenInitListExpr` too?
> >   It seems like an important optimization and could have large effect on 
> > compile times if we don't 
> > 
> > - Same question for semantic and syntactic-form (similar to 
> > `InitListExpr`): should we have it here?
> >   I am not sure if it's semantically required (probably not?), but that's 
> > definitely something that `clang-tidy` and other source tools will rely on.
> > 
> > We should probably share the code there, I suggest moving it to a shared 
> > base class and using it where appropriate instead of the derived classes.
> > Should we have a filler for CXXParenInitListExpr too? It seems like an 
> > important optimization and could have large effect on compile times if we 
> > don't
> 
> This feels like premature optimization - presumably, wouldn't this only be an 
> issue with extraordinarily large (say, O(1000)) arrays?
> 
> > Same question for semantic and syntactic-form (similar to InitListExpr): 
> > should we have it here? I am not sure if it's semantically required 
> > (probably not?), but that's definitely something that clang-tidy and other 
> > source tools will rely on
> 
> IIRC this doesn't apply to paren list aggregate expressions, as the syntatic 
> form would be the enclosing `ParenListExpr`.
> This feels like premature optimization - presumably, wouldn't this only be an 
> issue with extraordinarily large (say, O(1000)) arrays?
Yes, this should only happen with large arrays. Normally I would agree, but 
it's surprising that changing `{}` to `()` in the compiler would lead to 
performance degradation.
In that sense, this premature optimization is already implemented, we are 
rather degrading performance for a different syntax to do the same thing.

Although we could also land without it, but in that case could you open a GH 
issue and add a FIXME to track the implementation of this particular 
optimization?
This should increase the chances of users finding the root cause of the issue 
if they happen to hit it.

> IIRC this doesn't apply to paren list aggregate expressions, as the syntatic 
> form would be the enclosing ParenListExpr.
Do we even have the enclosing `ParenListExpr`? If I dump the AST with `clang 
-fsyntax-only -Xclang=-ast-dump ...`  for the following code:
```
struct pair { int a; int b = 2; };
int main() {
  pair(1); pair p(1);
  pair b{1}; pair{1};
}
```

I get 
```
`-FunctionDecl 0x557d79717e98  line:2:5 main 'int ()'
  `-CompoundStmt 0x557d797369d0 
|-CXXFunctionalCastExpr 0x557d79718528  'pair':'pair' 
functional cast to pair 
| `-CXXParenListInitExpr 0x557d79718500  'pair':'pair'
|   |-IntegerLiteral 0x557d79718010  'int' 1
|   `-IntegerLiteral 0x557d79717e18  'int' 2
|-DeclStmt 0x557d79718650 
| `-VarDecl 0x557d79718568  col:17 p 'pair':'pair' 
parenlistinit
|   `-CXXParenListInitExpr 0x557d79718610  'pair':'pair'
| |-IntegerLiteral 0x557d797185d0  'int' 1
| `-IntegerLiteral 0x557d79717e18  'int' 2
|-DeclStmt 0x557d797187d8 
| `-VarDecl 0x557d79718680  col:8 b 'pair':'pair' listinit
|   `-InitListExpr 0x557d79718750  'pair':'pair'
| |-IntegerLiteral 0x557d797186e8  'int' 1
| `-CXXDefaultInitExpr 0x557d797187a0  'int'
`-CXXFunctionalCastExpr 0x557d797369a8  'pair':'pair' 
functional cast to pair 
  `-InitListExpr 0x557d79718868  'pair':'pair'
|-IntegerLiteral 0x557d79718800  'int' 1
`-CXXDefaultInitExpr 0x557d797188b8  'int'
```
It feels like the `ParentListExpr` is replaced during semantic analysis and 
there is no way to get it back. I also tried running `clang-query` and trying 
to `match parenListExpr()` and go 0 results. Is it just missing in the AST dump 
and I run `clang-query` incorrectly or do we actually not have the syntactic 
form of this expression 

[PATCH] D138777: [clang-tidy] Add check bugprone-multiple-new-in-one-expression.

2022-11-28 Thread Balázs Kéri via Phabricator via cfe-commits
balazske added a comment.

bitcoin, contour, qtbase, xerces was checked but nothing was detected by the 
check.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D138777/new/

https://reviews.llvm.org/D138777

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


[PATCH] D138807: [RISCV] Support vector crypto extension ISA string and assembly

2022-11-28 Thread Craig Topper via Phabricator via cfe-commits
craig.topper added a comment.

Can you link to a specification?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D138807/new/

https://reviews.llvm.org/D138807

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


[PATCH] D137487: [clang][Interp] Start implementing builtin functions

2022-11-28 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder added a comment.

Ping


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D137487/new/

https://reviews.llvm.org/D137487

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


[PATCH] D138822: [clang] Add test for CWG36

2022-11-28 Thread Vlad Serebrennikov via Phabricator via cfe-commits
Endill created this revision.
Endill added a project: clang-language-wg.
Herald added a project: All.
Endill requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D138822

Files:
  clang/test/CXX/drs/dr0xx.cpp
  clang/www/cxx_dr_status.html
  clang/www/make_cxx_dr_status

Index: clang/www/make_cxx_dr_status
===
--- clang/www/make_cxx_dr_status
+++ clang/www/make_cxx_dr_status
@@ -158,7 +158,7 @@
 # This refers to the old ("C++0x") concepts feature, which was not part
 # of any C++ International Standard or Technical Specification.
 continue
-  if dr.issue in (1432,2565):
+  if dr.issue in (2565, 2628):
 row_style = ' class="open"'
 avail, avail_style = availability(dr.issue)
   elif dr.status in ('open', 'concurrency', 'drafting', 'review', 'extension'):
Index: clang/www/cxx_dr_status.html
===
--- clang/www/cxx_dr_status.html
+++ clang/www/cxx_dr_status.html
@@ -252,9 +252,9 @@
   
   
 https://wg21.link/cwg36";>36
-DRWP
+CD6
 using-declarations in multiple-declaration contexts
-Unknown
+Yes
   
   
 https://wg21.link/cwg37";>37
@@ -696,7 +696,7 @@
   
   
 https://wg21.link/cwg110";>110
-DRWP
+CD6
 Can template functions and classes be declared in the same scope?
 Unknown
   
@@ -864,7 +864,7 @@
   
   
 https://wg21.link/cwg138";>138
-DRWP
+CD6
 Friend declaration name lookup
 Unknown
   
@@ -1056,7 +1056,7 @@
   
   
 https://wg21.link/cwg170";>170
-open
+review
 Pointer-to-member conversions
 Not resolved
   
@@ -1182,7 +1182,7 @@
   
   
 https://wg21.link/cwg191";>191
-DRWP
+CD6
 Name lookup does not handle complex nesting
 Unknown
   
@@ -1567,7 +1567,7 @@
   
   
 https://wg21.link/cwg255";>255
-DRWP
+CD6
 Placement deallocation functions and lookup ambiguity
 Unknown
   
@@ -1664,7 +1664,7 @@
   
   
 https://wg21.link/cwg271";>271
-DRWP
+CD6
 Explicit instantiation and template argument deduction
 Unknown
   
@@ -1712,7 +1712,7 @@
   
   
 https://wg21.link/cwg279";>279
-DRWP
+CD6
 Correspondence of "names for linkage purposes"
 Unknown
   
@@ -2066,7 +2066,7 @@
   
   
 https://wg21.link/cwg338";>338
-DRWP
+CD6
 Enumerator name with linkage used as class name in other translation unit
 Unknown
   
@@ -2198,7 +2198,7 @@
   
   
 https://wg21.link/cwg360";>360
-DRWP
+CD6
 Using-declaration that reduces access
 Unknown
   
@@ -2354,7 +2354,7 @@
   
   
 https://wg21.link/cwg386";>386
-DRWP
+CD6
 Friend declaration of name brought in by using-declaration
 Unknown
   
@@ -2432,7 +2432,7 @@
   
   
 https://wg21.link/cwg399";>399
-DRWP
+CD6
 Destructor lookup redux
 Unknown
   
@@ -2468,7 +2468,7 @@
   
   
 https://wg21.link/cwg405";>405
-DRWP
+CD6
 Unqualified function name lookup
 Unknown
   
@@ -2504,7 +2504,7 @@
   
   
 https://wg21.link/cwg411";>411
-WP
+CD6
 Use of universal-character-name in character versus string literals
 Unknown
   
@@ -2546,7 +2546,7 @@
   
   
 https://wg21.link/cwg418";>418
-DRWP
+CD6
 Imperfect wording on error on multiple default arguments on a called function
 Unknown
   
@@ -2766,11 +2766,11 @@
 When is a definition of a static data member required?
 Unknown
   
-  
+  
 https://wg21.link/cwg455";>455
-open
+NAD
 Partial ordering and non-deduced arguments
-Not resolved
+Unknown
   
   
 https://wg21.link/cwg456";>456
@@ -3254,7 +3254,7 @@
   
   
 https://wg21.link/cwg536";>536
-DRWP
+CD6
 Problems in the description of id-expressions
 Unknown
   
@@ -3364,7 +3364,7 @@
   
   
 https://wg21.link/cwg554";>554
-DRWP
+CD6
 Definition of “declarative region” and “scope”
 Unknown
   
@@ -3412,13 +3412,13 @@
   
   
 https://wg21.link/cwg562";>562
-DRWP
+CD6
 qualified-ids in non-expression contexts
 Unknown
   
   
 https://wg21.link/cwg563";>563
-DRWP
+CD6
 Linkage specification for objects
 Unknown
   
@@ -3506,11 +3506,11 @@
 void in an empty parameter list
 Yes
   
-  
+  
 https://wg21.link/cwg578";>578
-review
+CD6
 Phase 1 replacement of characters with universal-character-names
-Not resolved
+Unknown
   
   
 https://wg21.link/cwg579";>579
@@ -3640,7 +3640,7 @@
   
   
 https://wg21.link/cwg600";>600
-DRWP
+CD6
 Does access control apply to members or to names?
 Unknown
   
@@ -3682,7 +3682,7 @@
   
   
 https://wg21.link/cwg607";>607
-DRWP
+CD6
 Lookup of mem-initializer-ids
 Unknown
   
@@ -4760,11 +4760,11 @@

[PATCH] D129531: [clang][C++20] P0960R3 and P1975R0: Allow initializing aggregates from a parenthesized list of values

2022-11-28 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added inline comments.



Comment at: clang/lib/CodeGen/CGExprAgg.cpp:581
+  Expr *filler = nullptr;
+  if (auto *ILE = dyn_cast(ExprToVisit))
+filler = ILE->getArrayFiller();

ilya-biryukov wrote:
> ayzhao wrote:
> > ilya-biryukov wrote:
> > > - Should we have a filler for `CXXParenInitListExpr` too?
> > >   It seems like an important optimization and could have large effect on 
> > > compile times if we don't 
> > > 
> > > - Same question for semantic and syntactic-form (similar to 
> > > `InitListExpr`): should we have it here?
> > >   I am not sure if it's semantically required (probably not?), but that's 
> > > definitely something that `clang-tidy` and other source tools will rely 
> > > on.
> > > 
> > > We should probably share the code there, I suggest moving it to a shared 
> > > base class and using it where appropriate instead of the derived classes.
> > > Should we have a filler for CXXParenInitListExpr too? It seems like an 
> > > important optimization and could have large effect on compile times if we 
> > > don't
> > 
> > This feels like premature optimization - presumably, wouldn't this only be 
> > an issue with extraordinarily large (say, O(1000)) arrays?
> > 
> > > Same question for semantic and syntactic-form (similar to InitListExpr): 
> > > should we have it here? I am not sure if it's semantically required 
> > > (probably not?), but that's definitely something that clang-tidy and 
> > > other source tools will rely on
> > 
> > IIRC this doesn't apply to paren list aggregate expressions, as the 
> > syntatic form would be the enclosing `ParenListExpr`.
> > This feels like premature optimization - presumably, wouldn't this only be 
> > an issue with extraordinarily large (say, O(1000)) arrays?
> Yes, this should only happen with large arrays. Normally I would agree, but 
> it's surprising that changing `{}` to `()` in the compiler would lead to 
> performance degradation.
> In that sense, this premature optimization is already implemented, we are 
> rather degrading performance for a different syntax to do the same thing.
> 
> Although we could also land without it, but in that case could you open a GH 
> issue and add a FIXME to track the implementation of this particular 
> optimization?
> This should increase the chances of users finding the root cause of the issue 
> if they happen to hit it.
> 
> > IIRC this doesn't apply to paren list aggregate expressions, as the 
> > syntatic form would be the enclosing ParenListExpr.
> Do we even have the enclosing `ParenListExpr`? If I dump the AST with `clang 
> -fsyntax-only -Xclang=-ast-dump ...`  for the following code:
> ```
> struct pair { int a; int b = 2; };
> int main() {
>   pair(1); pair p(1);
>   pair b{1}; pair{1};
> }
> ```
> 
> I get 
> ```
> `-FunctionDecl 0x557d79717e98  line:2:5 main 'int ()'
>   `-CompoundStmt 0x557d797369d0 
> |-CXXFunctionalCastExpr 0x557d79718528  'pair':'pair' 
> functional cast to pair 
> | `-CXXParenListInitExpr 0x557d79718500  'pair':'pair'
> |   |-IntegerLiteral 0x557d79718010  'int' 1
> |   `-IntegerLiteral 0x557d79717e18  'int' 2
> |-DeclStmt 0x557d79718650 
> | `-VarDecl 0x557d79718568  col:17 p 'pair':'pair' 
> parenlistinit
> |   `-CXXParenListInitExpr 0x557d79718610  'pair':'pair'
> | |-IntegerLiteral 0x557d797185d0  'int' 1
> | `-IntegerLiteral 0x557d79717e18  'int' 2
> |-DeclStmt 0x557d797187d8 
> | `-VarDecl 0x557d79718680  col:8 b 'pair':'pair' listinit
> |   `-InitListExpr 0x557d79718750  'pair':'pair'
> | |-IntegerLiteral 0x557d797186e8  'int' 1
> | `-CXXDefaultInitExpr 0x557d797187a0  'int'
> `-CXXFunctionalCastExpr 0x557d797369a8  'pair':'pair' 
> functional cast to pair 
>   `-InitListExpr 0x557d79718868  'pair':'pair'
> |-IntegerLiteral 0x557d79718800  'int' 1
> `-CXXDefaultInitExpr 0x557d797188b8  'int'
> ```
> It feels like the `ParentListExpr` is replaced during semantic analysis and 
> there is no way to get it back. I also tried running `clang-query` and trying 
> to `match parenListExpr()` and go 0 results. Is it just missing in the AST 
> dump and I run `clang-query` incorrectly or do we actually not have the 
> syntactic form of this expression after all?
Another important thing to address from the dump: notice how braced 
initialization creates `CXXDefaultInitExpr` and `CXXParenListInitExpr` copies 
the default argument expression directly. It's really important to use the 
former form, here's the example that currently breaks:


```
#include 

struct func_init { int some_int; const char* fn = __builtin_FUNCTION(); };

int main() {
  func_init a(10);
  std::cout << "From paren init:" << a.fn << std::endl;

  func_init b{10};
  std::cout << "From braced init: " << b.fn << std::endl;
}
```

The program above is expected to report `main` for both cases, but instead we 
get:
```
From paren init:
From braced init: main
```


Repositor

[PATCH] D137487: [clang][Interp] Start implementing builtin functions

2022-11-28 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added inline comments.



Comment at: clang/lib/AST/Interp/ByteCodeExprGen.cpp:1374
   const Decl *Callee = E->getCalleeDecl();
-  if (const auto *FuncDecl = dyn_cast_or_null(Callee)) {
+  if (const auto *FuncDecl = dyn_cast_if_present(Callee)) {
 const Function *Func = getFunction(FuncDecl);

This is an unrelated change, perhaps could be in an NFC commit.



Comment at: clang/lib/AST/Interp/Interp.h:1354
 
-  APValue CallResult;
-  // Note that we cannot assert(CallResult.hasValue()) here since
-  // Ret() above only sets the APValue if the curent frame doesn't
-  // have a caller set.
-  if (Interpret(S, CallResult)) {
-NewFrame.release(); // Frame was delete'd already.
-assert(S.Current == FrameBefore);
-
-// For constructors, check that all fields have been initialized.
-if (Func->isConstructor()) {
-  if (!CheckCtorCall(S, PC, ThisPtr))
-return false;
+  // Evaluate builtin functions directly.
+  if (unsigned BID = Func->getBuiltinID()) {

`directly` reads oddly here?  Do you mean the 'immediately' definition of this?



Comment at: clang/lib/AST/Interp/Interp.h:1355
+  // Evaluate builtin functions directly.
+  if (unsigned BID = Func->getBuiltinID()) {
+if (InterpretBuiltin(S, PC, BID)) {

Rather than the 'if'/'else' pair, do we just want to immediately return on the 
failed builtin?  



Comment at: clang/lib/AST/Interp/Interp.h:1357
+if (InterpretBuiltin(S, PC, BID)) {
+  NewFrame.release();
+  return true;

What is going on here?  Why is this not a leak?  


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D137487/new/

https://reviews.llvm.org/D137487

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


[PATCH] D138822: [clang] Add test for CWG36

2022-11-28 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin added a comment.

Could you make a separate pull request for updating the core issue list (I 
didn't know it had been updated recently)?
Or, i think you could commit the update of the core issue list directly (do you 
have commit rights?) and then work on the DR.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D138822/new/

https://reviews.llvm.org/D138822

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


[PATCH] D137487: [clang][Interp] Start implementing builtin functions

2022-11-28 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder added inline comments.



Comment at: clang/lib/AST/Interp/ByteCodeExprGen.cpp:1374
   const Decl *Callee = E->getCalleeDecl();
-  if (const auto *FuncDecl = dyn_cast_or_null(Callee)) {
+  if (const auto *FuncDecl = dyn_cast_if_present(Callee)) {
 const Function *Func = getFunction(FuncDecl);

erichkeane wrote:
> This is an unrelated change, perhaps could be in an NFC commit.
Right, sure



Comment at: clang/lib/AST/Interp/Interp.h:1354
 
-  APValue CallResult;
-  // Note that we cannot assert(CallResult.hasValue()) here since
-  // Ret() above only sets the APValue if the curent frame doesn't
-  // have a caller set.
-  if (Interpret(S, CallResult)) {
-NewFrame.release(); // Frame was delete'd already.
-assert(S.Current == FrameBefore);
-
-// For constructors, check that all fields have been initialized.
-if (Func->isConstructor()) {
-  if (!CheckCtorCall(S, PC, ThisPtr))
-return false;
+  // Evaluate builtin functions directly.
+  if (unsigned BID = Func->getBuiltinID()) {

erichkeane wrote:
> `directly` reads oddly here?  Do you mean the 'immediately' definition of 
> this?
Yes, that was the purpose. I can reword it.



Comment at: clang/lib/AST/Interp/Interp.h:1355
+  // Evaluate builtin functions directly.
+  if (unsigned BID = Func->getBuiltinID()) {
+if (InterpretBuiltin(S, PC, BID)) {

erichkeane wrote:
> Rather than the 'if'/'else' pair, do we just want to immediately return on 
> the failed builtin?  
Sure, that's possible. I guess this ties into the question of whether to use a 
different opcode for builtin functions; but so far I have found builtin calls 
to be too similar to regular ones, esp. since they don't have a special AST 
node.



Comment at: clang/lib/AST/Interp/Interp.h:1357
+if (InterpretBuiltin(S, PC, BID)) {
+  NewFrame.release();
+  return true;

erichkeane wrote:
> What is going on here?  Why is this not a leak?  
The current frame is `delete`d when successfully returning the value of the 
function, this happens in the `Ret` (and `RetVoid`) function in `Interp.cpp`.

No opinion on whether that's the best way to do it though.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D137487/new/

https://reviews.llvm.org/D137487

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


[PATCH] D137487: [clang][Interp] Start implementing builtin functions

2022-11-28 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added inline comments.



Comment at: clang/lib/AST/Interp/Interp.h:1357
+if (InterpretBuiltin(S, PC, BID)) {
+  NewFrame.release();
+  return true;

tbaeder wrote:
> erichkeane wrote:
> > What is going on here?  Why is this not a leak?  
> The current frame is `delete`d when successfully returning the value of the 
> function, this happens in the `Ret` (and `RetVoid`) function in `Interp.cpp`.
> 
> No opinion on whether that's the best way to do it though.
I really dont like doing it this way, I see we're doing it the same in 1366, 
but if we're expecting someone else to delete a unique-ptr, we should give them 
ownership of the whole unique-ptr.  This mechanism is just obscuring the 
ownership semantics that unique_ptr is supposed to imply.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D137487/new/

https://reviews.llvm.org/D137487

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


[PATCH] D138598: [OpenMP] Do not add wrapper headers if using '-nogpuinc'

2022-11-28 Thread Joseph Huber via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG37edd910478d: [OpenMP] Do not add wrapper headers if using 
'-nogpuinc' (authored by jhuber6).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D138598/new/

https://reviews.llvm.org/D138598

Files:
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/test/Driver/openmp-offload-headers.c


Index: clang/test/Driver/openmp-offload-headers.c
===
--- /dev/null
+++ clang/test/Driver/openmp-offload-headers.c
@@ -0,0 +1,26 @@
+// REQUIRES: nvptx-registered-target
+// REQUIRES: amdgpu-registered-target
+
+// RUN:   %clang -### --target=x86_64-unknown-linux-gnu -fopenmp \
+// RUN: -fopenmp-targets=nvptx64-nvidia-cuda,amdgcn-amd-amdhsa 
-Xopenmp-target=nvptx64-nvidia-cuda --offload-arch=sm_70 \
+// RUN: -fopenmp-targets=nvptx64-nvidia-cuda,amdgcn-amd-amdhsa 
-Xopenmp-target=amdgcn-amd-amdhsa --offload-arch=gfx908  \
+// RUN: -nogpulib %s 2>&1 | FileCheck %s --check-prefix=CHECK-HEADERS
+// CHECK-HEADERS: "-cc1"{{.*}}"-internal-isystem" "{{.*}}openmp_wrappers" 
"-include" "__clang_openmp_device_functions.h"
+// CHECK-HEADERS: "-cc1"{{.*}}"-internal-isystem" "{{.*}}openmp_wrappers" 
"-include" "__clang_openmp_device_functions.h"
+
+// RUN:   %clang -### --target=x86_64-unknown-linux-gnu -fopenmp -nobuiltininc 
\
+// RUN: -fopenmp-targets=nvptx64-nvidia-cuda,amdgcn-amd-amdhsa 
-Xopenmp-target=nvptx64-nvidia-cuda --offload-arch=sm_70 \
+// RUN: -fopenmp-targets=nvptx64-nvidia-cuda,amdgcn-amd-amdhsa 
-Xopenmp-target=amdgcn-amd-amdhsa --offload-arch=gfx908  \
+// RUN: -nogpulib %s 2>&1 | FileCheck %s 
--check-prefix=CHECK-HEADERS-BUILTIN
+// CHECK-HEADERS-BUILTIN: "-cc1"{{.*}}"-include" 
"__clang_openmp_device_functions.h"
+// CHECK-HEADERS-BUILTIN: "-cc1"{{.*}}"-include" 
"__clang_openmp_device_functions.h"
+
+// RUN:   %clang -### --target=x86_64-unknown-linux-gnu -fopenmp -nostdinc \
+// RUN: -fopenmp-targets=nvptx64-nvidia-cuda,amdgcn-amd-amdhsa 
-Xopenmp-target=nvptx64-nvidia-cuda --offload-arch=sm_70 \
+// RUN: -fopenmp-targets=nvptx64-nvidia-cuda,amdgcn-amd-amdhsa 
-Xopenmp-target=amdgcn-amd-amdhsa --offload-arch=gfx908  \
+// RUN: -nogpulib %s 2>&1 | FileCheck %s 
--check-prefix=CHECK-HEADERS-DISABLED
+// RUN:   %clang -### --target=x86_64-unknown-linux-gnu -fopenmp -nogpuinc \
+// RUN: -fopenmp-targets=nvptx64-nvidia-cuda,amdgcn-amd-amdhsa 
-Xopenmp-target=nvptx64-nvidia-cuda --offload-arch=sm_70 \
+// RUN: -fopenmp-targets=nvptx64-nvidia-cuda,amdgcn-amd-amdhsa 
-Xopenmp-target=amdgcn-amd-amdhsa --offload-arch=gfx908  \
+// RUN: -nogpulib %s 2>&1 | FileCheck %s 
--check-prefix=CHECK-HEADERS-DISABLED
+// CHECK-HEADERS-DISABLED-NOT: "-cc1"{{.*}}"__clang_openmp_device_functions.h"
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -1282,6 +1282,7 @@
   // openmp_wrappers folder which contains alternative system headers.
   if (JA.isDeviceOffloading(Action::OFK_OpenMP) &&
   !Args.hasArg(options::OPT_nostdinc) &&
+  !Args.hasArg(options::OPT_nogpuinc) &&
   (getToolChain().getTriple().isNVPTX() ||
getToolChain().getTriple().isAMDGCN())) {
 if (!Args.hasArg(options::OPT_nobuiltininc)) {


Index: clang/test/Driver/openmp-offload-headers.c
===
--- /dev/null
+++ clang/test/Driver/openmp-offload-headers.c
@@ -0,0 +1,26 @@
+// REQUIRES: nvptx-registered-target
+// REQUIRES: amdgpu-registered-target
+
+// RUN:   %clang -### --target=x86_64-unknown-linux-gnu -fopenmp \
+// RUN: -fopenmp-targets=nvptx64-nvidia-cuda,amdgcn-amd-amdhsa -Xopenmp-target=nvptx64-nvidia-cuda --offload-arch=sm_70 \
+// RUN: -fopenmp-targets=nvptx64-nvidia-cuda,amdgcn-amd-amdhsa -Xopenmp-target=amdgcn-amd-amdhsa --offload-arch=gfx908  \
+// RUN: -nogpulib %s 2>&1 | FileCheck %s --check-prefix=CHECK-HEADERS
+// CHECK-HEADERS: "-cc1"{{.*}}"-internal-isystem" "{{.*}}openmp_wrappers" "-include" "__clang_openmp_device_functions.h"
+// CHECK-HEADERS: "-cc1"{{.*}}"-internal-isystem" "{{.*}}openmp_wrappers" "-include" "__clang_openmp_device_functions.h"
+
+// RUN:   %clang -### --target=x86_64-unknown-linux-gnu -fopenmp -nobuiltininc \
+// RUN: -fopenmp-targets=nvptx64-nvidia-cuda,amdgcn-amd-amdhsa -Xopenmp-target=nvptx64-nvidia-cuda --offload-arch=sm_70 \
+// RUN: -fopenmp-targets=nvptx64-nvidia-cuda,amdgcn-amd-amdhsa -Xopenmp-target=amdgcn-amd-amdhsa --offload-arch=gfx908  \
+// RUN: -nogpulib %s 2>&1 | FileCheck %s --check-prefix=CHECK-HEADERS-BUILTIN
+// CHECK-HEADERS-BUILTIN: "-cc1"{{.*}}"-include" "__clang_openmp_device_functions.h"
+// CHECK-HEADERS-BUILTIN: "-cc1"{{.*}}"-include" "__clang_openmp_device_functions.h"
+
+// RUN:   %clang -### --target=x86_64-

[clang] 37edd91 - [OpenMP] Do not add wrapper headers if using '-nogpuinc'

2022-11-28 Thread Joseph Huber via cfe-commits

Author: Joseph Huber
Date: 2022-11-28T10:20:31-06:00
New Revision: 37edd910478d911f93044d524a61974c991e6cae

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

LOG: [OpenMP] Do not add wrapper headers if using '-nogpuinc'

The OpenMP offloading toolchain uses wrapper headers to implement some
standard features on the GPU. Currently there is no way to turn these
off without also disabling all the standard includes altogether. This
patch makes `-nogpuinc` apply to these wrapper headers so we can use a
sterile toolchain. This was causing problems when attempting to compile
a `libc` for the GPU using OpenMP.

Reviewed By: jdoerfert

Differential Revision: https://reviews.llvm.org/D138598

Added: 
clang/test/Driver/openmp-offload-headers.c

Modified: 
clang/lib/Driver/ToolChains/Clang.cpp

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 765e766c3952..d8a1ebb45f60 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -1282,6 +1282,7 @@ void Clang::AddPreprocessingOptions(Compilation &C, const 
JobAction &JA,
   // openmp_wrappers folder which contains alternative system headers.
   if (JA.isDeviceOffloading(Action::OFK_OpenMP) &&
   !Args.hasArg(options::OPT_nostdinc) &&
+  !Args.hasArg(options::OPT_nogpuinc) &&
   (getToolChain().getTriple().isNVPTX() ||
getToolChain().getTriple().isAMDGCN())) {
 if (!Args.hasArg(options::OPT_nobuiltininc)) {

diff  --git a/clang/test/Driver/openmp-offload-headers.c 
b/clang/test/Driver/openmp-offload-headers.c
new file mode 100644
index ..3cf6500d872c
--- /dev/null
+++ b/clang/test/Driver/openmp-offload-headers.c
@@ -0,0 +1,26 @@
+// REQUIRES: nvptx-registered-target
+// REQUIRES: amdgpu-registered-target
+
+// RUN:   %clang -### --target=x86_64-unknown-linux-gnu -fopenmp \
+// RUN: -fopenmp-targets=nvptx64-nvidia-cuda,amdgcn-amd-amdhsa 
-Xopenmp-target=nvptx64-nvidia-cuda --offload-arch=sm_70 \
+// RUN: -fopenmp-targets=nvptx64-nvidia-cuda,amdgcn-amd-amdhsa 
-Xopenmp-target=amdgcn-amd-amdhsa --offload-arch=gfx908  \
+// RUN: -nogpulib %s 2>&1 | FileCheck %s --check-prefix=CHECK-HEADERS
+// CHECK-HEADERS: "-cc1"{{.*}}"-internal-isystem" "{{.*}}openmp_wrappers" 
"-include" "__clang_openmp_device_functions.h"
+// CHECK-HEADERS: "-cc1"{{.*}}"-internal-isystem" "{{.*}}openmp_wrappers" 
"-include" "__clang_openmp_device_functions.h"
+
+// RUN:   %clang -### --target=x86_64-unknown-linux-gnu -fopenmp -nobuiltininc 
\
+// RUN: -fopenmp-targets=nvptx64-nvidia-cuda,amdgcn-amd-amdhsa 
-Xopenmp-target=nvptx64-nvidia-cuda --offload-arch=sm_70 \
+// RUN: -fopenmp-targets=nvptx64-nvidia-cuda,amdgcn-amd-amdhsa 
-Xopenmp-target=amdgcn-amd-amdhsa --offload-arch=gfx908  \
+// RUN: -nogpulib %s 2>&1 | FileCheck %s 
--check-prefix=CHECK-HEADERS-BUILTIN
+// CHECK-HEADERS-BUILTIN: "-cc1"{{.*}}"-include" 
"__clang_openmp_device_functions.h"
+// CHECK-HEADERS-BUILTIN: "-cc1"{{.*}}"-include" 
"__clang_openmp_device_functions.h"
+
+// RUN:   %clang -### --target=x86_64-unknown-linux-gnu -fopenmp -nostdinc \
+// RUN: -fopenmp-targets=nvptx64-nvidia-cuda,amdgcn-amd-amdhsa 
-Xopenmp-target=nvptx64-nvidia-cuda --offload-arch=sm_70 \
+// RUN: -fopenmp-targets=nvptx64-nvidia-cuda,amdgcn-amd-amdhsa 
-Xopenmp-target=amdgcn-amd-amdhsa --offload-arch=gfx908  \
+// RUN: -nogpulib %s 2>&1 | FileCheck %s 
--check-prefix=CHECK-HEADERS-DISABLED
+// RUN:   %clang -### --target=x86_64-unknown-linux-gnu -fopenmp -nogpuinc \
+// RUN: -fopenmp-targets=nvptx64-nvidia-cuda,amdgcn-amd-amdhsa 
-Xopenmp-target=nvptx64-nvidia-cuda --offload-arch=sm_70 \
+// RUN: -fopenmp-targets=nvptx64-nvidia-cuda,amdgcn-amd-amdhsa 
-Xopenmp-target=amdgcn-amd-amdhsa --offload-arch=gfx908  \
+// RUN: -nogpulib %s 2>&1 | FileCheck %s 
--check-prefix=CHECK-HEADERS-DISABLED
+// CHECK-HEADERS-DISABLED-NOT: "-cc1"{{.*}}"__clang_openmp_device_functions.h"



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


[PATCH] D137487: [clang][Interp] Start implementing builtin functions

2022-11-28 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder added inline comments.



Comment at: clang/lib/AST/Interp/Interp.h:1357
+if (InterpretBuiltin(S, PC, BID)) {
+  NewFrame.release();
+  return true;

erichkeane wrote:
> tbaeder wrote:
> > erichkeane wrote:
> > > What is going on here?  Why is this not a leak?  
> > The current frame is `delete`d when successfully returning the value of the 
> > function, this happens in the `Ret` (and `RetVoid`) function in 
> > `Interp.cpp`.
> > 
> > No opinion on whether that's the best way to do it though.
> I really dont like doing it this way, I see we're doing it the same in 1366, 
> but if we're expecting someone else to delete a unique-ptr, we should give 
> them ownership of the whole unique-ptr.  This mechanism is just obscuring the 
> ownership semantics that unique_ptr is supposed to imply.
I blame @aaron.ballman :)

I'm gonna write it on my list and create a follow-up patch.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D137487/new/

https://reviews.llvm.org/D137487

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


[PATCH] D138807: [RISCV] Support vector crypto extension ISA string and assembly

2022-11-28 Thread Craig Topper via Phabricator via cfe-commits
craig.topper added inline comments.



Comment at: llvm/lib/Support/RISCVISAInfo.cpp:827
 {{"zvfh"}, {ImpliedExtsZvfh}},
+{{"zvkb"}, {ImpliedExtsV}},
+{{"zvkg"}, {ImpliedExtsV}},

Does Crypto really require V or could it work with Zve?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D138807/new/

https://reviews.llvm.org/D138807

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


[PATCH] D138387: [Clang] Implement static operator[]

2022-11-28 Thread Erich Keane via Phabricator via cfe-commits
erichkeane accepted this revision.
erichkeane added a comment.

LGTM, thanks!


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D138387/new/

https://reviews.llvm.org/D138387

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


[PATCH] D138807: [RISCV] Support vector crypto extension ISA string and assembly

2022-11-28 Thread Philip Reames via Phabricator via cfe-commits
reames added a comment.

Some very high level comments for the moment.

Until the spec is frozen, these need to be moved into the experimental 
namespace.  You should also add a mention of them under the experimental list 
in docs/RISCVUsage.  A link to the current spec version - along with an exact 
version you're implementing - in both the docs, and commit comment is also 
needed.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D138807/new/

https://reviews.llvm.org/D138807

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


[PATCH] D138797: [include-cleaner] Implement IWYU begin_keep/end_keep pragma support.

2022-11-28 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo updated this revision to Diff 478256.
VitaNuo added a comment.

Address review comments. Use annotation points instead of line numbers.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D138797/new/

https://reviews.llvm.org/D138797

Files:
  clang-tools-extra/include-cleaner/lib/Record.cpp
  clang-tools-extra/include-cleaner/unittests/RecordTest.cpp

Index: clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
===
--- clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
+++ clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
@@ -308,38 +308,87 @@
 for (llvm::StringRef File : FileNames)
   Inputs.ExtraFiles[File] = "";
   }
+
+  size_t offsetToLineNum(llvm::Annotations MainFile, size_t Offset) {
+int Count = MainFile.code().substr(0, Offset).count('\n');
+return Count + 1;
+  }
 };
 
 TEST_F(PragmaIncludeTest, IWYUKeep) {
-  Inputs.Code = R"cpp(// Line 1
-#include "keep1.h" // IWYU pragma: keep
-#include "keep2.h" /* IWYU pragma: keep */
+  llvm::Annotations MainFile(R"cpp(
+$keep1^#include "keep1.h" // IWYU pragma: keep
+$keep2^#include "keep2.h" /* IWYU pragma: keep */
 
-#include "export1.h" // IWYU pragma: export // line 5
+$export1^#include "export1.h" // IWYU pragma: export
 // IWYU pragma: begin_exports
-#include "export2.h" // Line 7
-#include "export3.h"
+$export2^#include "export2.h"
+$export3^#include "export3.h"
 // IWYU pragma: end_exports
 
-#include "normal.h" // Line 11
-  )cpp";
-  createEmptyFiles({"keep1.h", "keep2.h", "export1.h", "export2.h", "export3.h",
-"normal.h"});
+$normal^#include "normal.h"
+
+// IWYU pragma: begin_keep // Line 13
+$keep3^#include "keep3.h"
+$keep4^#include "keep4.h"
+// IWYU pragma: end_keep
+
+// IWYU pragma: begin_keep // Line 18
+$keep5^#include "keep5.h"
+// IWYU pragma: begin_keep
+$keep6^#include "keep6.h"
+$keep7^#include "keep7.h"
+// IWYU pragma: end_keep
+$keep8^#include "keep8.h"
+// IWYU pragma: end_keep
+  )cpp");
+
+  Inputs.Code = MainFile.code();
+  createEmptyFiles({"keep1.h", "keep2.h", "keep3.h", "keep4.h", "keep5.h",
+"keep6.h", "keep7.h", "keep8.h", "export1.h", "export2.h",
+"export3.h", "normal.h"});
 
   TestAST Processed = build();
   EXPECT_FALSE(PI.shouldKeep(1));
+
   // Keep
-  EXPECT_TRUE(PI.shouldKeep(2));
-  EXPECT_TRUE(PI.shouldKeep(3));
+  EXPECT_TRUE(
+  PI.shouldKeep(offsetToLineNum(MainFile, MainFile.point("keep1";
+  EXPECT_TRUE(
+  PI.shouldKeep(offsetToLineNum(MainFile, MainFile.point("keep2";
+
+  EXPECT_FALSE(PI.shouldKeep(13)); // line with "begin_keep" pragma
+  EXPECT_TRUE(
+  PI.shouldKeep(offsetToLineNum(MainFile, MainFile.point("keep3";
+  EXPECT_TRUE(
+  PI.shouldKeep(offsetToLineNum(MainFile, MainFile.point("keep4";
+  EXPECT_FALSE(PI.shouldKeep(16)); // line with "end_keep" pragma
+
+  EXPECT_FALSE(PI.shouldKeep(18)); // line with "begin_keep" pragma
+  EXPECT_TRUE(
+  PI.shouldKeep(offsetToLineNum(MainFile, MainFile.point("keep5";
+  EXPECT_FALSE(PI.shouldKeep(20)); // line with "begin_keep" pragma
+  EXPECT_TRUE(
+  PI.shouldKeep(offsetToLineNum(MainFile, MainFile.point("keep6";
+  EXPECT_TRUE(
+  PI.shouldKeep(offsetToLineNum(MainFile, MainFile.point("keep7";
+  EXPECT_FALSE(PI.shouldKeep(23)); // line with "end_keep" pragma
+  EXPECT_TRUE(
+  PI.shouldKeep(offsetToLineNum(MainFile, MainFile.point("keep8";
+  EXPECT_FALSE(PI.shouldKeep(25)); // line with "end_keep" pragma
 
   // Exports
-  EXPECT_TRUE(PI.shouldKeep(5));
-  EXPECT_TRUE(PI.shouldKeep(7));
-  EXPECT_TRUE(PI.shouldKeep(8));
+  EXPECT_TRUE(
+  PI.shouldKeep(offsetToLineNum(MainFile, MainFile.point("export1";
+  EXPECT_TRUE(
+  PI.shouldKeep(offsetToLineNum(MainFile, MainFile.point("export2";
+  EXPECT_TRUE(
+  PI.shouldKeep(offsetToLineNum(MainFile, MainFile.point("export3";
   EXPECT_FALSE(PI.shouldKeep(6)); // no # directive
   EXPECT_FALSE(PI.shouldKeep(9)); // no # directive
 
-  EXPECT_FALSE(PI.shouldKeep(11));
+  EXPECT_FALSE(
+  PI.shouldKeep(offsetToLineNum(MainFile, MainFile.point("normal";
 }
 
 TEST_F(PragmaIncludeTest, IWYUPrivate) {
Index: clang-tools-extra/include-cleaner/lib/Record.cpp
===
--- clang-tools-extra/include-cleaner/lib/Record.cpp
+++ clang-tools-extra/include-cleaner/lib/Record.cpp
@@ -186,9 +186,7 @@
 FileID HashFID = SM.getFileID(HashLoc);
 int HashLine = SM.getLineNumber(HashFID, SM.getFileOffset(HashLoc));
 checkForExport(HashFID, HashLine, File ? &File->getFileEntry() : nullptr);
-
-if (InMainFile && LastPragmaKeepInMainFileLine == HashLine)
-  Out->ShouldKeep.insert(HashLine);
+checkForKeep(HashLine);
   }
 
   void checkFo

[PATCH] D138797: [include-cleaner] Implement IWYU begin_keep/end_keep pragma support.

2022-11-28 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo marked an inline comment as done.
VitaNuo added inline comments.



Comment at: clang-tools-extra/include-cleaner/unittests/RecordTest.cpp:349
   EXPECT_TRUE(PI.shouldKeep(3));
+  EXPECT_FALSE(PI.shouldKeep(13));
+  EXPECT_TRUE(PI.shouldKeep(14));

hokein wrote:
> with more tests being added, these line-number-inlined tests now are hard to 
> follow, even with the line comment in the example.
> 
> I think we can polish these tests by using the annotation point `^`, 
> something like. 
> ```
> llvm::Annotation Code = R"cpp(
> $keep1^#include "keep1.h" // IWYU pragma: keep
> 
> $normal^%include "normal.h"
> )cpp";
> 
> EXPECT_TRUE(PI.shouldKeep(offsetToLine(Code.point("keep1";
> EXPECT_FALSE(PI.shouldKeep(offsetToLine(Code.point("normal";
> ```
> 
> We need to implement an `offsetToLine` function, it should be trivial to add 
> (basically calculate the number of `\n`s to the offset point).
Ok, thanks. Have a look now please. 


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D138797/new/

https://reviews.llvm.org/D138797

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


[PATCH] D126818: Itanium ABI: Implement mangling for constrained friends

2022-11-28 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added a comment.

In D126818#3943071 , @dfrib wrote:

> In D126818#3941201 , @erichkeane 
> wrote:
>
>> [...] particularly since the suggested wording says the opposite of what I 
>> THOUGHT the discussion was doing at the end?
>> [...] We might find ourselves wanting to hold off until CWG comes up with 
>> actual wording?
>
> Same reflection, and agreed.
>
>> I think perhaps we need to wait on CWG to clarify what they mean, at least 
>> by including a wording consistent with that top thing.  The unfortunate part 
>> here is that Clang implements 1/2 of this at the moment: we implement the 
>> SEMA changes, but not the mangling changes for the current wording.
>
> Should consider asking on the CWG reflector to make sure they are aware of 
> Clang's quite far-going implementation experience with fixing this defect (in 
> the way originally proposed), and of Itanium C++'s/@rjmccall's view that the 
> proposed ABI updates looks reasonable?

That seems valuable, would you mind doing so?


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D126818/new/

https://reviews.llvm.org/D126818

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


[PATCH] D138210: [clang] Require parameter pack to be last argument in concepts.

2022-11-28 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

Thanks for the explanation. LGTM! And thanks for adding an assert.

It's interesting that recovery for classes seems 
 to be a bit better here:

  template  struct invalid {};
  int a = invalid(10); // there is no error: undefined identified 
'invalid' 

but I suspect chasing the improvements there is out of scope for this 
particular GH issue. Maybe worth adding a FIXME/filing a GH issue for improving 
this in the future.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D138210/new/

https://reviews.llvm.org/D138210

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


[PATCH] D138727: [clang] Skip defaulted functions in zero-as-null-pointer-constant.

2022-11-28 Thread Jens Massberg via Phabricator via cfe-commits
massberg updated this revision to Diff 478261.
massberg added a comment.

Run clang-format on changed files.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D138727/new/

https://reviews.llvm.org/D138727

Files:
  clang/lib/Sema/Sema.cpp
  clang/test/SemaCXX/warn-zero-nullptr-cxx20.cpp


Index: clang/test/SemaCXX/warn-zero-nullptr-cxx20.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/warn-zero-nullptr-cxx20.cpp
@@ -0,0 +1,53 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s -isystem %S/Inputs 
-Wzero-as-null-pointer-constant -std=c++20
+
+#include 
+
+namespace std {
+class strong_ordering;
+
+// Mock how STD defined unspecified parameters for the operators below.
+struct _CmpUnspecifiedParam {
+  consteval
+  _CmpUnspecifiedParam(int _CmpUnspecifiedParam::*) noexcept {}
+};
+
+struct strong_ordering {
+  signed char value;
+
+  friend constexpr bool operator==(strong_ordering v,
+   _CmpUnspecifiedParam) noexcept {
+return v.value == 0;
+  }
+  friend constexpr bool operator<(strong_ordering v,
+  _CmpUnspecifiedParam) noexcept {
+return v.value < 0;
+  }
+  friend constexpr bool operator>(strong_ordering v,
+  _CmpUnspecifiedParam) noexcept {
+return v.value > 0;
+  }
+  friend constexpr bool operator>=(strong_ordering v,
+   _CmpUnspecifiedParam) noexcept {
+return v.value >= 0;
+  }
+  static const strong_ordering equal, greater, less;
+};
+constexpr strong_ordering strong_ordering::equal = {0};
+constexpr strong_ordering strong_ordering::greater = {1};
+constexpr strong_ordering strong_ordering::less = {-1};
+} // namespace std
+
+struct A {
+  int a;
+  constexpr auto operator<=>(const A &other) const = default;
+};
+
+void test_cxx_rewritten_binary_ops() {
+  A a1, a2;
+  bool result;
+  result = (a1 < a2);
+  result = (a1 >= a2);
+  int *ptr = 0; // expected-warning{{zero as null pointer constant}}
+  result = (a1 > (ptr == 0 ? a1 : a2)); // expected-warning{{zero as null 
pointer constant}}
+  result = (a1 > ((a1 > (ptr == 0 ? a1 : a2)) ? a1 : a2)); // 
expected-warning{{zero as null pointer constant}}
+}
Index: clang/lib/Sema/Sema.cpp
===
--- clang/lib/Sema/Sema.cpp
+++ clang/lib/Sema/Sema.cpp
@@ -597,6 +597,13 @@
   CodeSynthesisContext::RewritingOperatorAsSpaceship)
 return;
 
+  // Ignore null pointers in defaulted functions, e.g. defaulted comparison
+  // operators.
+  FunctionDecl *FD = getCurFunctionDecl();
+  if (FD && FD->isDefaulted()) {
+return;
+  }
+
   // If it is a macro from system header, and if the macro name is not "NULL",
   // do not warn.
   SourceLocation MaybeMacroLoc = E->getBeginLoc();


Index: clang/test/SemaCXX/warn-zero-nullptr-cxx20.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/warn-zero-nullptr-cxx20.cpp
@@ -0,0 +1,53 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s -isystem %S/Inputs -Wzero-as-null-pointer-constant -std=c++20
+
+#include 
+
+namespace std {
+class strong_ordering;
+
+// Mock how STD defined unspecified parameters for the operators below.
+struct _CmpUnspecifiedParam {
+  consteval
+  _CmpUnspecifiedParam(int _CmpUnspecifiedParam::*) noexcept {}
+};
+
+struct strong_ordering {
+  signed char value;
+
+  friend constexpr bool operator==(strong_ordering v,
+   _CmpUnspecifiedParam) noexcept {
+return v.value == 0;
+  }
+  friend constexpr bool operator<(strong_ordering v,
+  _CmpUnspecifiedParam) noexcept {
+return v.value < 0;
+  }
+  friend constexpr bool operator>(strong_ordering v,
+  _CmpUnspecifiedParam) noexcept {
+return v.value > 0;
+  }
+  friend constexpr bool operator>=(strong_ordering v,
+   _CmpUnspecifiedParam) noexcept {
+return v.value >= 0;
+  }
+  static const strong_ordering equal, greater, less;
+};
+constexpr strong_ordering strong_ordering::equal = {0};
+constexpr strong_ordering strong_ordering::greater = {1};
+constexpr strong_ordering strong_ordering::less = {-1};
+} // namespace std
+
+struct A {
+  int a;
+  constexpr auto operator<=>(const A &other) const = default;
+};
+
+void test_cxx_rewritten_binary_ops() {
+  A a1, a2;
+  bool result;
+  result = (a1 < a2);
+  result = (a1 >= a2);
+  int *ptr = 0; // expected-warning{{zero as null pointer constant}}
+  result = (a1 > (ptr == 0 ? a1 : a2)); // expected-warning{{zero as null pointer constant}}
+  result = (a1 > ((a1 > (ptr == 0 ? a1 : a2)) ? a1 : a2)); // expected-warning{{zero as null pointer constant}}
+}
Index: clang/lib/Sema/Sema.cpp
===
--- clang/lib/Sema/Sema.cpp
+++ clang/lib

[PATCH] D136078: Use-after-return sanitizer binary metadata

2022-11-28 Thread Marco Elver via Phabricator via cfe-commits
melver added inline comments.



Comment at: 
llvm/include/llvm/Transforms/Instrumentation/SanitizerBinaryMetadata.h:38
+
+const char *const kSanitizerBinaryMetadataCoveredSection = "sanmd_covered";
+const char *const kSanitizerBinaryMetadataAtomicsSection = "sanmd_atomics";

inline constexpr char[]



Comment at: llvm/lib/CodeGen/SanitizerBinaryMetadata.cpp:79
+  };
+  MD->replaceOperandWith(1, MDNode::get(F.getContext(), NewAuxMDs));
+  return false;

dvyukov wrote:
> Should this be a new method on MDBuilder?
As discussed, this could just use the MDBuilder, and then extract the operand 
out of the new MDNode without using the full MDNode.



Comment at: llvm/lib/Transforms/Instrumentation/SanitizerBinaryMetadata.cpp:244
   // metadata (if enabled).
   uint32_t PerInstrFeatureMask = getEnabledPerInstructionFeature();
   // Don't emit unnecessary covered metadata for all functions to save space.

I think this is no longer PerInstrFeatureMask, but should instead become 
FeatureMask.



Comment at: llvm/lib/Transforms/Instrumentation/SanitizerBinaryMetadata.cpp:247
   bool RequiresCovered = false;
-  if (PerInstrFeatureMask) {
+  if (PerInstrFeatureMask || Options.UAR) {
 for (BasicBlock &BB : F)

Comment why also `|| Options.UAR` (because PerInstrFeatureMask setting of UAR 
bit is deferred?).



Comment at: llvm/lib/Transforms/Instrumentation/SanitizerBinaryMetadata.cpp:254
+  if (F.isVarArg())
+PerInstrFeatureMask &= ~kSanitizerBinaryMetadataUAR;
+  if (PerInstrFeatureMask & kSanitizerBinaryMetadataUAR)

What if Options.Covered==true?

Will it still emit some UAR metadata or will it emit something it shouldn't?


Should the F.isVarArg() check be done above in `if (PerInstrFeatureMask || 
(Options.UAR && !F.isVarArg())` ? Then you wouldn't need the 
`PerInstrFeatureMask && RequiresCovered` change below and it could still just 
check `RequiresCovered` as before.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D136078/new/

https://reviews.llvm.org/D136078

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


  1   2   3   >