[PATCH] D116633: Add -fsanitize-address-param-retval to clang.

2022-01-14 Thread Kevin Athey via Phabricator via cfe-commits
kda updated this revision to Diff 399917.
kda marked an inline comment as done.
kda added a comment.

rename file


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116633

Files:
  clang/include/clang/Basic/CodeGenOptions.def
  clang/include/clang/Driver/Options.td
  clang/include/clang/Driver/SanitizerArgs.h
  clang/lib/CodeGen/BackendUtil.cpp
  clang/lib/Driver/SanitizerArgs.cpp
  clang/test/CodeGen/msan-param-retval.c
  clang/test/Driver/fsanitize-memory-param-retval.c

Index: clang/test/Driver/fsanitize-memory-param-retval.c
===
--- /dev/null
+++ clang/test/Driver/fsanitize-memory-param-retval.c
@@ -0,0 +1,12 @@
+// RUN: %clang -target i386-gnu-linux %s -fsanitize=memory -fsanitize-memory-param-retval -c -### 2>&1 | FileCheck %s
+// RUN: %clang -target x86_64-linux-gnu %s -fsanitize=memory -fsanitize-memory-param-retval -c -### 2>&1 | FileCheck %s
+// RUN: %clang -target aarch64-linux-gnu %s -fsanitize=memory -fsanitize-memory-param-retval -c -### 2>&1 | FileCheck %s
+// RUN: %clang -target riscv32-linux-gnu %s -fsanitize=memory -fsanitize-memory-param-retval -c -### 2>&1 | FileCheck %s
+// RUN: %clang -target riscv64-linux-gnu %s -fsanitize=memory -fsanitize-memory-param-retval -c -### 2>&1 | FileCheck %s
+// CHECK: "-fsanitize-memory-param-retval"
+
+// RUN: %clang -target aarch64-linux-gnu -fsyntax-only %s -fsanitize=memory -fsanitize-memory-param-retval -c -### 2>&1 | FileCheck --check-prefix=11 %s
+// 11: "-fsanitize-memory-param-retval"
+
+// RUN: not %clang -target x86_64-linux-gnu -fsyntax-only %s -fsanitize=memory -fsanitize-memory-param-retval=1 2>&1 | FileCheck --check-prefix=EXCESS %s
+// EXCESS: error: unknown argument: '-fsanitize-memory-param-retval=
Index: clang/test/CodeGen/msan-param-retval.c
===
--- /dev/null
+++ clang/test/CodeGen/msan-param-retval.c
@@ -0,0 +1,19 @@
+// RUN: %clang -target x86_64-linux-gnu -S -emit-llvm -fsanitize=memory -o - %s | \
+// RUN: FileCheck %s --check-prefix=CLEAN
+// RUN: %clang -target x86_64-linux-gnu -S -emit-llvm -fsanitize=memory -Xclang -enable-noundef-analysis -o - %s | \
+// RUN: FileCheck %s --check-prefixes=NOUNDEF,NOUNDEF_ONLY
+// RUN: %clang -target x86_64-linux-gnu -S -emit-llvm -fsanitize=memory -Xclang -enable-noundef-analysis -mllvm -msan-eager-checks -o - %s | \
+// RUN: FileCheck %s --check-prefixes=NOUNDEF,EAGER
+// RUN: %clang -target x86_64-linux-gnu -S -emit-llvm -fsanitize=memory -fsanitize-memory-param-retval -o - %s | \
+// RUN: FileCheck %s --check-prefixes=CLEAN
+// RUN: %clang -target x86_64-linux-gnu -S -emit-llvm -fsanitize=memory -Xclang -enable-noundef-analysis -fsanitize-memory-param-retval -o - %s | \
+// RUN: FileCheck %s --check-prefixes=NOUNDEF,EAGER
+
+void bar(int x) {
+}
+
+// CLEAN:   define dso_local void @bar(i32 %x) #0 {
+// NOUNDEF: define dso_local void @bar(i32 noundef %x) #0 {
+// CLEAN:@__msan_param_tls
+// NOUNDEF_ONLY: @__msan_param_tls
+// EAGER-NOT:@__msan_param_tls
Index: clang/lib/Driver/SanitizerArgs.cpp
===
--- clang/lib/Driver/SanitizerArgs.cpp
+++ clang/lib/Driver/SanitizerArgs.cpp
@@ -641,10 +641,14 @@
 Args.hasFlag(options::OPT_fsanitize_memory_use_after_dtor,
  options::OPT_fno_sanitize_memory_use_after_dtor,
  MsanUseAfterDtor);
+MsanParamRetval = Args.hasFlag(
+options::OPT_fsanitize_memory_param_retval,
+options::OPT_fno_sanitize_memory_param_retval, MsanParamRetval);
 NeedPIE |= !(TC.getTriple().isOSLinux() &&
  TC.getTriple().getArch() == llvm::Triple::x86_64);
   } else {
 MsanUseAfterDtor = false;
+MsanParamRetval = false;
   }
 
   if (AllAddedKinds & SanitizerKind::Thread) {
@@ -1096,6 +1100,9 @@
   if (MsanUseAfterDtor)
 CmdArgs.push_back("-fsanitize-memory-use-after-dtor");
 
+  if (MsanParamRetval)
+CmdArgs.push_back("-fsanitize-memory-param-retval");
+
   // FIXME: Pass these parameters as function attributes, not as -llvm flags.
   if (!TsanMemoryAccess) {
 CmdArgs.push_back("-mllvm");
Index: clang/lib/CodeGen/BackendUtil.cpp
===
--- clang/lib/CodeGen/BackendUtil.cpp
+++ clang/lib/CodeGen/BackendUtil.cpp
@@ -358,7 +358,8 @@
   int TrackOrigins = CGOpts.SanitizeMemoryTrackOrigins;
   bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Memory);
   PM.add(createMemorySanitizerLegacyPassPass(
-  MemorySanitizerOptions{TrackOrigins, Recover, CompileKernel}));
+  MemorySanitizerOptions{TrackOrigins, Recover, CompileKernel,
+ CGOpts.SanitizeMemoryParamRetval != 0}));
 
   // MemorySanitizer inserts complex instrumentation that mostly follows
   // the logic of the original c

[PATCH] D116633: Add -fsanitize-address-param-retval to clang.

2022-01-14 Thread Kevin Athey via Phabricator via cfe-commits
kda added inline comments.



Comment at: clang/lib/CodeGen/BackendUtil.cpp:362
+  MemorySanitizerOptions{TrackOrigins, Recover, CompileKernel,
+ CGOpts.SanitizeMemoryParamRetval != 0}));
 

vitalybuka wrote:
> we use implicit cast mostly, e.g. addAddressSanitizerPasses
I agree, AND the compiler complains of needing a static_cast.
Of course, below (line 1167) where the constructor is called explicitly, it 
works fine.
I think this is a case of 2 implicit casts and hence the compiler balks.

There are 2 other possibilities aside from the static_cast:
 - assign to a bool, then use the bool
 - construct the options on the stack (like line 1167)

I found my solution to be the most direct, clear and simple.



Comment at: clang/test/CodeGen/param-retval-eager-checks.c:1
+// RUN: %clang -target x86_64-linux-gnu -S -emit-llvm -fsanitize=memory -o - 
%s | \
+// RUN: FileCheck %s --check-prefix=CLEAN

vitalybuka wrote:
> vitalybuka wrote:
> > Would you like to remove "| \" ?
> > 80 char limit is not enforced on tests, multi line RUN: is even harder to 
> > read then long line
> This dir contains tests for a lot of different componets
> can you please add msan in name
> 
> e.g. "msan-param-retval.c"
> Would you like to remove "| \" ?
> 80 char limit is not enforced on tests, multi line RUN: is even harder to 
> read then long line

No. I broke the lines there as it makes it easier to see the differences, as 
the flags and the FileCheck are aligned.  (It wasn't about 80 characters.)





Comment at: clang/test/CodeGen/param-retval-eager-checks.c:5
+// RUN: FileCheck %s --check-prefixes=NOUNDEF,NOUNDEF_ONLY
+// RUN: %clang -target x86_64-linux-gnu -S -emit-llvm -fsanitize=memory 
-Xclang -enable-noundef-analysis -mllvm -msan-eager-checks -o - %s | \
+// RUN: FileCheck %s --check-prefixes=NOUNDEF,EAGER

vitalybuka wrote:
> we probably don't need mllvm test here
No, not needed.
And I would like to keep it, as it shows the equivalency between the flags.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116633

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


[PATCH] D117289: [clang-format] Fix namespace end comments fixer with anonymous namespaces.

2022-01-14 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius created this revision.
curdeius added reviewers: MyDeveloperDay, HazardyKnusperkeks, owenpan.
curdeius requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Previously, a strange trailing comment was produced:

  namespace out { namespace {
  }} // namespace out::

(mind the "out::").


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D117289

Files:
  clang/lib/Format/NamespaceEndCommentsFixer.cpp
  clang/unittests/Format/NamespaceEndCommentsFixerTest.cpp


Index: clang/unittests/Format/NamespaceEndCommentsFixerTest.cpp
===
--- clang/unittests/Format/NamespaceEndCommentsFixerTest.cpp
+++ clang/unittests/Format/NamespaceEndCommentsFixerTest.cpp
@@ -256,6 +256,15 @@
 "int j;\n"
 "};}",
 CompactNamespacesStyle));
+  EXPECT_EQ("namespace out { namespace {\n"
+"int i;\n"
+"int j;\n"
+"}}// namespace out",
+fixNamespaceEndComments("namespace out { namespace {\n"
+"int i;\n"
+"int j;\n"
+"}}",
+CompactNamespacesStyle));
 
   // Adds an end comment after a semicolon.
   EXPECT_EQ("namespace {\n"
@@ -609,6 +618,11 @@
 "}// banamespace in\n"
 "} // namespace out",
 CompactNamespacesStyle));
+  EXPECT_EQ("namespace out { namespace {\n"
+"}} // namespace out",
+fixNamespaceEndComments("namespace out { namespace {\n"
+"}} // namespace out::",
+CompactNamespacesStyle));
 }
 
 TEST_F(NamespaceEndCommentsFixerTest, UpdatesInvalidMacroEndLineComment) {
Index: clang/lib/Format/NamespaceEndCommentsFixer.cpp
===
--- clang/lib/Format/NamespaceEndCommentsFixer.cpp
+++ clang/lib/Format/NamespaceEndCommentsFixer.cpp
@@ -261,7 +261,8 @@
   updateEndComment(EndCommentPrevTok, std::string(), SourceMgr, 
&Fixes);
 }
 ++CompactedNamespacesCount;
-AllNamespaceNames = "::" + NamespaceName + AllNamespaceNames;
+if (!NamespaceName.empty())
+  AllNamespaceNames = "::" + NamespaceName + AllNamespaceNames;
 continue;
   }
   NamespaceName += AllNamespaceNames;


Index: clang/unittests/Format/NamespaceEndCommentsFixerTest.cpp
===
--- clang/unittests/Format/NamespaceEndCommentsFixerTest.cpp
+++ clang/unittests/Format/NamespaceEndCommentsFixerTest.cpp
@@ -256,6 +256,15 @@
 "int j;\n"
 "};}",
 CompactNamespacesStyle));
+  EXPECT_EQ("namespace out { namespace {\n"
+"int i;\n"
+"int j;\n"
+"}}// namespace out",
+fixNamespaceEndComments("namespace out { namespace {\n"
+"int i;\n"
+"int j;\n"
+"}}",
+CompactNamespacesStyle));
 
   // Adds an end comment after a semicolon.
   EXPECT_EQ("namespace {\n"
@@ -609,6 +618,11 @@
 "}// banamespace in\n"
 "} // namespace out",
 CompactNamespacesStyle));
+  EXPECT_EQ("namespace out { namespace {\n"
+"}} // namespace out",
+fixNamespaceEndComments("namespace out { namespace {\n"
+"}} // namespace out::",
+CompactNamespacesStyle));
 }
 
 TEST_F(NamespaceEndCommentsFixerTest, UpdatesInvalidMacroEndLineComment) {
Index: clang/lib/Format/NamespaceEndCommentsFixer.cpp
===
--- clang/lib/Format/NamespaceEndCommentsFixer.cpp
+++ clang/lib/Format/NamespaceEndCommentsFixer.cpp
@@ -261,7 +261,8 @@
   updateEndComment(EndCommentPrevTok, std::string(), SourceMgr, &Fixes);
 }
 ++CompactedNamespacesCount;
-AllNamespaceNames = "::" + NamespaceName + AllNamespaceNames;
+if (!NamespaceName.empty())
+  AllNamespaceNames = "::" + NamespaceName + AllNamespaceNames;
 continue;
   }
   NamespaceName += AllNamespaceNames;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D105169: [Clang/Test]: Rename enable_noundef_analysis to disable-noundef-analysis and turn it off by default

2022-01-14 Thread Hyeongyu Kim via Phabricator via cfe-commits
hyeongyukim added a comment.

@nathanchance Hi, I analyzed all four warnings.

Warning #1: can be handled by x86-backend. filled issue #53118 

Warning #2: bug in the kernel, fixed in the next version.
Warning #3: same reason with #2
Warning #4: It was not reproduced in the latest clang.

As you see, one of this patch's advantages is that it exposed some bugs in the 
kernel!
All issues are either identified or will be fixed soon. Is it okay to recommit 
this patch?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105169

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


[PATCH] D117289: [clang-format] Fix namespace end comments fixer with anonymous namespaces.

2022-01-14 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay accepted this revision.
MyDeveloperDay added a comment.
This revision is now accepted and ready to land.

LGTM


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D117289

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


[PATCH] D117142: [clang-format] Fix short functions being considered as inline inside an indented namespace.

2022-01-14 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay accepted this revision.
MyDeveloperDay added a comment.
This revision is now accepted and ready to land.

LGTM


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D117142

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


[clang] a0458b5 - Add -fsanitize-address-param-retval to clang.

2022-01-14 Thread Kevin Athey via cfe-commits

Author: Kevin Athey
Date: 2022-01-14T00:41:28-08:00
New Revision: a0458b531cfc52fc1a93002f125b61842f6b30f7

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

LOG: Add -fsanitize-address-param-retval to clang.

With the introduction of this flag, it is no longer necessary to enable noundef 
analysis with 4 separate flags.
(-Xclang -enable-noundef-analysis -mllvm -msan-eager-checks=1).
This change only covers the introduction into the compiler.

This is a follow up to: https://reviews.llvm.org/D116855

Reviewed By: vitalybuka

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

Added: 
clang/test/CodeGen/msan-param-retval.c
clang/test/Driver/fsanitize-memory-param-retval.c

Modified: 
clang/include/clang/Basic/CodeGenOptions.def
clang/include/clang/Driver/Options.td
clang/include/clang/Driver/SanitizerArgs.h
clang/lib/CodeGen/BackendUtil.cpp
clang/lib/Driver/SanitizerArgs.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/CodeGenOptions.def 
b/clang/include/clang/Basic/CodeGenOptions.def
index 723302f108e20..035d0a665b26d 100644
--- a/clang/include/clang/Basic/CodeGenOptions.def
+++ b/clang/include/clang/Basic/CodeGenOptions.def
@@ -231,6 +231,9 @@ CODEGENOPT(SanitizeMemoryTrackOrigins, 2, 0) ///< Enable 
tracking origins in
 ENUM_CODEGENOPT(SanitizeAddressDtor, llvm::AsanDtorKind, 2,
 llvm::AsanDtorKind::Global)  ///< Set how ASan global
  ///< destructors are emitted.
+CODEGENOPT(SanitizeMemoryParamRetval, 1, 0) ///< Enable detection of 
uninitialized
+///< parameters and return values
+///< in MemorySanitizer
 CODEGENOPT(SanitizeMemoryUseAfterDtor, 1, 0) ///< Enable use-after-delete 
detection
  ///< in MemorySanitizer
 CODEGENOPT(SanitizeCfiCrossDso, 1, 0) ///< Enable cross-dso support in CFI.

diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 4bcb7bd4c3969..ecdeb900e1c0c 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -1669,6 +1669,13 @@ def sanitize_address_destructor_EQ
   NormalizedValuesScope<"llvm::AsanDtorKind">,
   NormalizedValues<["None", "Global"]>,
   MarshallingInfoEnum, "Global">;
+defm sanitize_memory_param_retval
+  : BoolOption<"f", "sanitize-memory-param-retval",
+  CodeGenOpts<"SanitizeMemoryParamRetval">,
+  DefaultFalse,
+  PosFlag, NegFlag,
+  BothFlags<[], " detection of uninitialized parameters and return 
values">>,
+Group;
 // Note: This flag was introduced when it was necessary to distinguish between
 //   ABI for correct codegen.  This is no longer needed, but the flag is
 //   not removed since targeting either ABI will behave the same.

diff  --git a/clang/include/clang/Driver/SanitizerArgs.h 
b/clang/include/clang/Driver/SanitizerArgs.h
index 84bb324775d18..d288b0151c9f7 100644
--- a/clang/include/clang/Driver/SanitizerArgs.h
+++ b/clang/include/clang/Driver/SanitizerArgs.h
@@ -33,6 +33,7 @@ class SanitizerArgs {
   int CoverageFeatures = 0;
   int MsanTrackOrigins = 0;
   bool MsanUseAfterDtor = true;
+  bool MsanParamRetval = false;
   bool CfiCrossDso = false;
   bool CfiICallGeneralizePointers = false;
   bool CfiCanonicalJumpTables = false;

diff  --git a/clang/lib/CodeGen/BackendUtil.cpp 
b/clang/lib/CodeGen/BackendUtil.cpp
index 6ce125c027366..67fee7f35ca17 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -358,7 +358,8 @@ static void addGeneralOptsForMemorySanitizer(const 
PassManagerBuilder &Builder,
   int TrackOrigins = CGOpts.SanitizeMemoryTrackOrigins;
   bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Memory);
   PM.add(createMemorySanitizerLegacyPassPass(
-  MemorySanitizerOptions{TrackOrigins, Recover, CompileKernel}));
+  MemorySanitizerOptions{TrackOrigins, Recover, CompileKernel,
+ CGOpts.SanitizeMemoryParamRetval != 0}));
 
   // MemorySanitizer inserts complex instrumentation that mostly follows
   // the logic of the original code, but operates on "shadow" values.
@@ -1163,11 +1164,11 @@ static void addSanitizers(const Triple &TargetTriple,
 int TrackOrigins = CodeGenOpts.SanitizeMemoryTrackOrigins;
 bool Recover = CodeGenOpts.SanitizeRecover.has(Mask);
 
-MPM.addPass(
-ModuleMemorySanitizerPass({TrackOrigins, Recover, CompileKernel}));
+MemorySanitizerOptions options(TrackOrigins, Recover, CompileKernel,
+   CodeGenOpts.SanitizeMemoryParamRetval);
+MPM.addPass(ModuleMemorySanitizerPass(options));

[PATCH] D116633: Add -fsanitize-address-param-retval to clang.

2022-01-14 Thread Kevin Athey 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 rGa0458b531cfc: Add -fsanitize-address-param-retval to clang. 
(authored by kda).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116633

Files:
  clang/include/clang/Basic/CodeGenOptions.def
  clang/include/clang/Driver/Options.td
  clang/include/clang/Driver/SanitizerArgs.h
  clang/lib/CodeGen/BackendUtil.cpp
  clang/lib/Driver/SanitizerArgs.cpp
  clang/test/CodeGen/msan-param-retval.c
  clang/test/Driver/fsanitize-memory-param-retval.c

Index: clang/test/Driver/fsanitize-memory-param-retval.c
===
--- /dev/null
+++ clang/test/Driver/fsanitize-memory-param-retval.c
@@ -0,0 +1,12 @@
+// RUN: %clang -target i386-gnu-linux %s -fsanitize=memory -fsanitize-memory-param-retval -c -### 2>&1 | FileCheck %s
+// RUN: %clang -target x86_64-linux-gnu %s -fsanitize=memory -fsanitize-memory-param-retval -c -### 2>&1 | FileCheck %s
+// RUN: %clang -target aarch64-linux-gnu %s -fsanitize=memory -fsanitize-memory-param-retval -c -### 2>&1 | FileCheck %s
+// RUN: %clang -target riscv32-linux-gnu %s -fsanitize=memory -fsanitize-memory-param-retval -c -### 2>&1 | FileCheck %s
+// RUN: %clang -target riscv64-linux-gnu %s -fsanitize=memory -fsanitize-memory-param-retval -c -### 2>&1 | FileCheck %s
+// CHECK: "-fsanitize-memory-param-retval"
+
+// RUN: %clang -target aarch64-linux-gnu -fsyntax-only %s -fsanitize=memory -fsanitize-memory-param-retval -c -### 2>&1 | FileCheck --check-prefix=11 %s
+// 11: "-fsanitize-memory-param-retval"
+
+// RUN: not %clang -target x86_64-linux-gnu -fsyntax-only %s -fsanitize=memory -fsanitize-memory-param-retval=1 2>&1 | FileCheck --check-prefix=EXCESS %s
+// EXCESS: error: unknown argument: '-fsanitize-memory-param-retval=
Index: clang/test/CodeGen/msan-param-retval.c
===
--- /dev/null
+++ clang/test/CodeGen/msan-param-retval.c
@@ -0,0 +1,19 @@
+// RUN: %clang -target x86_64-linux-gnu -S -emit-llvm -fsanitize=memory -o - %s | \
+// RUN: FileCheck %s --check-prefix=CLEAN
+// RUN: %clang -target x86_64-linux-gnu -S -emit-llvm -fsanitize=memory -Xclang -enable-noundef-analysis -o - %s | \
+// RUN: FileCheck %s --check-prefixes=NOUNDEF,NOUNDEF_ONLY
+// RUN: %clang -target x86_64-linux-gnu -S -emit-llvm -fsanitize=memory -Xclang -enable-noundef-analysis -mllvm -msan-eager-checks -o - %s | \
+// RUN: FileCheck %s --check-prefixes=NOUNDEF,EAGER
+// RUN: %clang -target x86_64-linux-gnu -S -emit-llvm -fsanitize=memory -fsanitize-memory-param-retval -o - %s | \
+// RUN: FileCheck %s --check-prefixes=CLEAN
+// RUN: %clang -target x86_64-linux-gnu -S -emit-llvm -fsanitize=memory -Xclang -enable-noundef-analysis -fsanitize-memory-param-retval -o - %s | \
+// RUN: FileCheck %s --check-prefixes=NOUNDEF,EAGER
+
+void bar(int x) {
+}
+
+// CLEAN:   define dso_local void @bar(i32 %x) #0 {
+// NOUNDEF: define dso_local void @bar(i32 noundef %x) #0 {
+// CLEAN:@__msan_param_tls
+// NOUNDEF_ONLY: @__msan_param_tls
+// EAGER-NOT:@__msan_param_tls
Index: clang/lib/Driver/SanitizerArgs.cpp
===
--- clang/lib/Driver/SanitizerArgs.cpp
+++ clang/lib/Driver/SanitizerArgs.cpp
@@ -641,10 +641,14 @@
 Args.hasFlag(options::OPT_fsanitize_memory_use_after_dtor,
  options::OPT_fno_sanitize_memory_use_after_dtor,
  MsanUseAfterDtor);
+MsanParamRetval = Args.hasFlag(
+options::OPT_fsanitize_memory_param_retval,
+options::OPT_fno_sanitize_memory_param_retval, MsanParamRetval);
 NeedPIE |= !(TC.getTriple().isOSLinux() &&
  TC.getTriple().getArch() == llvm::Triple::x86_64);
   } else {
 MsanUseAfterDtor = false;
+MsanParamRetval = false;
   }
 
   if (AllAddedKinds & SanitizerKind::Thread) {
@@ -1096,6 +1100,9 @@
   if (MsanUseAfterDtor)
 CmdArgs.push_back("-fsanitize-memory-use-after-dtor");
 
+  if (MsanParamRetval)
+CmdArgs.push_back("-fsanitize-memory-param-retval");
+
   // FIXME: Pass these parameters as function attributes, not as -llvm flags.
   if (!TsanMemoryAccess) {
 CmdArgs.push_back("-mllvm");
Index: clang/lib/CodeGen/BackendUtil.cpp
===
--- clang/lib/CodeGen/BackendUtil.cpp
+++ clang/lib/CodeGen/BackendUtil.cpp
@@ -358,7 +358,8 @@
   int TrackOrigins = CGOpts.SanitizeMemoryTrackOrigins;
   bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Memory);
   PM.add(createMemorySanitizerLegacyPassPass(
-  MemorySanitizerOptions{TrackOrigins, Recover, CompileKernel}));
+  MemorySanitizerOptions{TrackOrigins, Recover, CompileKernel,
+ CGOpts.SanitizeMemoryParamRetval != 0

[PATCH] D117197: [clang-format] Add new option to support adding a space between Javascript Union and Intersection types

2022-01-14 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay updated this revision to Diff 399922.
MyDeveloperDay marked 10 inline comments as done.
MyDeveloperDay added a comment.

Make suggested improvements 
Add additional test case


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

https://reviews.llvm.org/D117197

Files:
  clang/docs/ClangFormatStyleOptions.rst
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Format/Format.h
  clang/lib/Format/Format.cpp
  clang/lib/Format/TokenAnnotator.cpp
  clang/unittests/Format/FormatTest.cpp
  clang/unittests/Format/FormatTestJS.cpp

Index: clang/unittests/Format/FormatTestJS.cpp
===
--- clang/unittests/Format/FormatTestJS.cpp
+++ clang/unittests/Format/FormatTestJS.cpp
@@ -1674,6 +1674,31 @@
   verifyFormat("export type X = {\n"
"  a: Foo|Bar;\n"
"};");
+
+  auto Style = getGoogleJSStyleWithColumns(60);
+  Style.SpacesInJavaScriptUnion = true;
+  verifyFormat("let x: A | B = A | B;", Style);
+  verifyFormat("let x?: A | B = A | B;", Style);
+  verifyFormat("let x: A & B | C = A & B;", Style);
+  verifyFormat("let x: Foo = new Foo();", Style);
+  verifyFormat("function(x: A | B): C & D {}", Style);
+  verifyFormat("function(x: A | B = A | B): C & D {}", Style);
+  verifyFormat("function x(path: number | string) {}", Style);
+  verifyFormat("function x(): string | number {}", Style);
+  verifyFormat("type Foo = Bar | Baz;", Style);
+  verifyFormat("type Foo = Bar | Baz;", Style);
+  verifyFormat("type Foo = (Bar | Baz);", Style);
+  verifyFormat("let x: Bar | Baz;", Style);
+  verifyFormat("let x: Bar | Baz;", Style);
+  verifyFormat("let x: (Foo | Bar)[];", Style);
+  verifyFormat("type X = {\n"
+   "  a: Foo | Bar;\n"
+   "};",
+   Style);
+  verifyFormat("export type X = {\n"
+   "  a: Foo | Bar;\n"
+   "};",
+   Style);
 }
 
 TEST_F(FormatTestJS, UnionIntersectionTypesInObjectType) {
@@ -1686,6 +1711,19 @@
"b: b|null,\n"
"  }) {}\n"
"}");
+
+  auto Style = getGoogleJSStyleWithColumns(60);
+  Style.SpacesInJavaScriptUnion = true;
+  verifyFormat("let x: {x: number | null} = {x: number | null};", Style);
+  verifyFormat("let nested: {x: {y: number | null}};", Style);
+  verifyFormat("let mixed: {x: [number | null, {w: number}]};", Style);
+  verifyFormat("class X {\n"
+   "  contructor(x: {\n"
+   "a: a | null,\n"
+   "b: b | null,\n"
+   "  }) {}\n"
+   "}",
+   Style);
 }
 
 TEST_F(FormatTestJS, ClassDeclarations) {
Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -18789,6 +18789,7 @@
   CHECK_PARSE_BOOL(SpaceInEmptyParentheses);
   CHECK_PARSE_BOOL(SpacesInContainerLiterals);
   CHECK_PARSE_BOOL(SpacesInCStyleCastParentheses);
+  CHECK_PARSE_BOOL(SpacesInJavaScriptUnion);
   CHECK_PARSE_BOOL(SpaceAfterCStyleCast);
   CHECK_PARSE_BOOL(SpaceAfterTemplateKeyword);
   CHECK_PARSE_BOOL(SpaceAfterLogicalNot);
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -3517,8 +3517,13 @@
   return true;
 if (Right.isOneOf(TT_JsTypeColon, TT_JsTypeOptionalQuestion))
   return false;
-if (Left.is(TT_JsTypeOperator) || Right.is(TT_JsTypeOperator))
+if (Left.is(TT_JsTypeOperator) || Right.is(TT_JsTypeOperator)) {
+  if ((Left.is(TT_JsTypeOperator) && Right.isTypeOrIdentifier()) ||
+  (Left.isTypeOrIdentifier() || Left.is(TT_TemplateCloser)) &&
+  Right.is(TT_JsTypeOperator))
+return Style.SpacesInJavaScriptUnion;
   return false;
+}
 if ((Left.is(tok::l_brace) || Right.is(tok::r_brace)) &&
 Line.First->isOneOf(Keywords.kw_import, tok::kw_export))
   return false;
Index: clang/lib/Format/Format.cpp
===
--- clang/lib/Format/Format.cpp
+++ clang/lib/Format/Format.cpp
@@ -818,6 +818,7 @@
Style.SpacesInCStyleCastParentheses);
 IO.mapOptional("SpacesInLineCommentPrefix",
Style.SpacesInLineCommentPrefix);
+IO.mapOptional("SpacesInJavaScriptUnion", Style.SpacesInJavaScriptUnion);
 IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses);
 IO.mapOptional("SpacesInSquareBrackets", Style.SpacesInSquareBrackets);
 IO.mapOptional("SpaceBeforeSquareBrackets",
@@ -1221,6 +1222,7 @@
   LLVMStyle.SpacesInContainerLiterals = true;
   LLVMStyle.SpacesInCStyleCastParentheses = false;
   LLVMStyle.SpacesInLineCommentPrefix = {/*Minimum=*/1, /*Maximum=*/-1u};
+  LLVMStyle.SpacesInJavaScriptUnion = false;
   LLVMStyle.SpaceAfterCStyleCas

[PATCH] D99031: [clang-format] Fix CompactNamespaces corner case when AllowShortLambdasOnASingleLine/BraceWrapping.BeforeLambdaBody are set

2022-01-14 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius commandeered this revision.
curdeius edited reviewers, added: aybassiouny; removed: curdeius.
curdeius added a comment.

This bug is not present in clang-format 13 (nor master), but was there in v12.
I'll commandeer this revision to keep the regression tests.


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

https://reviews.llvm.org/D99031

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


[clang] bba729a - [clang-check] Adjust argument adjusters for clang-check to strip options blocking the static analyzer

2022-01-14 Thread Sam McCall via cfe-commits

Author: Sam McCall
Date: 2022-01-14T10:05:47+01:00
New Revision: bba729af3ef803c35c082417f89a1ac89462e22b

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

LOG: [clang-check] Adjust argument adjusters for clang-check to strip options 
blocking the static analyzer

Output generation options (like `-save-temps`) will make the analyzer not 
executed even `--analyze` option is provided in the driver arguments.
Besides, the original approach of adding `--analyze` option will not work when 
(more than one) `-fsyntax-only` options are provided in the driver arguments.

This patch fixes these two problems by using the syntax-only adjuster to remove 
output generation options and manually filter out redundant `-fsyntax-only` 
options.

In the new implementation, the adjusters added by `ClangTool` will not be 
removed but used as dependencies for clang-check adjusters for analyzer options.

Reviewed By: sammccall

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

Added: 
clang/test/Tooling/clang-check-analyze-save-temps.cpp

Modified: 
clang/tools/clang-check/ClangCheck.cpp

Removed: 




diff  --git a/clang/test/Tooling/clang-check-analyze-save-temps.cpp 
b/clang/test/Tooling/clang-check-analyze-save-temps.cpp
new file mode 100644
index 0..768f2580c2dba
--- /dev/null
+++ b/clang/test/Tooling/clang-check-analyze-save-temps.cpp
@@ -0,0 +1,19 @@
+// Check whether output generation options (like -save-temps) will not affect
+// the execution of the analyzer.
+
+// RUN: clang-check -analyze %s -- -save-temps -c -Xclang -verify
+
+// Check whether redundant -fsyntax-only options will affect the execution of
+// the analyzer.
+
+// RUN: clang-check -analyze %s -- \
+// RUN:   -fsyntax-only -c -fsyntax-only -Xclang -verify 2>&1 | \
+// RUN:   FileCheck %s --allow-empty
+
+// CHECK-NOT: argument unused during compilation: '--analyze'
+
+void a(int *x) {
+  if (x) {
+  }
+  *x = 47; // expected-warning {{Dereference of null pointer}}
+}

diff  --git a/clang/tools/clang-check/ClangCheck.cpp 
b/clang/tools/clang-check/ClangCheck.cpp
index 4d6ded029e2f0..df9a87a547608 100644
--- a/clang/tools/clang-check/ClangCheck.cpp
+++ b/clang/tools/clang-check/ClangCheck.cpp
@@ -208,27 +208,37 @@ int main(int argc, const char **argv) {
   ClangTool Tool(OptionsParser.getCompilations(),
  OptionsParser.getSourcePathList());
 
-  // Clear adjusters because -fsyntax-only is inserted by the default chain.
-  Tool.clearArgumentsAdjusters();
-
-  // Reset output path if is provided by user.
-  Tool.appendArgumentsAdjuster(
-  Analyze ? [&](const CommandLineArguments &Args, StringRef File) {
-  auto Ret = getClangStripOutputAdjuster()(Args, File);
-  if (!AnalyzerOutput.empty()) {
-Ret.emplace_back("-o");
-Ret.emplace_back(AnalyzerOutput);
-  }
-  return Ret;
-}
-  : getClangStripOutputAdjuster());
-
-  Tool.appendArgumentsAdjuster(getClangStripDependencyFileAdjuster());
-
-  // Running the analyzer requires --analyze. Other modes can work with the
-  // -fsyntax-only option.
-  Tool.appendArgumentsAdjuster(getInsertArgumentAdjuster(
-  Analyze ? "--analyze" : "-fsyntax-only", ArgumentInsertPosition::BEGIN));
+  if (Analyze) {
+// Set output path if is provided by user.
+//
+// As the original -o options have been removed by default via the
+// strip-output adjuster, we only need to add the analyzer -o options here
+// when it is provided by users.
+if (!AnalyzerOutput.empty())
+  Tool.appendArgumentsAdjuster(
+  getInsertArgumentAdjuster(CommandLineArguments{"-o", AnalyzerOutput},
+ArgumentInsertPosition::END));
+
+// Running the analyzer requires --analyze. Other modes can work with the
+// -fsyntax-only option.
+//
+// The syntax-only adjuster is installed by default.
+// Good: It also strips options that trigger extra output, like 
-save-temps.
+// Bad:  We don't want the -fsyntax-only when executing the static 
analyzer.
+//
+// To enable the static analyzer, we first strip all -fsyntax-only options
+// and then add an --analyze option to the front.
+Tool.appendArgumentsAdjuster(
+[&](const CommandLineArguments &Args, StringRef /*unused*/) {
+  CommandLineArguments AdjustedArgs;
+  for (const std::string &Arg : Args)
+if (Arg != "-fsyntax-only")
+  AdjustedArgs.emplace_back(Arg);
+  return AdjustedArgs;
+});
+Tool.appendArgumentsAdjuster(
+getInsertArgumentAdjuster("--analyze", ArgumentInsertPosition::BEGIN));
+  }
 
   ClangCheckActionFactory CheckFactory;

[PATCH] D116329: [clang-check] Adjust argument adjusters for clang-check to strip options blocking the static analyzer

2022-01-14 Thread Sam McCall via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGbba729af3ef8: [clang-check] Adjust argument adjusters for 
clang-check to strip options… (authored by sammccall).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116329

Files:
  clang/test/Tooling/clang-check-analyze-save-temps.cpp
  clang/tools/clang-check/ClangCheck.cpp


Index: clang/tools/clang-check/ClangCheck.cpp
===
--- clang/tools/clang-check/ClangCheck.cpp
+++ clang/tools/clang-check/ClangCheck.cpp
@@ -208,27 +208,37 @@
   ClangTool Tool(OptionsParser.getCompilations(),
  OptionsParser.getSourcePathList());
 
-  // Clear adjusters because -fsyntax-only is inserted by the default chain.
-  Tool.clearArgumentsAdjusters();
-
-  // Reset output path if is provided by user.
-  Tool.appendArgumentsAdjuster(
-  Analyze ? [&](const CommandLineArguments &Args, StringRef File) {
-  auto Ret = getClangStripOutputAdjuster()(Args, File);
-  if (!AnalyzerOutput.empty()) {
-Ret.emplace_back("-o");
-Ret.emplace_back(AnalyzerOutput);
-  }
-  return Ret;
-}
-  : getClangStripOutputAdjuster());
-
-  Tool.appendArgumentsAdjuster(getClangStripDependencyFileAdjuster());
-
-  // Running the analyzer requires --analyze. Other modes can work with the
-  // -fsyntax-only option.
-  Tool.appendArgumentsAdjuster(getInsertArgumentAdjuster(
-  Analyze ? "--analyze" : "-fsyntax-only", ArgumentInsertPosition::BEGIN));
+  if (Analyze) {
+// Set output path if is provided by user.
+//
+// As the original -o options have been removed by default via the
+// strip-output adjuster, we only need to add the analyzer -o options here
+// when it is provided by users.
+if (!AnalyzerOutput.empty())
+  Tool.appendArgumentsAdjuster(
+  getInsertArgumentAdjuster(CommandLineArguments{"-o", AnalyzerOutput},
+ArgumentInsertPosition::END));
+
+// Running the analyzer requires --analyze. Other modes can work with the
+// -fsyntax-only option.
+//
+// The syntax-only adjuster is installed by default.
+// Good: It also strips options that trigger extra output, like 
-save-temps.
+// Bad:  We don't want the -fsyntax-only when executing the static 
analyzer.
+//
+// To enable the static analyzer, we first strip all -fsyntax-only options
+// and then add an --analyze option to the front.
+Tool.appendArgumentsAdjuster(
+[&](const CommandLineArguments &Args, StringRef /*unused*/) {
+  CommandLineArguments AdjustedArgs;
+  for (const std::string &Arg : Args)
+if (Arg != "-fsyntax-only")
+  AdjustedArgs.emplace_back(Arg);
+  return AdjustedArgs;
+});
+Tool.appendArgumentsAdjuster(
+getInsertArgumentAdjuster("--analyze", ArgumentInsertPosition::BEGIN));
+  }
 
   ClangCheckActionFactory CheckFactory;
   std::unique_ptr FrontendFactory;
Index: clang/test/Tooling/clang-check-analyze-save-temps.cpp
===
--- /dev/null
+++ clang/test/Tooling/clang-check-analyze-save-temps.cpp
@@ -0,0 +1,19 @@
+// Check whether output generation options (like -save-temps) will not affect
+// the execution of the analyzer.
+
+// RUN: clang-check -analyze %s -- -save-temps -c -Xclang -verify
+
+// Check whether redundant -fsyntax-only options will affect the execution of
+// the analyzer.
+
+// RUN: clang-check -analyze %s -- \
+// RUN:   -fsyntax-only -c -fsyntax-only -Xclang -verify 2>&1 | \
+// RUN:   FileCheck %s --allow-empty
+
+// CHECK-NOT: argument unused during compilation: '--analyze'
+
+void a(int *x) {
+  if (x) {
+  }
+  *x = 47; // expected-warning {{Dereference of null pointer}}
+}


Index: clang/tools/clang-check/ClangCheck.cpp
===
--- clang/tools/clang-check/ClangCheck.cpp
+++ clang/tools/clang-check/ClangCheck.cpp
@@ -208,27 +208,37 @@
   ClangTool Tool(OptionsParser.getCompilations(),
  OptionsParser.getSourcePathList());
 
-  // Clear adjusters because -fsyntax-only is inserted by the default chain.
-  Tool.clearArgumentsAdjusters();
-
-  // Reset output path if is provided by user.
-  Tool.appendArgumentsAdjuster(
-  Analyze ? [&](const CommandLineArguments &Args, StringRef File) {
-  auto Ret = getClangStripOutputAdjuster()(Args, File);
-  if (!AnalyzerOutput.empty()) {
-Ret.emplace_back("-o");
-Ret.emplace_back(AnalyzerOutput);
-  }
-  return Ret;
-}
-  : getClangStripOutputAdjuster());
-
-  Tool.appendArgument

[PATCH] D116595: [clang][sema] Add missing diagnostic parameter

2022-01-14 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder updated this revision to Diff 399925.

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

https://reviews.llvm.org/D116595

Files:
  clang/lib/Sema/SemaModule.cpp
  clang/test/Modules/cxx20-export-import.cpp


Index: clang/test/Modules/cxx20-export-import.cpp
===
--- /dev/null
+++ clang/test/Modules/cxx20-export-import.cpp
@@ -0,0 +1,3 @@
+
+// RUN: %clang_cc1 -std=c++20 -fmodules -fmodules-cache-path=%t 
-fimplicit-module-maps -I%S/Inputs -verify %s
+export import dummy; // expected-error {{export declaration can only be used 
within a module interface unit after the module declaration}}
Index: clang/lib/Sema/SemaModule.cpp
===
--- clang/lib/Sema/SemaModule.cpp
+++ clang/lib/Sema/SemaModule.cpp
@@ -395,7 +395,7 @@
 // [module.interface]p1:
 // An export-declaration shall inhabit a namespace scope and appear in the
 // purview of a module interface unit.
-Diag(ExportLoc, diag::err_export_not_in_module_interface);
+Diag(ExportLoc, diag::err_export_not_in_module_interface) << 0;
   }
 
   return Import;


Index: clang/test/Modules/cxx20-export-import.cpp
===
--- /dev/null
+++ clang/test/Modules/cxx20-export-import.cpp
@@ -0,0 +1,3 @@
+
+// RUN: %clang_cc1 -std=c++20 -fmodules -fmodules-cache-path=%t -fimplicit-module-maps -I%S/Inputs -verify %s
+export import dummy; // expected-error {{export declaration can only be used within a module interface unit after the module declaration}}
Index: clang/lib/Sema/SemaModule.cpp
===
--- clang/lib/Sema/SemaModule.cpp
+++ clang/lib/Sema/SemaModule.cpp
@@ -395,7 +395,7 @@
 // [module.interface]p1:
 // An export-declaration shall inhabit a namespace scope and appear in the
 // purview of a module interface unit.
-Diag(ExportLoc, diag::err_export_not_in_module_interface);
+Diag(ExportLoc, diag::err_export_not_in_module_interface) << 0;
   }
 
   return Import;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D111617: [RISCV] Lazily add RVV C intrinsics.

2022-01-14 Thread Kito Cheng via Phabricator via cfe-commits
kito-cheng commandeered this revision.
kito-cheng edited reviewers, added: HsiangKai; removed: kito-cheng.
kito-cheng added a comment.

@HsiangKai hand over this revision to me.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111617

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


[PATCH] D99031: [clang-format] Fix CompactNamespaces corner case when AllowShortLambdasOnASingleLine/BraceWrapping.BeforeLambdaBody are set

2022-01-14 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius updated this revision to Diff 399926.
curdeius added a comment.

Keep tests only. Clean up.
Rebase.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D99031

Files:
  clang/unittests/Format/FormatTest.cpp


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -3824,6 +3824,21 @@
"} // namespace mid\n"
"} // namespace out",
Style));
+
+  Style.CompactNamespaces = true;
+  Style.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
+  Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+  Style.BraceWrapping.BeforeLambdaBody = true;
+  verifyFormat("namespace out { namespace in {\n"
+   "}} // namespace out::in",
+   Style);
+  EXPECT_EQ("namespace out { namespace in {\n"
+"}} // namespace out::in",
+format("namespace out {\n"
+   "namespace in {\n"
+   "} // namespace in\n"
+   "} // namespace out",
+   Style));
 }
 
 TEST_F(FormatTest, FormatsExternC) {


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -3824,6 +3824,21 @@
"} // namespace mid\n"
"} // namespace out",
Style));
+
+  Style.CompactNamespaces = true;
+  Style.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
+  Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+  Style.BraceWrapping.BeforeLambdaBody = true;
+  verifyFormat("namespace out { namespace in {\n"
+   "}} // namespace out::in",
+   Style);
+  EXPECT_EQ("namespace out { namespace in {\n"
+"}} // namespace out::in",
+format("namespace out {\n"
+   "namespace in {\n"
+   "} // namespace in\n"
+   "} // namespace out",
+   Style));
 }
 
 TEST_F(FormatTest, FormatsExternC) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D116595: [clang][sema] Add missing diagnostic parameter

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



Comment at: clang/test/Modules/cxx20-export-import.cpp:1-2
+
+// RUN: %clang_cc1 -std=c++20 -fmodules -fmodules-cache-path=%t 
-fimplicit-module-maps -I%S/Inputs -stdlib=libc++ -verify %s
+export import dummy; // expected-error {{export declaration can only be used 
within a module interface unit after the module declaration}}

aaron.ballman wrote:
> Also, does this test require `-fmodules-cache-path=%t` or 
> `-fimplicit-module-maps`?
They are all needed (including the `-I`). I could only remove the 
`-stdlib=libc++`, removing any of the others makes the test fail :(


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

https://reviews.llvm.org/D116595

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


[PATCH] D116329: [clang-check] Adjust argument adjusters for clang-check to strip options blocking the static analyzer

2022-01-14 Thread Ella Ma via Phabricator via cfe-commits
OikawaKirie added a comment.

It seems that it is not committed on my behalf. Maybe you have forgotten to add 
me as the author?
Sad : (


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116329

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


[PATCH] D116750: [clang][lex] Keep references to `DirectoryLookup` objects up-to-date

2022-01-14 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 reopened this revision.
jansvoboda11 added a comment.
This revision is now accepted and ready to land.

I'll need to figure out how to efficiently replace the pointer arithmetic 
performed by `Preprocessor::LookupFile`, or go back to my first solution: 
keeping `std::vector` and updating indices in 
`AddSearchPath`...


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116750

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


[PATCH] D117197: [clang-format] Add new option to support adding a space between Javascript Union and Intersection types

2022-01-14 Thread Martin Probst via Phabricator via cfe-commits
mprobst added inline comments.



Comment at: clang/lib/Format/TokenAnnotator.cpp:3522
+  if ((Left.is(TT_JsTypeOperator) && Right.isTypeOrIdentifier()) ||
+  (Left.isTypeOrIdentifier() || Left.is(TT_TemplateCloser)) &&
+  Right.is(TT_JsTypeOperator))

Why do we need this further qualification here? I'd have expect that you can 
simply "return Style.SpacesInJavaScriptUnion;"? identifier || template closer 
also sounds oddly specific, why exactly those?


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

https://reviews.llvm.org/D117197

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


[PATCH] D117292: [Driver] Pass the flag -dI to cc1 invocation

2022-01-14 Thread Qichao Gu via Phabricator via cfe-commits
qichaogu created this revision.
qichaogu added a reviewer: cfe-commits.
qichaogu requested review of this revision.

Hook up the flag -dI in the driver to pass it to cc1 invocation.


https://reviews.llvm.org/D117292

Files:
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/test/Driver/preprocessor.c


Index: clang/test/Driver/preprocessor.c
===
--- clang/test/Driver/preprocessor.c
+++ clang/test/Driver/preprocessor.c
@@ -4,3 +4,11 @@
 #define A B
 A A
 
+// The driver should pass preprocessor dump flags (-dD, -dM and -dI) to cc1 
invocation
+// RUN: %clang -### -E -dD %s 2>&1 | FileCheck --check-prefix=CHECK-dD %s
+// RUN: %clang -### -E -dM %s 2>&1 | FileCheck --check-prefix=CHECK-dM %s
+// RUN: %clang -### -E -dI %s 2>&1 | FileCheck --check-prefix=CHECK-dI %s
+// CHECK-dD: clang{{.*}} "-cc1" {{.*}} "-dD"
+// CHECK-dM: clang{{.*}} "-cc1" {{.*}} "-dM"
+// CHECK-dI: clang{{.*}} "-cc1" {{.*}} "-dI"
+
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -,6 +,7 @@
 
   Args.AddLastArg(CmdArgs, options::OPT_dM);
   Args.AddLastArg(CmdArgs, options::OPT_dD);
+  Args.AddLastArg(CmdArgs, options::OPT_dI);
 
   Args.AddLastArg(CmdArgs, options::OPT_fmax_tokens_EQ);
 


Index: clang/test/Driver/preprocessor.c
===
--- clang/test/Driver/preprocessor.c
+++ clang/test/Driver/preprocessor.c
@@ -4,3 +4,11 @@
 #define A B
 A A
 
+// The driver should pass preprocessor dump flags (-dD, -dM and -dI) to cc1 invocation
+// RUN: %clang -### -E -dD %s 2>&1 | FileCheck --check-prefix=CHECK-dD %s
+// RUN: %clang -### -E -dM %s 2>&1 | FileCheck --check-prefix=CHECK-dM %s
+// RUN: %clang -### -E -dI %s 2>&1 | FileCheck --check-prefix=CHECK-dI %s
+// CHECK-dD: clang{{.*}} "-cc1" {{.*}} "-dD"
+// CHECK-dM: clang{{.*}} "-cc1" {{.*}} "-dM"
+// CHECK-dI: clang{{.*}} "-cc1" {{.*}} "-dI"
+
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -,6 +,7 @@
 
   Args.AddLastArg(CmdArgs, options::OPT_dM);
   Args.AddLastArg(CmdArgs, options::OPT_dD);
+  Args.AddLastArg(CmdArgs, options::OPT_dI);
 
   Args.AddLastArg(CmdArgs, options::OPT_fmax_tokens_EQ);
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D117293: enable noundef analysis with -fsanitize-memory-param-retval

2022-01-14 Thread Kevin Athey via Phabricator via cfe-commits
kda created this revision.
kda added a reviewer: vitalybuka.
Herald added a subscriber: dang.
kda requested review of this revision.
Herald added projects: clang, Sanitizers.
Herald added subscribers: Sanitizers, cfe-commits.

Enable noundef analysis (-enable-noundef-analysis) via the 
-fsanitize-memory-param-retval clang flag.
This completes the work found in:

- https://reviews.llvm.org/D116855
- https://reviews.llvm.org/D116633


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D117293

Files:
  clang/include/clang/Driver/Options.td
  clang/test/CodeGen/msan-param-retval.c
  compiler-rt/test/msan/noundef_analysis.cpp


Index: compiler-rt/test/msan/noundef_analysis.cpp
===
--- compiler-rt/test/msan/noundef_analysis.cpp
+++ compiler-rt/test/msan/noundef_analysis.cpp
@@ -2,6 +2,8 @@
 // RUN: FileCheck %s --check-prefix=MISSED --allow-empty < %t.out
 // RUN: %clangxx_msan %s -Xclang -enable-noundef-analysis -mllvm 
-msan-eager-checks=1 -o %t && not %run %t >%t.out 2>&1
 // RUN: FileCheck %s < %t.out
+// RUN: %clangxx_msan %s -fsanitize-memory-param-retval -o %t && not %run %t 
>%t.out 2>&1
+// RUN: FileCheck %s < %t.out
 
 struct SimpleStruct {
   int md1;
Index: clang/test/CodeGen/msan-param-retval.c
===
--- clang/test/CodeGen/msan-param-retval.c
+++ clang/test/CodeGen/msan-param-retval.c
@@ -5,7 +5,7 @@
 // RUN: %clang -target x86_64-linux-gnu -S -emit-llvm -fsanitize=memory 
-Xclang -enable-noundef-analysis -mllvm -msan-eager-checks -o - %s | \
 // RUN: FileCheck %s --check-prefixes=NOUNDEF,EAGER
 // RUN: %clang -target x86_64-linux-gnu -S -emit-llvm -fsanitize=memory 
-fsanitize-memory-param-retval -o - %s | \
-// RUN: FileCheck %s --check-prefixes=CLEAN
+// RUN: FileCheck %s --check-prefixes=NOUNDEF,EAGER
 // RUN: %clang -target x86_64-linux-gnu -S -emit-llvm -fsanitize=memory 
-Xclang -enable-noundef-analysis -fsanitize-memory-param-retval -o - %s | \
 // RUN: FileCheck %s --check-prefixes=NOUNDEF,EAGER
 
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -1670,13 +1670,12 @@
   NormalizedValues<["None", "Global"]>,
   MarshallingInfoEnum, "Global">;
 defm sanitize_memory_param_retval
-  : BoolOption<"f", "sanitize-memory-param-retval",
-  CodeGenOpts<"SanitizeMemoryParamRetval">,
-  DefaultFalse,
-  PosFlag, NegFlag,
-  BothFlags<[], " detection of uninitialized parameters and return 
values">>,
-Group;
-// Note: This flag was introduced when it was necessary to distinguish between
+: BoolFOption<"sanitize-memory-param-retval",
+CodeGenOpts<"SanitizeMemoryParamRetval">,
+DefaultFalse,
+PosFlag, NegFlag,
+BothFlags<[], " detection of uninitialized parameters and return 
values">>;
+ Note: This flag was introduced when it was necessary to distinguish 
between
 //   ABI for correct codegen.  This is no longer needed, but the flag is
 //   not removed since targeting either ABI will behave the same.
 //   This way we cause no disturbance to existing scripts & code, and if we
@@ -5399,7 +5398,8 @@
   BothFlags<[], " the Clang AST before running backend code generation">>;
 def enable_noundef_analysis : Flag<["-"], "enable-noundef-analysis">, 
Group,
   HelpText<"Enable analyzing function argument and return types for mandatory 
definedness">,
-  MarshallingInfoFlag>;
+  MarshallingInfoFlag>,
+  ImpliedByAnyOf<[fsanitize_memory_param_retval.KeyPath]>;
 def discard_value_names : Flag<["-"], "discard-value-names">,
   HelpText<"Discard value names in LLVM IR">,
   MarshallingInfoFlag>;


Index: compiler-rt/test/msan/noundef_analysis.cpp
===
--- compiler-rt/test/msan/noundef_analysis.cpp
+++ compiler-rt/test/msan/noundef_analysis.cpp
@@ -2,6 +2,8 @@
 // RUN: FileCheck %s --check-prefix=MISSED --allow-empty < %t.out
 // RUN: %clangxx_msan %s -Xclang -enable-noundef-analysis -mllvm -msan-eager-checks=1 -o %t && not %run %t >%t.out 2>&1
 // RUN: FileCheck %s < %t.out
+// RUN: %clangxx_msan %s -fsanitize-memory-param-retval -o %t && not %run %t >%t.out 2>&1
+// RUN: FileCheck %s < %t.out
 
 struct SimpleStruct {
   int md1;
Index: clang/test/CodeGen/msan-param-retval.c
===
--- clang/test/CodeGen/msan-param-retval.c
+++ clang/test/CodeGen/msan-param-retval.c
@@ -5,7 +5,7 @@
 // RUN: %clang -target x86_64-linux-gnu -S -emit-llvm -fsanitize=memory -Xclang -enable-noundef-analysis -mllvm -msan-eager-checks -o - %s | \
 // RUN: FileCheck %s --check-prefixes=NOUNDEF,EAGER
 // RUN: %clang -target x86_64-linux-gnu -S -emit-llvm -fsanitize=memory -fsanitize-memory-param-retval -o - %s | \
-// RUN: FileCheck 

[PATCH] D117293: enable noundef analysis with -fsanitize-memory-param-retval

2022-01-14 Thread Kevin Athey via Phabricator via cfe-commits
kda updated this revision to Diff 399937.
kda added a comment.

add missing files.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D117293

Files:
  clang/include/clang/Driver/Options.td
  clang/test/CodeGen/attr-noundef.cpp
  clang/test/CodeGen/indirect-noundef.cpp
  clang/test/CodeGen/msan-param-retval.c
  compiler-rt/test/msan/noundef_analysis.cpp


Index: compiler-rt/test/msan/noundef_analysis.cpp
===
--- compiler-rt/test/msan/noundef_analysis.cpp
+++ compiler-rt/test/msan/noundef_analysis.cpp
@@ -2,6 +2,8 @@
 // RUN: FileCheck %s --check-prefix=MISSED --allow-empty < %t.out
 // RUN: %clangxx_msan %s -Xclang -enable-noundef-analysis -mllvm 
-msan-eager-checks=1 -o %t && not %run %t >%t.out 2>&1
 // RUN: FileCheck %s < %t.out
+// RUN: %clangxx_msan %s -fsanitize-memory-param-retval -o %t && not %run %t 
>%t.out 2>&1
+// RUN: FileCheck %s < %t.out
 
 struct SimpleStruct {
   int md1;
Index: clang/test/CodeGen/msan-param-retval.c
===
--- clang/test/CodeGen/msan-param-retval.c
+++ clang/test/CodeGen/msan-param-retval.c
@@ -5,7 +5,7 @@
 // RUN: %clang -target x86_64-linux-gnu -S -emit-llvm -fsanitize=memory 
-Xclang -enable-noundef-analysis -mllvm -msan-eager-checks -o - %s | \
 // RUN: FileCheck %s --check-prefixes=NOUNDEF,EAGER
 // RUN: %clang -target x86_64-linux-gnu -S -emit-llvm -fsanitize=memory 
-fsanitize-memory-param-retval -o - %s | \
-// RUN: FileCheck %s --check-prefixes=CLEAN
+// RUN: FileCheck %s --check-prefixes=NOUNDEF,EAGER
 // RUN: %clang -target x86_64-linux-gnu -S -emit-llvm -fsanitize=memory 
-Xclang -enable-noundef-analysis -fsanitize-memory-param-retval -o - %s | \
 // RUN: FileCheck %s --check-prefixes=NOUNDEF,EAGER
 
Index: clang/test/CodeGen/indirect-noundef.cpp
===
--- clang/test/CodeGen/indirect-noundef.cpp
+++ clang/test/CodeGen/indirect-noundef.cpp
@@ -1,4 +1,9 @@
 // RUN: %clang -cc1 -x c++ -triple x86_64-unknown-unknown -O0 -emit-llvm 
-enable-noundef-analysis -o - %s | FileCheck %s
+// RUN: %clang -cc1 -x c++ -triple x86_64-unknown-unknown -O0 -emit-llvm 
-fsanitize-memory-param-retval -o - %s | FileCheck %s
+
+// no-sanitize-memory-param-retval does NOT conflict with 
enable-noundef-analysis
+// RUN: %clang -cc1 -x c++ -triple x86_64-unknown-unknown -O0 -emit-llvm 
-fno-sanitize-memory-param-retval -enable-noundef-analysis -o - %s | FileCheck 
%s
+// RUN: %clang -cc1 -x c++ -triple x86_64-unknown-unknown -O0 -emit-llvm 
-enable-noundef-analysis -fno-sanitize-memory-param-retval -o - %s | FileCheck 
%s
 
 union u1 {
   int val;
Index: clang/test/CodeGen/attr-noundef.cpp
===
--- clang/test/CodeGen/attr-noundef.cpp
+++ clang/test/CodeGen/attr-noundef.cpp
@@ -1,5 +1,11 @@
 // RUN: %clang -cc1 -triple x86_64-gnu-linux -x c++ -S -emit-llvm 
-enable-noundef-analysis %s -o - | FileCheck %s --check-prefix=CHECK 
--check-prefix=CHECK-INTEL
 // RUN: %clang -cc1 -triple aarch64-gnu-linux -x c++ -S -emit-llvm 
-enable-noundef-analysis %s -o - | FileCheck %s --check-prefix=CHECK 
--check-prefix=CHECK-AARCH
+// RUN: %clang -cc1 -triple x86_64-gnu-linux -x c++ -S -emit-llvm 
-fsanitize-memory-param-retval %s -o - | FileCheck %s --check-prefix=CHECK 
--check-prefix=CHECK-INTEL
+// RUN: %clang -cc1 -triple aarch64-gnu-linux -x c++ -S -emit-llvm 
-fsanitize-memory-param-retval %s -o - | FileCheck %s --check-prefix=CHECK 
--check-prefix=CHECK-AARCH
+
+// no-sanitize-memory-param-retval does NOT conflict with 
enable-noundef-analysis
+// RUN: %clang -cc1 -triple x86_64-gnu-linux -x c++ -S -emit-llvm 
-enable-noundef-analysis -fno-sanitize-memory-param-retval %s -o - | FileCheck 
%s --check-prefix=CHECK --check-prefix=CHECK-INTEL
+// RUN: %clang -cc1 -triple x86_64-gnu-linux -x c++ -S -emit-llvm 
-fno-sanitize-memory-param-retval -enable-noundef-analysis %s -o - | FileCheck 
%s --check-prefix=CHECK --check-prefix=CHECK-INTEL
 
 // Passing structs by value
 // TODO: No structs may currently be marked noundef
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -1670,13 +1670,12 @@
   NormalizedValues<["None", "Global"]>,
   MarshallingInfoEnum, "Global">;
 defm sanitize_memory_param_retval
-  : BoolOption<"f", "sanitize-memory-param-retval",
-  CodeGenOpts<"SanitizeMemoryParamRetval">,
-  DefaultFalse,
-  PosFlag, NegFlag,
-  BothFlags<[], " detection of uninitialized parameters and return 
values">>,
-Group;
-// Note: This flag was introduced when it was necessary to distinguish between
+: BoolFOption<"sanitize-memory-param-retval",
+CodeGenOpts<"San

[PATCH] D117294: [clangd] Better handling `\n` in the synthesized diagnostic message.

2022-01-14 Thread Haojian Wu via Phabricator via cfe-commits
hokein created this revision.
hokein added a reviewer: sammccall.
Herald added subscribers: usaxena95, kadircet, arphaman.
hokein requested review of this revision.
Herald added subscribers: MaskRay, ilya-biryukov.
Herald added a project: clang-tools-extra.

The newline-eof fix was rendered as "insert '...'", this patch
special-case it.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D117294

Files:
  clang-tools-extra/clangd/Diagnostics.cpp
  clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp


Index: clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
===
--- clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
+++ clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
@@ -623,6 +623,15 @@
   Fix(Source.range(), "ident", "change 'ide\\…' to 
'ident'";
 }
 
+TEST(DiagnosticTest, NewLineFixMessage) {
+  Annotations Source("int a;[[]]");
+  TestTU TU = TestTU::withCode(Source.code());
+  TU.ExtraArgs = {"-Wnewline-eof"};
+  EXPECT_THAT(
+  *TU.build().getDiagnostics(),
+  ElementsAre(WithFix((Fix(Source.range(), "\n", "insert '\\n'");
+}
+
 TEST(DiagnosticTest, ClangTidySuppressionCommentTrumpsWarningAsError) {
   Annotations Main(R"cpp(
 int main() {
Index: clang-tools-extra/clangd/Diagnostics.cpp
===
--- clang-tools-extra/clangd/Diagnostics.cpp
+++ clang-tools-extra/clangd/Diagnostics.cpp
@@ -631,7 +631,10 @@
 /// the result is not too large and does not contain newlines.
 static void writeCodeToFixMessage(llvm::raw_ostream &OS, llvm::StringRef Code) 
{
   constexpr unsigned MaxLen = 50;
-
+  if (Code == "\n") {
+OS << "\\n";
+return;
+  }
   // Only show the first line if there are many.
   llvm::StringRef R = Code.split('\n').first;
   // Shorten the message if it's too long.


Index: clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
===
--- clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
+++ clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
@@ -623,6 +623,15 @@
   Fix(Source.range(), "ident", "change 'ide\\…' to 'ident'";
 }
 
+TEST(DiagnosticTest, NewLineFixMessage) {
+  Annotations Source("int a;[[]]");
+  TestTU TU = TestTU::withCode(Source.code());
+  TU.ExtraArgs = {"-Wnewline-eof"};
+  EXPECT_THAT(
+  *TU.build().getDiagnostics(),
+  ElementsAre(WithFix((Fix(Source.range(), "\n", "insert '\\n'");
+}
+
 TEST(DiagnosticTest, ClangTidySuppressionCommentTrumpsWarningAsError) {
   Annotations Main(R"cpp(
 int main() {
Index: clang-tools-extra/clangd/Diagnostics.cpp
===
--- clang-tools-extra/clangd/Diagnostics.cpp
+++ clang-tools-extra/clangd/Diagnostics.cpp
@@ -631,7 +631,10 @@
 /// the result is not too large and does not contain newlines.
 static void writeCodeToFixMessage(llvm::raw_ostream &OS, llvm::StringRef Code) {
   constexpr unsigned MaxLen = 50;
-
+  if (Code == "\n") {
+OS << "\\n";
+return;
+  }
   // Only show the first line if there are many.
   llvm::StringRef R = Code.split('\n').first;
   // Shorten the message if it's too long.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D117295: [clang][sema] Allow unnamed decls in C++20 module export{} blocks

2022-01-14 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder created this revision.
tbaeder added reviewers: rsmith, aaron.ballman.
tbaeder requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

As part of P1766R1 
, allow 
unnamed decls in `export{}` blocks.

I've adjusted the module-ts tests as well, but I am (generally) not sure 
whether code for C++20 modules should affect the modules-ts cases. What's the 
policy here?


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D117295

Files:
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaModule.cpp
  clang/test/CXX/module/module.interface/p3.cpp
  clang/test/Modules/cxx20-export.cpp
  clang/test/SemaCXX/modules-ts.cppm

Index: clang/test/SemaCXX/modules-ts.cppm
===
--- clang/test/SemaCXX/modules-ts.cppm
+++ clang/test/SemaCXX/modules-ts.cppm
@@ -50,11 +50,8 @@
 import foo;
 
 export {} // expected-error {{export declaration cannot be empty}}
-export {  // expected-note {{begins here}}
-  ;   // expected-warning {{ISO C++20 does not permit an empty declaration to appear in an export block}}
-}
-export {   // expected-note {{begins here}}
-  static_assert(true); // expected-warning {{ISO C++20 does not permit a static_assert declaration to appear in an export block}}
+export {
+  static_assert(true);
 }
 
 int use_b = b;
Index: clang/test/Modules/cxx20-export.cpp
===
--- /dev/null
+++ clang/test/Modules/cxx20-export.cpp
@@ -0,0 +1,22 @@
+
+// RUN: %clang_cc1 -std=c++20 -fmodules -verify %s
+export module testmodule;
+
+export static_assert(true); // expected-error {{static_assert declaration cannot be exported}}
+
+namespace A {};
+
+export {
+#define STR(x) constexpr char x[] = #x;
+  STR(foo);
+#undef STR
+
+  static_assert(true);
+
+  template  struct X { T t; };
+  template  X(T) -> X;
+
+  ; // Empty declaration
+
+  using namespace A;
+}
Index: clang/test/CXX/module/module.interface/p3.cpp
===
--- clang/test/CXX/module/module.interface/p3.cpp
+++ clang/test/CXX/module/module.interface/p3.cpp
@@ -9,12 +9,6 @@
 export static_assert(true); // expected-error {{static_assert declaration cannot be exported}}
 export using namespace A; // expected-error {{ISO C++20 does not permit using directive to be exported}}
 
-export { // expected-note 3{{export block begins here}}
-  ; // expected-error {{ISO C++20 does not permit an empty declaration to appear in an export block}}
-  static_assert(true); // expected-error {{ISO C++20 does not permit a static_assert declaration to appear in an export block}}
-  using namespace A; // expected-error {{ISO C++20 does not permit using directive to be exported}}
-}
-
 export struct {}; // expected-error {{must be class member}} expected-error {{GNU extension}} expected-error {{does not declare anything}}
 export struct {} struct_;
 export union {}; // expected-error {{must be declared 'static'}} expected-error {{does not declare anything}}
Index: clang/lib/Sema/SemaModule.cpp
===
--- clang/lib/Sema/SemaModule.cpp
+++ clang/lib/Sema/SemaModule.cpp
@@ -615,13 +615,11 @@
   return llvm::None;
 }
 
-unsigned getUnnamedDeclDiag(UnnamedDeclKind UDK, bool InBlock) {
+static unsigned getUnnamedDeclDiag(UnnamedDeclKind UDK) {
   switch (UDK) {
   case UnnamedDeclKind::Empty:
   case UnnamedDeclKind::StaticAssert:
-// Allow empty-declarations and static_asserts in an export block as an
-// extension.
-return InBlock ? diag::ext_export_no_name_block : diag::err_export_no_name;
+return diag::err_export_no_name;
 
   case UnnamedDeclKind::UsingDirective:
 // Allow exporting using-directives as an extension.
@@ -640,8 +638,7 @@
 
 static void diagExportedUnnamedDecl(Sema &S, UnnamedDeclKind UDK, Decl *D,
 SourceLocation BlockStart) {
-  S.Diag(D->getLocation(), getUnnamedDeclDiag(UDK, BlockStart.isValid()))
-  << (unsigned)UDK;
+  S.Diag(D->getLocation(), getUnnamedDeclDiag(UDK)) << (unsigned)UDK;
   if (BlockStart.isValid())
 S.Diag(BlockStart, diag::note_export);
 }
@@ -650,8 +647,10 @@
 static bool checkExportedDecl(Sema &S, Decl *D, SourceLocation BlockStart) {
   // C++2a [module.interface]p3:
   //   An exported declaration shall declare at least one name
-  if (auto UDK = getUnnamedDeclKind(D))
-diagExportedUnnamedDecl(S, *UDK, D, BlockStart);
+  if (!BlockStart.isValid()) {
+if (auto UDK = getUnnamedDeclKind(D))
+  diagExportedUnnamedDecl(S, *UDK, D, BlockStart);
+  }
 
   //   [...] shall not declare a name with internal linkage.
   if (auto *ND = dyn_cast(D)) {
Index: clang/include/clang/Basic/DiagnosticSemaKinds.td
===

[PATCH] D117295: [clang][sema] Allow unnamed decls in C++20 module export{} blocks

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

Reading this 

 again, it sounds like this is not expected to happen for C++20; I was using 
https://clang.llvm.org/cxx_status.html#cxx20 as guidance here.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D117295

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


[PATCH] D116736: [Clang] Add __builtin_reduce_or and __builtin_reduce_and

2022-01-14 Thread Florian Hahn via Phabricator via cfe-commits
fhahn accepted this revision.
fhahn added a comment.
This revision is now accepted and ready to land.

In D116736#3242623 , @junaire wrote:

>> @junaire did you already get commit access or should I commit this change on 
>> your behalf?
>
> Yeah, I already have commit access, just waiting for your approval ;D

Ah sorry, I thought I already approved the change.

LGTM again


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116736

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


[clang] 717cd16 - [clang-format] Fix namespace end comments fixer with anonymous namespaces.

2022-01-14 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-01-14T11:41:14+01:00
New Revision: 717cd16e85faa6498cf6c46838241b0e7ddaaaba

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

LOG: [clang-format] Fix namespace end comments fixer with anonymous namespaces.

Previously, a strange trailing comment was produced:
```
namespace out { namespace {
}} // namespace out::
```
(mind the "out::").

Reviewed By: MyDeveloperDay, owenpan

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

Added: 


Modified: 
clang/lib/Format/NamespaceEndCommentsFixer.cpp
clang/unittests/Format/NamespaceEndCommentsFixerTest.cpp

Removed: 




diff  --git a/clang/lib/Format/NamespaceEndCommentsFixer.cpp 
b/clang/lib/Format/NamespaceEndCommentsFixer.cpp
index 951a982580519..0c34c6126c214 100644
--- a/clang/lib/Format/NamespaceEndCommentsFixer.cpp
+++ b/clang/lib/Format/NamespaceEndCommentsFixer.cpp
@@ -261,7 +261,8 @@ std::pair 
NamespaceEndCommentsFixer::analyze(
   updateEndComment(EndCommentPrevTok, std::string(), SourceMgr, 
&Fixes);
 }
 ++CompactedNamespacesCount;
-AllNamespaceNames = "::" + NamespaceName + AllNamespaceNames;
+if (!NamespaceName.empty())
+  AllNamespaceNames = "::" + NamespaceName + AllNamespaceNames;
 continue;
   }
   NamespaceName += AllNamespaceNames;

diff  --git a/clang/unittests/Format/NamespaceEndCommentsFixerTest.cpp 
b/clang/unittests/Format/NamespaceEndCommentsFixerTest.cpp
index 3afe35e7ea34f..925b0e3b2e4c9 100644
--- a/clang/unittests/Format/NamespaceEndCommentsFixerTest.cpp
+++ b/clang/unittests/Format/NamespaceEndCommentsFixerTest.cpp
@@ -256,6 +256,15 @@ TEST_F(NamespaceEndCommentsFixerTest, AddsEndComment) {
 "int j;\n"
 "};}",
 CompactNamespacesStyle));
+  EXPECT_EQ("namespace out { namespace {\n"
+"int i;\n"
+"int j;\n"
+"}}// namespace out",
+fixNamespaceEndComments("namespace out { namespace {\n"
+"int i;\n"
+"int j;\n"
+"}}",
+CompactNamespacesStyle));
 
   // Adds an end comment after a semicolon.
   EXPECT_EQ("namespace {\n"
@@ -609,6 +618,11 @@ TEST_F(NamespaceEndCommentsFixerTest, 
UpdatesInvalidEndLineComment) {
 "}// banamespace in\n"
 "} // namespace out",
 CompactNamespacesStyle));
+  EXPECT_EQ("namespace out { namespace {\n"
+"}} // namespace out",
+fixNamespaceEndComments("namespace out { namespace {\n"
+"}} // namespace out::",
+CompactNamespacesStyle));
 }
 
 TEST_F(NamespaceEndCommentsFixerTest, UpdatesInvalidMacroEndLineComment) {



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


[PATCH] D117289: [clang-format] Fix namespace end comments fixer with anonymous namespaces.

2022-01-14 Thread Marek Kurdej 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 rG717cd16e85fa: [clang-format] Fix namespace end comments 
fixer with anonymous namespaces. (authored by curdeius).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D117289

Files:
  clang/lib/Format/NamespaceEndCommentsFixer.cpp
  clang/unittests/Format/NamespaceEndCommentsFixerTest.cpp


Index: clang/unittests/Format/NamespaceEndCommentsFixerTest.cpp
===
--- clang/unittests/Format/NamespaceEndCommentsFixerTest.cpp
+++ clang/unittests/Format/NamespaceEndCommentsFixerTest.cpp
@@ -256,6 +256,15 @@
 "int j;\n"
 "};}",
 CompactNamespacesStyle));
+  EXPECT_EQ("namespace out { namespace {\n"
+"int i;\n"
+"int j;\n"
+"}}// namespace out",
+fixNamespaceEndComments("namespace out { namespace {\n"
+"int i;\n"
+"int j;\n"
+"}}",
+CompactNamespacesStyle));
 
   // Adds an end comment after a semicolon.
   EXPECT_EQ("namespace {\n"
@@ -609,6 +618,11 @@
 "}// banamespace in\n"
 "} // namespace out",
 CompactNamespacesStyle));
+  EXPECT_EQ("namespace out { namespace {\n"
+"}} // namespace out",
+fixNamespaceEndComments("namespace out { namespace {\n"
+"}} // namespace out::",
+CompactNamespacesStyle));
 }
 
 TEST_F(NamespaceEndCommentsFixerTest, UpdatesInvalidMacroEndLineComment) {
Index: clang/lib/Format/NamespaceEndCommentsFixer.cpp
===
--- clang/lib/Format/NamespaceEndCommentsFixer.cpp
+++ clang/lib/Format/NamespaceEndCommentsFixer.cpp
@@ -261,7 +261,8 @@
   updateEndComment(EndCommentPrevTok, std::string(), SourceMgr, 
&Fixes);
 }
 ++CompactedNamespacesCount;
-AllNamespaceNames = "::" + NamespaceName + AllNamespaceNames;
+if (!NamespaceName.empty())
+  AllNamespaceNames = "::" + NamespaceName + AllNamespaceNames;
 continue;
   }
   NamespaceName += AllNamespaceNames;


Index: clang/unittests/Format/NamespaceEndCommentsFixerTest.cpp
===
--- clang/unittests/Format/NamespaceEndCommentsFixerTest.cpp
+++ clang/unittests/Format/NamespaceEndCommentsFixerTest.cpp
@@ -256,6 +256,15 @@
 "int j;\n"
 "};}",
 CompactNamespacesStyle));
+  EXPECT_EQ("namespace out { namespace {\n"
+"int i;\n"
+"int j;\n"
+"}}// namespace out",
+fixNamespaceEndComments("namespace out { namespace {\n"
+"int i;\n"
+"int j;\n"
+"}}",
+CompactNamespacesStyle));
 
   // Adds an end comment after a semicolon.
   EXPECT_EQ("namespace {\n"
@@ -609,6 +618,11 @@
 "}// banamespace in\n"
 "} // namespace out",
 CompactNamespacesStyle));
+  EXPECT_EQ("namespace out { namespace {\n"
+"}} // namespace out",
+fixNamespaceEndComments("namespace out { namespace {\n"
+"}} // namespace out::",
+CompactNamespacesStyle));
 }
 
 TEST_F(NamespaceEndCommentsFixerTest, UpdatesInvalidMacroEndLineComment) {
Index: clang/lib/Format/NamespaceEndCommentsFixer.cpp
===
--- clang/lib/Format/NamespaceEndCommentsFixer.cpp
+++ clang/lib/Format/NamespaceEndCommentsFixer.cpp
@@ -261,7 +261,8 @@
   updateEndComment(EndCommentPrevTok, std::string(), SourceMgr, &Fixes);
 }
 ++CompactedNamespacesCount;
-AllNamespaceNames = "::" + NamespaceName + AllNamespaceNames;
+if (!NamespaceName.empty())
+  AllNamespaceNames = "::" + NamespaceName + AllNamespaceNames;
 continue;
   }
   NamespaceName += AllNamespaceNames;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D117296: Document several clang-supported builtins

2022-01-14 Thread serge via Phabricator via cfe-commits
serge-sans-paille created this revision.
serge-sans-paille added reviewers: aaron.ballman, rsmith.
serge-sans-paille requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Namely

__builtin_alloca
__builtin_alloca_with_align
__builtin_call_with_static_chain
__builtin_expect
__builtin_expect_with_probablity
__builtin_prefetch


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D117296

Files:
  clang/docs/LanguageExtensions.rst

Index: clang/docs/LanguageExtensions.rst
===
--- clang/docs/LanguageExtensions.rst
+++ clang/docs/LanguageExtensions.rst
@@ -2125,43 +2125,104 @@
 ` instead of builtins, in order to reduce the number of
 builtins that we need to implement.
 
-.. _langext-__builtin_assume:
-
-``__builtin_assume``
---
+``__builtin_alloca``
+
 
-``__builtin_assume`` is used to provide the optimizer with a boolean
-invariant that is defined to be true.
+``__builtin_alloca`` is used to dynamically allocate memory on the stack. Memory
+is automatically freed upon function termination.
 
 **Syntax**:
 
 .. code-block:: c++
 
-  __builtin_assume(bool)
+  __builtin_alloca(size_t n)
 
 **Example of Use**:
 
 .. code-block:: c++
 
-  int foo(int x) {
-__builtin_assume(x != 0);
+  void init(float* data, size_t nbelems);
+  void process(float* data, size_t nbelems);
+  int foo(size_t n) {
+auto mem = (float*)__builtin_alloca(n * sizeof(float));
+init(mem, n);
+process(mem, n);
+/* mem is automatically freed at this point */
+  }
+
+**Description**:
+
+``__builtin_alloca`` is meant to be used to allocate a dynamic amount of memory
+on the stack. This amount is subject to stack allocation limits.
+
+Query for this feature with ``__has_builtin(__builtin_alloca)``.
+
+``__builtin_alloca_with_align``
+---
 
-// The optimizer may short-circuit this check using the invariant.
-if (x == 0)
-  return do_something();
+``__builtin_alloca_with_align`` is used to dynamically allocate memory on the
+stack while controlling its alignment. Memory is automatically freed upon
+function termination.
 
-return do_something_else();
+
+**Syntax**:
+
+.. code-block:: c++
+
+  __builtin_alloca_with_align(size_t n, size_t align)
+
+**Example of Use**:
+
+.. code-block:: c++
+
+  void init(float* data, size_t nbelems);
+  void process(float* data, size_t nbelems);
+  int foo(size_t n) {
+auto mem = (float*)__builtin_alloca_with_align(
+n * sizeof(float),
+8 * alignof(float));
+init(mem, n);
+process(mem, n);
+/* mem is automatically freed at this point */
   }
 
 **Description**:
 
-The boolean argument to this function is defined to be true. The optimizer may
-analyze the form of the expression provided as the argument and deduce from
-that information used to optimize the program. If the condition is violated
-during execution, the behavior is undefined. The argument itself is never
-evaluated, so any side effects of the expression will be discarded.
+``__builtin_alloca_with_align`` is meant to be used to allocate a dynamic amount of memory
+on the stack. It is similar to ``__builtin_alloca`` but accepts a second
+argument whose value is the alignment constraint, as a power of 2 in *bits*.
+
+Query for this feature with ``__has_builtin(__builtin_alloca_with_align)``.
 
-Query for this feature with ``__has_builtin(__builtin_assume)``.
+.. _langext-__builtin_assume:
+
+``__builtin_call_with_static_chain``
+
+
+``__builtin_call_with_static_chain`` is used to perform a static call while
+setting updating the static chain register.
+
+**Syntax**:
+
+.. code-block:: c++
+
+  T __builtin_call_with_static_chain(T expr, void* ptr)
+
+**Example of Use**:
+
+.. code-block:: c++
+
+  auto v = __builtin_call_with_static_chain(foo(3), foo);
+
+**Description**:
+
+This builtin returns ``expr`` after checking that ``expr`` is a non-member
+static call expression. The call to that expression is made while using ``ptr``
+as a function pointer stored in a dedicated register to implement *static chain*
+calling convention, as used by some language to implement closures or nested
+functions.
+
+Query for this feature with ``__has_builtin(__builtin_call_with_static_chain)``.
 
 ``__builtin_readcyclecounter``
 --
@@ -2501,6 +2562,95 @@
 
 Query for this feature with ``__has_builtin(__builtin_unpredictable)``.
 
+
+``__builtin_expect``
+
+
+``__builtin_expect`` is used to indicate that an expression is expected (I;e.
+very likely to) take a given value.
+
+**Syntax**:
+
+.. code-block:: c++
+
+long __builtin_expect(long expr, long val)
+
+**Example of use**:
+
+.. code-block:: c++
+
+  if (__builtin_expect(x, 0)) {
+ bar();
+  }
+
+**Description**:
+
+The ``__builtin_e

[PATCH] D117142: [clang-format] Fix short functions being considered as inline inside an indented namespace.

2022-01-14 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius updated this revision to Diff 399945.
curdeius added a comment.

Minor clean up.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D117142

Files:
  clang/lib/Format/UnwrappedLineFormatter.cpp
  clang/unittests/Format/FormatTest.cpp
  clang/unittests/Format/FormatTestCSharp.cpp
  clang/unittests/Format/FormatTestJava.cpp

Index: clang/unittests/Format/FormatTestJava.cpp
===
--- clang/unittests/Format/FormatTestJava.cpp
+++ clang/unittests/Format/FormatTestJava.cpp
@@ -602,5 +602,16 @@
"}");
 }
 
+TEST_F(FormatTestJava, ShortFunctions) {
+  FormatStyle Style = getLLVMStyle(FormatStyle::LK_Java);
+  Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
+  verifyFormat("enum Enum {\n"
+   "  E1,\n"
+   "  E2;\n"
+   "  void f() { return; }\n"
+   "}",
+   Style);
+}
+
 } // namespace format
 } // end namespace clang
Index: clang/unittests/Format/FormatTestCSharp.cpp
===
--- clang/unittests/Format/FormatTestCSharp.cpp
+++ clang/unittests/Format/FormatTestCSharp.cpp
@@ -1518,5 +1518,32 @@
Style);
 }
 
+TEST_F(FormatTestCSharp, ShortFunctions) {
+  FormatStyle Style = getLLVMStyle(FormatStyle::LK_CSharp);
+  Style.NamespaceIndentation = FormatStyle::NI_All;
+  Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
+  verifyFormat("interface Interface {\n"
+   "  void f() { return; }\n"
+   "};",
+   Style);
+  verifyFormat("public interface Interface {\n"
+   "  void f() { return; }\n"
+   "};",
+   Style);
+  verifyFormat("namespace {\n"
+   "  void f() {\n"
+   "return;\n"
+   "  }\n"
+   "};",
+   Style);
+  // "union" is not a keyword in C#.
+  verifyFormat("namespace union {\n"
+   "  void f() {\n"
+   "return;\n"
+   "  }\n"
+   "};",
+   Style);
+}
+
 } // namespace format
 } // end namespace clang
Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -3554,6 +3554,86 @@
"} // namespace out",
Style));
 
+  FormatStyle ShortInlineFunctions = getLLVMStyle();
+  ShortInlineFunctions.NamespaceIndentation = FormatStyle::NI_All;
+  ShortInlineFunctions.AllowShortFunctionsOnASingleLine =
+  FormatStyle::SFS_Inline;
+  verifyFormat("namespace {\n"
+   "  void f() {\n"
+   "return;\n"
+   "  }\n"
+   "} // namespace\n",
+   ShortInlineFunctions);
+  verifyFormat("namespace {\n"
+   "  int some_int;\n"
+   "  void f() {\n"
+   "return;\n"
+   "  }\n"
+   "} // namespace\n",
+   ShortInlineFunctions);
+  verifyFormat("namespace interface {\n"
+   "  void f() {\n"
+   "return;\n"
+   "  }\n"
+   "} // namespace interface\n",
+   ShortInlineFunctions);
+  verifyFormat("namespace {\n"
+   "  class X {\n"
+   "void f() { return; }\n"
+   "  };\n"
+   "} // namespace\n",
+   ShortInlineFunctions);
+  verifyFormat("namespace {\n"
+   "  struct X {\n"
+   "void f() { return; }\n"
+   "  };\n"
+   "} // namespace\n",
+   ShortInlineFunctions);
+  verifyFormat("namespace {\n"
+   "  union X {\n"
+   "void f() { return; }\n"
+   "  };\n"
+   "} // namespace\n",
+   ShortInlineFunctions);
+  verifyFormat("extern \"C\" {\n"
+   "void f() {\n"
+   "  return;\n"
+   "}\n"
+   "} // namespace\n",
+   ShortInlineFunctions);
+  verifyFormat("namespace {\n"
+   "  class X {\n"
+   "void f() { return; }\n"
+   "  } x;\n"
+   "} // namespace\n",
+   ShortInlineFunctions);
+  verifyFormat("namespace {\n"
+   "  [[nodiscard]] class X {\n"
+   "void f() { return; }\n"
+   "  };\n"
+   "} // namespace\n",
+   ShortInlineFunctions);
+  verifyFormat("namespace {\n"
+   "  static class X {\n"
+   "void f() { return; }\n"
+   "  } x;\n"
+   "} // namespace\n",
+   ShortInlineFunctions);
+  verifyFormat("namespace {\n"
+   "  constexpr class X {\n"
+   "void f() { return

[PATCH] D116316: [clang-format] Add an experimental option to remove optional control statement braces in LLVM C++ code

2022-01-14 Thread Owen Pan via Phabricator via cfe-commits
owenpan added a comment.

@MyDeveloperDay @curdeius I will land this patch if you have no more comments. 
:)


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

https://reviews.llvm.org/D116316

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


[PATCH] D117142: [clang-format] Fix short functions being considered as inline inside an indented namespace.

2022-01-14 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius updated this revision to Diff 399946.
curdeius added a comment.

Rebase to fix Windows CI.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D117142

Files:
  clang/lib/Format/UnwrappedLineFormatter.cpp
  clang/unittests/Format/FormatTest.cpp
  clang/unittests/Format/FormatTestCSharp.cpp
  clang/unittests/Format/FormatTestJava.cpp

Index: clang/unittests/Format/FormatTestJava.cpp
===
--- clang/unittests/Format/FormatTestJava.cpp
+++ clang/unittests/Format/FormatTestJava.cpp
@@ -602,5 +602,16 @@
"}");
 }
 
+TEST_F(FormatTestJava, ShortFunctions) {
+  FormatStyle Style = getLLVMStyle(FormatStyle::LK_Java);
+  Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
+  verifyFormat("enum Enum {\n"
+   "  E1,\n"
+   "  E2;\n"
+   "  void f() { return; }\n"
+   "}",
+   Style);
+}
+
 } // namespace format
 } // end namespace clang
Index: clang/unittests/Format/FormatTestCSharp.cpp
===
--- clang/unittests/Format/FormatTestCSharp.cpp
+++ clang/unittests/Format/FormatTestCSharp.cpp
@@ -1518,5 +1518,32 @@
Style);
 }
 
+TEST_F(FormatTestCSharp, ShortFunctions) {
+  FormatStyle Style = getLLVMStyle(FormatStyle::LK_CSharp);
+  Style.NamespaceIndentation = FormatStyle::NI_All;
+  Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
+  verifyFormat("interface Interface {\n"
+   "  void f() { return; }\n"
+   "};",
+   Style);
+  verifyFormat("public interface Interface {\n"
+   "  void f() { return; }\n"
+   "};",
+   Style);
+  verifyFormat("namespace {\n"
+   "  void f() {\n"
+   "return;\n"
+   "  }\n"
+   "};",
+   Style);
+  // "union" is not a keyword in C#.
+  verifyFormat("namespace union {\n"
+   "  void f() {\n"
+   "return;\n"
+   "  }\n"
+   "};",
+   Style);
+}
+
 } // namespace format
 } // end namespace clang
Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -3554,6 +3554,86 @@
"} // namespace out",
Style));
 
+  FormatStyle ShortInlineFunctions = getLLVMStyle();
+  ShortInlineFunctions.NamespaceIndentation = FormatStyle::NI_All;
+  ShortInlineFunctions.AllowShortFunctionsOnASingleLine =
+  FormatStyle::SFS_Inline;
+  verifyFormat("namespace {\n"
+   "  void f() {\n"
+   "return;\n"
+   "  }\n"
+   "} // namespace\n",
+   ShortInlineFunctions);
+  verifyFormat("namespace {\n"
+   "  int some_int;\n"
+   "  void f() {\n"
+   "return;\n"
+   "  }\n"
+   "} // namespace\n",
+   ShortInlineFunctions);
+  verifyFormat("namespace interface {\n"
+   "  void f() {\n"
+   "return;\n"
+   "  }\n"
+   "} // namespace interface\n",
+   ShortInlineFunctions);
+  verifyFormat("namespace {\n"
+   "  class X {\n"
+   "void f() { return; }\n"
+   "  };\n"
+   "} // namespace\n",
+   ShortInlineFunctions);
+  verifyFormat("namespace {\n"
+   "  struct X {\n"
+   "void f() { return; }\n"
+   "  };\n"
+   "} // namespace\n",
+   ShortInlineFunctions);
+  verifyFormat("namespace {\n"
+   "  union X {\n"
+   "void f() { return; }\n"
+   "  };\n"
+   "} // namespace\n",
+   ShortInlineFunctions);
+  verifyFormat("extern \"C\" {\n"
+   "void f() {\n"
+   "  return;\n"
+   "}\n"
+   "} // namespace\n",
+   ShortInlineFunctions);
+  verifyFormat("namespace {\n"
+   "  class X {\n"
+   "void f() { return; }\n"
+   "  } x;\n"
+   "} // namespace\n",
+   ShortInlineFunctions);
+  verifyFormat("namespace {\n"
+   "  [[nodiscard]] class X {\n"
+   "void f() { return; }\n"
+   "  };\n"
+   "} // namespace\n",
+   ShortInlineFunctions);
+  verifyFormat("namespace {\n"
+   "  static class X {\n"
+   "void f() { return; }\n"
+   "  } x;\n"
+   "} // namespace\n",
+   ShortInlineFunctions);
+  verifyFormat("namespace {\n"
+   "  constexpr class X {\n"
+   "void f(

[PATCH] D116316: [clang-format] Add an experimental option to remove optional control statement braces in LLVM C++ code

2022-01-14 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius accepted this revision.
curdeius added a comment.
This revision is now accepted and ready to land.

LGTM.




Comment at: clang/docs/ClangFormatStyleOptions.rst:3398
 
+**RemoveBracesLLVM** (``Boolean``) :versionbadge:`clang-format 14`
+  Remove optional braces of control statements (``if``, ``else``, ``for``,

owenpan wrote:
> MyDeveloperDay wrote:
> > Can we agree on one set of options that can be used for both insertion and 
> > removal even if this patch only does removal 
> > Can we agree on one set of options that can be used for both insertion and 
> > removal even if this patch only does removal 
> 
> One idea is to run insertion for all missing braces and then this option to 
> remove the optional ones for LLVM, i.e., an `AutomaticBraces` if you will.
Have you agreed upon this?


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

https://reviews.llvm.org/D116316

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


[PATCH] D116316: [clang-format] Add an experimental option to remove optional control statement braces in LLVM C++ code

2022-01-14 Thread Owen Pan via Phabricator via cfe-commits
owenpan added inline comments.



Comment at: clang/docs/ClangFormatStyleOptions.rst:3398
 
+**RemoveBracesLLVM** (``Boolean``) :versionbadge:`clang-format 14`
+  Remove optional braces of control statements (``if``, ``else``, ``for``,

curdeius wrote:
> owenpan wrote:
> > MyDeveloperDay wrote:
> > > Can we agree on one set of options that can be used for both insertion 
> > > and removal even if this patch only does removal 
> > > Can we agree on one set of options that can be used for both insertion 
> > > and removal even if this patch only does removal 
> > 
> > One idea is to run insertion for all missing braces and then this option to 
> > remove the optional ones for LLVM, i.e., an `AutomaticBraces` if you will.
> Have you agreed upon this?
Not yet. We probably want to test inserting braces `Always` on check-clang if 
it's not already been done.


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

https://reviews.llvm.org/D116316

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


[PATCH] D107450: [clang-tidy] Fix wrong FixIt in performance-move-const-arg

2022-01-14 Thread gehry via Phabricator via cfe-commits
Sockke added a comment.

Friendly ping. @aaron.ballman


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

https://reviews.llvm.org/D107450

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


[PATCH] D116439: [clang-tidy] Fix `readability-const-return-type` for pure virtual function.

2022-01-14 Thread gehry via Phabricator via cfe-commits
Sockke added a comment.

Friendly ping. @aaron.ballman


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116439

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


[PATCH] D116593: Fix `performance-unnecessary-value-param` for template specialization

2022-01-14 Thread gehry via Phabricator via cfe-commits
Sockke added a comment.

Friendly ping.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116593

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


[PATCH] D117090: [clang-tidy] Fix `readability-non-const-parameter` for parameter referenced by an lvalue

2022-01-14 Thread gehry via Phabricator via cfe-commits
Sockke added inline comments.



Comment at: 
clang-tools-extra/clang-tidy/readability/NonConstParameterCheck.cpp:86-99
+  // Data passed by nonconst reference should not be made const.
+  unsigned ArgNr = 0U;
+  if (const auto *CD = CE->getConstructor()) {
+for (const auto *Par : CD->parameters()) {
+  if (ArgNr >= CE->getNumArgs())
+break;
+  const Expr *Arg = CE->getArg(ArgNr++);

MTC wrote:
> `86~99` is pretty close to `64~81`, could you please refactor it?
> `86~99` is pretty close to `64~81`, could you please refactor it?

`FunctionDecl` and `CXXConstructDecl` have different methods with the same name.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D117090

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


[PATCH] D117294: [clangd] Better handling `\n` in the synthesized diagnostic message.

2022-01-14 Thread Sam McCall via Phabricator via cfe-commits
sammccall accepted this revision.
sammccall added inline comments.
This revision is now accepted and ready to land.



Comment at: clang-tools-extra/clangd/Diagnostics.cpp:635
+  if (Code == "\n") {
+OS << "\\n";
+return;

or "newline"?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D117294

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


[clang] cd3ab15 - [clang-format] Fix typos in test. NFC.

2022-01-14 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-01-14T13:24:16+01:00
New Revision: cd3ab156a74b57432f6337f6e0405fa7f207604e

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

LOG: [clang-format] Fix typos in test. NFC.

Added: 


Modified: 
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 9d1273184807c..a2470daeca03a 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -2157,7 +2157,7 @@ TEST_F(FormatTest, ForEachLoops) {
"  foreach (Item *item, itemlist) {}\n"
"  Q_FOREACH (Item *item, itemlist) {}\n"
"  BOOST_FOREACH (Item *item, itemlist) {}\n"
-   "  UNKNOWN_FORACH(Item * item, itemlist) {}\n"
+   "  UNKNOWN_FOREACH(Item * item, itemlist) {}\n"
"}");
 
   FormatStyle Style = getLLVMStyle();
@@ -2167,7 +2167,7 @@ TEST_F(FormatTest, ForEachLoops) {
"  foreach(Item *item, itemlist) {}\n"
"  Q_FOREACH(Item *item, itemlist) {}\n"
"  BOOST_FOREACH(Item *item, itemlist) {}\n"
-   "  UNKNOWN_FORACH(Item * item, itemlist) {}\n"
+   "  UNKNOWN_FOREACH(Item * item, itemlist) {}\n"
"}",
Style);
 



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


[PATCH] D117301: [clang][NFC] Wrap TYPE_SWITCH in "do while (0)" in the interpreter

2022-01-14 Thread Owen Pan via Phabricator via cfe-commits
owenpan created this revision.
owenpan added reviewers: jfb, rsmith, RKSimon, nand.
owenpan added a project: clang.
owenpan requested review of this revision.
Herald added a subscriber: cfe-commits.

Wraps the expansion of TYPE_SWITCH of the constexpr interpreter 
in `do { ... } while (0)` so that the macro can be used like this:

  if (llvm::Optional T = Ctx.classify(FieldTy)) 
TYPE_SWITCH(*T, Ok &= ReturnValue(FP.deref(), Value));
  else 
Ok &= Composite(FieldTy, FP, Value);

This bug was found while testing D116316 .  
See also this review comment 
.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D117301

Files:
  clang/lib/AST/Interp/PrimType.h


Index: clang/lib/AST/Interp/PrimType.h
===
--- clang/lib/AST/Interp/PrimType.h
+++ clang/lib/AST/Interp/PrimType.h
@@ -83,18 +83,20 @@
 #define TYPE_SWITCH_CASE(Name, B) \
   case Name: { using T = PrimConv::T; do {B;} while(0); break; }
 #define TYPE_SWITCH(Expr, B)   
\
-  switch (Expr) {  
\
-TYPE_SWITCH_CASE(PT_Sint8, B)  
\
-TYPE_SWITCH_CASE(PT_Uint8, B)  
\
-TYPE_SWITCH_CASE(PT_Sint16, B) 
\
-TYPE_SWITCH_CASE(PT_Uint16, B) 
\
-TYPE_SWITCH_CASE(PT_Sint32, B) 
\
-TYPE_SWITCH_CASE(PT_Uint32, B) 
\
-TYPE_SWITCH_CASE(PT_Sint64, B) 
\
-TYPE_SWITCH_CASE(PT_Uint64, B) 
\
-TYPE_SWITCH_CASE(PT_Bool, B)   
\
-TYPE_SWITCH_CASE(PT_Ptr, B)
\
-  }
+  do { 
\
+switch (Expr) {
\
+  TYPE_SWITCH_CASE(PT_Sint8, B)
\
+  TYPE_SWITCH_CASE(PT_Uint8, B)
\
+  TYPE_SWITCH_CASE(PT_Sint16, B)   
\
+  TYPE_SWITCH_CASE(PT_Uint16, B)   
\
+  TYPE_SWITCH_CASE(PT_Sint32, B)   
\
+  TYPE_SWITCH_CASE(PT_Uint32, B)   
\
+  TYPE_SWITCH_CASE(PT_Sint64, B)   
\
+  TYPE_SWITCH_CASE(PT_Uint64, B)   
\
+  TYPE_SWITCH_CASE(PT_Bool, B) 
\
+  TYPE_SWITCH_CASE(PT_Ptr, B)  
\
+}  
\
+  } while (0)
 #define COMPOSITE_TYPE_SWITCH(Expr, B, D)  
\
   switch (Expr) {  
\
 TYPE_SWITCH_CASE(PT_Ptr, B)
\


Index: clang/lib/AST/Interp/PrimType.h
===
--- clang/lib/AST/Interp/PrimType.h
+++ clang/lib/AST/Interp/PrimType.h
@@ -83,18 +83,20 @@
 #define TYPE_SWITCH_CASE(Name, B) \
   case Name: { using T = PrimConv::T; do {B;} while(0); break; }
 #define TYPE_SWITCH(Expr, B)   \
-  switch (Expr) {  \
-TYPE_SWITCH_CASE(PT_Sint8, B)  \
-TYPE_SWITCH_CASE(PT_Uint8, B)  \
-TYPE_SWITCH_CASE(PT_Sint16, B) \
-TYPE_SWITCH_CASE(PT_Uint16, B) \
-TYPE_SWITCH_CASE(PT_Sint32, B) \
-TYPE_SWITCH_CASE(PT_Uint32, B) \
-TYPE_SWITCH_CASE(PT_Sint64, B) \
-TYPE_SWITCH_CASE(PT_Uint64, B) \
-TYPE_SWITCH_CASE(PT_Bool, B)   \
-TYPE_SWITCH_CASE(PT_Ptr, B)\
-  }
+  do { \
+switch (Expr) {\
+  TYPE_SWITCH_CASE(PT_Sint8, B)\
+  TYPE_SWITCH_CASE(PT_Uint8, B) 

[PATCH] D107450: [clang-tidy] Fix wrong FixIt in performance-move-const-arg

2022-01-14 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman accepted this revision.
aaron.ballman added a comment.

LGTM! @Quuxplusone, you're still marked as requesting changes, are you okay 
with the way this has progressed?


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

https://reviews.llvm.org/D107450

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


[PATCH] D116966: [analyzer] Don't specify PLUGIN_TOOL for analyzer plugins

2022-01-14 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added reviewers: thakis, rnk, majnemer.
aaron.ballman added a comment.

AFAIK, we don't support plugins on Windows. See: 
https://reviews.llvm.org/D16761#1441359 I don't think anything has changed in 
this regard. Based on that, I don't think this patch is necessary, but I'm 
adding some other folks who may be more familiar with the current state of 
plugin support on Windows just in case.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116966

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


[PATCH] D117304: [clang][dataflow] Remove TestingSupport's dependency on gtest

2022-01-14 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel created this revision.
ymandel added a reviewer: gribozavr2.
ymandel requested review of this revision.
Herald added a project: clang.

Users outside of the clang repo may use different googletest versions. So, it's
better not to depend on llvm's googletest. This patch removes the dependency by
having `checkDataflow` return an `llvm::Error` instead of calling googletest's
`FAIL` or `ASSERT...` macros.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D117304

Files:
  clang/unittests/Analysis/FlowSensitive/MultiVarConstantPropagationTest.cpp
  clang/unittests/Analysis/FlowSensitive/SingleVarConstantPropagationTest.cpp
  clang/unittests/Analysis/FlowSensitive/TestingSupport.cpp
  clang/unittests/Analysis/FlowSensitive/TestingSupport.h
  clang/unittests/Analysis/FlowSensitive/TestingSupportTest.cpp
  clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
  clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
@@ -21,6 +21,7 @@
 #include "llvm/ADT/SmallSet.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Error.h"
+#include "llvm/Testing/Support/Error.h"
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
 #include 
@@ -196,15 +197,19 @@
   };
 )"));
 
-test::checkDataflow(
-Code, "target",
-[](ASTContext &C, Environment &) { return FunctionCallAnalysis(C); },
-[&Expectations](
-llvm::ArrayRef>>
-Results,
-ASTContext &) { EXPECT_THAT(Results, Expectations); },
-{"-fsyntax-only", "-std=c++17"}, FilesContents);
+ASSERT_THAT_ERROR(
+test::checkDataflow(
+Code, "target",
+[](ASTContext &C, Environment &) {
+  return FunctionCallAnalysis(C);
+},
+[&Expectations](
+llvm::ArrayRef>>
+Results,
+ASTContext &) { EXPECT_THAT(Results, Expectations); },
+{"-fsyntax-only", "-std=c++17"}, FilesContents),
+llvm::Succeeded());
   }
 };
 
Index: clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
@@ -18,6 +18,7 @@
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Casting.h"
+#include "llvm/Testing/Support/Error.h"
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
 #include 
@@ -38,14 +39,17 @@
 protected:
   template 
   void runDataflow(llvm::StringRef Code, Matcher Match) {
-test::checkDataflow(
-Code, "target",
-[](ASTContext &C, Environment &) { return NoopAnalysis(C); },
-[&Match](llvm::ArrayRef<
- std::pair>>
- Results,
- ASTContext &ASTCtx) { Match(Results, ASTCtx); },
-{"-fsyntax-only", "-std=c++17"});
+ASSERT_THAT_ERROR(
+test::checkDataflow(
+Code, "target",
+[](ASTContext &C, Environment &) { return NoopAnalysis(C); },
+[&Match](
+llvm::ArrayRef<
+std::pair>>
+Results,
+ASTContext &ASTCtx) { Match(Results, ASTCtx); },
+{"-fsyntax-only", "-std=c++17"}),
+llvm::Succeeded());
   }
 };
 
Index: clang/unittests/Analysis/FlowSensitive/TestingSupportTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TestingSupportTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TestingSupportTest.cpp
@@ -4,6 +4,7 @@
 #include "clang/ASTMatchers/ASTMatchFinder.h"
 #include "clang/ASTMatchers/ASTMatchers.h"
 #include "clang/Tooling/Tooling.h"
+#include "llvm/Testing/Support/Error.h"
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
 
@@ -77,10 +78,14 @@
std::string, DataflowAnalysisState>>,
ASTContext &)>
 Expectations) {
-  test::checkDataflow(
-  Code, Target,
-  [](ASTContext &Context, Environment &) { return NoopAnalysis(Context); },
-  std::move(Expectations), {"-fsyntax-only", "-std=c++17"});
+  ASSERT_THAT_ERROR(
+  test::checkDataflow(Code, Target,
+[](ASTContext &Context, Environment &) {
+  return NoopAnalysis(Context);
+},
+std::move(Expectations),
+{"-fsyntax-only", "-std=c++17"}),
+  llvm::Succeeded());
 }
 
 TEST(ProgramPointAnnotations, NoAnnotat

[PATCH] D116966: [analyzer] Don't specify PLUGIN_TOOL for analyzer plugins

2022-01-14 Thread Aleksandr Platonov via Phabricator via cfe-commits
ArcsinX added a comment.

In D116966#3243318 , @aaron.ballman 
wrote:

> AFAIK, we don't support plugins on Windows. See: 
> https://reviews.llvm.org/D16761#1441359 I don't think anything has changed in 
> this regard.

I can say that I successfully use clang plugins on Windows (and analyzer 
plugins too, which works in a bit different way). Seems this became possible 
after https://reviews.llvm.org/D18826


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116966

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


[PATCH] D117271: [AArch64] clang support for Armv8.8/9.3 MOPS

2022-01-14 Thread Sam Elliott via Phabricator via cfe-commits
lenary accepted this revision.
lenary added a comment.
This revision is now accepted and ready to land.

LGTM


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D117271

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


[PATCH] D116190: Comment parsing: Don't recognize commands in single-line double quotation

2022-01-14 Thread Aaron Puchert via Phabricator via cfe-commits
aaronpuchert marked an inline comment as done.
aaronpuchert added inline comments.



Comment at: clang/lib/AST/CommentLexer.cpp:278
+
+again:
+  size_t End =

gribozavr2 wrote:
> I'd suggest refactoring to a `while (true)` if you don't mind.
I was imitating `lexVerbatimBlockFirstLine`, but I don't mind either way.



Comment at: clang/lib/AST/CommentLexer.cpp:290
+if (End != StringRef::npos && *(TokenPtr + End) == '\"')
+  TokenPtr += End + 1;
+goto again;

gribozavr2 wrote:
> Does Doxygen understand escaped quotes?
> 
> ```
> /// "@hello\"@hello"
> ```
Vim syntax highlighting suggests it does, but at least my version actually 
doesn't: `"@c a \" @c b"` is translated to `"@c a \" b"`. So the 
escaped quote seems to end the quotation.



Comment at: clang/lib/AST/CommentLexer.cpp:485
 void Lexer::lexVerbatimBlockFirstLine(Token &T) {
 again:
   assert(BufferPtr < CommentEnd);

This is what I was imitating.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116190

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


[PATCH] D116186: Comment parsing: Simplify Lexer::skipLineStartingDecorations (NFC)

2022-01-14 Thread Aaron Puchert via Phabricator via cfe-commits
aaronpuchert added a comment.

Ping @gribozavr2.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116186

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


[PATCH] D116966: [analyzer] Don't specify PLUGIN_TOOL for analyzer plugins

2022-01-14 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D116966#3243346 , @ArcsinX wrote:

> In D116966#3243318 , @aaron.ballman 
> wrote:
>
>> AFAIK, we don't support plugins on Windows. See: 
>> https://reviews.llvm.org/D16761#1441359 I don't think anything has changed 
>> in this regard.
>
> I can say that I successfully use clang plugins on Windows (and analyzer 
> plugins too, which works in a bit different way). Seems this became possible 
> after https://reviews.llvm.org/D18826

That's good to know, but looking at the dates of the two reviews still confuses 
me.

2016: https://reviews.llvm.org/D18826
2019: https://reviews.llvm.org/D16761#1441359

It doesn't help that we don't document supported platforms one way or the other 
in https://clang.llvm.org/docs/ClangPlugins.html.

Does your plugin work against a Clang built with `BUILD_SHARED_LIB=0`?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116966

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


[PATCH] D116966: [analyzer] Don't specify PLUGIN_TOOL for analyzer plugins

2022-01-14 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

To be clear, I'm trying to figure out whether plugins are *actually* supported 
on Windows or whether they just so happen to work if the stars line up right 
for you. If they're supported, then awesome, let's go forward with this. If 
they're not supported, it's less clear whether we want to make it easier for 
the stars to line up or not.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116966

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


[clang-tools-extra] 1093b9f - Revert "[clangd] Elide even more checks in SelectionTree."

2022-01-14 Thread Kadir Cetinkaya via cfe-commits

Author: Kadir Cetinkaya
Date: 2022-01-14T14:32:43+01:00
New Revision: 1093b9f2e9842982d97534940a643e3a4657c60b

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

LOG: Revert "[clangd] Elide even more checks in SelectionTree."

This reverts commit 07f9fb8b51417ec3e6f46508e1b5ef78287b32ad.

Added: 


Modified: 
clang-tools-extra/clangd/Selection.cpp
clang-tools-extra/clangd/unittests/SelectionTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/Selection.cpp 
b/clang-tools-extra/clangd/Selection.cpp
index 8fb5918c5d000..011e24ee70b2f 100644
--- a/clang-tools-extra/clangd/Selection.cpp
+++ b/clang-tools-extra/clangd/Selection.cpp
@@ -274,37 +274,22 @@ class SelectionTester {
 for (unsigned I = 0; I < Sel.size(); ++I) {
   if (shouldIgnore(Sel[I]) || PPIgnored[I])
 continue;
-  SelectedSpelled.emplace_back();
-  Tok &S = SelectedSpelled.back();
+  SpelledTokens.emplace_back();
+  Tok &S = SpelledTokens.back();
   S.Offset = SM.getFileOffset(Sel[I].location());
   if (S.Offset >= SelBegin && S.Offset + Sel[I].length() <= SelEnd)
 S.Selected = SelectionTree::Complete;
   else
 S.Selected = SelectionTree::Partial;
 }
-MaybeSelectedExpanded = computeMaybeSelectedExpandedTokens(Buf);
   }
 
   // Test whether a consecutive range of tokens is selected.
   // The tokens are taken from the expanded token stream.
   SelectionTree::Selection
   test(llvm::ArrayRef ExpandedTokens) const {
-if (ExpandedTokens.empty())
+if (SpelledTokens.empty())
   return NoTokens;
-if (SelectedSpelled.empty())
-  return SelectionTree::Unselected;
-// Cheap (pointer) check whether any of the tokens could touch selection.
-// In most cases, the node's overall source range touches ExpandedTokens,
-// or we would have failed mayHit(). However now we're only considering
-// the *unclaimed* spans of expanded tokens.
-// This is a significant performance improvement when a lot of nodes
-// surround the selection, including when generated by macros.
-if (MaybeSelectedExpanded.empty() ||
-&ExpandedTokens.front() > &MaybeSelectedExpanded.back() ||
-&ExpandedTokens.back() < &MaybeSelectedExpanded.front()) {
-  return SelectionTree::Unselected;
-}
-
 SelectionTree::Selection Result = NoTokens;
 while (!ExpandedTokens.empty()) {
   // Take consecutive tokens from the same context together for efficiency.
@@ -327,14 +312,14 @@ class SelectionTester {
   // If it returns false, test() will return NoTokens or Unselected.
   // If it returns true, test() may return any value.
   bool mayHit(SourceRange R) const {
-if (SelectedSpelled.empty() || MaybeSelectedExpanded.empty())
+if (SpelledTokens.empty())
   return false;
 // If the node starts after the selection ends, it is not selected.
 // Tokens a macro location might claim are >= its expansion start.
 // So if the expansion start > last selected token, we can prune it.
 // (This is particularly helpful for GTest's TEST macro).
 if (auto B = offsetInSelFile(getExpansionStart(R.getBegin(
-  if (*B > SelectedSpelled.back().Offset)
+  if (*B > SpelledTokens.back().Offset)
 return false;
 // If the node ends before the selection begins, it is not selected.
 SourceLocation EndLoc = R.getEnd();
@@ -343,72 +328,12 @@ class SelectionTester {
 // In the rare case that the expansion range is a char range, EndLoc is
 // ~one token too far to the right. We may fail to prune, that's OK.
 if (auto E = offsetInSelFile(EndLoc))
-  if (*E < SelectedSpelled.front().Offset)
+  if (*E < SpelledTokens.front().Offset)
 return false;
 return true;
   }
 
 private:
-  // Plausible expanded tokens that might be affected by the selection.
-  // This is an overestimate, it may contain tokens that are not selected.
-  // The point is to allow cheap pruning in test()
-  llvm::ArrayRef
-  computeMaybeSelectedExpandedTokens(const syntax::TokenBuffer &Toks) {
-if (SelectedSpelled.empty())
-  return {};
-
-bool StartInvalid = false;
-const syntax::Token *Start = llvm::partition_point(
-Toks.expandedTokens(),
-[&, First = SelectedSpelled.front().Offset](const syntax::Token &Tok) {
-  if (Tok.kind() == tok::eof)
-return false;
-  // Implausible if upperbound(Tok) < First.
-  SourceLocation Loc = Tok.location();
-  auto Offset = offsetInSelFile(Loc);
-  while (Loc.isValid() && !Offset) {
-Loc = Loc.isMacroID() ? SM.getImmediateExpansionRange(Loc).getEnd()
-  : SM.getIncludeLoc(SM.getFileID(Loc));
-Offset = offsetInSelF

[clang] 6a4957c - [clang-format] Add missing test for loops formatting. NFC.

2022-01-14 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-01-14T14:43:15+01:00
New Revision: 6a4957cbdff5d60de40639e6c9c8edd056b9a082

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

LOG: [clang-format] Add missing test for loops formatting. NFC.

The case with an inner while loop wasn't tested before. Same for outer loop 
with a ForeachMacro.

Added: 


Modified: 
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index a2470daeca03..d6e1f7341030 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -1473,6 +1473,12 @@ TEST_F(FormatTest, FormatLoopsWithoutCompoundStatement) {
   verifyFormat("for (;;)\n"
"  for (;;) continue;",
AllowsMergedLoops);
+  verifyFormat("for (;;)\n"
+   "  while (true) continue;",
+   AllowsMergedLoops);
+  verifyFormat("BOOST_FOREACH (int v, vec)\n"
+   "  for (;;) continue;",
+   AllowsMergedLoops);
   verifyFormat("for (;;) // Can't merge this\n"
"  continue;",
AllowsMergedLoops);



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


[PATCH] D117218: [clang][dataflow] Add transfer functions for constructors

2022-01-14 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel accepted this revision.
ymandel added inline comments.



Comment at: clang/lib/Analysis/FlowSensitive/Transfer.cpp:105
 
-  assert(SubExpr != nullptr);
+if (S->getCastKind() == CK_LValueToRValue) {
   auto *SubExprVal = Env.getValue(*SubExpr, SkipPast::Reference);

use a switch?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D117218

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


[PATCH] D116966: [analyzer] Don't specify PLUGIN_TOOL for analyzer plugins

2022-01-14 Thread Aleksandr Platonov via Phabricator via cfe-commits
ArcsinX added a comment.

In D116966#3243374 , @aaron.ballman 
wrote:

> To be clear, I'm trying to figure out whether plugins are *actually* 
> supported on Windows or whether they just so happen to work if the stars line 
> up right for you. If they're supported, then awesome, let's go forward with 
> this. If they're not supported, it's less clear whether we want to make it 
> easier for the stars to line up or not.

That how it work for me (extra cmake flags: -DLLVM_ENABLE_PLUGINS=On 
-DCLANG_PLUGINS_SUPPORT=On -DLLVM_EXPORT_SYMBOLS_FOR_PLUGINS=On)

  d:\work\llvm-all\build>bin\clang.exe -Xclang -plugin -Xclang print-fns 
d:\work\1.cpp -c
  error: unable to find plugin 'print-fns'
  
  d:\work\llvm-project\build>bin\clang.exe -fplugin=bin\PrintFunctionNames.dll 
-Xclang -plugin -Xclang print-fns d:\work\1.cpp -c
  top-level-decl: "main"
  top-level-decl: "a"
  
  d:\work\llvm-project\build>cat CMakeCache.txt | grep BUILD_SHARED_LIB
  BUILD_SHARED_LIBS:BOOL=OFF


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116966

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


[clang] 8de0c1f - [Clang] Add __builtin_reduce_or and __builtin_reduce_and

2022-01-14 Thread Jun Zhang via cfe-commits

Author: Jun Zhang
Date: 2022-01-14T22:05:26+08:00
New Revision: 8de0c1feca28e3de49b4d1d1140703cb6f739969

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

LOG: [Clang] Add __builtin_reduce_or and __builtin_reduce_and

This patch implements two builtins specified in D111529.
The last __builtin_reduce_add will be seperated into another one.

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

Added: 


Modified: 
clang/include/clang/Basic/Builtins.def
clang/lib/CodeGen/CGBuiltin.cpp
clang/lib/Sema/SemaChecking.cpp
clang/test/CodeGen/builtins-reduction-math.c
clang/test/Sema/builtins-reduction-math.c

Removed: 




diff  --git a/clang/include/clang/Basic/Builtins.def 
b/clang/include/clang/Basic/Builtins.def
index c7c47cf99aba..d2cb14d2fd8c 100644
--- a/clang/include/clang/Basic/Builtins.def
+++ b/clang/include/clang/Basic/Builtins.def
@@ -656,6 +656,8 @@ BUILTIN(__builtin_elementwise_trunc, "v.", "nct")
 BUILTIN(__builtin_reduce_max, "v.", "nct")
 BUILTIN(__builtin_reduce_min, "v.", "nct")
 BUILTIN(__builtin_reduce_xor, "v.", "nct")
+BUILTIN(__builtin_reduce_or, "v.", "nct")
+BUILTIN(__builtin_reduce_and, "v.", "nct")
 
 BUILTIN(__builtin_matrix_transpose, "v.", "nFt")
 BUILTIN(__builtin_matrix_column_major_load, "v.", "nFt")

diff  --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 187a603ff1c5..f68b7d3260e1 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -3221,6 +3221,12 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl 
GD, unsigned BuiltinID,
   case Builtin::BI__builtin_reduce_xor:
 return RValue::get(emitUnaryBuiltin(
 *this, E, llvm::Intrinsic::vector_reduce_xor, "rdx.xor"));
+  case Builtin::BI__builtin_reduce_or:
+return RValue::get(emitUnaryBuiltin(
+*this, E, llvm::Intrinsic::vector_reduce_or, "rdx.or"));
+  case Builtin::BI__builtin_reduce_and:
+return RValue::get(emitUnaryBuiltin(
+*this, E, llvm::Intrinsic::vector_reduce_and, "rdx.and"));
 
   case Builtin::BI__builtin_matrix_transpose: {
 auto *MatrixTy = E->getArg(0)->getType()->castAs();

diff  --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index d067ac31dc1e..a17ede85d3eb 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -2237,8 +2237,10 @@ Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, 
unsigned BuiltinID,
 break;
   }
 
-  // __builtin_reduce_xor supports vector of integers only.
-  case Builtin::BI__builtin_reduce_xor: {
+  // These builtins support vectors of integers only.
+  case Builtin::BI__builtin_reduce_xor:
+  case Builtin::BI__builtin_reduce_or:
+  case Builtin::BI__builtin_reduce_and: {
 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
   return ExprError();
 

diff  --git a/clang/test/CodeGen/builtins-reduction-math.c 
b/clang/test/CodeGen/builtins-reduction-math.c
index babd3345d787..43d47fc9dbfe 100644
--- a/clang/test/CodeGen/builtins-reduction-math.c
+++ b/clang/test/CodeGen/builtins-reduction-math.c
@@ -68,3 +68,25 @@ void test_builtin_reduce_xor(si8 vi1, u4 vu1) {
   // CHECK-NEXT: call i32 @llvm.vector.reduce.xor.v4i32(<4 x i32> [[VU1]])
   unsigned r3 = __builtin_reduce_xor(vu1);
 }
+
+void test_builtin_reduce_or(si8 vi1, u4 vu1) {
+
+  // CHECK:  [[VI1:%.+]] = load <8 x i16>, <8 x i16>* %vi1.addr, align 16
+  // CHECK-NEXT: call i16 @llvm.vector.reduce.or.v8i16(<8 x i16> [[VI1]])
+  short r2 = __builtin_reduce_or(vi1);
+
+  // CHECK:  [[VU1:%.+]] = load <4 x i32>, <4 x i32>* %vu1.addr, align 16
+  // CHECK-NEXT: call i32 @llvm.vector.reduce.or.v4i32(<4 x i32> [[VU1]])
+  unsigned r3 = __builtin_reduce_or(vu1);
+}
+
+void test_builtin_reduce_and(si8 vi1, u4 vu1) {
+
+  // CHECK:  [[VI1:%.+]] = load <8 x i16>, <8 x i16>* %vi1.addr, align 16
+  // CHECK-NEXT: call i16 @llvm.vector.reduce.and.v8i16(<8 x i16> [[VI1]])
+  short r2 = __builtin_reduce_and(vi1);
+
+  // CHECK:  [[VU1:%.+]] = load <4 x i32>, <4 x i32>* %vu1.addr, align 16
+  // CHECK-NEXT: call i32 @llvm.vector.reduce.and.v4i32(<4 x i32> [[VU1]])
+  unsigned r3 = __builtin_reduce_and(vu1);
+}

diff  --git a/clang/test/Sema/builtins-reduction-math.c 
b/clang/test/Sema/builtins-reduction-math.c
index 8ee64d50de38..a72922605603 100644
--- a/clang/test/Sema/builtins-reduction-math.c
+++ b/clang/test/Sema/builtins-reduction-math.c
@@ -52,3 +52,37 @@ void test_builtin_reduce_xor(int i, float4 v, int3 iv) {
   i = __builtin_reduce_xor(v);
   // expected-error@-1 {{1st argument must be a vector of integers (was 
'float4' (vector of 4 'float' values))}}
 }
+
+void test_builtin_reduce_or(int i, float4 v, int3 iv) {
+  struct Foo s = __builtin_reduce_or(iv);
+  // expected-error@-1 {{initializing 'struct Foo' with

[PATCH] D116736: [Clang] Add __builtin_reduce_or and __builtin_reduce_and

2022-01-14 Thread Jun Zhang via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG8de0c1feca28: [Clang] Add __builtin_reduce_or and 
__builtin_reduce_and (authored by junaire).

Changed prior to commit:
  https://reviews.llvm.org/D116736?vs=398838&id=399966#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116736

Files:
  clang/include/clang/Basic/Builtins.def
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/Sema/SemaChecking.cpp
  clang/test/CodeGen/builtins-reduction-math.c
  clang/test/Sema/builtins-reduction-math.c

Index: clang/test/Sema/builtins-reduction-math.c
===
--- clang/test/Sema/builtins-reduction-math.c
+++ clang/test/Sema/builtins-reduction-math.c
@@ -52,3 +52,37 @@
   i = __builtin_reduce_xor(v);
   // expected-error@-1 {{1st argument must be a vector of integers (was 'float4' (vector of 4 'float' values))}}
 }
+
+void test_builtin_reduce_or(int i, float4 v, int3 iv) {
+  struct Foo s = __builtin_reduce_or(iv);
+  // expected-error@-1 {{initializing 'struct Foo' with an expression of incompatible type 'int'}}
+
+  i = __builtin_reduce_or();
+  // expected-error@-1 {{too few arguments to function call, expected 1, have 0}}
+
+  i = __builtin_reduce_or(iv, iv);
+  // expected-error@-1 {{too many arguments to function call, expected 1, have 2}}
+
+  i = __builtin_reduce_or(i);
+  // expected-error@-1 {{1st argument must be a vector of integers (was 'int')}}
+
+  i = __builtin_reduce_or(v);
+  // expected-error@-1 {{1st argument must be a vector of integers (was 'float4' (vector of 4 'float' values))}}
+}
+
+void test_builtin_reduce_and(int i, float4 v, int3 iv) {
+  struct Foo s = __builtin_reduce_and(iv);
+  // expected-error@-1 {{initializing 'struct Foo' with an expression of incompatible type 'int'}}
+
+  i = __builtin_reduce_and();
+  // expected-error@-1 {{too few arguments to function call, expected 1, have 0}}
+
+  i = __builtin_reduce_and(iv, iv);
+  // expected-error@-1 {{too many arguments to function call, expected 1, have 2}}
+
+  i = __builtin_reduce_and(i);
+  // expected-error@-1 {{1st argument must be a vector of integers (was 'int')}}
+
+  i = __builtin_reduce_and(v);
+  // expected-error@-1 {{1st argument must be a vector of integers (was 'float4' (vector of 4 'float' values))}}
+}
Index: clang/test/CodeGen/builtins-reduction-math.c
===
--- clang/test/CodeGen/builtins-reduction-math.c
+++ clang/test/CodeGen/builtins-reduction-math.c
@@ -68,3 +68,25 @@
   // CHECK-NEXT: call i32 @llvm.vector.reduce.xor.v4i32(<4 x i32> [[VU1]])
   unsigned r3 = __builtin_reduce_xor(vu1);
 }
+
+void test_builtin_reduce_or(si8 vi1, u4 vu1) {
+
+  // CHECK:  [[VI1:%.+]] = load <8 x i16>, <8 x i16>* %vi1.addr, align 16
+  // CHECK-NEXT: call i16 @llvm.vector.reduce.or.v8i16(<8 x i16> [[VI1]])
+  short r2 = __builtin_reduce_or(vi1);
+
+  // CHECK:  [[VU1:%.+]] = load <4 x i32>, <4 x i32>* %vu1.addr, align 16
+  // CHECK-NEXT: call i32 @llvm.vector.reduce.or.v4i32(<4 x i32> [[VU1]])
+  unsigned r3 = __builtin_reduce_or(vu1);
+}
+
+void test_builtin_reduce_and(si8 vi1, u4 vu1) {
+
+  // CHECK:  [[VI1:%.+]] = load <8 x i16>, <8 x i16>* %vi1.addr, align 16
+  // CHECK-NEXT: call i16 @llvm.vector.reduce.and.v8i16(<8 x i16> [[VI1]])
+  short r2 = __builtin_reduce_and(vi1);
+
+  // CHECK:  [[VU1:%.+]] = load <4 x i32>, <4 x i32>* %vu1.addr, align 16
+  // CHECK-NEXT: call i32 @llvm.vector.reduce.and.v4i32(<4 x i32> [[VU1]])
+  unsigned r3 = __builtin_reduce_and(vu1);
+}
Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -2237,8 +2237,10 @@
 break;
   }
 
-  // __builtin_reduce_xor supports vector of integers only.
-  case Builtin::BI__builtin_reduce_xor: {
+  // These builtins support vectors of integers only.
+  case Builtin::BI__builtin_reduce_xor:
+  case Builtin::BI__builtin_reduce_or:
+  case Builtin::BI__builtin_reduce_and: {
 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
   return ExprError();
 
Index: clang/lib/CodeGen/CGBuiltin.cpp
===
--- clang/lib/CodeGen/CGBuiltin.cpp
+++ clang/lib/CodeGen/CGBuiltin.cpp
@@ -3221,6 +3221,12 @@
   case Builtin::BI__builtin_reduce_xor:
 return RValue::get(emitUnaryBuiltin(
 *this, E, llvm::Intrinsic::vector_reduce_xor, "rdx.xor"));
+  case Builtin::BI__builtin_reduce_or:
+return RValue::get(emitUnaryBuiltin(
+*this, E, llvm::Intrinsic::vector_reduce_or, "rdx.or"));
+  case Builtin::BI__builtin_reduce_and:
+return RValue::get(emitUnaryBuiltin(
+*this, E, llvm::Intrinsic::vector_reduce_and, "rdx.and"));
 
   case Builtin::BI__builtin_matrix_transpose: {
 auto *MatrixTy = E->getArg(0)-

[PATCH] D114235: [clang] Extend ParsedAttr to allow custom handling for type attributes

2022-01-14 Thread Martin Böhme via Phabricator via cfe-commits
mboehme added a comment.

Thanks for the feedback! And no worries about the delay -- I know you've got a 
lot on your plate, and the proposed change is invasive.

To make sure I understand correctly: The issue is that if a `Type` is replaced 
by an `AttributedType` in places where Clang does not (yet) expect this to 
happen, this can cause performance regressions or assertions?

The motivation behind making type attributes pluggable is that I'd like to 
annotate pointers with additional information for use in a memory safety static 
analysis. The goal here is the same as for the proposal I discussed with you a 
while ago of extending the `annotate` attribute to types (or possibly adding a 
new `annotate_type` attribute) on this lengthy mailing list thread (no need to 
reread it):

https://lists.llvm.org/pipermail/cfe-dev/2021-October/thread.html#69087

In this discussion, I mentioned that I was thinking about making type 
attributes pluggable too. I eventually realized that this might actually be an 
easier avenue to pursue than extending `annotate` to types. (As we discussed, 
there might be cases where the GNU spelling of the `annotate` attribute would 
associate with a declaration while the C++ spelling would associate with a 
type, and we hadn't reached a firm conclusion on how best to resolve this. An 
entirely new pluggable attribute wouldn't have this problem.)

From your feedback, it sounds as if I should return to my earlier idea of 
extending `annotate` to types. I wonder though: Wouldn't this suffer from the 
same problems that you raise above since, again, Clang would see 
`AttributedType`s in places where it might not expect them?

If the same concerns apply to both of these approaches, do you have any 
suggestions for alternative ways that I could add annotations to types? Or does 
this mean that I would have to do the work of making sure that Clang can handle 
`AttributedType`s in these new places after all?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114235

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


[PATCH] D117218: [clang][dataflow] Add transfer functions for constructors

2022-01-14 Thread Stanislav Gatev via Phabricator via cfe-commits
sgatev updated this revision to Diff 399968.
sgatev marked an inline comment as done.
sgatev added a comment.

Address reviewers' comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D117218

Files:
  clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
  clang/lib/Analysis/FlowSensitive/Transfer.cpp
  clang/unittests/Analysis/FlowSensitive/TransferTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
@@ -15,6 +15,7 @@
 #include "clang/Analysis/FlowSensitive/DataflowEnvironment.h"
 #include "clang/Analysis/FlowSensitive/StorageLocation.h"
 #include "clang/Analysis/FlowSensitive/Value.h"
+#include "clang/Basic/LangStandard.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Casting.h"
@@ -37,7 +38,8 @@
 class TransferTest : public ::testing::Test {
 protected:
   template 
-  void runDataflow(llvm::StringRef Code, Matcher Match) {
+  void runDataflow(llvm::StringRef Code, Matcher Match,
+   LangStandard::Kind Std = LangStandard::lang_cxx17) {
 test::checkDataflow(
 Code, "target",
 [](ASTContext &C, Environment &) { return NoopAnalysis(C); },
@@ -45,7 +47,9 @@
  std::pair>>
  Results,
  ASTContext &ASTCtx) { Match(Results, ASTCtx); },
-{"-fsyntax-only", "-std=c++17"});
+{"-fsyntax-only",
+ "-std=" +
+ std::string(LangStandard::getLangStandardForKind(Std).getName())});
   }
 };
 
@@ -1281,4 +1285,308 @@
   });
 }
 
+TEST_F(TransferTest, TemporaryObject) {
+  std::string Code = R"(
+struct A {
+  int Bar;
+};
+
+void target() {
+  A Foo = A();
+  // [[p]]
+}
+  )";
+  runDataflow(
+  Code, [](llvm::ArrayRef<
+   std::pair>>
+   Results,
+   ASTContext &ASTCtx) {
+ASSERT_THAT(Results, ElementsAre(Pair("p", _)));
+const Environment &Env = Results[0].second.Env;
+
+const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo");
+ASSERT_THAT(FooDecl, NotNull());
+
+const ValueDecl *BarDecl = findValueDecl(ASTCtx, "Bar");
+ASSERT_THAT(BarDecl, NotNull());
+
+const auto *FooLoc = cast(
+Env.getStorageLocation(*FooDecl, SkipPast::None));
+const auto *BarLoc =
+cast(&FooLoc->getChild(*BarDecl));
+
+const auto *FooVal = cast(Env.getValue(*FooLoc));
+const auto *BarVal = cast(&FooVal->getChild(*BarDecl));
+EXPECT_EQ(Env.getValue(*BarLoc), BarVal);
+  });
+}
+
+TEST_F(TransferTest, ElidableConstructor) {
+  // This test is effectively the same as TransferTest.TemporaryObject, but
+  // the code is compiled as C++ 14.
+  std::string Code = R"(
+struct A {
+  int Bar;
+};
+
+void target() {
+  A Foo = A();
+  // [[p]]
+}
+  )";
+  runDataflow(
+  Code,
+  [](llvm::ArrayRef<
+ std::pair>>
+ Results,
+ ASTContext &ASTCtx) {
+ASSERT_THAT(Results, ElementsAre(Pair("p", _)));
+const Environment &Env = Results[0].second.Env;
+
+const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo");
+ASSERT_THAT(FooDecl, NotNull());
+
+const ValueDecl *BarDecl = findValueDecl(ASTCtx, "Bar");
+ASSERT_THAT(BarDecl, NotNull());
+
+const auto *FooLoc = cast(
+Env.getStorageLocation(*FooDecl, SkipPast::None));
+const auto *BarLoc =
+cast(&FooLoc->getChild(*BarDecl));
+
+const auto *FooVal = cast(Env.getValue(*FooLoc));
+const auto *BarVal = cast(&FooVal->getChild(*BarDecl));
+EXPECT_EQ(Env.getValue(*BarLoc), BarVal);
+  },
+  LangStandard::lang_cxx14);
+}
+
+TEST_F(TransferTest, AssignmentOperator) {
+  std::string Code = R"(
+struct A {
+  int Baz;
+};
+
+void target() {
+  A Foo;
+  A Bar;
+  // [[p1]]
+  Foo = Bar;
+  // [[p2]]
+}
+  )";
+  runDataflow(
+  Code, [](llvm::ArrayRef<
+   std::pair>>
+   Results,
+   ASTContext &ASTCtx) {
+ASSERT_THAT(Results, ElementsAre(Pair("p1", _), Pair("p2", _)));
+const Environment &Env1 = Results[0].second.Env;
+const Environment &Env2 = Results[1].second.Env;
+
+const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo");
+ASSERT_THAT(FooDecl, NotNull());
+
+const ValueDecl *BarDecl = findValueDecl(ASTCtx, "Bar");
+ASSERT_THAT(BarDecl, NotNull());
+
+const ValueDecl *BazDecl = findValueDecl(ASTCtx, "Baz");
+ASSERT_THAT(BazDecl, NotNull());
+
+const auto *FooLoc1 = cast(
+Env1.getStorageLocation(*FooDecl, 

[PATCH] D117218: [clang][dataflow] Add transfer functions for constructors

2022-01-14 Thread Stanislav Gatev via Phabricator via cfe-commits
sgatev added inline comments.



Comment at: clang/lib/Analysis/FlowSensitive/Transfer.cpp:105
 
-  assert(SubExpr != nullptr);
+if (S->getCastKind() == CK_LValueToRValue) {
   auto *SubExprVal = Env.getValue(*SubExpr, SkipPast::Reference);

ymandel wrote:
> use a switch?
Refactored to use a `switch`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D117218

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


[PATCH] D117306: [clang-tidy] Add new check 'shared-ptr-array-mismatch'.

2022-01-14 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, mgorny.
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/D117306

Files:
  clang-tools-extra/clang-tidy/misc/CMakeLists.txt
  clang-tools-extra/clang-tidy/misc/MiscTidyModule.cpp
  clang-tools-extra/clang-tidy/misc/SharedPtrArrayMismatchCheck.cpp
  clang-tools-extra/clang-tidy/misc/SharedPtrArrayMismatchCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  clang-tools-extra/docs/clang-tidy/checks/misc-shared-ptr-array-mismatch.rst
  clang-tools-extra/test/clang-tidy/checkers/misc-shared-ptr-array-mismatch.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/misc-shared-ptr-array-mismatch.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/misc-shared-ptr-array-mismatch.cpp
@@ -0,0 +1,96 @@
+// RUN: %check_clang_tidy %s misc-shared-ptr-array-mismatch %t
+
+namespace std {
+
+template 
+struct default_delete {};
+
+template 
+struct shared_ptr {
+  template 
+  explicit shared_ptr(Y *) {}
+  template 
+  shared_ptr(Y *, Deleter) {}
+};
+
+} // namespace std
+
+struct A {};
+
+void f1() {
+  std::shared_ptr P1{new int};
+  std::shared_ptr P2{new int[10]};
+  // CHECK-MESSAGES: :[[@LINE-1]]:27: warning: shared pointer to non-array is initialized with array [misc-shared-ptr-array-mismatch]
+  // CHECK-FIXES: std::shared_ptr P2{new int[10]};
+  std::shared_ptr<  int  > P3{new int[10]};
+  // CHECK-MESSAGES: :[[@LINE-1]]:31: warning: shared pointer to non-array is initialized with array [misc-shared-ptr-array-mismatch]
+  // CHECK-FIXES: std::shared_ptr<  int[]  > P3{new int[10]};
+  std::shared_ptr P4(new int[10]);
+  // CHECK-MESSAGES: :[[@LINE-1]]:27: warning: shared pointer to non-array is initialized with array [misc-shared-ptr-array-mismatch]
+  // CHECK-FIXES: std::shared_ptr P4(new int[10]);
+  new std::shared_ptr(new int[10]);
+  // CHECK-MESSAGES: :[[@LINE-1]]:28: warning: shared pointer to non-array is initialized with array [misc-shared-ptr-array-mismatch]
+  std::shared_ptr P5(new int[10]);
+  std::shared_ptr P6(new int[10], [](const int *Ptr) {});
+}
+
+void f2() {
+  std::shared_ptr P1(new A);
+  std::shared_ptr P2(new A[10]);
+  // CHECK-MESSAGES: :[[@LINE-1]]:25: warning: shared pointer to non-array is initialized with array [misc-shared-ptr-array-mismatch]
+  // CHECK-FIXES: std::shared_ptr P2(new A[10]);
+  std::shared_ptr P3(new A[10]);
+}
+
+void f3() {
+  std::shared_ptr P1{new int}, P2{new int[10]}, P3{new int[10]};
+  // CHECK-MESSAGES: :[[@LINE-1]]:40: warning: shared pointer to non-array is initialized with array [misc-shared-ptr-array-mismatch]
+  // CHECK-MESSAGES: :[[@LINE-2]]:57: warning: shared pointer to non-array is initialized with array [misc-shared-ptr-array-mismatch]
+}
+
+struct S {
+  std::shared_ptr P1;
+  std::shared_ptr P2{new int[10]};
+  // CHECK-MESSAGES: :[[@LINE-1]]:27: warning: shared pointer to non-array is initialized with array [misc-shared-ptr-array-mismatch]
+  std::shared_ptr P3{new int}, P4{new int[10]};
+  // CHECK-MESSAGES: :[[@LINE-1]]:40: warning: shared pointer to non-array is initialized with array [misc-shared-ptr-array-mismatch]
+  S() : P1{new int[10]} {}
+  // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: shared pointer to non-array is initialized with array [misc-shared-ptr-array-mismatch]
+};
+
+void f_parm(std::shared_ptr);
+
+void f4() {
+  f_parm(std::shared_ptr{new int[10]});
+  // CHECK-MESSAGES: :[[@LINE-1]]:31: warning: shared pointer to non-array is initialized with array [misc-shared-ptr-array-mismatch]
+}
+
+std::shared_ptr f_ret() {
+  return std::shared_ptr(new int[10]);
+  // CHECK-MESSAGES: :[[@LINE-1]]:31: warning: shared pointer to non-array is initialized with array [misc-shared-ptr-array-mismatch]
+}
+
+template 
+void f_tmpl() {
+  std::shared_ptr P1{new T[10]};
+}
+
+void f5() {
+  f_tmpl();
+}
+
+#define CHAR_PTR_TYPE std::shared_ptr
+#define CHAR_PTR_VAR(X) \
+  X { new char[10] }
+#define CHAR_PTR_INIT(X, Y) \
+  std::shared_ptr X { Y }
+
+void f6() {
+  CHAR_PTR_TYPE P1{new char[10]};
+  // CHECK-MESSAGES: :[[@LINE-1]]:20: warning: shared pointer to non-array is initialized with array [misc-shared-ptr-array-mismatch]
+  std::shared_ptr CHAR_PTR_VAR(P2);
+  // CHECK-MESSAGES: :[[@LINE-1]]:25: warning: shared pointer to non-array is initialized with array [misc-shared-ptr-array-mismatch]
+  // CHECK-FIXES: std::shared_ptr CHAR_PTR_VAR(P2);
+  CHAR_PTR_INIT(P3, new char[10]);
+  // CHECK-MESSAGES: :[[@LINE-1]]:21: warning: shared pointer to non-array is initialized with array [misc-shared-ptr-array-mismatch]
+}
Index: clang-tools-extra/docs/clang-tidy/checks/misc-shared-ptr-array-mismatch.rst

[PATCH] D116439: [clang-tidy] Fix `readability-const-return-type` for pure virtual function.

2022-01-14 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: 
clang-tools-extra/clang-tidy/readability/ConstReturnTypeCheck.cpp:101
+  functionDecl(returns(isConstQualified()),
+   anyOf(isDefinition(), cxxMethodDecl(isPure(
+  .bind("func"),

MTC wrote:
> Like @flx comments in https://reviews.llvm.org/D116593, the better choice is 
> that we suppress the fix for the virtual method. What do you think @Sockke?
I agree that the fix needs to be suppressed here as well, for the same reasons 
as the quoted review. e.g., https://godbolt.org/z/Yvsb37Yzr


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116439

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


[PATCH] D117309: [clang] NFC: Remove unused `DirectoryLookup`

2022-01-14 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 created this revision.
jansvoboda11 added a reviewer: ahoppen.
jansvoboda11 requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This patch removes bitrotten/dead uses of `DirectoryLookup` in 
`InclusionRewriter.cpp`.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D117309

Files:
  clang/lib/Frontend/Rewrite/InclusionRewriter.cpp


Index: clang/lib/Frontend/Rewrite/InclusionRewriter.cpp
===
--- clang/lib/Frontend/Rewrite/InclusionRewriter.cpp
+++ clang/lib/Frontend/Rewrite/InclusionRewriter.cpp
@@ -14,7 +14,6 @@
 #include "clang/Rewrite/Frontend/Rewriters.h"
 #include "clang/Basic/SourceManager.h"
 #include "clang/Frontend/PreprocessorOutputOptions.h"
-#include "clang/Lex/HeaderSearch.h"
 #include "clang/Lex/Pragma.h"
 #include "clang/Lex/Preprocessor.h"
 #include "llvm/ADT/SmallString.h"
@@ -31,10 +30,8 @@
   struct IncludedFile {
 FileID Id;
 SrcMgr::CharacteristicKind FileType;
-const DirectoryLookup *DirLookup;
-IncludedFile(FileID Id, SrcMgr::CharacteristicKind FileType,
- const DirectoryLookup *DirLookup)
-: Id(Id), FileType(FileType), DirLookup(DirLookup) {}
+IncludedFile(FileID Id, SrcMgr::CharacteristicKind FileType)
+: Id(Id), FileType(FileType) {}
   };
   Preprocessor &PP; ///< Used to find inclusion directives.
   SourceManager &SM; ///< Used to read and manage source files.
@@ -57,8 +54,7 @@
 public:
   InclusionRewriter(Preprocessor &PP, raw_ostream &OS, bool ShowLineMarkers,
 bool UseLineDirectives);
-  void Process(FileID FileId, SrcMgr::CharacteristicKind FileType,
-   const DirectoryLookup *DirLookup);
+  void Process(FileID FileId, SrcMgr::CharacteristicKind FileType);
   void setPredefinesBuffer(const llvm::MemoryBufferRef &Buf) {
 PredefinesBuffer = Buf;
   }
@@ -162,8 +158,7 @@
 return;
   FileID Id = FullSourceLoc(Loc, SM).getFileID();
   auto P = FileIncludes.insert(
-  std::make_pair(LastInclusionLocation,
- IncludedFile(Id, NewFileType, PP.GetCurDirLookup(;
+  std::make_pair(LastInclusionLocation, IncludedFile(Id, NewFileType)));
   (void)P;
   assert(P.second && "Unexpected revisitation of the same include directive");
   LastInclusionLocation = SourceLocation();
@@ -371,8 +366,7 @@
 /// Use a raw lexer to analyze \p FileId, incrementally copying parts of it
 /// and including content of included files recursively.
 void InclusionRewriter::Process(FileID FileId,
-SrcMgr::CharacteristicKind FileType,
-const DirectoryLookup *DirLookup) {
+SrcMgr::CharacteristicKind FileType) {
   MemoryBufferRef FromFile;
   {
 auto B = SM.getBufferOrNone(FileId);
@@ -433,7 +427,7 @@
<< Mod->getFullModuleName(true) << "\n";
 
   // Include and recursively process the file.
-  Process(Inc->Id, Inc->FileType, Inc->DirLookup);
+  Process(Inc->Id, Inc->FileType);
 
   if (Mod)
 OS << "#pragma clang module end /*"
@@ -559,7 +553,7 @@
   Rewrite->handleModuleBegin(Tok);
   } while (Tok.isNot(tok::eof));
   Rewrite->setPredefinesBuffer(SM.getBufferOrFake(PP.getPredefinesFileID()));
-  Rewrite->Process(PP.getPredefinesFileID(), SrcMgr::C_User, nullptr);
-  Rewrite->Process(SM.getMainFileID(), SrcMgr::C_User, nullptr);
+  Rewrite->Process(PP.getPredefinesFileID(), SrcMgr::C_User);
+  Rewrite->Process(SM.getMainFileID(), SrcMgr::C_User);
   OS->flush();
 }


Index: clang/lib/Frontend/Rewrite/InclusionRewriter.cpp
===
--- clang/lib/Frontend/Rewrite/InclusionRewriter.cpp
+++ clang/lib/Frontend/Rewrite/InclusionRewriter.cpp
@@ -14,7 +14,6 @@
 #include "clang/Rewrite/Frontend/Rewriters.h"
 #include "clang/Basic/SourceManager.h"
 #include "clang/Frontend/PreprocessorOutputOptions.h"
-#include "clang/Lex/HeaderSearch.h"
 #include "clang/Lex/Pragma.h"
 #include "clang/Lex/Preprocessor.h"
 #include "llvm/ADT/SmallString.h"
@@ -31,10 +30,8 @@
   struct IncludedFile {
 FileID Id;
 SrcMgr::CharacteristicKind FileType;
-const DirectoryLookup *DirLookup;
-IncludedFile(FileID Id, SrcMgr::CharacteristicKind FileType,
- const DirectoryLookup *DirLookup)
-: Id(Id), FileType(FileType), DirLookup(DirLookup) {}
+IncludedFile(FileID Id, SrcMgr::CharacteristicKind FileType)
+: Id(Id), FileType(FileType) {}
   };
   Preprocessor &PP; ///< Used to find inclusion directives.
   SourceManager &SM; ///< Used to read and manage source files.
@@ -57,8 +54,7 @@
 public:
   InclusionRewriter(Preprocessor &PP, raw_ostream &OS, bool ShowLineMarkers,
 bool UseLineDirectives);
-  void Process(FileID FileId, SrcMgr::CharacteristicKind FileType,
-  

[PATCH] D117312: [clang][lex] NFC: Simplify calls to `LookupFile`

2022-01-14 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 created this revision.
jansvoboda11 added a reviewer: ahoppen.
Herald added a subscriber: carlosgalvezp.
jansvoboda11 requested review of this revision.
Herald added projects: clang, clang-tools-extra.
Herald added a subscriber: cfe-commits.

The `{HeaderSearch,Preprocessor}::LookupFile()` functions take an out-parameter 
`const DirectoryLookup *&`. Most callers end up creating a `const 
DirectoryLookup *` variable that's otherwise unused.

This patch changes the out-parameter from reference to a pointer, making it 
possible to simply pass `nullptr` to the function without the ceremony.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D117312

Files:
  clang-tools-extra/clang-tidy/bugprone/SuspiciousIncludeCheck.cpp
  clang/include/clang/Lex/HeaderSearch.h
  clang/include/clang/Lex/Preprocessor.h
  clang/lib/Frontend/FrontendActions.cpp
  clang/lib/Frontend/VerifyDiagnosticConsumer.cpp
  clang/lib/Lex/HeaderSearch.cpp
  clang/lib/Lex/PPDirectives.cpp
  clang/lib/Lex/PPMacroExpansion.cpp
  clang/lib/Lex/Pragma.cpp
  clang/lib/Lex/Preprocessor.cpp
  clang/unittests/Lex/HeaderSearchTest.cpp

Index: clang/unittests/Lex/HeaderSearchTest.cpp
===
--- clang/unittests/Lex/HeaderSearchTest.cpp
+++ clang/unittests/Lex/HeaderSearchTest.cpp
@@ -238,10 +238,9 @@
   /*User=*/None, /*Group=*/None, llvm::sys::fs::file_type::regular_file);
 
   bool IsMapped = false;
-  const DirectoryLookup *CurDir = nullptr;
   auto FoundFile = Search.LookupFile(
   "Foo/Foo.h", SourceLocation(), /*isAngled=*/true, /*FromDir=*/nullptr,
-  CurDir, /*Includers=*/{}, /*SearchPath=*/nullptr,
+  /*CurDir=*/nullptr, /*Includers=*/{}, /*SearchPath=*/nullptr,
   /*RelativePath=*/nullptr, /*RequestingModule=*/nullptr,
   /*SuggestedModule=*/nullptr, &IsMapped,
   /*IsFrameworkFound=*/nullptr);
Index: clang/lib/Lex/Preprocessor.cpp
===
--- clang/lib/Lex/Preprocessor.cpp
+++ clang/lib/Lex/Preprocessor.cpp
@@ -566,11 +566,10 @@
   if (!PPOpts->PCHThroughHeader.empty()) {
 // Lookup and save the FileID for the through header. If it isn't found
 // in the search path, it's a fatal error.
-const DirectoryLookup *CurDir;
 Optional File = LookupFile(
 SourceLocation(), PPOpts->PCHThroughHeader,
-/*isAngled=*/false, /*FromDir=*/nullptr, /*FromFile=*/nullptr, CurDir,
-/*SearchPath=*/nullptr, /*RelativePath=*/nullptr,
+/*isAngled=*/false, /*FromDir=*/nullptr, /*FromFile=*/nullptr,
+/*CurDir=*/nullptr, /*SearchPath=*/nullptr, /*RelativePath=*/nullptr,
 /*SuggestedModule=*/nullptr, /*IsMapped=*/nullptr,
 /*IsFrameworkFound=*/nullptr);
 if (!File) {
Index: clang/lib/Lex/Pragma.cpp
===
--- clang/lib/Lex/Pragma.cpp
+++ clang/lib/Lex/Pragma.cpp
@@ -526,9 +526,8 @@
 return llvm::None;
 
   // Search include directories for this file.
-  const DirectoryLookup *CurDir;
   File = PP.LookupFile(FilenameTok.getLocation(), Filename, isAngled, nullptr,
-   nullptr, CurDir, nullptr, nullptr, nullptr, nullptr,
+   nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
nullptr);
   if (!File) {
 if (!SuppressIncludeNotFoundError)
Index: clang/lib/Lex/PPMacroExpansion.cpp
===
--- clang/lib/Lex/PPMacroExpansion.cpp
+++ clang/lib/Lex/PPMacroExpansion.cpp
@@ -1228,10 +1228,9 @@
 return false;
 
   // Search include directories.
-  const DirectoryLookup *CurDir;
   Optional File =
   PP.LookupFile(FilenameLoc, Filename, isAngled, LookupFrom, LookupFromFile,
-CurDir, nullptr, nullptr, nullptr, nullptr, nullptr);
+nullptr, nullptr, nullptr, nullptr, nullptr, nullptr);
 
   if (PPCallbacks *Callbacks = PP.getPPCallbacks()) {
 SrcMgr::CharacteristicKind FileType = SrcMgr::C_User;
Index: clang/lib/Lex/PPDirectives.cpp
===
--- clang/lib/Lex/PPDirectives.cpp
+++ clang/lib/Lex/PPDirectives.cpp
@@ -818,10 +818,13 @@
 Optional Preprocessor::LookupFile(
 SourceLocation FilenameLoc, StringRef Filename, bool isAngled,
 const DirectoryLookup *FromDir, const FileEntry *FromFile,
-const DirectoryLookup *&CurDir, SmallVectorImpl *SearchPath,
+const DirectoryLookup **CurDirArg, SmallVectorImpl *SearchPath,
 SmallVectorImpl *RelativePath,
 ModuleMap::KnownHeader *SuggestedModule, bool *IsMapped,
 bool *IsFrameworkFound, bool SkipCache) {
+  const DirectoryLookup *CurDirLocal = nullptr;
+  const DirectoryLookup *&CurDir = CurDirArg ? *CurDirArg : CurDirLocal;
+
   Module *RequestingModule = getModuleForLocation(FilenameLoc);
   bool RequestingModuleIsModuleInterface = !SourceMgr.isInMainFile(FilenameLoc);

[PATCH] D94955: [clang-format] Treat ForEachMacros as loops

2022-01-14 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius commandeered this revision.
curdeius edited reviewers, added: GoBigorGoHome; removed: curdeius.
curdeius added a comment.

Commandeering as it's stale..


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94955

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


[PATCH] D116750: [clang][lex] Keep references to `DirectoryLookup` objects up-to-date

2022-01-14 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 updated this revision to Diff 399981.
jansvoboda11 added a comment.
This revision is now accepted and ready to land.

Replace external uses of `const DirectoryLookup *` by an optional iterator. 
That's how they get treated by callers.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116750

Files:
  clang/include/clang/Lex/HeaderSearch.h
  clang/include/clang/Lex/Preprocessor.h
  clang/lib/Frontend/FrontendActions.cpp
  clang/lib/Frontend/VerifyDiagnosticConsumer.cpp
  clang/lib/Interpreter/IncrementalParser.cpp
  clang/lib/Lex/HeaderSearch.cpp
  clang/lib/Lex/PPDirectives.cpp
  clang/lib/Lex/PPLexerChange.cpp
  clang/lib/Lex/PPMacroExpansion.cpp
  clang/lib/Lex/Pragma.cpp
  clang/lib/Lex/Preprocessor.cpp
  clang/unittests/Lex/HeaderSearchTest.cpp

Index: clang/unittests/Lex/HeaderSearchTest.cpp
===
--- clang/unittests/Lex/HeaderSearchTest.cpp
+++ clang/unittests/Lex/HeaderSearchTest.cpp
@@ -23,6 +23,12 @@
 namespace clang {
 namespace {
 
+static std::shared_ptr createTargetOptions() {
+  auto TargetOpts = std::make_shared();
+  TargetOpts->Triple = "x86_64-apple-darwin11.1.0";
+  return TargetOpts;
+}
+
 // The test fixture.
 class HeaderSearchTest : public ::testing::Test {
 protected:
@@ -30,12 +36,10 @@
   : VFS(new llvm::vfs::InMemoryFileSystem), FileMgr(FileMgrOpts, VFS),
 DiagID(new DiagnosticIDs()),
 Diags(DiagID, new DiagnosticOptions, new IgnoringDiagConsumer()),
-SourceMgr(Diags, FileMgr), TargetOpts(new TargetOptions),
+SourceMgr(Diags, FileMgr), TargetOpts(createTargetOptions()),
+Target(TargetInfo::CreateTargetInfo(Diags, TargetOpts)),
 Search(std::make_shared(), SourceMgr, Diags,
-   LangOpts, Target.get()) {
-TargetOpts->Triple = "x86_64-apple-darwin11.1.0";
-Target = TargetInfo::CreateTargetInfo(Diags, TargetOpts);
-  }
+   LangOpts, Target.get()) {}
 
   void addSearchDir(llvm::StringRef Dir) {
 VFS->addFile(Dir, 0, llvm::MemoryBuffer::getMemBuffer(""), /*User=*/None,
@@ -55,6 +59,27 @@
 Search.AddSystemSearchPath(DL);
   }
 
+  void setSearchDirs(llvm::ArrayRef QuotedDirs,
+ llvm::ArrayRef AngledDirs) {
+auto AddPath = [&](StringRef Dir, bool IsAngled) {
+  VFS->addFile(Dir, 0, llvm::MemoryBuffer::getMemBuffer(""), /*User=*/None,
+   /*Group=*/None, llvm::sys::fs::file_type::directory_file);
+  auto Group = IsAngled ? frontend::IncludeDirGroup::Angled
+: frontend::IncludeDirGroup::Quoted;
+  Search.getHeaderSearchOpts().AddPath(Dir, Group,
+   /*IsFramework=*/false,
+   /*IgnoreSysRoot=*/true);
+};
+
+for (llvm::StringRef Dir : QuotedDirs)
+  AddPath(Dir, /*IsAngled=*/false);
+for (llvm::StringRef Dir : AngledDirs)
+  AddPath(Dir, /*IsAngled=*/true);
+
+clang::ApplyHeaderSearchOptions(Search, Search.getHeaderSearchOpts(),
+LangOpts, Target->getTriple());
+  }
+
   void addHeaderMap(llvm::StringRef Filename,
 std::unique_ptr Buf,
 bool isAngled = false) {
@@ -71,6 +96,17 @@
 Search.AddSearchPath(DL, isAngled);
   }
 
+  void createModule(StringRef Mod) {
+std::string ModDir = ("/" + Mod).str();
+std::string ModHeader = (Mod + ".h").str();
+VFS->addFile(
+ModDir + "/module.modulemap", 0,
+llvm::MemoryBuffer::getMemBufferCopy(
+("module " + Mod + " { header \"" + ModHeader + "\" }").str()));
+VFS->addFile(ModDir + "/" + ModHeader, 0,
+ llvm::MemoryBuffer::getMemBuffer(""));
+  }
+
   IntrusiveRefCntPtr VFS;
   FileSystemOptions FileMgrOpts;
   FileManager FileMgr;
@@ -239,7 +275,7 @@
 
   bool IsMapped = false;
   auto FoundFile = Search.LookupFile(
-  "Foo/Foo.h", SourceLocation(), /*isAngled=*/true, /*FromDir=*/nullptr,
+  "Foo/Foo.h", SourceLocation(), /*isAngled=*/true, /*FromDir=*/None,
   /*CurDir=*/nullptr, /*Includers=*/{}, /*SearchPath=*/nullptr,
   /*RelativePath=*/nullptr, /*RequestingModule=*/nullptr,
   /*SuggestedModule=*/nullptr, &IsMapped,
@@ -254,5 +290,31 @@
   EXPECT_EQ(FI->Framework.str(), "Foo");
 }
 
+TEST_F(HeaderSearchTest, SearchPathUsage) {
+  Search.getHeaderSearchOpts().ImplicitModuleMaps = true;
+
+  setSearchDirs(/*QuotedDirs=*/{"/M0"}, /*AngledDirs=*/{"/M2", "/M3"});
+  createModule("M0");
+  createModule("M2");
+  createModule("M3");
+
+  {
+Module *M2 = Search.lookupModule("M2");
+EXPECT_NE(M2, nullptr);
+EXPECT_EQ(Search.getSearchDirUsage(), (std::vector{0, 1, 0}));
+EXPECT_EQ(Search.computeUserEntryUsage(), (std::vector{0, 1, 0}));
+  }
+
+  addSearchDir("/M1");
+  createModule("M1");
+
+  {
+Module *M1 = Search.lookupModule("M1");
+EXPECT_NE(M1

[PATCH] D94955: [clang-format] Treat ForEachMacros as loops

2022-01-14 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius updated this revision to Diff 399982.
curdeius added a comment.

Add more tests. Fix missed cases.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94955

Files:
  clang/lib/Format/UnwrappedLineFormatter.cpp
  clang/unittests/Format/FormatTest.cpp

Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -1464,6 +1464,7 @@
   verifyFormat("while (true) continue;", AllowsMergedLoops);
   verifyFormat("for (;;) continue;", AllowsMergedLoops);
   verifyFormat("for (int &v : vec) v *= 2;", AllowsMergedLoops);
+  verifyFormat("BOOST_FOREACH (int &v, vec) v *= 2;", AllowsMergedLoops);
   verifyFormat("while (true)\n"
"  ;",
AllowsMergedLoops);
@@ -1476,9 +1477,15 @@
   verifyFormat("for (;;)\n"
"  while (true) continue;",
AllowsMergedLoops);
-  verifyFormat("BOOST_FOREACH (int v, vec)\n"
+  verifyFormat("while (true)\n"
+   "  for (;;) continue;",
+   AllowsMergedLoops);
+  verifyFormat("BOOST_FOREACH (int &v, vec)\n"
"  for (;;) continue;",
AllowsMergedLoops);
+  verifyFormat("for (;;)\n"
+   "  BOOST_FOREACH (int &v, vec) continue;",
+   AllowsMergedLoops);
   verifyFormat("for (;;) // Can't merge this\n"
"  continue;",
AllowsMergedLoops);
@@ -1645,6 +1652,11 @@
"  f();\n"
"}",
AllowSimpleBracedStatements);
+  verifyFormat("BOOST_FOREACH (int v, vec) {}", AllowSimpleBracedStatements);
+  verifyFormat("BOOST_FOREACH (int v, vec) {\n"
+   "  f();\n"
+   "}",
+   AllowSimpleBracedStatements);
 
   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
   FormatStyle::SIS_WithoutElse;
@@ -1775,6 +1787,12 @@
"  f();\n"
"}",
AllowSimpleBracedStatements);
+  verifyFormat("BOOST_FOREACH (int v, vec) {}", AllowSimpleBracedStatements);
+  verifyFormat("BOOST_FOREACH (int v, vec)\n"
+   "{\n"
+   "  f();\n"
+   "}",
+   AllowSimpleBracedStatements);
 }
 
 TEST_F(FormatTest, ShortBlocksInMacrosDontMergeWithCodeAfterMacro) {
@@ -2159,20 +2177,33 @@
 }
 
 TEST_F(FormatTest, ForEachLoops) {
+  FormatStyle Style = getLLVMStyle();
+  EXPECT_EQ(Style.AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
+  EXPECT_EQ(Style.AllowShortLoopsOnASingleLine, false);
   verifyFormat("void f() {\n"
-   "  foreach (Item *item, itemlist) {}\n"
-   "  Q_FOREACH (Item *item, itemlist) {}\n"
-   "  BOOST_FOREACH (Item *item, itemlist) {}\n"
+   "  for (;;) {\n"
+   "  }\n"
+   "  foreach (Item *item, itemlist) {\n"
+   "  }\n"
+   "  Q_FOREACH (Item *item, itemlist) {\n"
+   "  }\n"
+   "  BOOST_FOREACH (Item *item, itemlist) {\n"
+   "  }\n"
"  UNKNOWN_FOREACH(Item * item, itemlist) {}\n"
-   "}");
+   "}",
+   Style);
 
-  FormatStyle Style = getLLVMStyle();
   Style.SpaceBeforeParens =
   FormatStyle::SBPO_ControlStatementsExceptControlMacros;
   verifyFormat("void f() {\n"
-   "  foreach(Item *item, itemlist) {}\n"
-   "  Q_FOREACH(Item *item, itemlist) {}\n"
-   "  BOOST_FOREACH(Item *item, itemlist) {}\n"
+   "  for (;;) {\n"
+   "  }\n"
+   "  foreach(Item *item, itemlist) {\n"
+   "  }\n"
+   "  Q_FOREACH(Item *item, itemlist) {\n"
+   "  }\n"
+   "  BOOST_FOREACH(Item *item, itemlist) {\n"
+   "  }\n"
"  UNKNOWN_FOREACH(Item * item, itemlist) {}\n"
"}",
Style);
@@ -2191,6 +,47 @@
 
   // handle microsoft non standard extension
   verifyFormat("for each (char c in x->MyStringProperty)");
+
+  FormatStyle ShortBlocks = getLLVMStyle();
+  ShortBlocks.ForEachMacros.push_back("rng");
+  EXPECT_EQ(ShortBlocks.AllowShortLoopsOnASingleLine, false);
+  ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
+  verifyFormat("for (;;) {\n"
+   "  int j = 1;\n"
+   "}",
+   ShortBlocks);
+  verifyFormat("rng (i, 0, 10) {\n"
+   "  int j = 1;\n"
+   "}",
+   ShortBlocks);
+  ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
+  verifyFormat("for (;;)\n"
+   "  int j = 1;",
+   ShortBlocks);
+  verifyFormat("rng (i, 0, 10)\n"
+   "  int j = 1;",
+   ShortBlocks);
+  verifyFormat("for (;;) {\n"
+   "  int j = 1;\n"
+  

[clang] 7d941d6 - [clang][dataflow] Add transfer functions for constructors

2022-01-14 Thread Stanislav Gatev via cfe-commits

Author: Stanislav Gatev
Date: 2022-01-14T14:58:01Z
New Revision: 7d941d6d21e91e8466bf200da094d027338b92fa

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

LOG: [clang][dataflow] Add transfer functions for constructors

This is part of the implementation of the dataflow analysis framework.
See "[RFC] A dataflow analysis framework for Clang AST" on cfe-dev.

Reviewed-by: ymandel, xazax.hun

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

Added: 


Modified: 
clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
clang/lib/Analysis/FlowSensitive/Transfer.cpp
clang/unittests/Analysis/FlowSensitive/TransferTest.cpp

Removed: 




diff  --git a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp 
b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
index 5824bc13ce7b6..7d0cbf3f656bd 100644
--- a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
+++ b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
@@ -154,8 +154,20 @@ StorageLocation 
*Environment::getThisPointeeStorageLocation() const {
   return DACtx->getThisPointeeStorageLocation();
 }
 
-void Environment::setValue(const StorageLocation &Loc, Value &Value) {
-  LocToVal[&Loc] = &Value;
+void Environment::setValue(const StorageLocation &Loc, Value &Val) {
+  LocToVal[&Loc] = &Val;
+
+  if (auto *StructVal = dyn_cast(&Val)) {
+auto &AggregateLoc = *cast(&Loc);
+
+const QualType Type = AggregateLoc.getType();
+assert(Type->isStructureOrClassType());
+
+for (const FieldDecl *Field : Type->getAsRecordDecl()->fields()) {
+  assert(Field != nullptr);
+  setValue(AggregateLoc.getChild(*Field), StructVal->getChild(*Field));
+}
+  }
 }
 
 Value *Environment::getValue(const StorageLocation &Loc) const {

diff  --git a/clang/lib/Analysis/FlowSensitive/Transfer.cpp 
b/clang/lib/Analysis/FlowSensitive/Transfer.cpp
index 7681b729d2b8e..8b35ec023ecc1 100644
--- a/clang/lib/Analysis/FlowSensitive/Transfer.cpp
+++ b/clang/lib/Analysis/FlowSensitive/Transfer.cpp
@@ -14,6 +14,7 @@
 #include "clang/Analysis/FlowSensitive/Transfer.h"
 #include "clang/AST/Decl.h"
 #include "clang/AST/DeclBase.h"
+#include "clang/AST/DeclCXX.h"
 #include "clang/AST/Expr.h"
 #include "clang/AST/ExprCXX.h"
 #include "clang/AST/OperationKinds.h"
@@ -28,6 +29,12 @@
 namespace clang {
 namespace dataflow {
 
+static const Expr *skipExprWithCleanups(const Expr *E) {
+  if (auto *C = dyn_cast_or_null(E))
+return C->getSubExpr();
+  return E;
+}
+
 class TransferVisitor : public ConstStmtVisitor {
 public:
   TransferVisitor(Environment &Env) : Env(Env) {}
@@ -89,23 +96,39 @@ class TransferVisitor : public 
ConstStmtVisitor {
   }
 
   void VisitImplicitCastExpr(const ImplicitCastExpr *S) {
-if (S->getCastKind() == CK_LValueToRValue) {
-  // The CFG does not contain `ParenExpr` as top-level statements in basic
-  // blocks, however sub-expressions can still be of that type.
-  assert(S->getSubExpr() != nullptr);
-  const Expr *SubExpr = S->getSubExpr()->IgnoreParens();
-
-  assert(SubExpr != nullptr);
+// The CFG does not contain `ParenExpr` as top-level statements in basic
+// blocks, however sub-expressions can still be of that type.
+assert(S->getSubExpr() != nullptr);
+const Expr *SubExpr = S->getSubExpr()->IgnoreParens();
+assert(SubExpr != nullptr);
+
+switch (S->getCastKind()) {
+case CK_LValueToRValue: {
   auto *SubExprVal = Env.getValue(*SubExpr, SkipPast::Reference);
   if (SubExprVal == nullptr)
-return;
+break;
 
   auto &ExprLoc = Env.createStorageLocation(*S);
   Env.setStorageLocation(*S, ExprLoc);
   Env.setValue(ExprLoc, *SubExprVal);
+  break;
+}
+case CK_NoOp: {
+  // FIXME: Consider making `Environment::getStorageLocation` skip noop
+  // expressions (this and other similar expressions in the file) instead 
of
+  // assigning them storage locations.
+  auto *SubExprLoc = Env.getStorageLocation(*SubExpr, SkipPast::None);
+  if (SubExprLoc == nullptr)
+break;
+
+  Env.setStorageLocation(*S, *SubExprLoc);
+  break;
+}
+default:
+  // FIXME: Add support for CK_UserDefinedConversion,
+  // CK_ConstructorConversion, CK_UncheckedDerivedToBase.
+  break;
 }
-// FIXME: Add support for CK_NoOp, CK_UserDefinedConversion,
-// CK_ConstructorConversion, CK_UncheckedDerivedToBase.
   }
 
   void VisitUnaryOperator(const UnaryOperator *S) {
@@ -181,15 +204,115 @@ class TransferVisitor : public 
ConstStmtVisitor {
 Env.setValue(FieldLoc, *InitExprVal);
   }
 
+  void VisitCXXConstructExpr(const CXXConstructExpr *S) {
+const CXXConstructorDecl *ConstructorDecl = S->getConstructor();
+assert(ConstructorDecl != nullptr);
+

[PATCH] D117218: [clang][dataflow] Add transfer functions for constructors

2022-01-14 Thread Stanislav Gatev via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG7d941d6d21e9: [clang][dataflow] Add transfer functions for 
constructors (authored by sgatev).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D117218

Files:
  clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
  clang/lib/Analysis/FlowSensitive/Transfer.cpp
  clang/unittests/Analysis/FlowSensitive/TransferTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
@@ -15,6 +15,7 @@
 #include "clang/Analysis/FlowSensitive/DataflowEnvironment.h"
 #include "clang/Analysis/FlowSensitive/StorageLocation.h"
 #include "clang/Analysis/FlowSensitive/Value.h"
+#include "clang/Basic/LangStandard.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Casting.h"
@@ -37,7 +38,8 @@
 class TransferTest : public ::testing::Test {
 protected:
   template 
-  void runDataflow(llvm::StringRef Code, Matcher Match) {
+  void runDataflow(llvm::StringRef Code, Matcher Match,
+   LangStandard::Kind Std = LangStandard::lang_cxx17) {
 test::checkDataflow(
 Code, "target",
 [](ASTContext &C, Environment &) { return NoopAnalysis(C); },
@@ -45,7 +47,9 @@
  std::pair>>
  Results,
  ASTContext &ASTCtx) { Match(Results, ASTCtx); },
-{"-fsyntax-only", "-std=c++17"});
+{"-fsyntax-only",
+ "-std=" +
+ std::string(LangStandard::getLangStandardForKind(Std).getName())});
   }
 };
 
@@ -1281,4 +1285,308 @@
   });
 }
 
+TEST_F(TransferTest, TemporaryObject) {
+  std::string Code = R"(
+struct A {
+  int Bar;
+};
+
+void target() {
+  A Foo = A();
+  // [[p]]
+}
+  )";
+  runDataflow(
+  Code, [](llvm::ArrayRef<
+   std::pair>>
+   Results,
+   ASTContext &ASTCtx) {
+ASSERT_THAT(Results, ElementsAre(Pair("p", _)));
+const Environment &Env = Results[0].second.Env;
+
+const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo");
+ASSERT_THAT(FooDecl, NotNull());
+
+const ValueDecl *BarDecl = findValueDecl(ASTCtx, "Bar");
+ASSERT_THAT(BarDecl, NotNull());
+
+const auto *FooLoc = cast(
+Env.getStorageLocation(*FooDecl, SkipPast::None));
+const auto *BarLoc =
+cast(&FooLoc->getChild(*BarDecl));
+
+const auto *FooVal = cast(Env.getValue(*FooLoc));
+const auto *BarVal = cast(&FooVal->getChild(*BarDecl));
+EXPECT_EQ(Env.getValue(*BarLoc), BarVal);
+  });
+}
+
+TEST_F(TransferTest, ElidableConstructor) {
+  // This test is effectively the same as TransferTest.TemporaryObject, but
+  // the code is compiled as C++ 14.
+  std::string Code = R"(
+struct A {
+  int Bar;
+};
+
+void target() {
+  A Foo = A();
+  // [[p]]
+}
+  )";
+  runDataflow(
+  Code,
+  [](llvm::ArrayRef<
+ std::pair>>
+ Results,
+ ASTContext &ASTCtx) {
+ASSERT_THAT(Results, ElementsAre(Pair("p", _)));
+const Environment &Env = Results[0].second.Env;
+
+const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo");
+ASSERT_THAT(FooDecl, NotNull());
+
+const ValueDecl *BarDecl = findValueDecl(ASTCtx, "Bar");
+ASSERT_THAT(BarDecl, NotNull());
+
+const auto *FooLoc = cast(
+Env.getStorageLocation(*FooDecl, SkipPast::None));
+const auto *BarLoc =
+cast(&FooLoc->getChild(*BarDecl));
+
+const auto *FooVal = cast(Env.getValue(*FooLoc));
+const auto *BarVal = cast(&FooVal->getChild(*BarDecl));
+EXPECT_EQ(Env.getValue(*BarLoc), BarVal);
+  },
+  LangStandard::lang_cxx14);
+}
+
+TEST_F(TransferTest, AssignmentOperator) {
+  std::string Code = R"(
+struct A {
+  int Baz;
+};
+
+void target() {
+  A Foo;
+  A Bar;
+  // [[p1]]
+  Foo = Bar;
+  // [[p2]]
+}
+  )";
+  runDataflow(
+  Code, [](llvm::ArrayRef<
+   std::pair>>
+   Results,
+   ASTContext &ASTCtx) {
+ASSERT_THAT(Results, ElementsAre(Pair("p1", _), Pair("p2", _)));
+const Environment &Env1 = Results[0].second.Env;
+const Environment &Env2 = Results[1].second.Env;
+
+const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo");
+ASSERT_THAT(FooDecl, NotNull());
+
+const ValueDecl *BarDecl = findValueDecl(ASTCtx, "Bar");
+ASSERT_THAT(BarDecl, NotNull());
+
+const ValueDecl *BazDecl = findValueDecl(ASTCtx, "Baz");
+ASSERT_THAT(BazDecl, NotNull());
+
+const auto *FooLoc1 = cast(

[clang] 765dd8b - [CGBuiltin] Simplify code. NFCI.

2022-01-14 Thread Benjamin Kramer via cfe-commits

Author: Benjamin Kramer
Date: 2022-01-14T16:02:02+01:00
New Revision: 765dd8b8a44cd9689c87c0433739f421b9871061

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

LOG: [CGBuiltin] Simplify code. NFCI.

Added: 


Modified: 
clang/lib/CodeGen/CGBuiltin.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index f68b7d3260e1..f9633f875b61 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -18462,15 +18462,11 @@ Value 
*CodeGenFunction::EmitWebAssemblyBuiltinExpr(unsigned BuiltinID,
   llvm_unreachable("unexpected builtin ID");
 }
 llvm::Type *SrcT = Vec->getType();
-llvm::Type *TruncT =
-SrcT->getWithNewType(llvm::IntegerType::get(getLLVMContext(), 32));
+llvm::Type *TruncT = SrcT->getWithNewType(Builder.getInt32Ty());
 Function *Callee = CGM.getIntrinsic(IntNo, {TruncT, SrcT});
 Value *Trunc = Builder.CreateCall(Callee, Vec);
-Value *Splat = Builder.CreateVectorSplat(2, Builder.getInt32(0));
-Value *ConcatMask =
-llvm::ConstantVector::get({Builder.getInt32(0), Builder.getInt32(1),
-   Builder.getInt32(2), Builder.getInt32(3)});
-return Builder.CreateShuffleVector(Trunc, Splat, ConcatMask);
+Value *Splat = Constant::getNullValue(TruncT);
+return Builder.CreateShuffleVector(Trunc, Splat, ArrayRef{0, 1, 2, 
3});
   }
   case WebAssembly::BI__builtin_wasm_shuffle_i8x16: {
 Value *Ops[18];



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


[PATCH] D94955: [clang-format] Treat ForEachMacros as loops

2022-01-14 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius updated this revision to Diff 399987.
curdeius added a comment.

Assert + test for loop.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94955

Files:
  clang/lib/Format/UnwrappedLineFormatter.cpp
  clang/unittests/Format/FormatTest.cpp

Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -1464,6 +1464,7 @@
   verifyFormat("while (true) continue;", AllowsMergedLoops);
   verifyFormat("for (;;) continue;", AllowsMergedLoops);
   verifyFormat("for (int &v : vec) v *= 2;", AllowsMergedLoops);
+  verifyFormat("BOOST_FOREACH (int &v, vec) v *= 2;", AllowsMergedLoops);
   verifyFormat("while (true)\n"
"  ;",
AllowsMergedLoops);
@@ -1476,9 +1477,15 @@
   verifyFormat("for (;;)\n"
"  while (true) continue;",
AllowsMergedLoops);
-  verifyFormat("BOOST_FOREACH (int v, vec)\n"
+  verifyFormat("while (true)\n"
+   "  for (;;) continue;",
+   AllowsMergedLoops);
+  verifyFormat("BOOST_FOREACH (int &v, vec)\n"
"  for (;;) continue;",
AllowsMergedLoops);
+  verifyFormat("for (;;)\n"
+   "  BOOST_FOREACH (int &v, vec) continue;",
+   AllowsMergedLoops);
   verifyFormat("for (;;) // Can't merge this\n"
"  continue;",
AllowsMergedLoops);
@@ -1645,6 +1652,11 @@
"  f();\n"
"}",
AllowSimpleBracedStatements);
+  verifyFormat("BOOST_FOREACH (int v, vec) {}", AllowSimpleBracedStatements);
+  verifyFormat("BOOST_FOREACH (int v, vec) {\n"
+   "  f();\n"
+   "}",
+   AllowSimpleBracedStatements);
 
   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
   FormatStyle::SIS_WithoutElse;
@@ -1775,6 +1787,12 @@
"  f();\n"
"}",
AllowSimpleBracedStatements);
+  verifyFormat("BOOST_FOREACH (int v, vec) {}", AllowSimpleBracedStatements);
+  verifyFormat("BOOST_FOREACH (int v, vec)\n"
+   "{\n"
+   "  f();\n"
+   "}",
+   AllowSimpleBracedStatements);
 }
 
 TEST_F(FormatTest, ShortBlocksInMacrosDontMergeWithCodeAfterMacro) {
@@ -2159,20 +2177,33 @@
 }
 
 TEST_F(FormatTest, ForEachLoops) {
+  FormatStyle Style = getLLVMStyle();
+  EXPECT_EQ(Style.AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
+  EXPECT_EQ(Style.AllowShortLoopsOnASingleLine, false);
   verifyFormat("void f() {\n"
-   "  foreach (Item *item, itemlist) {}\n"
-   "  Q_FOREACH (Item *item, itemlist) {}\n"
-   "  BOOST_FOREACH (Item *item, itemlist) {}\n"
+   "  for (;;) {\n"
+   "  }\n"
+   "  foreach (Item *item, itemlist) {\n"
+   "  }\n"
+   "  Q_FOREACH (Item *item, itemlist) {\n"
+   "  }\n"
+   "  BOOST_FOREACH (Item *item, itemlist) {\n"
+   "  }\n"
"  UNKNOWN_FOREACH(Item * item, itemlist) {}\n"
-   "}");
+   "}",
+   Style);
 
-  FormatStyle Style = getLLVMStyle();
   Style.SpaceBeforeParens =
   FormatStyle::SBPO_ControlStatementsExceptControlMacros;
   verifyFormat("void f() {\n"
-   "  foreach(Item *item, itemlist) {}\n"
-   "  Q_FOREACH(Item *item, itemlist) {}\n"
-   "  BOOST_FOREACH(Item *item, itemlist) {}\n"
+   "  for (;;) {\n"
+   "  }\n"
+   "  foreach(Item *item, itemlist) {\n"
+   "  }\n"
+   "  Q_FOREACH(Item *item, itemlist) {\n"
+   "  }\n"
+   "  BOOST_FOREACH(Item *item, itemlist) {\n"
+   "  }\n"
"  UNKNOWN_FOREACH(Item * item, itemlist) {}\n"
"}",
Style);
@@ -2191,6 +,47 @@
 
   // handle microsoft non standard extension
   verifyFormat("for each (char c in x->MyStringProperty)");
+
+  FormatStyle ShortBlocks = getLLVMStyle();
+  ShortBlocks.ForEachMacros.push_back("rng");
+  EXPECT_EQ(ShortBlocks.AllowShortLoopsOnASingleLine, false);
+  ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
+  verifyFormat("for (;;) {\n"
+   "  int j = 1;\n"
+   "}",
+   ShortBlocks);
+  verifyFormat("rng (i, 0, 10) {\n"
+   "  int j = 1;\n"
+   "}",
+   ShortBlocks);
+  ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
+  verifyFormat("for (;;)\n"
+   "  int j = 1;",
+   ShortBlocks);
+  verifyFormat("rng (i, 0, 10)\n"
+   "  int j = 1;",
+   ShortBlocks);
+  verifyFormat("for (;;) {\n"
+   "  int j = 1;\n"
+   "}",

[PATCH] D94955: [clang-format] Treat ForEachMacros as loops

2022-01-14 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius marked 5 inline comments as done.
curdeius added inline comments.



Comment at: clang/unittests/Format/FormatTest.cpp:2181-2185
+  EXPECT_EQ(Style.AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
+  EXPECT_EQ(Style.AllowShortLoopsOnASingleLine, false);
   verifyFormat("void f() {\n"
-   "  foreach (Item *item, itemlist) {}\n"
-   "  Q_FOREACH (Item *item, itemlist) {}\n"
-   "  BOOST_FOREACH (Item *item, itemlist) {}\n"
+   "  for (;;) {\n"
+   "  }\n"

The existing tests have changed here. I added the tests case for a pure `for` 
loop to show the similarity.
I also check values of 
AllowShortBlocksOnASingleLine/AllowShortLoopsOnASingleLine.



Comment at: clang/unittests/Format/FormatTest.cpp:2226
+
+  FormatStyle ShortBlocks = getLLVMStyle();
+  ShortBlocks.ForEachMacros.push_back("rng");

Euuh, I might need to so come clean up here.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94955

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


[PATCH] D116750: [clang][lex] Keep references to `DirectoryLookup` objects up-to-date

2022-01-14 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 added inline comments.



Comment at: clang/include/clang/Lex/HeaderSearch.h:415
   StringRef Filename, SourceLocation IncludeLoc, bool isAngled,
-  const DirectoryLookup *FromDir, const DirectoryLookup **CurDir,
+  maybe_search_dir_iterator FromDir, maybe_search_dir_iterator *CurDir,
   ArrayRef> Includers,

This is the interesting change in the latest revision. Callers of this function 
performed pointer arithmetics on `const DirectoryLookup *`, essentially 
treating it as an iterator. Since `DirectoryLookup` objects are no longer 
stored in contiguous memory, that's unsafe. I'm using an iterator to allow 
doing that safely and using `llvm::Optional` to provide the nullability clients 
take advantage of.

I don't love the long name that causes a bunch of formatting changes. Maybe 
it's worth extracting it out of `HeaderSearch` and giving it shorter name. I 
also don't love that the API is not the same as for `const DirectoryLookup *`, 
leading to some "unnecessary" changes (e.g. `CurDir = nullptr` -> 
`CurDir.reset()`). I think it might be worth creating custom iterator type that 
would have the original API, but would behave correctly with the new memory 
setup.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116750

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


[PATCH] D116593: Fix `performance-unnecessary-value-param` for template specialization

2022-01-14 Thread Felix Berger via Phabricator via cfe-commits
flx added inline comments.



Comment at: 
clang-tools-extra/clang-tidy/performance/UnnecessaryValueParamCheck.cpp:177-178
 const auto &CurrentParam = *FunctionDecl->getParamDecl(Index);
+if (IsExplicitTemplateSpecialization && Function != FunctionDecl)
+  continue;
 Diag << utils::fixit::changeVarDeclToReference(CurrentParam,

Sockke wrote:
> flx wrote:
> > Could you add a comment here why we're skipping the fix here?
> > Could you add a comment here why we're skipping the fix here?
> 
> Specialization template may match the primary template again by 
> `getPreviousDecl`. Skipping the fix to avoid repeated fixes for the primary 
> template.
Thanks for the explanation. Would you mind adding this as code comment?



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/performance-unnecessary-value-param.cpp:388
+  // CHECK-MESSAGES: [[@LINE-1]]:54: warning: the parameter 'E' is copied
+  // CHECK-FIXES: T templateSpecializationFunction(const ExpensiveToCopyType& 
E) {
+  return T();

Sockke wrote:
> flx wrote:
> > Should we apply the fixes or just issue the warning? For virtual methods we 
> > suppress the fix since we can't necessarily update all overrides of the 
> > method. Are template specializations always guaranteed to be in the same 
> > translation unit which  would make this safe?
> > Should we apply the fixes or just issue the warning? For virtual methods we 
> > suppress the fix since we can't necessarily update all overrides of the 
> > method. Are template specializations always guaranteed to be in the same 
> > translation unit which  would make this safe?
> 
> Do you mean that specialization templates are defined in different 
> translation units?  If fixing one by one translation unit does have the 
> problem, the `readability-const-return-type` also has such a problem. 
> clang-tidy can not analyze across translation units, but the diagnosis and 
> fix of it are separate, we can specify the complete `compile_commands.json` 
> to avoid it. 
> I'm not sure whether this is reasonable, we may make a choice between 
> clang-tidy's fault tolerance and advantages. What's your suggestion?
> > Should we apply the fixes or just issue the warning? For virtual methods we 
> > suppress the fix since we can't necessarily update all overrides of the 
> > method. Are template specializations always guaranteed to be in the same 
> > translation unit which  would make this safe?
> 
> Do you mean that specialization templates are defined in different 
> translation units?  If fixing one by one translation unit does have the 
> problem, the `readability-const-return-type` also has such a problem. 
> clang-tidy can not analyze across translation units, but the diagnosis and 
> fix of it are separate, we can specify the complete `compile_commands.json` 
> to avoid it. 

I'm not sure how I understand how the compile command json file would help. I 
think std::hash (https://en.cppreference.com/w/cpp/utility/hash) is an example 
where you would specialize a type across translation units. If std::hash itself 
had the issue you wouldn't be able to modify it since it is an external library.

> I'm not sure whether this is reasonable, we may make a choice between 
> clang-tidy's fault tolerance and advantages. What's your suggestion?

Yeah, this is not an easy balance to strike. ClangTidy is used in many 
different contexts, in some where you would like to see aggressive fixes, in 
others where only the safest fixes should be applied.

From previous reviews and my own experience we should by default only provide 
safe fixes with low false positive rate. If you think its' not enough to only 
notify the user of an inefficiency in template specializations you could add an 
option to the check for fixing these occurrences.

This was done for example here to make a check find issues (including false 
positives) and report them:  
https://github.com/llvm/llvm-project/blob/765dd8b8a44cd9689c87c0433739f421b9871061/clang-tools-extra/clang-tidy/performance/ForRangeCopyCheck.cpp#L26
 

In summary, I would make this a warning only, but not issue the fix here.




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116593

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


[PATCH] D117315: [AIX][ZOS] Handle unsupported builtin function CFStringMakeConstantString

2022-01-14 Thread Jake Egan via Phabricator via cfe-commits
Jake-Egan created this revision.
Jake-Egan 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/D117315

Files:
  clang/lib/Sema/SemaChecking.cpp
  clang/test/Analysis/cfref_PR2519.c
  clang/test/CodeGen/cfstring2.c
  clang/test/Modules/builtins.m
  clang/test/SemaCXX/builtins.cpp

Index: clang/test/SemaCXX/builtins.cpp
===
--- clang/test/SemaCXX/builtins.cpp
+++ clang/test/SemaCXX/builtins.cpp
@@ -4,7 +4,11 @@
 #define CFSTR __builtin___CFStringMakeConstantString
 
 void f() {
+#if !defined(__MVS__) && !defined(_AIX)
+  // Builtin function __builtin___CFStringMakeConstantString is currently
+  // unsupported on z/OS and AIX.
   (void)CFStringRef(CFSTR("Hello"));
+#endif
 }
 
 void a() { __builtin_va_list x, y; ::__builtin_va_copy(x, y); }
Index: clang/test/Modules/builtins.m
===
--- clang/test/Modules/builtins.m
+++ clang/test/Modules/builtins.m
@@ -1,3 +1,4 @@
+// UNSUPPORTED: -zos, -aix
 // RUN: rm -rf %t
 // RUN: %clang_cc1 -fmodules-cache-path=%t -fmodules -fimplicit-module-maps -I %S/Inputs %s -verify
 // RUN: %clang_cc1 -fmodules-cache-path=%t -fmodules -fimplicit-module-maps -I %S/Inputs -x c %s -verify
Index: clang/test/CodeGen/cfstring2.c
===
--- clang/test/CodeGen/cfstring2.c
+++ clang/test/CodeGen/cfstring2.c
@@ -1,3 +1,4 @@
+// UNSUPPORTED: -zos, -aix
 // RUN: %clang_cc1 -emit-llvm %s -o %t
 
 typedef const struct __CFString * CFStringRef;
Index: clang/test/Analysis/cfref_PR2519.c
===
--- clang/test/Analysis/cfref_PR2519.c
+++ clang/test/Analysis/cfref_PR2519.c
@@ -1,3 +1,4 @@
+// UNSUPPORTED: -zos, -aix
 // RUN: %clang_analyze_cc1 -analyzer-checker=core,osx.cocoa.RetainCount,alpha.core -analyzer-store=region -verify %s
 // expected-no-diagnostics
 
Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -1578,11 +1578,26 @@
   return TheCall;
 }
 
+// Emit an error and return true if the current object format type is in the
+// list of unsupported types.
+static bool CheckBuiltinTargetNotInUnsupported(
+Sema &S, unsigned BuiltinID, CallExpr *TheCall,
+ArrayRef UnsupportedObjectFormatTypes) {
+  llvm::Triple::ObjectFormatType CurObjFormat =
+  S.getASTContext().getTargetInfo().getTriple().getObjectFormat();
+  if (llvm::is_contained(UnsupportedObjectFormatTypes, CurObjFormat)) {
+S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
+<< TheCall->getSourceRange();
+return true;
+  }
+  return false;
+}
+
 // Emit an error and return true if the current architecture is not in the list
 // of supported architectures.
 static bool
-CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
-  ArrayRef SupportedArchs) {
+CheckBuiltinTargetInSupported(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
+  ArrayRef SupportedArchs) {
   llvm::Triple::ArchType CurArch =
   S.getASTContext().getTargetInfo().getTriple().getArch();
   if (llvm::is_contained(SupportedArchs, CurArch))
@@ -1664,6 +1679,12 @@
 
   switch (BuiltinID) {
   case Builtin::BI__builtin___CFStringMakeConstantString:
+// CFStringMakeConstantString is currently not implemented for GOFF (i.e.,
+// on z/OS) and for XCOFF (i.e., on AIX). Emit unsupported
+if (CheckBuiltinTargetNotInUnsupported(
+*this, BuiltinID, TheCall,
+{llvm::Triple::GOFF, llvm::Triple::XCOFF}))
+  return ExprError();
 assert(TheCall->getNumArgs() == 1 &&
"Wrong # arguments to builtin CFStringMakeConstantString");
 if (CheckObjCString(TheCall->getArg(0)))
@@ -1698,7 +1719,7 @@
   case Builtin::BI_interlockedbittestandreset_acq:
   case Builtin::BI_interlockedbittestandreset_rel:
   case Builtin::BI_interlockedbittestandreset_nf:
-if (CheckBuiltinTargetSupport(
+if (CheckBuiltinTargetInSupported(
 *this, BuiltinID, TheCall,
 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
   return ExprError();
@@ -1711,9 +1732,10 @@
   case Builtin::BI_bittestandset64:
   case Builtin::BI_interlockedbittestandreset64:
   case Builtin::BI_interlockedbittestandset64:
-if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
-  {llvm::Triple::x86_64, llvm::Triple::arm,
-   llvm::Triple::thumb, llvm::Triple::aarch64}))
+if (CheckBuiltinTargetInSupported(*this, BuiltinID, TheCall,
+  {llvm::Triple::x86_64, llvm::Triple::arm,
+   llvm::Tr

[PATCH] D116518: [ast-matchers] Add hasSubstatementSequence matcher

2022-01-14 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel added a comment.

Sorry for the delay. Read through the whole thread today. I agree with Aaron -- 
we shouldn't add this until

1. we have a general interface
2. we're sure this serves a general audience

As I mentioned in my previous reply, I have a working general interface that I 
shared and whose implementation I'd be happy to upstream. But, that brings us 
to point 2, for which I'm on the fence. I think it serves a general audience 
but I also suspect its really just a frustrating "not quite good enough" 
solution.

To the point of opening up matchers to a wider audience and the cost of 
`ASTMatchers.h` -- this sounds like a broader issue that we should find a way 
to address, well beyond this patch. Happy to be in on that discussion, but I 
don't think I have the cycles now to drive it. :)

Regarding CFG matchers -- none that I know of.  We've had it as project on our 
"interesting clang projects" list (in our heads) for a while, but have yet to 
invest in it.  What we *have* started is a dataflow analysis framework: 
clang/Analysis/FlowSensitive (see the unittests for some example uses). My main 
use of `hasSubstatementSequence` was to find pointer variables which could be 
safely converted to `unique_ptr`.  I converted that into a dataflow analysis 
built on the new framework and it's a lot cleaner.


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

https://reviews.llvm.org/D116518

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


[PATCH] D116518: [ast-matchers] Add hasSubstatementSequence matcher

2022-01-14 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel added a comment.

Clarification: I'm totally fine with it existing privately, my concerns were 
with a public implementation.


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

https://reviews.llvm.org/D116518

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


[PATCH] D117306: [clang-tidy] Add new check 'shared-ptr-array-mismatch'.

2022-01-14 Thread Eugene Zelenko via Phabricator via cfe-commits
Eugene.Zelenko added a comment.

I think this check belongs to `bugprone` module. How about `std::unique_ptr`?




Comment at: clang-tools-extra/clang-tidy/misc/SharedPtrArrayMismatchCheck.cpp:1
+//===--- SharedPtrArrayMismatchCheck.cpp - clang-tidy
+//--===//

Please make it same length and single line as closing comment.



Comment at: 
clang-tools-extra/docs/clang-tidy/checks/misc-shared-ptr-array-mismatch.rst:6
+
+Find construction of ``std::shared_ptr`` where it is initialized with a 
new-expression ``new T[]``.
+The check offers replacement of ``shared_ptr`` to ``shared_ptr`` if it 
is used at a single variable declaration.

Please make first statement same as in Release Notes.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D117306

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


[PATCH] D107450: [clang-tidy] Fix wrong FixIt in performance-move-const-arg

2022-01-14 Thread Arthur O'Dwyer via Phabricator via cfe-commits
Quuxplusone accepted this revision.
Quuxplusone added a comment.
This revision is now accepted and ready to land.

@Sockke: Throughout, `trivially-copyable` should be `trivially copyable` (two 
words).
Other than that, sure, I have no particular opinions at this point.




Comment at: clang-tools-extra/clang-tidy/performance/MoveConstArgCheck.cpp:179
+  QualType NoRefType = (*InvocationParmType)->getPointeeType();
+  PrintingPolicy PolicyWithSupressedTag(getLangOpts());
+  PolicyWithSupressedTag.SuppressTagKeyword = true;

Throughout, `Supress` should be `Suppress`.



Comment at: clang-tools-extra/docs/ReleaseNotes.rst:118
+
+  Removed a wrong FixIt for trivially-copyable objects wrapped by 
``std::move()`` and passed to an rvalue reference parameter. Removal of 
``std::move()`` would break the code.
+




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

https://reviews.llvm.org/D107450

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


[PATCH] D94955: [clang-format] Treat ForEachMacros as loops

2022-01-14 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius updated this revision to Diff 36.
curdeius added a comment.

Clean up tests.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94955

Files:
  clang/lib/Format/UnwrappedLineFormatter.cpp
  clang/unittests/Format/FormatTest.cpp

Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -1464,6 +1464,7 @@
   verifyFormat("while (true) continue;", AllowsMergedLoops);
   verifyFormat("for (;;) continue;", AllowsMergedLoops);
   verifyFormat("for (int &v : vec) v *= 2;", AllowsMergedLoops);
+  verifyFormat("BOOST_FOREACH (int &v, vec) v *= 2;", AllowsMergedLoops);
   verifyFormat("while (true)\n"
"  ;",
AllowsMergedLoops);
@@ -1476,9 +1477,15 @@
   verifyFormat("for (;;)\n"
"  while (true) continue;",
AllowsMergedLoops);
-  verifyFormat("BOOST_FOREACH (int v, vec)\n"
+  verifyFormat("while (true)\n"
+   "  for (;;) continue;",
+   AllowsMergedLoops);
+  verifyFormat("BOOST_FOREACH (int &v, vec)\n"
"  for (;;) continue;",
AllowsMergedLoops);
+  verifyFormat("for (;;)\n"
+   "  BOOST_FOREACH (int &v, vec) continue;",
+   AllowsMergedLoops);
   verifyFormat("for (;;) // Can't merge this\n"
"  continue;",
AllowsMergedLoops);
@@ -1645,6 +1652,11 @@
"  f();\n"
"}",
AllowSimpleBracedStatements);
+  verifyFormat("BOOST_FOREACH (int v, vec) {}", AllowSimpleBracedStatements);
+  verifyFormat("BOOST_FOREACH (int v, vec) {\n"
+   "  f();\n"
+   "}",
+   AllowSimpleBracedStatements);
 
   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
   FormatStyle::SIS_WithoutElse;
@@ -1775,6 +1787,12 @@
"  f();\n"
"}",
AllowSimpleBracedStatements);
+  verifyFormat("BOOST_FOREACH (int v, vec) {}", AllowSimpleBracedStatements);
+  verifyFormat("BOOST_FOREACH (int v, vec)\n"
+   "{\n"
+   "  f();\n"
+   "}",
+   AllowSimpleBracedStatements);
 }
 
 TEST_F(FormatTest, ShortBlocksInMacrosDontMergeWithCodeAfterMacro) {
@@ -2159,20 +2177,89 @@
 }
 
 TEST_F(FormatTest, ForEachLoops) {
+  FormatStyle Style = getLLVMStyle();
+  EXPECT_EQ(Style.AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
+  EXPECT_EQ(Style.AllowShortLoopsOnASingleLine, false);
   verifyFormat("void f() {\n"
-   "  foreach (Item *item, itemlist) {}\n"
-   "  Q_FOREACH (Item *item, itemlist) {}\n"
-   "  BOOST_FOREACH (Item *item, itemlist) {}\n"
+   "  for (;;) {\n"
+   "  }\n"
+   "  foreach (Item *item, itemlist) {\n"
+   "  }\n"
+   "  Q_FOREACH (Item *item, itemlist) {\n"
+   "  }\n"
+   "  BOOST_FOREACH (Item *item, itemlist) {\n"
+   "  }\n"
"  UNKNOWN_FOREACH(Item * item, itemlist) {}\n"
-   "}");
+   "}",
+   Style);
+  verifyFormat("void f() {\n"
+   "  for (;;)\n"
+   "int j = 1;\n"
+   "  Q_FOREACH (int v, vec)\n"
+   "v *= 2;\n"
+   "  for (;;) {\n"
+   "int j = 1;\n"
+   "  }\n"
+   "  Q_FOREACH (int v, vec) {\n"
+   "v *= 2;\n"
+   "  }\n"
+   "}",
+   Style);
+
+  FormatStyle ShortBlocks = getLLVMStyle();
+  ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
+  EXPECT_EQ(ShortBlocks.AllowShortLoopsOnASingleLine, false);
+  verifyFormat("void f() {\n"
+   "  for (;;)\n"
+   "int j = 1;\n"
+   "  Q_FOREACH (int &v, vec)\n"
+   "v *= 2;\n"
+   "  for (;;) {\n"
+   "int j = 1;\n"
+   "  }\n"
+   "  Q_FOREACH (int &v, vec) {\n"
+   "int j = 1;\n"
+   "  }\n"
+   "}",
+   ShortBlocks);
+
+  FormatStyle ShortLoops = getLLVMStyle();
+  ShortLoops.AllowShortLoopsOnASingleLine = true;
+  EXPECT_EQ(ShortLoops.AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
+  verifyFormat("void f() {\n"
+   "  for (;;) int j = 1;\n"
+   "  Q_FOREACH (int &v, vec) int j = 1;\n"
+   "  for (;;) {\n"
+   "int j = 1;\n"
+   "  }\n"
+   "  Q_FOREACH (int &v, vec) {\n"
+   "int j = 1;\n"
+   "  }\n"
+   "}",
+   ShortLoops);
+
+  FormatStyle ShortBlocksAndLoops = getLLVMStyle();
+  ShortBlocksAndLoops.AllowShortBlocksOnASingleLine = FormatS

[PATCH] D94955: [clang-format] Treat ForEachMacros as loops

2022-01-14 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius added inline comments.



Comment at: clang/unittests/Format/FormatTest.cpp:2209
+
+  FormatStyle ShortBlocks = getLLVMStyle();
+  ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;

If wanted, I might commit the new tests without ForEachMacros before we follow 
on this review.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94955

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


[PATCH] D116174: [clang] support relative roots to vfs overlays

2022-01-14 Thread Richard Howell via Phabricator via cfe-commits
rmaz added a comment.

In D116174#3242087 , @benlangmuir 
wrote:

> Each VFS may have its own working directory, so it could be surprising if we 
> use the OS working directory instead of that.  This is complicated by the 
> fact the VFS working directory may not be set yet during parsing the yaml (I 
> haven't checked).  I'm not really sure what to recommend here. If we do 
> change this, we should document the new behaviour in the doc comment for 
> RedirectingFileSystem though.

I don't believe the working directory will be set on the VFS at this point, no. 
If you're happy with the change then i'll update the header docs to describe 
this behaviour, unless there is another way to achieve using relative paths for 
root entries in the overlay yaml?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116174

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


[PATCH] D116673: [Clang][NVPTX]Add NVPTX intrinsics and builtins for CUDA PTX cvt sm80 instructions

2022-01-14 Thread Jack Kirk via Phabricator via cfe-commits
JackAKirk added a comment.

In D116673#3241721 , @tra wrote:

> In D116673#3237873 , @JackAKirk 
> wrote:
>
 I can land the patch on your behalf. Are you OK to use the name/email in 
 this patch or do you prefer to use a different email for the LLVM commit?
>>
>> Thanks very much.  Yes the name/email in the patch is fine.
>
> Note for the future. It would make it easier to land the patch if it was 
> submitted to phabricator as a git patch, according to the instructions here: 
> https://llvm.org/docs/Phabricator.html#requesting-a-review-via-the-web-interface
>
> Review tracker would then include info about relevant base commit, author, 
> commit message, etc. and it can be easily applied with `arc patch` to my 
> tree. Using plain diff requires a bit of extra manual work to transfer all of 
> that from the review tracker to the git commit.

OK thanks for the tip.  I'll make sure to submit it to Phabricator as a git 
patch next time.  Thanks again for making the commit.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116673

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


[PATCH] D117293: enable noundef analysis with -fsanitize-memory-param-retval

2022-01-14 Thread Vitaly Buka via Phabricator via cfe-commits
vitalybuka accepted this revision.
vitalybuka added a comment.
This revision is now accepted and ready to land.

Nice!

>> This completes the work found in:

It's too late for this set of patches, but phabricator supports "Depends on"  
comments (I guess only of the first patch upload), and manual editing of 
"parent/child" revisions. Check "Edit Related Revisions..." in the top right 
corner.
So you can create convenient "Stack" tab like in 
liihttps://reviews.llvm.org/D117286




Comment at: clang/include/clang/Driver/Options.td:1678
+BothFlags<[], " detection of uninitialized parameters and return 
values">>;
+ Note: This flag was introduced when it was necessary to distinguish 
between
 //   ABI for correct codegen.  This is no longer needed, but the flag is




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D117293

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


[PATCH] D94955: [clang-format] Treat ForEachMacros as loops

2022-01-14 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added a comment.

LGTM


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94955

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


[PATCH] D117321: [clang] Remap file path in __PRETTY_FUNCTION__

2022-01-14 Thread Jyun-Yan You via Phabricator via cfe-commits
jyyou.tw created this revision.
jyyou.tw requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

__PRETTY_FUNCTION__ may have file path in template argument
but -fmacro-prefix-map can't remap it. This patch tries to fix the problem.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D117321

Files:
  clang/lib/AST/Expr.cpp
  clang/test/CodeGenCXX/macro-prefix-map.cpp


Index: clang/test/CodeGenCXX/macro-prefix-map.cpp
===
--- /dev/null
+++ clang/test/CodeGenCXX/macro-prefix-map.cpp
@@ -0,0 +1,14 @@
+// RUN: %clang_cc1 -fmacro-prefix-map=%p=/UNLIKELY/PATH -emit-llvm -o - %s | 
FileCheck %s
+//
+// CHECK: /UNLIKELY/PATH{{/|}}macro-prefix-map.cpp
+template 
+const char *pretty(T) {
+  return __PRETTY_FUNCTION__;
+}
+
+const char *testEnum() {
+  enum {
+A
+  };
+  return pretty(A);
+}
Index: clang/lib/AST/Expr.cpp
===
--- clang/lib/AST/Expr.cpp
+++ clang/lib/AST/Expr.cpp
@@ -635,6 +635,21 @@
   llvm_unreachable("Unknown ident kind for PredefinedExpr");
 }
 
+namespace {
+class PPCallbacks final : public PrintingCallbacks {
+  const LangOptions &LO;
+
+public:
+  PPCallbacks(const LangOptions &LO) : LO(LO) {}
+
+  std::string remapPath(StringRef Path) const override {
+SmallString<256> Buffer(Path);
+LO.remapPathPrefix(Buffer);
+return static_cast(Buffer);
+  }
+};
+} // namespace
+
 // FIXME: Maybe this should use DeclPrinter with a special "print predefined
 // expr" policy instead.
 std::string PredefinedExpr::ComputeName(IdentKind IK, const Decl *CurrentDecl) 
{
@@ -700,6 +715,9 @@
 }
 
 PrintingPolicy Policy(Context.getLangOpts());
+PPCallbacks Callbacks(Context.getLangOpts());
+Policy.Callbacks = &Callbacks;
+
 std::string Proto;
 llvm::raw_string_ostream POut(Proto);
 


Index: clang/test/CodeGenCXX/macro-prefix-map.cpp
===
--- /dev/null
+++ clang/test/CodeGenCXX/macro-prefix-map.cpp
@@ -0,0 +1,14 @@
+// RUN: %clang_cc1 -fmacro-prefix-map=%p=/UNLIKELY/PATH -emit-llvm -o - %s | FileCheck %s
+//
+// CHECK: /UNLIKELY/PATH{{/|}}macro-prefix-map.cpp
+template 
+const char *pretty(T) {
+  return __PRETTY_FUNCTION__;
+}
+
+const char *testEnum() {
+  enum {
+A
+  };
+  return pretty(A);
+}
Index: clang/lib/AST/Expr.cpp
===
--- clang/lib/AST/Expr.cpp
+++ clang/lib/AST/Expr.cpp
@@ -635,6 +635,21 @@
   llvm_unreachable("Unknown ident kind for PredefinedExpr");
 }
 
+namespace {
+class PPCallbacks final : public PrintingCallbacks {
+  const LangOptions &LO;
+
+public:
+  PPCallbacks(const LangOptions &LO) : LO(LO) {}
+
+  std::string remapPath(StringRef Path) const override {
+SmallString<256> Buffer(Path);
+LO.remapPathPrefix(Buffer);
+return static_cast(Buffer);
+  }
+};
+} // namespace
+
 // FIXME: Maybe this should use DeclPrinter with a special "print predefined
 // expr" policy instead.
 std::string PredefinedExpr::ComputeName(IdentKind IK, const Decl *CurrentDecl) {
@@ -700,6 +715,9 @@
 }
 
 PrintingPolicy Policy(Context.getLangOpts());
+PPCallbacks Callbacks(Context.getLangOpts());
+Policy.Callbacks = &Callbacks;
+
 std::string Proto;
 llvm::raw_string_ostream POut(Proto);
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D117197: [clang-format] Add new option to support adding a space between Javascript Union and Intersection types

2022-01-14 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added inline comments.



Comment at: clang/lib/Format/TokenAnnotator.cpp:3522
+  if ((Left.is(TT_JsTypeOperator) && Right.isTypeOrIdentifier()) ||
+  (Left.isTypeOrIdentifier() || Left.is(TT_TemplateCloser)) &&
+  Right.is(TT_JsTypeOperator))

mprobst wrote:
> Why do we need this further qualification here? I'd have expect that you can 
> simply "return Style.SpacesInJavaScriptUnion;"? identifier || template closer 
> also sounds oddly specific, why exactly those?
Left =  template closer, Right =JsTypeOperator is for this case

```
type Foo = Bar | Baz;
   ^
```

Left =  type or identifier, Right =JsTypeOperator is for this case


```
let x: A | B = A | B;
^
```


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

https://reviews.llvm.org/D117197

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


[PATCH] D117293: enable noundef analysis with -fsanitize-memory-param-retval

2022-01-14 Thread Vitaly Buka via Phabricator via cfe-commits
vitalybuka added a comment.

Just noticed, -enable-noundef-analysis is missing tests undef 
llvm/llvm-project/clang/test/Driver/
Can you add few near maybe before 
llvm-project/clang/test/Driver/clang_f_opts.c:531 (just before 
discard-value-names tests)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D117293

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


[PATCH] D116174: [clang] support relative roots to vfs overlays

2022-01-14 Thread Richard Howell via Phabricator via cfe-commits
rmaz updated this revision to Diff 48.
rmaz added a comment.

Add comment to describe relative root path behaviour


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116174

Files:
  clang/test/VFS/Inputs/vfsoverlay-root-relative.yaml
  clang/test/VFS/vfsoverlay-relative-root.c
  llvm/include/llvm/Support/VirtualFileSystem.h
  llvm/lib/Support/VirtualFileSystem.cpp


Index: llvm/lib/Support/VirtualFileSystem.cpp
===
--- llvm/lib/Support/VirtualFileSystem.cpp
+++ llvm/lib/Support/VirtualFileSystem.cpp
@@ -1649,10 +1649,19 @@
 sys::path::Style::windows_backslash)) {
 path_style = sys::path::Style::windows_backslash;
   } else {
-assert(NameValueNode && "Name presence should be checked earlier");
-error(NameValueNode,
+// Relative VFS root entries are made absolute to the current working
+// directory, then we can determine the path style from that.
+auto EC = sys::fs::make_absolute(Name);
+if (EC) {
+  assert(NameValueNode && "Name presence should be checked earlier");
+  error(
+  NameValueNode,
   "entry with relative path at the root level is not 
discoverable");
-return nullptr;
+  return nullptr;
+}
+path_style = sys::path::is_absolute(Name, sys::path::Style::posix)
+ ? sys::path::Style::posix
+ : sys::path::Style::windows_backslash;
   }
 }
 
Index: llvm/include/llvm/Support/VirtualFileSystem.h
===
--- llvm/include/llvm/Support/VirtualFileSystem.h
+++ llvm/include/llvm/Support/VirtualFileSystem.h
@@ -547,6 +547,9 @@
 /// }
 /// \endverbatim
 ///
+/// The roots may be absolute or relative. If relative they will be made
+/// absolute against the current working directory.
+///
 /// All configuration options are optional.
 ///   'case-sensitive': 
 ///   'use-external-names': 
Index: clang/test/VFS/vfsoverlay-relative-root.c
===
--- /dev/null
+++ clang/test/VFS/vfsoverlay-relative-root.c
@@ -0,0 +1,3 @@
+// RUN: %clang_cc1 -Werror -ivfsoverlay 
%S/Inputs/vfsoverlay-root-relative.yaml -I virtual -fsyntax-only %s
+
+#include "virtual_header.h"
Index: clang/test/VFS/Inputs/vfsoverlay-root-relative.yaml
===
--- /dev/null
+++ clang/test/VFS/Inputs/vfsoverlay-root-relative.yaml
@@ -0,0 +1,17 @@
+{
+  'version': 0,
+  'fallthrough': true,
+  'overlay-relative': true,
+  'roots': [
+{ 'name': 'virtual',
+  'type': 'directory',
+  'contents': [
+{
+  'external-contents': 'actual_header.h',
+  'type': 'file',
+  'name': 'virtual_header.h',
+}
+  ]
+}
+  ]
+}


Index: llvm/lib/Support/VirtualFileSystem.cpp
===
--- llvm/lib/Support/VirtualFileSystem.cpp
+++ llvm/lib/Support/VirtualFileSystem.cpp
@@ -1649,10 +1649,19 @@
 sys::path::Style::windows_backslash)) {
 path_style = sys::path::Style::windows_backslash;
   } else {
-assert(NameValueNode && "Name presence should be checked earlier");
-error(NameValueNode,
+// Relative VFS root entries are made absolute to the current working
+// directory, then we can determine the path style from that.
+auto EC = sys::fs::make_absolute(Name);
+if (EC) {
+  assert(NameValueNode && "Name presence should be checked earlier");
+  error(
+  NameValueNode,
   "entry with relative path at the root level is not discoverable");
-return nullptr;
+  return nullptr;
+}
+path_style = sys::path::is_absolute(Name, sys::path::Style::posix)
+ ? sys::path::Style::posix
+ : sys::path::Style::windows_backslash;
   }
 }
 
Index: llvm/include/llvm/Support/VirtualFileSystem.h
===
--- llvm/include/llvm/Support/VirtualFileSystem.h
+++ llvm/include/llvm/Support/VirtualFileSystem.h
@@ -547,6 +547,9 @@
 /// }
 /// \endverbatim
 ///
+/// The roots may be absolute or relative. If relative they will be made
+/// absolute against the current working directory.
+///
 /// All configuration options are optional.
 ///   'case-sensitive': 
 ///   'use-external-names': 
Index: clang/test/VFS/vfsoverlay-relative-root.c
===
--- /dev/null
+++ clang/test/VFS/vfsoverlay-relative-root.c
@@ -0,0 +1,3 @@
+// RUN: %clang_cc1 -Werror -ivfsoverlay %S/Inputs/vfsoverlay-root-relative.yaml -I virtu

[PATCH] D117197: [clang-format] Add new option to support adding a space between Javascript Union and Intersection types

2022-01-14 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius accepted this revision.
curdeius added a comment.
This revision is now accepted and ready to land.

Looks ok from my side.


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

https://reviews.llvm.org/D117197

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


[PATCH] D116713: [clangd] Support configuration of inlay hints.

2022-01-14 Thread Jack Andersen via Phabricator via cfe-commits
jackoalan added a comment.

Assuming origin/maain is a branch typo and is no longer being tracked, would 
you please delete the upstream one in 
https://github.com/llvm/llvm-project/branches?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116713

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


[PATCH] D111400: [Clang] Implement P2242R3

2022-01-14 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D111400#3172097 , @cor3ntin wrote:

> Regression compared to the status quo:
> This code no longer warns (as noted by Hubert above)
>
>   auto f = [](bool b) {
> if (b) return 42;
> static int x = 0;
> return x;
>   };
>   constexpr int x = f(true);
>   const int *p = &x;
>
> GCC doesn't warn and... if we wanted to produce a warning there, I have no 
> idea how to go about it.

I think I found the issue in the code, but one thing that's strange is that we 
don't seem to treat it as an extension but instead issue an error, but the 
behavior is consistent with other things we handle as an extension there (e.g., 
a local variable in C++14 mode).




Comment at: clang/lib/Sema/SemaDeclCXX.cpp:1900
+<< (VD->getTLSKind() == VarDecl::TLS_Dynamic);
   }
 }

I think this is missing an `else` case to return `false` when checking for 
validity, similar to what's done on line 1916 and 1928.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111400

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


[PATCH] D116316: [clang-format] Add an experimental option to remove optional control statement braces in LLVM C++ code

2022-01-14 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay accepted this revision.
MyDeveloperDay added a comment.

LGTM go for it.


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

https://reviews.llvm.org/D116316

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


[PATCH] D117293: enable noundef analysis with -fsanitize-memory-param-retval

2022-01-14 Thread Vitaly Buka via Phabricator via cfe-commits
vitalybuka added a comment.

In D117293#3243772 , @vitalybuka 
wrote:

> Just noticed, -enable-noundef-analysis is missing tests undef 
> llvm/llvm-project/clang/test/Driver/
> Can you add few near maybe before 
> llvm-project/clang/test/Driver/clang_f_opts.c:531 (just before 
> discard-value-names tests)

Actually noundef is not f_opt, and I am not sure how or do we need to test 
ImpliedByAnyOf in Driver.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D117293

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


[PATCH] D117197: [clang-format] Add new option to support adding a space between Javascript Union and Intersection types

2022-01-14 Thread Martin Probst via Phabricator via cfe-commits
mprobst added inline comments.



Comment at: clang/lib/Format/TokenAnnotator.cpp:3522
+  if ((Left.is(TT_JsTypeOperator) && Right.isTypeOrIdentifier()) ||
+  (Left.isTypeOrIdentifier() || Left.is(TT_TemplateCloser)) &&
+  Right.is(TT_JsTypeOperator))

MyDeveloperDay wrote:
> mprobst wrote:
> > Why do we need this further qualification here? I'd have expect that you 
> > can simply "return Style.SpacesInJavaScriptUnion;"? identifier || template 
> > closer also sounds oddly specific, why exactly those?
> Left =  template closer, Right =JsTypeOperator is for this case
> 
> ```
> type Foo = Bar | Baz;
>^
> ```
> 
> Left =  type or identifier, Right =JsTypeOperator is for this case
> 
> 
> ```
> let x: A | B = A | B;
> ^
> ```
What about:

```
let x: {foo: string}&{bar: number};
```

I'm not sure including curlies would be comprehensive. It might be worth 
checking the TS grammar.

But coming back, did you try this:

```
if (Left.is(TT_JsTypeOperator) || Right.is(TT_JsTypeOperator)) {
  return Style.SpacesInJavaScriptUnion;
```

(We might also need to do something in `spaceRequiredBefore`, maybe that fires 
earlier?)




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

https://reviews.llvm.org/D117197

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


[PATCH] D116633: Add -fsanitize-address-param-retval to clang.

2022-01-14 Thread Vitaly Buka via Phabricator via cfe-commits
vitalybuka added inline comments.



Comment at: clang/test/Driver/fsanitize-memory-param-retval.c:8-9
+
+// RUN: %clang -target aarch64-linux-gnu -fsyntax-only %s -fsanitize=memory 
-fsanitize-memory-param-retval -c -### 2>&1 | FileCheck --check-prefix=11 %s
+// 11: "-fsanitize-memory-param-retval"
+

I guess this copied by mistake from example. This is essentially the same as 
line 2.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116633

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


[PATCH] D114235: [clang] Extend ParsedAttr to allow custom handling for type attributes

2022-01-14 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a reviewer: erichkeane.
aaron.ballman added a subscriber: erichkeane.
aaron.ballman added a comment.

In D114235#3243429 , @mboehme wrote:

> Thanks for the feedback! And no worries about the delay -- I know you've got 
> a lot on your plate, and the proposed change is invasive.
>
> To make sure I understand correctly: The issue is that if a `Type` is 
> replaced by an `AttributedType` in places where Clang does not (yet) expect 
> this to happen, this can cause performance regressions or assertions?

More that an attributed type generally carries extra information that needs to 
be stored somewhere (like, a calling convention type attribute needs to store 
which calling convention is represented by the attributed type) and that extra 
overhead can cause performance regressions. Additionally, depending on the kind 
of type attribute the plugin wants to create, there may be failed assertions 
without updating all of the places in clang that expect to handle a class type 
attribute (such as a plugin attempting to add a new calling convention 
attribute). And on top of that, there are very likely places where the compiler 
is inspecting the type via `isa<>` (etc) and that's not going to look through 
the attributed type because one isn't expected yet (so you may not get crashes, 
but obtuse compile errors about mismatched types).

> The motivation behind making type attributes pluggable is that I'd like to 
> annotate pointers with additional information for use in a memory safety 
> static analysis. The goal here is the same as for the proposal I discussed 
> with you a while ago of extending the `annotate` attribute to types (or 
> possibly adding a new `annotate_type` attribute) on this lengthy mailing list 
> thread (no need to reread it):
>
> https://lists.llvm.org/pipermail/cfe-dev/2021-October/thread.html#69087
>
> In this discussion, I mentioned that I was thinking about making type 
> attributes pluggable too. I eventually realized that this might actually be 
> an easier avenue to pursue than extending `annotate` to types. (As we 
> discussed, there might be cases where the GNU spelling of the `annotate` 
> attribute would associate with a declaration while the C++ spelling would 
> associate with a type, and we hadn't reached a firm conclusion on how best to 
> resolve this. An entirely new pluggable attribute wouldn't have this problem.)
>
> From your feedback, it sounds as if I should return to my earlier idea of 
> extending `annotate` to types. I wonder though: Wouldn't this suffer from the 
> same problems that you raise above since, again, Clang would see 
> `AttributedType`s in places where it might not expect them?

An `AttributedType` for an annotation attribute would require a new type in the 
type system, so there could likely be places that need updating to look 
"through" the attributed type. But unlike with arbitrary plugins, the number of 
places is hopefully more reasonable. There's still the concern about memory 
overhead, but that should only be paid by people who use the annotated type and 
hopefully isn't too much of a problem.

> If the same concerns apply to both of these approaches, do you have any 
> suggestions for alternative ways that I could add annotations to types? Or 
> does this mean that I would have to do the work of making sure that Clang can 
> handle `AttributedType`s in these new places after all?

No, I think you basically have to muck about with the type system no matter 
what. I love the idea of plugin type attributes in theory, but I don't think 
we're architecturally in a place where we can do that very easily. I suspect a 
dedicated attribute may be easier, but that's largely a guess. Both approaches 
strike me as likely to have a long tail of bugs we'll have to fight through.

Adding @erichkeane as he's also thought a fair amount about attributes before, 
just in case I'm forgetting anything.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114235

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


[PATCH] D116190: Comment parsing: Don't recognize commands in single-line double quotation

2022-01-14 Thread Dmitri Gribenko via Phabricator via cfe-commits
gribozavr2 accepted this revision.
gribozavr2 added inline comments.
This revision is now accepted and ready to land.



Comment at: clang/lib/AST/CommentLexer.cpp:278
+
+again:
+  size_t End =

aaronpuchert wrote:
> gribozavr2 wrote:
> > I'd suggest refactoring to a `while (true)` if you don't mind.
> I was imitating `lexVerbatimBlockFirstLine`, but I don't mind either way.
I see. No worries then.



Comment at: clang/lib/AST/CommentLexer.cpp:290
+if (End != StringRef::npos && *(TokenPtr + End) == '\"')
+  TokenPtr += End + 1;
+goto again;

aaronpuchert wrote:
> gribozavr2 wrote:
> > Does Doxygen understand escaped quotes?
> > 
> > ```
> > /// "@hello\"@hello"
> > ```
> Vim syntax highlighting suggests it does, but at least my version actually 
> doesn't: `"@c a \" @c b"` is translated to `"@c a \" b"`. So the 
> escaped quote seems to end the quotation.
Got it, thanks for checking!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116190

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


[PATCH] D114235: [clang] Extend ParsedAttr to allow custom handling for type attributes

2022-01-14 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added a comment.

Right, yeah, so there are a couple of problems with AttributedType.  First, it 
gets lost almost as soon as you get out of SemaType about 90% of the time.  
Anything that does some level of canonicalization ends up losing it, so the 
AttributedType information is lost almost immediately.  This is why the current 
ones all store information in the ExtInfo.  The worst place for this ends up 
being in the template instantiator, which immediately canonicalizes/desugars 
types all over the place.

However, making AttributedType 'survive' is actually going to be troublesome as 
well. A lot of the type-checking compares types using == on their pointer 
values, so that would be broken if they are an AttributedType.

So I think the 'first' thing that needs to happen is to make the entire CFE 
'AttributedType' maintaining, AND tolerant. I can't think of a good way to do 
that reliably (my naive thought would be to come up with some way to 
temporarily (during development) wrap EVERY type in an AttributedType with a 
random attribute (so that they are all unique!) and do comparisons that way. 
Additionally, you'd need SOMETHING to validate that the AttributedTypes are the 
only one that survives (again, during development) to make sure it 'works 
right'.

Additionally, you'll likely  have a lot of work to do in the template engine to 
make sure that the attributes are inherited correctly through  instantiations, 
specializations, etc.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114235

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


[PATCH] D116186: Comment parsing: Simplify Lexer::skipLineStartingDecorations (NFC)

2022-01-14 Thread Dmitri Gribenko via Phabricator via cfe-commits
gribozavr2 accepted this revision.
gribozavr2 added a comment.
This revision is now accepted and ready to land.

Nice simplification, thank you!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116186

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


[PATCH] D117296: Document several clang-supported builtins

2022-01-14 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

Thanks for this new documentation! I'm by no means an expert in these builtins, 
so I had some questions on places we might want to expand things a bit more.




Comment at: clang/docs/LanguageExtensions.rst:2183
+n * sizeof(float),
+8 * alignof(float));
+init(mem, n);





Comment at: clang/docs/LanguageExtensions.rst:2569-2570
+
+``__builtin_expect`` is used to indicate that an expression is expected (I;e.
+very likely to) take a given value.
+





Comment at: clang/docs/LanguageExtensions.rst:2588
+
+The ``__builtin_expect()`` builtin is expected to be used with control flow
+conditions such as in ``if`` and ``switch`` statements to help branch





Comment at: clang/docs/LanguageExtensions.rst:2617
+
+The ``__builtin_expect_with_probability()`` builtin is expected to be used 
with control flow
+conditions such as in ``if`` and ``switch`` statements to help branch





Comment at: clang/docs/LanguageExtensions.rst:2620
+prediction. It means that its first argument ``expr`` is expected to take the
+value of its second argument ``val`` with probability ``p``. It always returns 
``expr``.
+

Should we mention that the probability should be specified as a value between 
[0.0, 1.0]?



Comment at: clang/docs/LanguageExtensions.rst:2627-2628
+
+``__builtin_prefetch`` is used to communicate with the cache handler and bring
+data in cache before it gets used.
+





Comment at: clang/docs/LanguageExtensions.rst:2647-2648
+are going to be used next. ``addr`` is the address that needs to be brought 
into
+the cache. ``rw`` indicates the expected access mode: ``0`` for *read* and 
``1``
+for *write*. ``locality`` indicates the expected persistance of data in cache,
+from ``0`` which means that data can be discarded from cache after its next use

Is there a way to specify both read and write at the same time? Or does write 
access imply read access? (If so, it'd be good to make that explicit.)



Comment at: clang/docs/LanguageExtensions.rst:2649-2650
+for *write*. ``locality`` indicates the expected persistance of data in cache,
+from ``0`` which means that data can be discarded from cache after its next use
+to ``3`` which means that data is going to be resued a lot once in cache.
+

How do users know whether to pick `1` or `2`? Should we list the values in 
table form with some prose describing when to use each value?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D117296

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


  1   2   >