[PATCH] D153943: [test] Replace aarch64-*-eabi with aarch64

2023-06-28 Thread Michael Platings via Phabricator via cfe-commits
michaelplatings created this revision.
michaelplatings added a reviewer: MaskRay.
Herald added subscribers: kmitropoulou, asbirlea, kristof.beyls.
Herald added a project: All.
michaelplatings requested review of this revision.
Herald added a reviewer: jdoerfert.
Herald added subscribers: llvm-commits, cfe-commits, jplehr, sstefan1.
Herald added projects: clang, LLVM.

Also replace aarch64_be-*-eabi with aarch64_be

Using "eabi" for aarch64 targets is a common mistake and warned by Clang Driver.
We want to avoid it elsewhere as well. Just use the common "aarch64" without
other triple components.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D153943

Files:
  clang/test/CodeGen/aarch64-bf16-lane-intrinsics.c
  clang/test/CodeGen/aarch64-branch-protection-attr.c
  clang/test/CodeGen/codemodels.c
  clang/test/CodeGenCXX/bitfield-layout.cpp
  clang/test/Driver/aarch64-features.c
  clang/test/Driver/aarch64-security-options.c
  clang/test/Driver/arm-wchar_t-defaults.c
  clang/test/Driver/sls-hardening-options.c
  clang/test/Preprocessor/init-arm.c
  clang/test/Sema/aarch64-sve-alias-attribute.c
  llvm/test/Analysis/MemorySSA/pr43320.ll
  llvm/test/CodeGen/AArch64/arm64-aapcs-be.ll
  llvm/test/CodeGen/AArch64/arm64-big-endian-varargs.ll
  llvm/test/CodeGen/AArch64/arm64-ld-from-st.ll
  llvm/test/CodeGen/AArch64/arm64-narrow-st-merge.ll
  llvm/test/CodeGen/AArch64/arm64-trn.ll
  llvm/test/CodeGen/AArch64/branch-target-enforcement-indirect-calls.ll
  llvm/test/CodeGen/AArch64/bti-branch-relaxation.ll
  llvm/test/CodeGen/AArch64/combine-andintoload.ll
  llvm/test/CodeGen/AArch64/machine-outliner-outline-bti.ll
  llvm/test/CodeGen/AArch64/stack-tagging-ex-2.ll
  llvm/test/CodeGen/AArch64/tme.ll
  llvm/test/DebugInfo/AArch64/big-endian.ll
  llvm/test/MC/AArch64/align.s
  llvm/test/MC/AArch64/directive-arch-negative.s
  llvm/test/MC/AArch64/directive-arch.s
  llvm/test/MC/AArch64/directive-cpu.s
  llvm/test/MC/AArch64/directive-variant_pcs-err.s
  llvm/test/MC/AArch64/error-location-during-layout.s
  llvm/test/MC/AArch64/error-location-ldr-pseudo.s
  llvm/test/MC/AArch64/error-location-post-layout.s
  llvm/test/MC/AArch64/error-location.s
  llvm/test/MC/AArch64/fixup-absolute-signed.s
  llvm/test/MC/AArch64/fixup-absolute.s
  llvm/test/MC/AArch64/fixup-out-of-range-edge.s
  llvm/test/MC/AArch64/fixup-out-of-range.s
  llvm/test/Transforms/LoopVectorize/AArch64/maximize-bandwidth-invalidate.ll

Index: llvm/test/Transforms/LoopVectorize/AArch64/maximize-bandwidth-invalidate.ll
===
--- llvm/test/Transforms/LoopVectorize/AArch64/maximize-bandwidth-invalidate.ll
+++ llvm/test/Transforms/LoopVectorize/AArch64/maximize-bandwidth-invalidate.ll
@@ -4,7 +4,7 @@
 ; RUN: opt < %s -passes=loop-vectorize -vectorizer-maximize-bandwidth -S -debug-only=loop-vectorize 2>&1 -disable-output | FileCheck %s --check-prefix=COST
 
 target datalayout = "e-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128"
-target triple = "aarch64-none-unknown-eabi"
+target triple = "aarch64"
 
 ; Check that the maximize vector bandwidth option does not give incorrect costs
 ; due to invalid cost decisions. The loop below has a low maximum trip count,
Index: llvm/test/MC/AArch64/fixup-out-of-range.s
===
--- llvm/test/MC/AArch64/fixup-out-of-range.s
+++ llvm/test/MC/AArch64/fixup-out-of-range.s
@@ -1,4 +1,4 @@
-// RUN: not llvm-mc -triple aarch64--none-eabi -filetype obj < %s -o /dev/null 2>&1 | FileCheck %s
+// RUN: not llvm-mc -triple aarch64 -filetype obj < %s -o /dev/null 2>&1 | FileCheck %s
 // RUN: not llvm-mc -triple aarch64-windows -filetype obj < %s -o /dev/null 2>&1 | FileCheck %s -check-prefixes=CHECK,CHECK-WIN
 
 // CHECK: :[[@LINE+1]]:{{[0-9]+}}: error: fixup value out of range
Index: llvm/test/MC/AArch64/fixup-out-of-range-edge.s
===
--- llvm/test/MC/AArch64/fixup-out-of-range-edge.s
+++ llvm/test/MC/AArch64/fixup-out-of-range-edge.s
@@ -1,4 +1,4 @@
-// RUN: not llvm-mc -triple aarch64--none-eabi -filetype obj < %s -o /dev/null 2>&1 | FileCheck %s
+// RUN: not llvm-mc -triple aarch64 -filetype obj < %s -o /dev/null 2>&1 | FileCheck %s
 
 // COM: Edge case testing for branches and ADR[P]
 // CHECK-LABEL: :{{[0-9]+}}:{{[0-9]+}}: error: fixup value out of range
Index: llvm/test/MC/AArch64/fixup-absolute.s
===
--- llvm/test/MC/AArch64/fixup-absolute.s
+++ llvm/test/MC/AArch64/fixup-absolute.s
@@ -1,4 +1,4 @@
-// RUN: llvm-mc -triple aarch64--none-eabi -filetype obj < %s -o - | llvm-objdump --no-print-imm-hex -d - | FileCheck %s
+// RUN: llvm-mc -triple aarch64 -filetype obj < %s -o - | llvm-objdump --no-print-imm-hex -d - | FileCheck %s
 
 onepart_before = 0x1234
 twopart_before = 0x12345678
Index: llvm/test/MC/AArch64/fixup-absolute-signed.s
===

[PATCH] D153430: [Clang][Driver] Warn on invalid Arm or AArch64 baremetal target triple

2023-06-28 Thread Michael Platings via Phabricator via cfe-commits
michaelplatings added a comment.

In D153430#4453908 , @MaskRay wrote:

> Thank you for implementing this warning. Side note: it would be better to (a) 
> fix the tests separately from (b) implementing the warning and (c) adding 
> tests to demonstrate the warning.
> This way the patch is more focused.

Agreed, it would have been better to fix the tests first in a separate patch.

In D153430#4454371 , @alexfh wrote:

> After the patch, LLVM still has a number of `aarch64-arm-none-eabi` usages in 
> tests, which is also considered invalid now: 
> https://gcc.godbolt.org/z/z8cY5j68M

Huh. I have no idea why they didn't come up in my find-and-replace. Thanks 
@MaskRay for fixing. I found some more: D153943 



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153430

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


[PATCH] D153798: [clang-format] Correctly annotate operator free function call

2023-06-28 Thread Owen Pan via Phabricator via cfe-commits
owenpan added inline comments.



Comment at: clang/lib/Format/TokenAnnotator.cpp:319
+   Prev->Previous->isOneOf(tok::period, tok::arrow)) ||
+  (!Line.MustBeDeclaration && !Line.InMacroBody);
   Contexts.back().IsExpression = OperatorCalledAsMemberFunction;

Why not `Line.InMacroBody`? Wouldn't it misformat the following snippet?
```
#define FOO   \
  void foo() {\
operator+(a * b); \
  }
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153798

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


[PATCH] D153946: [clangd] Add a flag to allow indexing of reserved identifiers

2023-06-28 Thread Nathan Ridge via Phabricator via cfe-commits
nridge created this revision.
nridge added reviewers: hokein, kadircet.
Herald added a subscriber: arphaman.
Herald added a project: All.
nridge requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay, ilya-biryukov.
Herald added a project: clang-tools-extra.

Some projects, like the Linux kernel, make extensive use of such
identifiers, making it a usability if they can't be indexed.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D153946

Files:
  clang-tools-extra/clangd/Config.h
  clang-tools-extra/clangd/ConfigCompile.cpp
  clang-tools-extra/clangd/ConfigFragment.h
  clang-tools-extra/clangd/ConfigYAML.cpp
  clang-tools-extra/clangd/Hover.cpp
  clang-tools-extra/clangd/XRefs.cpp
  clang-tools-extra/clangd/index/Background.cpp
  clang-tools-extra/clangd/index/FileIndex.cpp
  clang-tools-extra/clangd/index/StdLib.cpp
  clang-tools-extra/clangd/indexer/IndexerMain.cpp
  clang-tools-extra/clangd/refactor/Rename.cpp

Index: clang-tools-extra/clangd/refactor/Rename.cpp
===
--- clang-tools-extra/clangd/refactor/Rename.cpp
+++ clang-tools-extra/clangd/refactor/Rename.cpp
@@ -8,6 +8,7 @@
 
 #include "refactor/Rename.h"
 #include "AST.h"
+#include "Config.h"
 #include "FindTarget.h"
 #include "ParsedAST.h"
 #include "Selection.h"
@@ -234,9 +235,10 @@
   else if (!DeclaredInMainFile)
 IsMainFileOnly = false;
   // If the symbol is not indexable, we disallow rename.
+  SymbolCollector::Options Options;
+  Options.CollectReserved = Config::current().Index.ReservedIdentifiers;
   if (!SymbolCollector::shouldCollectSymbol(
-  RenameDecl, RenameDecl.getASTContext(), SymbolCollector::Options(),
-  IsMainFileOnly))
+  RenameDecl, RenameDecl.getASTContext(), Options, IsMainFileOnly))
 return ReasonToReject::NonIndexable;
 
   return std::nullopt;
Index: clang-tools-extra/clangd/indexer/IndexerMain.cpp
===
--- clang-tools-extra/clangd/indexer/IndexerMain.cpp
+++ clang-tools-extra/clangd/indexer/IndexerMain.cpp
@@ -45,6 +45,8 @@
   std::unique_ptr create() override {
 SymbolCollector::Options Opts;
 Opts.CountReferences = true;
+// FIXME: Do we have access to Config here? If so, should we respect
+// Index.ReservedIdentifiers?
 Opts.FileFilter = [&](const SourceManager &SM, FileID FID) {
   const auto F = SM.getFileEntryRefForID(FID);
   if (!F)
Index: clang-tools-extra/clangd/index/StdLib.cpp
===
--- clang-tools-extra/clangd/index/StdLib.cpp
+++ clang-tools-extra/clangd/index/StdLib.cpp
@@ -230,6 +230,7 @@
   IndexOpts.CollectMainFileRefs = false;
   IndexOpts.CollectMacro = true;
   IndexOpts.StoreAllDocumentation = true;
+  // FIXME: Should we respect the Index.ReservedIdentifiers config here?
   // Sadly we can't use IndexOpts.FileFilter to restrict indexing scope.
   // Files from outside the StdLibLocation may define true std symbols anyway.
   // We end up "blessing" such headers, and can only do that by indexing
Index: clang-tools-extra/clangd/index/FileIndex.cpp
===
--- clang-tools-extra/clangd/index/FileIndex.cpp
+++ clang-tools-extra/clangd/index/FileIndex.cpp
@@ -8,6 +8,7 @@
 
 #include "FileIndex.h"
 #include "CollectMacros.h"
+#include "Config.h"
 #include "ParsedAST.h"
 #include "index/CanonicalIncludes.h"
 #include "index/Index.h"
@@ -57,7 +58,8 @@
   CollectorOpts.CollectMainFileRefs = CollectMainFileRefs;
   // We want stdlib implementation details in the index only if we've opened the
   // file in question. This does means xrefs won't work, though.
-  CollectorOpts.CollectReserved = IsIndexMainAST;
+  CollectorOpts.CollectReserved =
+  IsIndexMainAST || Config::current().Index.ReservedIdentifiers;
 
   index::IndexingOptions IndexOpts;
   // We only need declarations, because we don't count references.
Index: clang-tools-extra/clangd/index/Background.cpp
===
--- clang-tools-extra/clangd/index/Background.cpp
+++ clang-tools-extra/clangd/index/Background.cpp
@@ -304,6 +304,7 @@
 return true;
   };
   IndexOpts.CollectMainFileRefs = true;
+  IndexOpts.CollectReserved = Config::current().Index.ReservedIdentifiers;
 
   IndexFileIn Index;
   auto Action = createStaticIndexingAction(
Index: clang-tools-extra/clangd/XRefs.cpp
===
--- clang-tools-extra/clangd/XRefs.cpp
+++ clang-tools-extra/clangd/XRefs.cpp
@@ -7,6 +7,7 @@
 //===--===//
 #include "XRefs.h"
 #include "AST.h"
+#include "Config.h"
 #include "FindSymbols.h"
 #include "FindTarget.h"
 #include "Headers.h"
@@ -929,6 +930,7 @@
 
 SymbolCollector::Options CollectorOpts;
 CollectorOpts.Collect

[PATCH] D153946: [clangd] Add a flag to allow indexing of reserved identifiers

2023-06-28 Thread Nathan Ridge via Phabricator via cfe-commits
nridge added a comment.

No tests yet, posting for early feedback.




Comment at: clang-tools-extra/clangd/index/StdLib.cpp:233
   IndexOpts.StoreAllDocumentation = true;
+  // FIXME: Should we respect the Index.ReservedIdentifiers config here?
   // Sadly we can't use IndexOpts.FileFilter to restrict indexing scope.

I'm thinking **no**: the only time you'd want reserved identifiers from the 
standard library is if you're working on the standard library itself, but in 
that case the standard library source files would be part of the project and 
you'd be indexing them "normally", not via `indexStandardLibrary()` (so your 
configuration would be:

```
Index:
  ReservedIdentifiers: true
  StandardLibrary: false
```

and the `StandardLibrary: false` means this codepath is not taken).



Comment at: clang-tools-extra/clangd/indexer/IndexerMain.cpp:48
 Opts.CountReferences = true;
+// FIXME: Do we have access to Config here? If so, should we respect
+// Index.ReservedIdentifiers?

I'm thinking we should, so that projects that want to enable this (like e.g. 
the kernel) can use a remote index if desired.

I'm just not sure if we have the machinery in place to use Config from 
`clangd-indexer`.



Comment at: clang-tools-extra/clangd/refactor/Rename.cpp:239
+  SymbolCollector::Options Options;
+  Options.CollectReserved = Config::current().Index.ReservedIdentifiers;
   if (!SymbolCollector::shouldCollectSymbol(

Would it be inappropriate to set this in the `SymbolCollector::Options` 
constructor, instead of every place where we call it?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153946

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


[PATCH] D153409: [clang][dataflow] Add a test that we can access fields of anonymous records.

2023-06-28 Thread Martin Böhme via Phabricator via cfe-commits
mboehme marked 2 inline comments as done.
mboehme added a comment.

Pre-merge failure looks unrelated


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153409

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


[PATCH] D153851: [clang][dataflow] Output debug info if `getChild()` doesn't find field.

2023-06-28 Thread Martin Böhme via Phabricator via cfe-commits
mboehme added a comment.

Pre-merge failures look unrelated


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153851

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


[PATCH] D153001: [clang][ThreadSafety] Add __builtin_instance_member (WIP)

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

Didn't remember and re-checked, using it that way makes the implementation 
harder I think:

  tsa2.c:7:54: error: incomplete definition of type 'struct Mutex'
  7 |   int counter GUARDED_BY(__builtin_instance_member(M)->M);
|  ^
  tsa2.c:6:10: note: forward declaration of 'struct Mutex'
  6 |   struct Mutex *M;
|  ^
  1 error generated.

and I didn't immediately know how to fix that.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153001

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


[PATCH] D151696: [x86] Remove CPU_SPECIFIC* MACROs and add getCPUDispatchMangling

2023-06-28 Thread Freddy, Ye via Phabricator via cfe-commits
FreddyYe updated this revision to Diff 535277.
FreddyYe added a comment.

1. Fixed copy errors of some CPU's manglings
2. Updated resolver function checkers due to more complete feature list changes.
3. Added more cpu checks in attr-cpuspecific-cpus.c


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151696

Files:
  clang/lib/Basic/Targets/X86.cpp
  clang/lib/Basic/Targets/X86.h
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/test/CodeGen/attr-cpuspecific-avx-abi.c
  clang/test/CodeGen/attr-cpuspecific-cpus.c
  clang/test/CodeGen/attr-cpuspecific.c
  llvm/include/llvm/TargetParser/X86TargetParser.def
  llvm/include/llvm/TargetParser/X86TargetParser.h
  llvm/lib/Target/X86/X86.td
  llvm/lib/TargetParser/X86TargetParser.cpp
  llvm/test/CodeGen/X86/cpus-intel.ll

Index: llvm/test/CodeGen/X86/cpus-intel.ll
===
--- llvm/test/CodeGen/X86/cpus-intel.ll
+++ llvm/test/CodeGen/X86/cpus-intel.ll
@@ -6,16 +6,24 @@
 ; RUN: llc < %s -o /dev/null -mtriple=i686-unknown-unknown -mcpu=i586 2>&1 | FileCheck %s --check-prefix=CHECK-NO-ERROR --allow-empty
 ; RUN: llc < %s -o /dev/null -mtriple=i686-unknown-unknown -mcpu=pentium 2>&1 | FileCheck %s --check-prefix=CHECK-NO-ERROR --allow-empty
 ; RUN: llc < %s -o /dev/null -mtriple=i686-unknown-unknown -mcpu=pentium-mmx 2>&1 | FileCheck %s --check-prefix=CHECK-NO-ERROR --allow-empty
+; RUN: llc < %s -o /dev/null -mtriple=i686-unknown-unknown -mcpu=pentium_mmx 2>&1 | FileCheck %s --check-prefix=CHECK-NO-ERROR --allow-empty
 ; RUN: llc < %s -o /dev/null -mtriple=i686-unknown-unknown -mcpu=i686 2>&1 | FileCheck %s --check-prefix=CHECK-NO-ERROR --allow-empty
 ; RUN: llc < %s -o /dev/null -mtriple=i686-unknown-unknown -mcpu=pentiumpro 2>&1 | FileCheck %s --check-prefix=CHECK-NO-ERROR --allow-empty
+; RUN: llc < %s -o /dev/null -mtriple=i686-unknown-unknown -mcpu=pentium_pro 2>&1 | FileCheck %s --check-prefix=CHECK-NO-ERROR --allow-empty
 ; RUN: llc < %s -o /dev/null -mtriple=i686-unknown-unknown -mcpu=pentium2 2>&1 | FileCheck %s --check-prefix=CHECK-NO-ERROR --allow-empty
+; RUN: llc < %s -o /dev/null -mtriple=i686-unknown-unknown -mcpu=pentium_ii 2>&1 | FileCheck %s --check-prefix=CHECK-NO-ERROR --allow-empty
 ; RUN: llc < %s -o /dev/null -mtriple=i686-unknown-unknown -mcpu=pentium3 2>&1 | FileCheck %s --check-prefix=CHECK-NO-ERROR --allow-empty
 ; RUN: llc < %s -o /dev/null -mtriple=i686-unknown-unknown -mcpu=pentium3m 2>&1 | FileCheck %s --check-prefix=CHECK-NO-ERROR --allow-empty
+; RUN: llc < %s -o /dev/null -mtriple=i686-unknown-unknown -mcpu=pentium_iii 2>&1 | FileCheck %s --check-prefix=CHECK-NO-ERROR --allow-empty
+; RUN: llc < %s -o /dev/null -mtriple=i686-unknown-unknown -mcpu=pentium_iii_no_xmm_regs 2>&1 | FileCheck %s --check-prefix=CHECK-NO-ERROR --allow-empty
+; RUN: llc < %s -o /dev/null -mtriple=i686-unknown-unknown -mcpu=pentium_m 2>&1 | FileCheck %s --check-prefix=CHECK-NO-ERROR --allow-empty
 ; RUN: llc < %s -o /dev/null -mtriple=i686-unknown-unknown -mcpu=pentium-m 2>&1 | FileCheck %s --check-prefix=CHECK-NO-ERROR --allow-empty
 ; RUN: llc < %s -o /dev/null -mtriple=i686-unknown-unknown -mcpu=pentium4 2>&1 | FileCheck %s --check-prefix=CHECK-NO-ERROR --allow-empty
 ; RUN: llc < %s -o /dev/null -mtriple=i686-unknown-unknown -mcpu=pentium4m 2>&1 | FileCheck %s --check-prefix=CHECK-NO-ERROR --allow-empty
+; RUN: llc < %s -o /dev/null -mtriple=i686-unknown-unknown -mcpu=pentium_4 2>&1 | FileCheck %s --check-prefix=CHECK-NO-ERROR --allow-empty
 ; RUN: llc < %s -o /dev/null -mtriple=i686-unknown-unknown -mcpu=yonah 2>&1 | FileCheck %s --check-prefix=CHECK-NO-ERROR --allow-empty
 ; RUN: llc < %s -o /dev/null -mtriple=i686-unknown-unknown -mcpu=prescott 2>&1 | FileCheck %s --check-prefix=CHECK-NO-ERROR --allow-empty
+; RUN: llc < %s -o /dev/null -mtriple=i686-unknown-unknown -mcpu=pentium_4_sse3 2>&1 | FileCheck %s --check-prefix=CHECK-NO-ERROR --allow-empty
 ; RUN: llc < %s -o /dev/null -mtriple=i686-unknown-unknown -mcpu=lakemont 2>&1 | FileCheck %s --check-prefix=CHECK-NO-ERROR --allow-empty
 ; RUN: llc < %s -o /dev/null -mtriple=i686-unknown-unknown -mcpu=raptorlake 2>&1 | FileCheck %s --check-prefix=CHECK-NO-ERROR --allow-empty
 ; RUN: llc < %s -o /dev/null -mtriple=i686-unknown-unknown -mcpu=meteorlake 2>&1 | FileCheck %s --check-prefix=CHECK-NO-ERROR --allow-empty
@@ -26,26 +34,39 @@
 
 ; RUN: llc < %s -o /dev/null -mtriple=x86_64-unknown-unknown -mcpu=nocona 2>&1 | FileCheck %s --check-prefix=CHECK-NO-ERROR --allow-empty
 ; RUN: llc < %s -o /dev/null -mtriple=x86_64-unknown-unknown -mcpu=core2 2>&1 | FileCheck %s --check-prefix=CHECK-NO-ERROR --allow-empty
+; RUN: llc < %s -o /dev/null -mtriple=x86_64-unknown-unknown -mcpu=core_2_duo_ssse3 2>&1 | FileCheck %s --check-prefix=CHECK-NO-ERROR --allow-empty
 ; RUN: llc < %s -o /dev/null -mtriple=x86_64-unknown-unknown -mcpu=penryn 2>&1 | FileCheck %s --check-prefix=CHECK-NO

[PATCH] D153882: [clangd] Always allow diagnostics from stale preambles

2023-06-28 Thread Haojian Wu via Phabricator via cfe-commits
hokein accepted this revision.
hokein added inline comments.
This revision is now accepted and ready to land.



Comment at: clang-tools-extra/clangd/ConfigYAML.cpp:137
 Dict.handle("ClangTidy", [&](Node &N) { parse(F.ClangTidy, N); });
-Dict.handle("AllowStalePreamble", [&](Node &N) {
-  F.AllowStalePreamble = boolValue(N, "AllowStalePreamble");

I wonder whether it is worth keeping this flag, but no-op (just emitting an 
warning message, this flag is no-op).

Probably not worth, since this flag was introduced recently, and it is not in 
any release.



Comment at: clang-tools-extra/clangd/ParsedAST.h:157
   std::vector Marks;
   // Data, stored after parsing. std::nullopt if AST was built with a stale
   // preamble.

nit: update the comment.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153882

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


[PATCH] D151696: [x86] Remove CPU_SPECIFIC* MACROs and add getCPUDispatchMangling

2023-06-28 Thread Freddy, Ye via Phabricator via cfe-commits
FreddyYe added a comment.

Notice that these two changes are both expected since a more complete feature 
list won't influence the _cpu_dispatch/specific multiversion to not work.




Comment at: clang/test/CodeGen/attr-cpuspecific.c:47
 // LINUX: %[[FEAT_INIT:.+]] = load i32, ptr getelementptr inbounds ({ i32, 
i32, i32, [1 x i32] }, ptr @__cpu_model, i32 0, i32 3, i32 0), align 4
-// LINUX: %[[FEAT_JOIN:.+]] = and i32 %[[FEAT_INIT]], 1023
-// LINUX: %[[FEAT_CHECK:.+]] = icmp eq i32 %[[FEAT_JOIN]], 1023
+// LINUX: %[[FEAT_JOIN:.+]] = and i32 %[[FEAT_INIT]], 525311
+// LINUX: %[[FEAT_CHECK:.+]] = icmp eq i32 %[[FEAT_JOIN]], 525311

This value change is because the feature list of ivybridge described in 
X86TargetParser.def before missed feature "pclmul".



Comment at: clang/test/CodeGen/attr-cpuspecific.c:56
 // WINDOWS: %[[FEAT_INIT:.+]] = load i32, ptr getelementptr inbounds ({ i32, 
i32, i32, [1 x i32] }, ptr @__cpu_model, i32 0, i32 3, i32 0), align 4
-// WINDOWS: %[[FEAT_JOIN:.+]] = and i32 %[[FEAT_INIT]], 1023
-// WINDOWS: %[[FEAT_CHECK:.+]] = icmp eq i32 %[[FEAT_JOIN]], 1023
+// WINDOWS: %[[FEAT_JOIN:.+]] = and i32 %[[FEAT_INIT]], 525311
+// WINDOWS: %[[FEAT_CHECK:.+]] = icmp eq i32 %[[FEAT_JOIN]], 525311

This value change is because the feature list of knl described in 
X86TargetParser.def before missed feature "bmi2" and "aes".


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151696

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


[PATCH] D153953: Revert "[AMDGPU] Mark mbcnt as convergent"

2023-06-28 Thread Sameer Sahasrabuddhe via Phabricator via cfe-commits
sameerds created this revision.
Herald added subscribers: kerbowa, tpr, dstuttard, yaxunl, jvesely, kzhuravl.
Herald added a project: All.
sameerds requested review of this revision.
Herald added subscribers: llvm-commits, cfe-commits, wdng.
Herald added projects: clang, LLVM.

This reverts commit 37114036aa57e53217a57afacd7f47b36114edfb 
.

The output of mbcnt does not depend on other active lanes, and hence it is not
convergent. The original change was made as a possible fix for

https://github.com/ROCm-Developer-Tools/HIP/issues/3172

But changing mbcnt does not fix that issue.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D153953

Files:
  clang/test/CodeGenOpenCL/builtins-amdgcn.cl
  llvm/include/llvm/IR/IntrinsicsAMDGPU.td


Index: llvm/include/llvm/IR/IntrinsicsAMDGPU.td
===
--- llvm/include/llvm/IR/IntrinsicsAMDGPU.td
+++ llvm/include/llvm/IR/IntrinsicsAMDGPU.td
@@ -1833,12 +1833,12 @@
 def int_amdgcn_mbcnt_lo :
   ClangBuiltin<"__builtin_amdgcn_mbcnt_lo">,
   DefaultAttrsIntrinsic<[llvm_i32_ty], [llvm_i32_ty, llvm_i32_ty],
-   [IntrNoMem, IntrConvergent]>;
+   [IntrNoMem]>;
 
 def int_amdgcn_mbcnt_hi :
   ClangBuiltin<"__builtin_amdgcn_mbcnt_hi">,
   DefaultAttrsIntrinsic<[llvm_i32_ty], [llvm_i32_ty, llvm_i32_ty],
-[IntrNoMem, IntrConvergent]>;
+[IntrNoMem]>;
 
 // llvm.amdgcn.ds.swizzle src offset
 def int_amdgcn_ds_swizzle :
Index: clang/test/CodeGenOpenCL/builtins-amdgcn.cl
===
--- clang/test/CodeGenOpenCL/builtins-amdgcn.cl
+++ clang/test/CodeGenOpenCL/builtins-amdgcn.cl
@@ -690,14 +690,12 @@
 
 // CHECK-LABEL: @test_mbcnt_lo(
 // CHECK: call i32 @llvm.amdgcn.mbcnt.lo(i32 %src0, i32 %src1)
-// CHECK: declare i32 @llvm.amdgcn.mbcnt.lo(i32, i32) #[[$MBCNT_ATTRS:[0-9]+]]
 kernel void test_mbcnt_lo(global uint* out, uint src0, uint src1) {
   *out = __builtin_amdgcn_mbcnt_lo(src0, src1);
 }
 
 // CHECK-LABEL: @test_mbcnt_hi(
 // CHECK: call i32 @llvm.amdgcn.mbcnt.hi(i32 %src0, i32 %src1)
-// CHECK: declare i32 @llvm.amdgcn.mbcnt.hi(i32, i32) #[[$MBCNT_ATTRS]]
 kernel void test_mbcnt_hi(global uint* out, uint src0, uint src1) {
   *out = __builtin_amdgcn_mbcnt_hi(src0, src1);
 }
@@ -834,7 +832,6 @@
 // CHECK-DAG: [[$WS_RANGE]] = !{i16 1, i16 1025}
 // CHECK-DAG: attributes #[[$NOUNWIND_READONLY]] = { mustprogress nocallback 
nofree nosync nounwind willreturn memory(read) }
 // CHECK-DAG: attributes #[[$READ_EXEC_ATTRS]] = { convergent }
-// CHECK-DAG: attributes #[[$MBCNT_ATTRS]] = {{.* convergent .*}}
 // CHECK-DAG: ![[$EXEC]] = !{!"exec"}
 // CHECK-DAG: ![[$EXEC_LO]] = !{!"exec_lo"}
 // CHECK-DAG: ![[$EXEC_HI]] = !{!"exec_hi"}


Index: llvm/include/llvm/IR/IntrinsicsAMDGPU.td
===
--- llvm/include/llvm/IR/IntrinsicsAMDGPU.td
+++ llvm/include/llvm/IR/IntrinsicsAMDGPU.td
@@ -1833,12 +1833,12 @@
 def int_amdgcn_mbcnt_lo :
   ClangBuiltin<"__builtin_amdgcn_mbcnt_lo">,
   DefaultAttrsIntrinsic<[llvm_i32_ty], [llvm_i32_ty, llvm_i32_ty],
-   [IntrNoMem, IntrConvergent]>;
+   [IntrNoMem]>;
 
 def int_amdgcn_mbcnt_hi :
   ClangBuiltin<"__builtin_amdgcn_mbcnt_hi">,
   DefaultAttrsIntrinsic<[llvm_i32_ty], [llvm_i32_ty, llvm_i32_ty],
-[IntrNoMem, IntrConvergent]>;
+[IntrNoMem]>;
 
 // llvm.amdgcn.ds.swizzle src offset
 def int_amdgcn_ds_swizzle :
Index: clang/test/CodeGenOpenCL/builtins-amdgcn.cl
===
--- clang/test/CodeGenOpenCL/builtins-amdgcn.cl
+++ clang/test/CodeGenOpenCL/builtins-amdgcn.cl
@@ -690,14 +690,12 @@
 
 // CHECK-LABEL: @test_mbcnt_lo(
 // CHECK: call i32 @llvm.amdgcn.mbcnt.lo(i32 %src0, i32 %src1)
-// CHECK: declare i32 @llvm.amdgcn.mbcnt.lo(i32, i32) #[[$MBCNT_ATTRS:[0-9]+]]
 kernel void test_mbcnt_lo(global uint* out, uint src0, uint src1) {
   *out = __builtin_amdgcn_mbcnt_lo(src0, src1);
 }
 
 // CHECK-LABEL: @test_mbcnt_hi(
 // CHECK: call i32 @llvm.amdgcn.mbcnt.hi(i32 %src0, i32 %src1)
-// CHECK: declare i32 @llvm.amdgcn.mbcnt.hi(i32, i32) #[[$MBCNT_ATTRS]]
 kernel void test_mbcnt_hi(global uint* out, uint src0, uint src1) {
   *out = __builtin_amdgcn_mbcnt_hi(src0, src1);
 }
@@ -834,7 +832,6 @@
 // CHECK-DAG: [[$WS_RANGE]] = !{i16 1, i16 1025}
 // CHECK-DAG: attributes #[[$NOUNWIND_READONLY]] = { mustprogress nocallback nofree nosync nounwind willreturn memory(read) }
 // CHECK-DAG: attributes #[[$READ_EXEC_ATTRS]] = { convergent }
-// CHECK-DAG: attributes #[[$MBCNT_ATTRS]] = {{.* convergent .*}}
 // CHECK-DAG: ![[$EXEC]] = !{!"exec"}
 // CHECK-DAG: ![[$EXEC_LO]] = !{!"exec_lo"}
 // CHECK-DAG: ![[$EXEC_HI]] = !{!"exec_hi"}
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D151315: [clangd] Add a switch to specify a default clangd configuration file

2023-06-28 Thread Thilo Vörtler via Phabricator via cfe-commits
voertler added a comment.

Ping!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151315

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


[PATCH] D153852: [clang][dataflow] Initialize fields of anonymous records correctly.

2023-06-28 Thread Martin Böhme via Phabricator via cfe-commits
mboehme updated this revision to Diff 535284.
mboehme added a comment.

Ensure we model a field of an anonymous record even if the only place it's used
is in an initializer.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153852

Files:
  clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
  clang/lib/Analysis/FlowSensitive/Transfer.cpp
  clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.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
@@ -5468,4 +5468,35 @@
   });
 }
 
+TEST(TransferTest, AnonymousStructWithInitializer) {
+  std::string Code = R"(
+struct target {
+  target() {
+(void)0;
+// [[p]]
+  }
+  struct {
+bool b = true;
+  };
+};
+  )";
+  runDataflow(
+  Code,
+  [](const llvm::StringMap> &Results,
+ ASTContext &ASTCtx) {
+const Environment &Env = getEnvironmentAtAnnotation(Results, "p");
+const ValueDecl *BDecl = findValueDecl(ASTCtx, "b");
+const IndirectFieldDecl *IndirectField =
+findIndirectFieldDecl(ASTCtx, "b");
+
+auto *ThisLoc =
+cast(Env.getThisPointeeStorageLocation());
+auto &AnonStruct = cast(ThisLoc->getChild(
+*cast(IndirectField->chain().front(;
+
+auto *B = cast(Env.getValue(AnonStruct.getChild(*BDecl)));
+ASSERT_TRUE(Env.flowConditionImplies(*B));
+  });
+}
+
 } // namespace
Index: clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
===
--- clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
+++ clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
@@ -332,27 +332,41 @@
   assert(Init != nullptr);
 
   auto &Env = InputState.Env;
-  const auto &ThisLoc =
+  auto &ThisLoc =
   *cast(Env.getThisPointeeStorageLocation());
 
-  const FieldDecl *Member = Init->getMember();
-  if (Member == nullptr)
-// Not a field initializer.
+  if (!Init->isAnyMemberInitializer())
+// FIXME: Handle base initialization
 return;
 
   auto *InitStmt = Init->getInit();
   assert(InitStmt != nullptr);
 
+  const FieldDecl *Member = nullptr;
+  StorageLocation *MemberLoc = nullptr;
+  if (Init->isMemberInitializer()) {
+Member = Init->getMember();
+MemberLoc = &ThisLoc.getChild(*Member);
+  } else {
+IndirectFieldDecl *IndirectField = Init->getIndirectMember();
+assert(IndirectField != nullptr);
+MemberLoc = &ThisLoc;
+for (const auto *I : IndirectField->chain()) {
+  Member = cast(I);
+  MemberLoc = &cast(MemberLoc)->getChild(*Member);
+}
+  }
+  assert(Member != nullptr);
+  assert(MemberLoc != nullptr);
+
   if (Member->getType()->isReferenceType()) {
 auto *InitStmtLoc = Env.getStorageLocationStrict(*InitStmt);
 if (InitStmtLoc == nullptr)
   return;
 
-auto &MemberLoc = ThisLoc.getChild(*Member);
-Env.setValue(MemberLoc, Env.create(*InitStmtLoc));
+Env.setValue(*MemberLoc, Env.create(*InitStmtLoc));
   } else if (auto *InitStmtVal = Env.getValueStrict(*InitStmt)) {
-auto &MemberLoc = ThisLoc.getChild(*Member);
-Env.setValue(MemberLoc, *InitStmtVal);
+Env.setValue(*MemberLoc, *InitStmtVal);
   }
 }
 
Index: clang/lib/Analysis/FlowSensitive/Transfer.cpp
===
--- clang/lib/Analysis/FlowSensitive/Transfer.cpp
+++ clang/lib/Analysis/FlowSensitive/Transfer.cpp
@@ -153,7 +153,7 @@
 Env.setStorageLocationStrict(To, *Loc);
 }
 
-// Forwards the value or storage location of `From` to `To` in cases where
+// Propagates the value or storage location of `From` to `To` in cases where
 // `From` may be either a glvalue or a prvalue. `To` must be a glvalue iff
 // `From` is a glvalue.
 static void propagateValueOrStorageLocation(const Expr &From, const Expr &To,
@@ -572,18 +572,7 @@
   void VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *S) {
 const Expr *InitExpr = S->getExpr();
 assert(InitExpr != nullptr);
-
-Value *InitExprVal = Env.getValue(*InitExpr, SkipPast::None);
-if (InitExprVal == nullptr)
-  return;
-
-const FieldDecl *Field = S->getField();
-assert(Field != nullptr);
-
-auto &ThisLoc =
-*cast(Env.getThisPointeeStorageLocation());
-auto &FieldLoc = ThisLoc.getChild(*Field);
-Env.setValue(FieldLoc, *InitExprVal);
+propagateValueOrStorageLocation(*InitExpr, *S, Env);
   }
 
   void VisitCXXConstructExpr(const CXXConstructExpr *S) {
Index: clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
===
--- clang/lib/An

[PATCH] D153852: [clang][dataflow] Initialize fields of anonymous records correctly.

2023-06-28 Thread Martin Böhme via Phabricator via cfe-commits
mboehme added a comment.

Pre-merge failure looks unrelated


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153852

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


[PATCH] D153882: [clangd] Always allow diagnostics from stale preambles

2023-06-28 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet marked an inline comment as done.
kadircet added inline comments.



Comment at: clang-tools-extra/clangd/ConfigYAML.cpp:137
 Dict.handle("ClangTidy", [&](Node &N) { parse(F.ClangTidy, N); });
-Dict.handle("AllowStalePreamble", [&](Node &N) {
-  F.AllowStalePreamble = boolValue(N, "AllowStalePreamble");

hokein wrote:
> I wonder whether it is worth keeping this flag, but no-op (just emitting an 
> warning message, this flag is no-op).
> 
> Probably not worth, since this flag was introduced recently, and it is not in 
> any release.
that's what happens to unrecognized config keys already. user will get a diag 
message when parsing their config that says `AllowStalePreamble` is not 
recognized.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153882

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


[PATCH] D153954: Relax alpha.cplusplusEnumCastOutOfRange This checker previously gave many false positives, because only the enum

2023-06-28 Thread Endre Fülöp via Phabricator via cfe-commits
gamesh411 created this revision.
Herald added subscribers: steakhal, martong, Szelethus, dkrupp.
Herald added a reviewer: Szelethus.
Herald added a reviewer: NoQ.
Herald added a project: All.
gamesh411 requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Modify EnumCastOutOfRange implementation


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D153954

Files:
  clang/lib/StaticAnalyzer/Checkers/EnumCastOutOfRangeChecker.cpp
  clang/test/Analysis/enum-cast-out-of-range.c
  clang/test/Analysis/enum-cast-out-of-range.cpp

Index: clang/test/Analysis/enum-cast-out-of-range.cpp
===
--- clang/test/Analysis/enum-cast-out-of-range.cpp
+++ clang/test/Analysis/enum-cast-out-of-range.cpp
@@ -2,199 +2,45 @@
 // RUN:   -analyzer-checker=core,alpha.cplusplus.EnumCastOutOfRange \
 // RUN:   -std=c++11 -verify %s
 
-enum unscoped_unspecified_t {
-  unscoped_unspecified_0 = -4,
-  unscoped_unspecified_1,
-  unscoped_unspecified_2 = 1,
-  unscoped_unspecified_3,
-  unscoped_unspecified_4 = 4
-};
+#define UINT_MAX (~0U)
+#define INT_MAX (int)(UINT_MAX & (UINT_MAX >> 1))
 
-enum unscoped_specified_t : int {
-  unscoped_specified_0 = -4,
-  unscoped_specified_1,
-  unscoped_specified_2 = 1,
-  unscoped_specified_3,
-  unscoped_specified_4 = 4
-};
+enum unscoped_specified_t : unsigned char;
 
-enum class scoped_unspecified_t {
-  scoped_unspecified_0 = -4,
-  scoped_unspecified_1,
-  scoped_unspecified_2 = 1,
-  scoped_unspecified_3,
-  scoped_unspecified_4 = 4
-};
-
-enum class scoped_specified_t : int {
-  scoped_specified_0 = -4,
-  scoped_specified_1,
-  scoped_specified_2 = 1,
-  scoped_specified_3,
-  scoped_specified_4 = 4
-};
-
-struct S {
-  unscoped_unspecified_t E : 5;
-};
-
-void unscopedUnspecified() {
-  unscoped_unspecified_t InvalidBeforeRangeBegin = static_cast(-5); // expected-warning {{The value provided to the cast expression is not in the valid range of values for the enum}}
-  unscoped_unspecified_t ValidNegativeValue1 = static_cast(-4); // OK.
-  unscoped_unspecified_t ValidNegativeValue2 = static_cast(-3); // OK.
-  unscoped_unspecified_t InvalidInsideRange1 = static_cast(-2); // expected-warning {{The value provided to the cast expression is not in the valid range of values for the enum}}
-  unscoped_unspecified_t InvalidInsideRange2 = static_cast(-1); // expected-warning {{The value provided to the cast expression is not in the valid range of values for the enum}}
-  unscoped_unspecified_t InvalidInsideRange3 = static_cast(0); // expected-warning {{The value provided to the cast expression is not in the valid range of values for the enum}}
-  unscoped_unspecified_t ValidPositiveValue1 = static_cast(1); // OK.
-  unscoped_unspecified_t ValidPositiveValue2 = static_cast(2); // OK.
-  unscoped_unspecified_t InvalidInsideRange4 = static_cast(3); // expected-warning {{The value provided to the cast expression is not in the valid range of values for the enum}}
-  unscoped_unspecified_t ValidPositiveValue3 = static_cast(4); // OK.
-  unscoped_unspecified_t InvalidAfterRangeEnd = static_cast(5); // expected-warning {{The value provided to the cast expression is not in the valid range of values for the enum}}
-}
+enum class scoped_specified_t : unsigned char;
 
 void unscopedSpecified() {
-  unscoped_specified_t InvalidBeforeRangeBegin = static_cast(-5); // expected-warning {{The value provided to the cast expression is not in the valid range of values for the enum}}
-  unscoped_specified_t ValidNegativeValue1 = static_cast(-4); // OK.
-  unscoped_specified_t ValidNegativeValue2 = static_cast(-3); // OK.
-  unscoped_specified_t InvalidInsideRange1 = static_cast(-2); // expected-warning {{The value provided to the cast expression is not in the valid range of values for the enum}}
-  unscoped_specified_t InvalidInsideRange2 = static_cast(-1); // expected-warning {{The value provided to the cast expression is not in the valid range of values for the enum}}
-  unscoped_specified_t InvalidInsideRange3 = static_cast(0); // expected-warning {{The value provided to the cast expression is not in the valid range of values for the enum}}
-  unscoped_specified_t ValidPositiveValue1 = static_cast(1); // OK.
-  unscoped_specified_t ValidPositiveValue2 = static_cast(2); // OK.
-  unscoped_specified_t InvalidInsideRange4 = static_cast(3); // expected-warning {{The value provided to the cast expression is not in the valid range of values for the enum}}
-  unscoped_specified_t ValidPositiveValue3 = static_cast(4); // OK.
-  unscoped_specified_t InvalidAfterRangeEnd = static_cast(5); // expected-warning {{The value provided to the cast expression is not in the valid range of values for the enum}}
-}
+  auto InvalidBeforeRangeBegin = static_cast(-1); // expected-warning {{The value provided to the cast expression is not in the valid range of values for the enum}}
+  auto Zero = static_cast(0); // OK.

[clang-tools-extra] bd89f9e - [clangd] Always allow diagnostics from stale preambles

2023-06-28 Thread Kadir Cetinkaya via cfe-commits

Author: Kadir Cetinkaya
Date: 2023-06-28T10:41:45+02:00
New Revision: bd89f9ec293ea5e20e89d4bce49135431239cf3e

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

LOG: [clangd] Always allow diagnostics from stale preambles

We've been running this internally for months now, without any
stability or correctness concerns. It has ~40% speed up on incremental
diagnostics latencies (as preamble can get invalidated through code completion
etc.).

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

Added: 


Modified: 
clang-tools-extra/clangd/ClangdLSPServer.cpp
clang-tools-extra/clangd/ClangdLSPServer.h
clang-tools-extra/clangd/ClangdServer.cpp
clang-tools-extra/clangd/ClangdServer.h
clang-tools-extra/clangd/Config.h
clang-tools-extra/clangd/ConfigCompile.cpp
clang-tools-extra/clangd/ConfigFragment.h
clang-tools-extra/clangd/ConfigYAML.cpp
clang-tools-extra/clangd/ParsedAST.cpp
clang-tools-extra/clangd/ParsedAST.h
clang-tools-extra/clangd/Preamble.cpp
clang-tools-extra/clangd/Preamble.h
clang-tools-extra/clangd/TUScheduler.cpp
clang-tools-extra/clangd/tool/Check.cpp
clang-tools-extra/clangd/unittests/ClangdTests.cpp
clang-tools-extra/clangd/unittests/ConfigCompileTests.cpp
clang-tools-extra/clangd/unittests/ConfigYAMLTests.cpp
clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
clang-tools-extra/clangd/unittests/FeatureModulesTests.cpp
clang-tools-extra/clangd/unittests/ModulesTests.cpp
clang-tools-extra/clangd/unittests/ParsedASTTests.cpp
clang-tools-extra/clangd/unittests/PreambleTests.cpp
clang-tools-extra/clangd/unittests/SelectionTests.cpp
clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
clang-tools-extra/clangd/unittests/TestTU.cpp
clang-tools-extra/clangd/unittests/TypeHierarchyTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/ClangdLSPServer.cpp 
b/clang-tools-extra/clangd/ClangdLSPServer.cpp
index 396b903a9a762..bf4c1a982834b 100644
--- a/clang-tools-extra/clangd/ClangdLSPServer.cpp
+++ b/clang-tools-extra/clangd/ClangdLSPServer.cpp
@@ -650,7 +650,6 @@ void ClangdLSPServer::onInitialize(const InitializeParams 
&Params,
  CodeAction::INFO_KIND}}}
   : llvm::json::Value(true);
 
-
   std::vector Commands;
   for (llvm::StringRef Command : Handlers.CommandHandlers.keys())
 Commands.push_back(Command);
@@ -1744,7 +1743,7 @@ bool ClangdLSPServer::shouldRunCompletion(
 }
 
 void ClangdLSPServer::onDiagnosticsReady(PathRef File, llvm::StringRef Version,
- std::vector Diagnostics) {
+ llvm::ArrayRef Diagnostics) {
   PublishDiagnosticsParams Notification;
   Notification.version = decodeVersion(Version);
   Notification.uri = URIForFile::canonicalize(File, /*TUPath=*/File);

diff  --git a/clang-tools-extra/clangd/ClangdLSPServer.h 
b/clang-tools-extra/clangd/ClangdLSPServer.h
index a483d1110f64c..6cf1db4306324 100644
--- a/clang-tools-extra/clangd/ClangdLSPServer.h
+++ b/clang-tools-extra/clangd/ClangdLSPServer.h
@@ -10,6 +10,7 @@
 #define LLVM_CLANG_TOOLS_EXTRA_CLANGD_CLANGDLSPSERVER_H
 
 #include "ClangdServer.h"
+#include "Diagnostics.h"
 #include "GlobalCompilationDatabase.h"
 #include "LSPBinder.h"
 #include "Protocol.h"
@@ -18,6 +19,7 @@
 #include "support/MemoryTree.h"
 #include "support/Path.h"
 #include "support/Threading.h"
+#include "llvm/ADT/ArrayRef.h"
 #include "llvm/Support/JSON.h"
 #include 
 #include 
@@ -80,7 +82,7 @@ class ClangdLSPServer : private ClangdServer::Callbacks,
 private:
   // Implement ClangdServer::Callbacks.
   void onDiagnosticsReady(PathRef File, llvm::StringRef Version,
-  std::vector Diagnostics) override;
+  llvm::ArrayRef Diagnostics) override;
   void onFileUpdated(PathRef File, const TUStatus &Status) override;
   void onBackgroundIndexProgress(const BackgroundQueue::Stats &Stats) override;
   void onSemanticsMaybeChanged(PathRef File) override;
@@ -197,7 +199,6 @@ class ClangdLSPServer : private ClangdServer::Callbacks,
   void bindMethods(LSPBinder &, const ClientCapabilities &Caps);
   std::vector getFixes(StringRef File, const clangd::Diagnostic 
&D);
 
-
   /// Checks if completion request should be ignored. We need this due to the
   /// limitation of the LSP. Per LSP, a client sends requests for all "trigger
   /// character" we specify, but for '>' and ':' we need to check they actually

diff  --git a/clang-tools-extra/clangd/ClangdServer.cpp 
b/clang-tools-extra/clangd/ClangdServer.cpp
index 7b4224a20cec3..d8df4c6a69910 100644
--- a/clang-tools-extra/clangd/ClangdServer.cpp
+++ b/clang-tools-extra/clangd/ClangdServer.cpp
@@ -124,13 +124,

[PATCH] D153882: [clangd] Always allow diagnostics from stale preambles

2023-06-28 Thread Kadir Cetinkaya via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
kadircet marked an inline comment as done.
Closed by commit rGbd89f9ec293e: [clangd] Always allow diagnostics from stale 
preambles (authored by kadircet).

Changed prior to commit:
  https://reviews.llvm.org/D153882?vs=534995&id=535287#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153882

Files:
  clang-tools-extra/clangd/ClangdLSPServer.cpp
  clang-tools-extra/clangd/ClangdLSPServer.h
  clang-tools-extra/clangd/ClangdServer.cpp
  clang-tools-extra/clangd/ClangdServer.h
  clang-tools-extra/clangd/Config.h
  clang-tools-extra/clangd/ConfigCompile.cpp
  clang-tools-extra/clangd/ConfigFragment.h
  clang-tools-extra/clangd/ConfigYAML.cpp
  clang-tools-extra/clangd/ParsedAST.cpp
  clang-tools-extra/clangd/ParsedAST.h
  clang-tools-extra/clangd/Preamble.cpp
  clang-tools-extra/clangd/Preamble.h
  clang-tools-extra/clangd/TUScheduler.cpp
  clang-tools-extra/clangd/tool/Check.cpp
  clang-tools-extra/clangd/unittests/ClangdTests.cpp
  clang-tools-extra/clangd/unittests/ConfigCompileTests.cpp
  clang-tools-extra/clangd/unittests/ConfigYAMLTests.cpp
  clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
  clang-tools-extra/clangd/unittests/FeatureModulesTests.cpp
  clang-tools-extra/clangd/unittests/ModulesTests.cpp
  clang-tools-extra/clangd/unittests/ParsedASTTests.cpp
  clang-tools-extra/clangd/unittests/PreambleTests.cpp
  clang-tools-extra/clangd/unittests/SelectionTests.cpp
  clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
  clang-tools-extra/clangd/unittests/TestTU.cpp
  clang-tools-extra/clangd/unittests/TypeHierarchyTests.cpp

Index: clang-tools-extra/clangd/unittests/TypeHierarchyTests.cpp
===
--- clang-tools-extra/clangd/unittests/TypeHierarchyTests.cpp
+++ clang-tools-extra/clangd/unittests/TypeHierarchyTests.cpp
@@ -402,7 +402,7 @@
 
   // The compiler should produce a diagnostic for hitting the
   // template instantiation depth.
-  ASSERT_TRUE(!AST.getDiagnostics()->empty());
+  ASSERT_FALSE(AST.getDiagnostics().empty());
 
   // Make sure getTypeHierarchy() doesn't get into an infinite recursion.
   // The parent is reported as "S" because "S<0>" is an invalid instantiation.
Index: clang-tools-extra/clangd/unittests/TestTU.cpp
===
--- clang-tools-extra/clangd/unittests/TestTU.cpp
+++ clang-tools-extra/clangd/unittests/TestTU.cpp
@@ -132,8 +132,6 @@
 llvm::errs() << "Failed to build code:\n" << Code;
 std::abort();
   }
-  assert(AST->getDiagnostics() &&
- "TestTU should always build an AST with a fresh Preamble");
   // Check for error diagnostics and report gtest failures (unless expected).
   // This guards against accidental syntax errors silently subverting tests.
   // error-ok is awfully primitive - using clang -verify would be nicer.
@@ -150,7 +148,7 @@
   }();
   if (!ErrorOk) {
 // We always build AST with a fresh preamble in TestTU.
-for (const auto &D : *AST->getDiagnostics())
+for (const auto &D : AST->getDiagnostics())
   if (D.Severity >= DiagnosticsEngine::Error) {
 llvm::errs()
 << "TestTU failed to build (suppress with /*error-ok*/): \n"
Index: clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
===
--- clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
+++ clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
@@ -126,7 +126,7 @@
 class CaptureDiags : public ParsingCallbacks {
 public:
   void onMainAST(PathRef File, ParsedAST &AST, PublishFn Publish) override {
-reportDiagnostics(File, *AST.getDiagnostics(), Publish);
+reportDiagnostics(File, AST.getDiagnostics(), Publish);
   }
 
   void onFailedAST(PathRef File, llvm::StringRef Version,
@@ -141,9 +141,8 @@
 if (!D)
   return;
 Publish([&]() {
-  const_cast<
-  llvm::unique_function)> &> (*D)(
-  File, std::move(Diags));
+  const_cast)> &>(
+  *D)(File, Diags);
 });
   }
 };
@@ -230,20 +229,24 @@
 Notification Ready;
 TUScheduler S(CDB, optsForTest(), captureDiags());
 auto Path = testPath("foo.cpp");
-updateWithDiags(S, Path, "", WantDiagnostics::Yes,
+// Semicolons here and in the following inputs are significant. They ensure
+// preamble stays the same across runs. Otherwise we might get multiple
+// diagnostics callbacks, once with the stale preamble and another with the
+// fresh preamble.
+updateWithDiags(S, Path, ";", WantDiagnostics::Yes,
 [&](std::vector) { Ready.wait(); });
-updateWithDiags(S, Path, "request diags", WantDiagnostics::Yes,
+updateWithDiags(S, Path, ";request diags", WantDiagnostics::Yes,

[PATCH] D153556: [OPENMP52] Initial support for doacross clause.

2023-06-28 Thread Jennifer Yu via Phabricator via cfe-commits
jyu2 updated this revision to Diff 535289.
jyu2 added a comment.

Thanks Alex for the review.  This is to address his comments.


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

https://reviews.llvm.org/D153556

Files:
  clang/include/clang/AST/OpenMPClause.h
  clang/include/clang/AST/RecursiveASTVisitor.h
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Basic/OpenMPKinds.def
  clang/include/clang/Basic/OpenMPKinds.h
  clang/include/clang/Sema/Sema.h
  clang/lib/AST/OpenMPClause.cpp
  clang/lib/AST/StmtProfile.cpp
  clang/lib/Basic/OpenMPKinds.cpp
  clang/lib/Parse/ParseOpenMP.cpp
  clang/lib/Sema/SemaOpenMP.cpp
  clang/lib/Sema/TreeTransform.h
  clang/lib/Serialization/ASTReader.cpp
  clang/lib/Serialization/ASTWriter.cpp
  clang/test/OpenMP/ordered_ast_print.cpp
  clang/test/OpenMP/ordered_messages.cpp
  clang/tools/libclang/CIndex.cpp
  flang/lib/Semantics/check-omp-structure.cpp
  llvm/include/llvm/Frontend/OpenMP/OMP.td

Index: llvm/include/llvm/Frontend/OpenMP/OMP.td
===
--- llvm/include/llvm/Frontend/OpenMP/OMP.td
+++ llvm/include/llvm/Frontend/OpenMP/OMP.td
@@ -444,6 +444,10 @@
   let flangClass = "ScalarIntExpr";
 }
 
+def OMPC_Doacross : Clause<"doacross"> {
+  let clangClass = "OMPDoacrossClause";
+}
+
 //===--===//
 // Definition of OpenMP directives
 //===--===//
@@ -604,7 +608,8 @@
 }
 def OMP_Ordered : Directive<"ordered"> {
   let allowedClauses = [
-VersionedClause
+VersionedClause,
+VersionedClause
   ];
   let allowedOnceClauses = [
 VersionedClause,
Index: flang/lib/Semantics/check-omp-structure.cpp
===
--- flang/lib/Semantics/check-omp-structure.cpp
+++ flang/lib/Semantics/check-omp-structure.cpp
@@ -1937,6 +1937,7 @@
 CHECK_SIMPLE_CLAUSE(Align, OMPC_align)
 CHECK_SIMPLE_CLAUSE(Compare, OMPC_compare)
 CHECK_SIMPLE_CLAUSE(CancellationConstructType, OMPC_cancellation_construct_type)
+CHECK_SIMPLE_CLAUSE(Doacross, OMPC_doacross)
 
 CHECK_REQ_SCALAR_INT_CLAUSE(Grainsize, OMPC_grainsize)
 CHECK_REQ_SCALAR_INT_CLAUSE(NumTasks, OMPC_num_tasks)
Index: clang/tools/libclang/CIndex.cpp
===
--- clang/tools/libclang/CIndex.cpp
+++ clang/tools/libclang/CIndex.cpp
@@ -2717,6 +2717,9 @@
   VisitOMPClauseWithPreInit(C);
   Visitor->AddStmt(C->getSize());
 }
+void OMPClauseEnqueue::VisitOMPDoacrossClause(const OMPDoacrossClause *C) {
+  VisitOMPClauseList(C);
+}
 
 } // namespace
 
Index: clang/test/OpenMP/ordered_messages.cpp
===
--- clang/test/OpenMP/ordered_messages.cpp
+++ clang/test/OpenMP/ordered_messages.cpp
@@ -1,6 +1,7 @@
 // RUN: %clang_cc1 -verify -fopenmp -ferror-limit 100 -o - %s -Wuninitialized
 // RUN: %clang_cc1 -verify -fopenmp -ferror-limit 100 -std=c++98 -o - %s -Wuninitialized
 // RUN: %clang_cc1 -verify -fopenmp -ferror-limit 100 -std=c++11 -o - %s -Wuninitialized
+// RUN: %clang_cc1 -verify=expected,omp52 -fopenmp -fopenmp-version=52 -ferror-limit 100 -o - %s -Wuninitialized
 
 // RUN: %clang_cc1 -verify -fopenmp-simd -ferror-limit 100 -o - %s -Wuninitialized
 // RUN: %clang_cc1 -verify -fopenmp-simd -ferror-limit 100 -std=c++98 -o - %s -Wuninitialized
@@ -135,12 +136,48 @@
   }
 #pragma omp parallel for ordered
   for (int i = 0; i < 10; ++i) {
+#if _OPENMP >= 202111
+#pragma omp ordered doacross(source:) // omp52-error {{'ordered' directive with 'doacross' clause cannot be closely nested inside ordered region without specified parameter}}
+#pragma omp ordered doacross(sink : i) // omp52-error {{'ordered' directive with 'doacross' clause cannot be closely nested inside ordered region without specified parameter}}
+#else
 #pragma omp ordered depend(source) // expected-error {{'ordered' directive with 'depend' clause cannot be closely nested inside ordered region without specified parameter}}
 #pragma omp ordered depend(sink : i) // expected-error {{'ordered' directive with 'depend' clause cannot be closely nested inside ordered region without specified parameter}}
+#endif
   }
 #pragma omp parallel for ordered(2) // expected-note 3 {{'ordered' clause with specified parameter}}
   for (int i = 0; i < 10; ++i) {
 for (int j = 0; j < 10; ++j) {
+#if _OPENMP >= 202111
+#pragma omp ordered doacross // omp52-error {{expected '(' after 'doacross'}} omp52-error {{'ordered' directive without any clauses cannot be closely nested inside ordered region with specified parameter}}
+#pragma omp ordered doacross( // omp52-error {{expected ')'}} omp52-error {{expected 'source' or 'sink' in OpenMP clause 'doacross'}} omp52-error {{'ordered' directive without any clauses cannot be closely nested inside ordered region with specified parame

[PATCH] D153556: [OPENMP52] Initial support for doacross clause.

2023-06-28 Thread Jennifer Yu via Phabricator via cfe-commits
jyu2 added a comment.

Thanks Alexey for the review.




Comment at: clang/lib/Parse/ParseOpenMP.cpp:4415-4439
+  } else if (Kind == OMPC_doacross) {
+// Handle dependence type for the doacross clause.
+ColonProtectionRAIIObject ColonRAII(*this);
+Data.ExtraModifier = getOpenMPSimpleClauseType(
+Kind, Tok.is(tok::identifier) ? PP.getSpelling(Tok) : "",
+getLangOpts());
+Data.ExtraModifierLoc = Tok.getLocation();

ABataev wrote:
> Can it be unified with depenbd clause parsing? (Maybe in a separate template 
> function)
I don't really has an idea on how to combine this two with template function.  
Since depend clause in ordered is deprecated in 52, and will be removed, should 
we leave as this?



Comment at: clang/lib/Sema/SemaOpenMP.cpp:91
   llvm::SmallVector, 4>;
-  using DoacrossDependMapTy =
-  llvm::DenseMap;
+  using DoacrossDependMapTy = llvm::DenseMap;
   /// Kind of the declaration used in the uses_allocators clauses.

ABataev wrote:
> DoacrossClauseMapTy? Since it is intended to handle also doacross clauses.
Changed.  Thanks.



Comment at: clang/lib/Sema/SemaOpenMP.cpp:11299-11344
   if (DC->getDependencyKind() == OMPC_DEPEND_source) {
 if (DependSourceClause) {
   Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
   << getOpenMPDirectiveName(OMPD_ordered)
   << getOpenMPClauseName(OMPC_depend) << 2;
   ErrorFound = true;
 } else {

ABataev wrote:
> Try to avoid copy-paste. Maybe introduce templated function?
Not sure how to do this part.



Comment at: clang/lib/Sema/SemaOpenMP.cpp:11359-11371
+  } else if ((DependFound || DoacrossFound) && (TC || SC)) {
+SourceLocation Loc =
+DependFound ? DependFound->getBeginLoc() : 
DoacrossFound->getBeginLoc();
+Diag(Loc, diag::err_omp_depend_clause_thread_simd)
+<< getOpenMPClauseName(DependFound ? OMPC_depend : OMPC_doacross)
 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
 ErrorFound = true;

ABataev wrote:
> Same, try to avoid copy-paste
The code is for both Depend and Doacross with is really try to avoid copy-paste.



Comment at: clang/lib/Sema/SemaOpenMP.cpp:24002
+
+OMPClause *Sema::ActOnOpenMPDoacrossClause(
+OpenMPDoacrossClauseModifier DepType, SourceLocation DepLoc,

ABataev wrote:
> Same, if possible try to unify handling with the depend clause, if possible
ActOnOpenMPDoacrossClauseCommon is added which called in 
ActOnOpenMPDependClause
and
ActOnOpenMPDoacrossClause



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

https://reviews.llvm.org/D153556

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


[clang] d04b198 - [clang][dataflow] Add a test that we can access fields of anonymous records.

2023-06-28 Thread Martin Braenne via cfe-commits

Author: Martin Braenne
Date: 2023-06-28T09:12:03Z
New Revision: d04b198973c9bda2376209b460943ac393190752

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

LOG: [clang][dataflow] Add a test that we can access fields of anonymous 
records.

Reviewed By: sammccall, ymandel, gribozavr2, xazax.hun

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

Added: 


Modified: 
clang/unittests/Analysis/FlowSensitive/TestingSupport.cpp
clang/unittests/Analysis/FlowSensitive/TestingSupport.h
clang/unittests/Analysis/FlowSensitive/TransferTest.cpp

Removed: 




diff  --git a/clang/unittests/Analysis/FlowSensitive/TestingSupport.cpp 
b/clang/unittests/Analysis/FlowSensitive/TestingSupport.cpp
index 0d441b71e69c6..a88b8d88c74c0 100644
--- a/clang/unittests/Analysis/FlowSensitive/TestingSupport.cpp
+++ b/clang/unittests/Analysis/FlowSensitive/TestingSupport.cpp
@@ -154,9 +154,19 @@ test::buildStatementToAnnotationMapping(const FunctionDecl 
*Func,
 }
 
 const ValueDecl *test::findValueDecl(ASTContext &ASTCtx, llvm::StringRef Name) 
{
-  auto TargetNodes = match(valueDecl(hasName(Name)).bind("v"), ASTCtx);
+  auto TargetNodes = match(
+  valueDecl(unless(indirectFieldDecl()), hasName(Name)).bind("v"), ASTCtx);
   assert(TargetNodes.size() == 1 && "Name must be unique");
   auto *const Result = selectFirst("v", TargetNodes);
   assert(Result != nullptr);
   return Result;
 }
+
+const IndirectFieldDecl *test::findIndirectFieldDecl(ASTContext &ASTCtx,
+ llvm::StringRef Name) {
+  auto TargetNodes = match(indirectFieldDecl(hasName(Name)).bind("i"), ASTCtx);
+  assert(TargetNodes.size() == 1 && "Name must be unique");
+  const auto *Result = selectFirst("i", TargetNodes);
+  assert(Result != nullptr);
+  return Result;
+}

diff  --git a/clang/unittests/Analysis/FlowSensitive/TestingSupport.h 
b/clang/unittests/Analysis/FlowSensitive/TestingSupport.h
index e22600d7b2e44..856737d034855 100644
--- a/clang/unittests/Analysis/FlowSensitive/TestingSupport.h
+++ b/clang/unittests/Analysis/FlowSensitive/TestingSupport.h
@@ -428,6 +428,14 @@ runDataflowReturnError(llvm::StringRef Code, 
VerifyResultsT VerifyResults,
 ///   `Name` must be unique in `ASTCtx`.
 const ValueDecl *findValueDecl(ASTContext &ASTCtx, llvm::StringRef Name);
 
+/// Returns the `IndirectFieldDecl` for the given identifier.
+///
+/// Requirements:
+///
+///   `Name` must be unique in `ASTCtx`.
+const IndirectFieldDecl *findIndirectFieldDecl(ASTContext &ASTCtx,
+   llvm::StringRef Name);
+
 /// Returns the storage location (of type `LocT`) for the given identifier.
 /// `LocT` must be a subclass of `StorageLocation` and must be of the
 /// appropriate type.

diff  --git a/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp 
b/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
index 5e7abcc6ce750..51550adeea894 100644
--- a/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
+++ b/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
@@ -5434,4 +5434,38 @@ TEST(TransferTest, BuiltinFunctionModeled) {
   });
 }
 
+// Check that fields of anonymous records are modeled.
+TEST(TransferTest, AnonymousStruct) {
+  std::string Code = R"(
+struct S {
+  struct {
+bool b;
+  };
+};
+void target() {
+  S s;
+  s.b = true;
+  // [[p]]
+}
+  )";
+  runDataflow(
+  Code,
+  [](const llvm::StringMap> &Results,
+ ASTContext &ASTCtx) {
+const Environment &Env = getEnvironmentAtAnnotation(Results, "p");
+const ValueDecl *SDecl = findValueDecl(ASTCtx, "s");
+const ValueDecl *BDecl = findValueDecl(ASTCtx, "b");
+const IndirectFieldDecl *IndirectField =
+findIndirectFieldDecl(ASTCtx, "b");
+
+auto *S =
+cast(Env.getStorageLocation(*SDecl));
+auto &AnonStruct = cast(
+S->getChild(*cast(IndirectField->chain().front(;
+
+auto *B = cast(Env.getValue(AnonStruct.getChild(*BDecl)));
+ASSERT_TRUE(Env.flowConditionImplies(*B));
+  });
+}
+
 } // namespace



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


[clang] 834a84d - [clang][dataflow] Output debug info if `getChild()` doesn't find field.

2023-06-28 Thread Martin Braenne via cfe-commits

Author: Martin Braenne
Date: 2023-06-28T09:12:08Z
New Revision: 834a84d091ab7d196e966d8f08101136eb1c1e06

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

LOG: [clang][dataflow] Output debug info if `getChild()` doesn't find field.

Depends On D153409

Reviewed By: xazax.hun

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

Added: 


Modified: 
clang/include/clang/Analysis/FlowSensitive/StorageLocation.h

Removed: 




diff  --git a/clang/include/clang/Analysis/FlowSensitive/StorageLocation.h 
b/clang/include/clang/Analysis/FlowSensitive/StorageLocation.h
index 58ebb9bf52586..453f1e13362b7 100644
--- a/clang/include/clang/Analysis/FlowSensitive/StorageLocation.h
+++ b/clang/include/clang/Analysis/FlowSensitive/StorageLocation.h
@@ -17,6 +17,9 @@
 #include "clang/AST/Decl.h"
 #include "clang/AST/Type.h"
 #include "llvm/ADT/DenseMap.h"
+#include "llvm/Support/Debug.h"
+
+#define DEBUG_TYPE "dataflow"
 
 namespace clang {
 namespace dataflow {
@@ -85,6 +88,17 @@ class AggregateStorageLocation final : public 
StorageLocation {
   /// Returns the child storage location for `D`.
   StorageLocation &getChild(const ValueDecl &D) const {
 auto It = Children.find(&D);
+LLVM_DEBUG({
+  if (It == Children.end()) {
+llvm::dbgs() << "Couldn't find child " << D.getNameAsString()
+ << " on StorageLocation " << this << " of type "
+ << getType() << "\n";
+llvm::dbgs() << "Existing children:\n";
+for ([[maybe_unused]] auto [Field, Loc] : Children) {
+  llvm::dbgs() << Field->getNameAsString() << "\n";
+}
+  }
+});
 assert(It != Children.end());
 return *It->second;
   }
@@ -100,4 +114,6 @@ class AggregateStorageLocation final : public 
StorageLocation {
 } // namespace dataflow
 } // namespace clang
 
+#undef DEBUG_TYPE
+
 #endif // LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_STORAGELOCATION_H



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


[PATCH] D153851: [clang][dataflow] Output debug info if `getChild()` doesn't find field.

2023-06-28 Thread Martin Böhme 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 rG834a84d091ab: [clang][dataflow] Output debug info if 
`getChild()` doesn't find field. (authored by mboehme).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153851

Files:
  clang/include/clang/Analysis/FlowSensitive/StorageLocation.h


Index: clang/include/clang/Analysis/FlowSensitive/StorageLocation.h
===
--- clang/include/clang/Analysis/FlowSensitive/StorageLocation.h
+++ clang/include/clang/Analysis/FlowSensitive/StorageLocation.h
@@ -17,6 +17,9 @@
 #include "clang/AST/Decl.h"
 #include "clang/AST/Type.h"
 #include "llvm/ADT/DenseMap.h"
+#include "llvm/Support/Debug.h"
+
+#define DEBUG_TYPE "dataflow"
 
 namespace clang {
 namespace dataflow {
@@ -85,6 +88,17 @@
   /// Returns the child storage location for `D`.
   StorageLocation &getChild(const ValueDecl &D) const {
 auto It = Children.find(&D);
+LLVM_DEBUG({
+  if (It == Children.end()) {
+llvm::dbgs() << "Couldn't find child " << D.getNameAsString()
+ << " on StorageLocation " << this << " of type "
+ << getType() << "\n";
+llvm::dbgs() << "Existing children:\n";
+for ([[maybe_unused]] auto [Field, Loc] : Children) {
+  llvm::dbgs() << Field->getNameAsString() << "\n";
+}
+  }
+});
 assert(It != Children.end());
 return *It->second;
   }
@@ -100,4 +114,6 @@
 } // namespace dataflow
 } // namespace clang
 
+#undef DEBUG_TYPE
+
 #endif // LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_STORAGELOCATION_H


Index: clang/include/clang/Analysis/FlowSensitive/StorageLocation.h
===
--- clang/include/clang/Analysis/FlowSensitive/StorageLocation.h
+++ clang/include/clang/Analysis/FlowSensitive/StorageLocation.h
@@ -17,6 +17,9 @@
 #include "clang/AST/Decl.h"
 #include "clang/AST/Type.h"
 #include "llvm/ADT/DenseMap.h"
+#include "llvm/Support/Debug.h"
+
+#define DEBUG_TYPE "dataflow"
 
 namespace clang {
 namespace dataflow {
@@ -85,6 +88,17 @@
   /// Returns the child storage location for `D`.
   StorageLocation &getChild(const ValueDecl &D) const {
 auto It = Children.find(&D);
+LLVM_DEBUG({
+  if (It == Children.end()) {
+llvm::dbgs() << "Couldn't find child " << D.getNameAsString()
+ << " on StorageLocation " << this << " of type "
+ << getType() << "\n";
+llvm::dbgs() << "Existing children:\n";
+for ([[maybe_unused]] auto [Field, Loc] : Children) {
+  llvm::dbgs() << Field->getNameAsString() << "\n";
+}
+  }
+});
 assert(It != Children.end());
 return *It->second;
   }
@@ -100,4 +114,6 @@
 } // namespace dataflow
 } // namespace clang
 
+#undef DEBUG_TYPE
+
 #endif // LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_STORAGELOCATION_H
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D153409: [clang][dataflow] Add a test that we can access fields of anonymous records.

2023-06-28 Thread Martin Böhme 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 rGd04b198973c9: [clang][dataflow] Add a test that we can 
access fields of anonymous records. (authored by mboehme).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153409

Files:
  clang/unittests/Analysis/FlowSensitive/TestingSupport.cpp
  clang/unittests/Analysis/FlowSensitive/TestingSupport.h
  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
@@ -5434,4 +5434,38 @@
   });
 }
 
+// Check that fields of anonymous records are modeled.
+TEST(TransferTest, AnonymousStruct) {
+  std::string Code = R"(
+struct S {
+  struct {
+bool b;
+  };
+};
+void target() {
+  S s;
+  s.b = true;
+  // [[p]]
+}
+  )";
+  runDataflow(
+  Code,
+  [](const llvm::StringMap> &Results,
+ ASTContext &ASTCtx) {
+const Environment &Env = getEnvironmentAtAnnotation(Results, "p");
+const ValueDecl *SDecl = findValueDecl(ASTCtx, "s");
+const ValueDecl *BDecl = findValueDecl(ASTCtx, "b");
+const IndirectFieldDecl *IndirectField =
+findIndirectFieldDecl(ASTCtx, "b");
+
+auto *S =
+cast(Env.getStorageLocation(*SDecl));
+auto &AnonStruct = cast(
+S->getChild(*cast(IndirectField->chain().front(;
+
+auto *B = cast(Env.getValue(AnonStruct.getChild(*BDecl)));
+ASSERT_TRUE(Env.flowConditionImplies(*B));
+  });
+}
+
 } // namespace
Index: clang/unittests/Analysis/FlowSensitive/TestingSupport.h
===
--- clang/unittests/Analysis/FlowSensitive/TestingSupport.h
+++ clang/unittests/Analysis/FlowSensitive/TestingSupport.h
@@ -428,6 +428,14 @@
 ///   `Name` must be unique in `ASTCtx`.
 const ValueDecl *findValueDecl(ASTContext &ASTCtx, llvm::StringRef Name);
 
+/// Returns the `IndirectFieldDecl` for the given identifier.
+///
+/// Requirements:
+///
+///   `Name` must be unique in `ASTCtx`.
+const IndirectFieldDecl *findIndirectFieldDecl(ASTContext &ASTCtx,
+   llvm::StringRef Name);
+
 /// Returns the storage location (of type `LocT`) for the given identifier.
 /// `LocT` must be a subclass of `StorageLocation` and must be of the
 /// appropriate type.
Index: clang/unittests/Analysis/FlowSensitive/TestingSupport.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TestingSupport.cpp
+++ clang/unittests/Analysis/FlowSensitive/TestingSupport.cpp
@@ -154,9 +154,19 @@
 }
 
 const ValueDecl *test::findValueDecl(ASTContext &ASTCtx, llvm::StringRef Name) 
{
-  auto TargetNodes = match(valueDecl(hasName(Name)).bind("v"), ASTCtx);
+  auto TargetNodes = match(
+  valueDecl(unless(indirectFieldDecl()), hasName(Name)).bind("v"), ASTCtx);
   assert(TargetNodes.size() == 1 && "Name must be unique");
   auto *const Result = selectFirst("v", TargetNodes);
   assert(Result != nullptr);
   return Result;
 }
+
+const IndirectFieldDecl *test::findIndirectFieldDecl(ASTContext &ASTCtx,
+ llvm::StringRef Name) {
+  auto TargetNodes = match(indirectFieldDecl(hasName(Name)).bind("i"), ASTCtx);
+  assert(TargetNodes.size() == 1 && "Name must be unique");
+  const auto *Result = selectFirst("i", TargetNodes);
+  assert(Result != nullptr);
+  return Result;
+}


Index: clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
@@ -5434,4 +5434,38 @@
   });
 }
 
+// Check that fields of anonymous records are modeled.
+TEST(TransferTest, AnonymousStruct) {
+  std::string Code = R"(
+struct S {
+  struct {
+bool b;
+  };
+};
+void target() {
+  S s;
+  s.b = true;
+  // [[p]]
+}
+  )";
+  runDataflow(
+  Code,
+  [](const llvm::StringMap> &Results,
+ ASTContext &ASTCtx) {
+const Environment &Env = getEnvironmentAtAnnotation(Results, "p");
+const ValueDecl *SDecl = findValueDecl(ASTCtx, "s");
+const ValueDecl *BDecl = findValueDecl(ASTCtx, "b");
+const IndirectFieldDecl *IndirectField =
+findIndirectFieldDecl(ASTCtx, "b");
+
+auto *S =
+cast(Env.getStorageLocation(*SDecl));
+auto &AnonStruct = cast(
+S->getChild(*cast(IndirectField->chain().front(;
+
+auto *B = cast(En

[PATCH] D153956: [clang][dataflow] Don't crash if copy constructor arg doesn't have a storage location.

2023-06-28 Thread Martin Böhme via Phabricator via cfe-commits
mboehme created this revision.
Herald added subscribers: martong, xazax.hun.
Herald added a reviewer: NoQ.
Herald added a project: All.
mboehme requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

I accidentally used `cast` instead of `cast_or_null`.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D153956

Files:
  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
@@ -2237,6 +2237,21 @@
   });
 }
 
+TEST(TransferTest, CopyConstructorArgIsRefReturnedByFunction) {
+  // This is a crash repro.
+  std::string Code = R"(
+struct S {};
+const S &returnsSRef();
+void target() {
+  S s(returnsSRef());
+}
+  )";
+  runDataflow(
+  Code,
+  [](const llvm::StringMap> &Results,
+ ASTContext &ASTCtx) {});
+}
+
 TEST(TransferTest, MoveConstructor) {
   std::string Code = R"(
 namespace std {
Index: clang/lib/Analysis/FlowSensitive/Transfer.cpp
===
--- clang/lib/Analysis/FlowSensitive/Transfer.cpp
+++ clang/lib/Analysis/FlowSensitive/Transfer.cpp
@@ -598,7 +598,7 @@
   const Expr *Arg = S->getArg(0);
   assert(Arg != nullptr);
 
-  auto *ArgLoc = cast(
+  auto *ArgLoc = cast_or_null(
   Env.getStorageLocation(*Arg, SkipPast::Reference));
   if (ArgLoc == nullptr)
 return;


Index: clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
@@ -2237,6 +2237,21 @@
   });
 }
 
+TEST(TransferTest, CopyConstructorArgIsRefReturnedByFunction) {
+  // This is a crash repro.
+  std::string Code = R"(
+struct S {};
+const S &returnsSRef();
+void target() {
+  S s(returnsSRef());
+}
+  )";
+  runDataflow(
+  Code,
+  [](const llvm::StringMap> &Results,
+ ASTContext &ASTCtx) {});
+}
+
 TEST(TransferTest, MoveConstructor) {
   std::string Code = R"(
 namespace std {
Index: clang/lib/Analysis/FlowSensitive/Transfer.cpp
===
--- clang/lib/Analysis/FlowSensitive/Transfer.cpp
+++ clang/lib/Analysis/FlowSensitive/Transfer.cpp
@@ -598,7 +598,7 @@
   const Expr *Arg = S->getArg(0);
   assert(Arg != nullptr);
 
-  auto *ArgLoc = cast(
+  auto *ArgLoc = cast_or_null(
   Env.getStorageLocation(*Arg, SkipPast::Reference));
   if (ArgLoc == nullptr)
 return;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


Re: [PATCH] D153674: [dataflow] Disallow implicit copy of Environment, use fork() instead

2023-06-28 Thread Sam McCall via cfe-commits
Hi, sorry about that - are you able to provide a full log, or link to a
failing bot?
That error message doesn't show where in the LLVM code the error occurs.

On Wed, Jun 28, 2023 at 7:52 AM Zixuan Wu via Phabricator <
revi...@reviews.llvm.org> wrote:

> zixuan-wu added a comment.
>
> Hi, there is a compiling error introduced recently as like following when
> files under clang/lib/Analysis/FlowSensitive/ are being compiled such as
> TypeErasedDataflowAnalysis.cpp and Transfer.cpp. Does anybody meet also?
>
> >   from /usr/include/c++/7/functional:60,
> >   from
> /iothome/wuzx/workspace/master-csky/clang/unittests/Analysis/FlowSensitive/TestingSupport.h:16,
> >   from
> /iothome/wuzx/workspace/master-csky/clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp:9:
> >
> > /usr/include/c++/7/optional:453:11: note:
> ‘std::optional
> >::optional(const
> std::optional
> >&)’ is implicitly deleted because the default definition would be
> ill-formed:
> >
> >   class optional
> > ^~~~
> >
> > /usr/include/c++/7/optional:453:11: error: use of deleted function
> ‘constexpr std::_Enable_copy_move _Tag>::_Enable_copy_move(const std::_Enable_copy_move true, _Tag>&) [with _Tag =
> std::optional
> >]’
> > In file included from /usr/include/c++/7/optional:43:0,
> >
> >   from /usr/include/c++/7/bits/node_handle.h:39,
> >   from /usr/include/c++/7/bits/hashtable.h:37,
> >   from /usr/include/c++/7/unordered_map:47,
> >   from /usr/include/c++/7/functional:60,
> >   from
> /iothome/wuzx/workspace/master-csky/clang/unittests/Analysis/FlowSensitive/TestingSupport.h:16,
> >   from
> /iothome/wuzx/workspace/master-csky/clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp:9:
> >
> > /usr/include/c++/7/bits/enable_special_members.h:157:15: note: declared
> here
> >
> >   constexpr _Enable_copy_move(_Enable_copy_move const&) noexcept  =
> delete;
> > ^
> >
> > In file included from /usr/include/c++/7
>
> The gcc version is gcc (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0.
>
>
> Repository:
>   rG LLVM Github Monorepo
>
> CHANGES SINCE LAST ACTION
>   https://reviews.llvm.org/D153674/new/
>
> https://reviews.llvm.org/D153674
>
>
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D153957: [C++20] [Modules] Allow Stmt::Profile to treat lambdas as equal conditionally

2023-06-28 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu created this revision.
ChuanqiXu added reviewers: rsmith, cor3ntin, aaron.ballman, tbaeder.
ChuanqiXu added projects: clang-modules, clang-language-wg.
Herald added a project: All.
ChuanqiXu requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Close https://github.com/llvm/llvm-project/issues/63544.

Background: We landed std modules in libcxx recently but we haven't landed the 
corresponding in-tree tests. According to @Mordante, there are only 1% libcxx 
tests failing with std modules. And the major blocking issue is the lambda 
expression in the require clauses.

The root cause of the issue is that previously we never consider any lambda 
expression as the same. Per [temp.over.link]p5:

> Two lambda-expressions are never considered equivalent.

I thought this is an oversight at first but @rsmith explains that in the 
wording, the program is as if there is only a single definition, and a single 
lambda-expression. So we don't need worry about this in the spec. The 
explanation makes sense. But it didn't reflect to the implementation directly.

Here is a cycle in the implementation. If we want to merge two definitions, we 
need to make sure its implementation are the same. But according to the 
explanation above, we need to judge if two lambda-expression are the same by 
looking at its parent definitions. So here is the problem.

To solve the problem, I think we have to profile the lambda expressions 
actually to get the accurate information. But we can't do this universally. So 
in this patch I tried to modify the interface of `Stmt::Profile` and only 
profile the lambda expression during the process of merging the constraint 
expressions.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D153957

Files:
  clang/include/clang/AST/Stmt.h
  clang/lib/AST/ASTContext.cpp
  clang/lib/AST/StmtProfile.cpp
  clang/test/Modules/merge-requires-with-lambdas.cppm
  clang/test/Modules/pr63544.cppm

Index: clang/test/Modules/pr63544.cppm
===
--- /dev/null
+++ clang/test/Modules/pr63544.cppm
@@ -0,0 +1,88 @@
+// RUN: rm -rf %t
+// RUN: mkdir -p %t
+// RUN: split-file %s %t
+//
+// RUN: %clang_cc1 -std=c++23 %t/a.cppm -emit-module-interface -o %t/m-a.pcm
+// RUN: %clang_cc1 -std=c++23 %t/b.cppm -emit-module-interface -o %t/m-b.pcm
+// RUN: %clang_cc1 -std=c++23 %t/m.cppm -emit-module-interface -o %t/m.pcm \
+// RUN: -fprebuilt-module-path=%t
+// RUN: %clang_cc1 -std=c++23 %t/pr63544.cpp -fprebuilt-module-path=%t -fsyntax-only -verify
+
+//--- foo.h
+
+namespace std {
+struct strong_ordering {
+  int n;
+  constexpr operator int() const { return n; }
+  static const strong_ordering equal, greater, less;
+};
+constexpr strong_ordering strong_ordering::equal = {0};
+constexpr strong_ordering strong_ordering::greater = {1};
+constexpr strong_ordering strong_ordering::less = {-1};
+} // namespace std
+
+namespace std {
+template 
+class optional {
+private:
+using value_type = _Tp;
+value_type __val_;
+bool __engaged_;
+public:
+constexpr bool has_value() const noexcept
+{
+return this->__engaged_;
+}
+
+constexpr const value_type& operator*() const& noexcept
+{
+return __val_;
+}
+
+optional(_Tp v) : __val_(v) {
+__engaged_ = true;
+}
+};
+
+template 
+concept __is_derived_from_optional = requires(const _Tp& __t) { [](const optional<__Up>&) {}(__t); };
+
+template 
+requires(!__is_derived_from_optional<_Up>)
+constexpr strong_ordering
+operator<=>(const optional<_Tp>& __x, const _Up& __v) {
+return __x.has_value() ? *__x <=> __v : strong_ordering::less;
+}
+} // namespace std
+
+//--- a.cppm
+module;
+#include "foo.h"
+export module m:a;
+export namespace std {
+using std::optional;
+using std::operator<=>;
+}
+
+//--- b.cppm
+module;
+#include "foo.h"
+export module m:b;
+export namespace std {
+using std::optional;
+using std::operator<=>;
+}
+
+//--- m.cppm
+export module m;
+export import :a;
+export import :b;
+
+//--- pr63544.cpp
+// expected-no-diagnostics
+import m;
+int pr63544() {
+std::optional a(43);
+int t{3};
+return a<=>t;
+}
Index: clang/test/Modules/merge-requires-with-lambdas.cppm
===
--- /dev/null
+++ clang/test/Modules/merge-requires-with-lambdas.cppm
@@ -0,0 +1,100 @@
+// Tests that we can merge the concept declarations with lambda well.
+//
+// RUN: rm -rf %t
+// RUN: mkdir -p %t
+// RUN: split-file %s %t
+//
+// RUN: %clang_cc1 -std=c++20 %t/A.cppm -emit-module-interface -o %t/A.pcm
+// RUN: %clang_cc1 -std=c++20 %t/A0.cppm -emit-module-interface -o %t/A0.pcm
+// RUN: %clang_cc1 -std=c++20 %t/TestA.cpp -fprebuilt-module-path=%t -fsyntax-only -verify
+//
+// RUN: %clang_cc1 -std=c++20 %t/A1.cppm -emit-module-interface -o %t/A1.pcm
+// RUN: %clang_cc1 -std=c++20 %t/TestA1.cpp -fprebuilt-module

[clang] 6f22de6 - [dataflow] Use consistent, symmetrical, non-mutating erased signature for join()

2023-06-28 Thread Sam McCall via cfe-commits

Author: Sam McCall
Date: 2023-06-28T11:30:16+02:00
New Revision: 6f22de67c585156aea6a4554f96315094092d211

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

LOG: [dataflow] Use consistent, symmetrical, non-mutating erased signature for 
join()

Mutating join() isn't used and so appears to be an anti-optimization.
Having Lattice vs Environment inconsistent is awkward, particularly when trying
to minimize copies while joining.

This patch eliminates the difference, but doesn't actually change the signature
of join on concrete lattice types (as that's a breaking change).

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

Added: 


Modified: 
clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
clang/include/clang/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.h
clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp

Removed: 




diff  --git a/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h 
b/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
index b6ba3be053c8d..c6e9f848477f8 100644
--- a/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
+++ b/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
@@ -61,6 +61,7 @@ namespace dataflow {
 /// argument by computing their least upper bound, modifies the object if
 /// necessary, and returns an effect indicating whether any changes were
 /// made to it;
+/// FIXME: make it `static LatticeT join(const LatticeT&, const LatticeT&)`
 ///   * `bool operator==(const LatticeT &) const` - returns true if and only if
 /// the object is equal to the argument.
 ///
@@ -98,11 +99,13 @@ class DataflowAnalysis : public TypeErasedDataflowAnalysis {
 return {static_cast(this)->initialElement()};
   }
 
-  LatticeJoinEffect joinTypeErased(TypeErasedLattice &E1,
+  TypeErasedLattice joinTypeErased(const TypeErasedLattice &E1,
const TypeErasedLattice &E2) final {
-Lattice &L1 = llvm::any_cast(E1.Value);
+// FIXME: change the signature of join() to avoid copying here.
+Lattice L1 = llvm::any_cast(E1.Value);
 const Lattice &L2 = llvm::any_cast(E2.Value);
-return L1.join(L2);
+L1.join(L2);
+return {std::move(L1)};
   }
 
   LatticeJoinEffect widenTypeErased(TypeErasedLattice &Current,

diff  --git a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h 
b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
index 8494bc197cb25..8da359880e3ce 100644
--- a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
+++ b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
@@ -218,16 +218,15 @@ class Environment {
   bool equivalentTo(const Environment &Other,
 Environment::ValueModel &Model) const;
 
-  /// Joins the environment with `Other` by taking the intersection of storage
-  /// locations and values that are stored in them. Distinct values that are
-  /// assigned to the same storage locations in the environment and `Other` are
-  /// merged using `Model`.
+  /// Joins two environments by taking the intersection of storage locations 
and
+  /// values that are stored in them. Distinct values that are assigned to the
+  /// same storage locations in `EnvA` and `EnvB` are merged using `Model`.
   ///
   /// Requirements:
   ///
-  ///  `Other` and `this` must use the same `DataflowAnalysisContext`.
-  Environment join(const Environment &Other,
-   Environment::ValueModel &Model) const;
+  ///  `EnvA` and `EnvB` must use the same `DataflowAnalysisContext`.
+  static Environment join(const Environment &EnvA, const Environment &EnvB,
+  Environment::ValueModel &Model);
 
   /// Widens the environment point-wise, using `PrevEnv` as needed to inform 
the
   /// approximation.

diff  --git 
a/clang/include/clang/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.h 
b/clang/include/clang/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.h
index 9ed3e25d63327..88a33d19f7d8f 100644
--- a/clang/include/clang/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.h
+++ b/clang/include/clang/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.h
@@ -72,7 +72,7 @@ class TypeErasedDataflowAnalysis : public 
Environment::ValueModel {
   /// Joins two type-erased lattice elements by computing their least upper
   /// bound. Places the join result in the left element and returns an effect
   /// indicating whether any changes were made to it.
-  virtual LatticeJoinEffect joinTypeErased(TypeErasedLattice &,
+  virtual TypeErasedLattice joinTypeErased(const TypeErasedLattice &,
   

[PATCH] D153908: [dataflow] Use consistent, symmetrical, non-mutating erased signature for join()

2023-06-28 Thread Sam McCall via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG6f22de67c585: [dataflow] Use consistent, symmetrical, 
non-mutating erased signature for join() (authored by sammccall).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153908

Files:
  clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
  clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
  clang/include/clang/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.h
  clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
  clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp

Index: clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
===
--- clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
+++ clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
@@ -227,50 +227,39 @@
 // Avoids unneccesary copies of the environment.
 class JoinedStateBuilder {
   AnalysisContext &AC;
-  std::optional OwnedState;
-  // Points either to OwnedState, an external Environment, or nothing.
-  const TypeErasedDataflowAnalysisState *CurrentState = nullptr;
+  std::vector All;
+  std::deque Owned;
+
+  TypeErasedDataflowAnalysisState
+  join(const TypeErasedDataflowAnalysisState &L,
+   const TypeErasedDataflowAnalysisState &R) {
+return {AC.Analysis.joinTypeErased(L.Lattice, R.Lattice),
+Environment::join(L.Env, R.Env, AC.Analysis)};
+  }
 
 public:
   JoinedStateBuilder(AnalysisContext &AC) : AC(AC) {}
 
   void addOwned(TypeErasedDataflowAnalysisState State) {
-if (!CurrentState) {
-  OwnedState = std::move(State);
-  CurrentState = &*OwnedState;
-} else if (!OwnedState) {
-  OwnedState.emplace(std::move(CurrentState->Lattice),
- CurrentState->Env.join(State.Env, AC.Analysis));
-  AC.Analysis.joinTypeErased(OwnedState->Lattice, State.Lattice);
-} else {
-  OwnedState->Env = CurrentState->Env.join(State.Env, AC.Analysis);
-  AC.Analysis.joinTypeErased(OwnedState->Lattice, State.Lattice);
-}
+Owned.push_back(std::move(State));
+All.push_back(&Owned.back());
   }
   void addUnowned(const TypeErasedDataflowAnalysisState &State) {
-if (!CurrentState) {
-  CurrentState = &State;
-} else if (!OwnedState) {
-  OwnedState.emplace(CurrentState->Lattice,
- CurrentState->Env.join(State.Env, AC.Analysis));
-  AC.Analysis.joinTypeErased(OwnedState->Lattice, State.Lattice);
-} else {
-  OwnedState->Env = CurrentState->Env.join(State.Env, AC.Analysis);
-  AC.Analysis.joinTypeErased(OwnedState->Lattice, State.Lattice);
-}
+All.push_back(&State);
   }
   TypeErasedDataflowAnalysisState take() && {
-if (!OwnedState) {
-  if (CurrentState)
-OwnedState.emplace(CurrentState->Lattice, CurrentState->Env.fork());
-  else
-// FIXME: Consider passing `Block` to Analysis.typeErasedInitialElement
-// to enable building analyses like computation of dominators that
-// initialize the state of each basic block differently.
-OwnedState.emplace(AC.Analysis.typeErasedInitialElement(),
-   AC.InitEnv.fork());
-}
-return std::move(*OwnedState);
+if (All.empty())
+  // FIXME: Consider passing `Block` to Analysis.typeErasedInitialElement
+  // to enable building analyses like computation of dominators that
+  // initialize the state of each basic block differently.
+  return {AC.Analysis.typeErasedInitialElement(), AC.InitEnv.fork()};
+if (All.size() == 1)
+  return Owned.empty() ? All.front()->fork() : std::move(Owned.front());
+
+auto Result = join(*All[0], *All[1]);
+for (unsigned I = 2; I < All.size(); ++I)
+  Result = join(Result, *All[I]);
+return Result;
   }
 };
 
Index: clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
===
--- clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
+++ clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
@@ -526,18 +526,18 @@
   return Effect;
 }
 
-Environment Environment::join(const Environment &Other,
-  Environment::ValueModel &Model) const {
-  assert(DACtx == Other.DACtx);
-  assert(ThisPointeeLoc == Other.ThisPointeeLoc);
-  assert(CallStack == Other.CallStack);
+Environment Environment::join(const Environment &EnvA, const Environment &EnvB,
+  Environment::ValueModel &Model) {
+  assert(EnvA.DACtx == EnvB.DACtx);
+  assert(EnvA.ThisPointeeLoc == EnvB.ThisPointeeLoc);
+  assert(EnvA.CallStack == EnvB.CallStack);
 
-  Environment JoinedEnv(*DACtx);
+  Environment JoinedEnv(*EnvA.DACtx);
 
-  JoinedEnv.CallStack = CallStack;
-  JoinedEnv.ThisPointeeL

[PATCH] D153674: [dataflow] Disallow implicit copy of Environment, use fork() instead

2023-06-28 Thread Zixuan Wu via Phabricator via cfe-commits
zixuan-wu added a comment.

In D153674#4455357 , @sammccall wrote:

> Hi, sorry about that - are you able to provide a full log, or link to a
> failing bot?
> That error message doesn't show where in the LLVM code the error occurs.

It can pass with gcc 8.  And I can upload the .i file.F28060172: error.i 


> g++ error.i -std=c++17
> In file included from /usr/include/c++/7/memory:64:0,
>
>   from 
> /iothome/wuzx/workspace/llvm-comm/llvm/include/llvm/Support/Casting.h:20,
>   from /iothome/wuzx/workspace/llvm-comm/clang/include/clang/Basic/LLVM.h:21,
>   from 
> /iothome/wuzx/workspace/llvm-comm/clang/include/clang/Basic/DiagnosticIDs.h:17,
>   from 
> /iothome/wuzx/workspace/llvm-comm/clang/include/clang/Basic/IdentifierTable.h:18,
>   from /iothome/wuzx/workspace/llvm-comm/clang/include/clang/AST/Stmt.h:20,
>   from 
> /iothome/wuzx/workspace/llvm-comm/clang/include/clang/Analysis/FlowSensitive/Transfer.h:17,
>   from 
> /iothome/wuzx/workspace/llvm-comm/clang/lib/Analysis/FlowSensitive/Transfer.cpp:14:
>
> /usr/include/c++/7/bits/stl_construct.h: In instantiation of ‘void 
> std::_Construct(_T1*, _Args&& ...) [with _T1 = 
> std::optional
>  >; _Args = {const 
> std::optional
>  >&}]’:
> /usr/include/c++/7/bits/stl_uninitialized.h:83:18:   required from ‘static 
> _ForwardIterator 
> std::__uninitialized_copy<_TrivialValueTypes>::__uninit_copy(_InputIterator, 
> _InputIterator, _ForwardIterator) [with _InputIterator = 
> __gnu_cxx::__normal_iterator std::optional
>  >*, 
> std::vector
>  >, 
> std::allocator
>  > > > >; _ForwardIterator = 
> std::optional
>  >*; bool _TrivialValueTypes = false]’
> /usr/include/c++/7/bits/stl_uninitialized.h:134:15:   required from 
> ‘_ForwardIterator std::uninitialized_copy(_InputIterator, _InputIterator, 
> _ForwardIterator) [with _InputIterator = __gnu_cxx::__normal_iterator std::optional
>  >*, 
> std::vector
>  >, 
> std::allocator
>  > > > >; _ForwardIterator = 
> std::optional
>  >*]’
> /usr/include/c++/7/bits/stl_uninitialized.h:289:37:   required from 
> ‘_ForwardIterator std::__uninitialized_copy_a(_InputIterator, _InputIterator, 
> _ForwardIterator, std::allocator<_Tp>&) [with _InputIterator = 
> __gnu_cxx::__normal_iterator std::optional
>  >*, 
> std::vector
>  >, 
> std::allocator
>  > > > >; _ForwardIterator = 
> std::optional
>  >*; _Tp = 
> std::optional
>  >]’
> /usr/include/c++/7/bits/stl_vector.h:331:31:   required from 
> ‘std::vector<_Tp, _Alloc>::vector(const std::vector<_Tp, _Alloc>&) [with _Tp 
> = 
> std::optional
>  >; _Alloc = 
> std::allocator
>  > >]’
> /iothome/wuzx/workspace/llvm-comm/llvm/include/llvm/Support/Error.h:520:5:   
> required from ‘llvm::Expected::Expected(OtherT&&, 
> std::enable_if_t >*) [with OtherT = 
> std::vector
>  >, 
> std::allocator
>  > > >&; T = 
> std::vector
>  >, 
> std::allocator
>  > > >; std::enable_if_t > = void]’
> /iothome/wuzx/workspace/llvm-comm/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h:235:10:
>required from 
> ‘llvm::Expected  AnalysisT::Lattice> > > > clang::dataflow::runDataflowAnalysis(const 
> clang::dataflow::ControlFlowContext&, AnalysisT&, const 
> clang::dataflow::Environment&, std::function const clang::dataflow::DataflowAnalysisState&)>) 
> [with AnalysisT = clang::dataflow::NoopAnalysis; typename AnalysisT::Lattice 
> = clang::dataflow::NoopLattice]’
> /iothome/wuzx/workspace/llvm-comm/clang/lib/Analysis/FlowSensitive/Transfer.cpp:871:38:
>required from ‘void 
> clang::dataflow::{anonymous}::TransferVisitor::transferInlineCall(const E*, 
> const clang::FunctionDecl*) [with E = clang::CXXConstructExpr]’
> /iothome/wuzx/workspace/llvm-comm/clang/lib/Analysis/FlowSensitive/Transfer.cpp:625:42:
>required from here
> /usr/include/c++/7/bits/stl_construct.h:75:7: error: use of deleted function 
> ‘std::optional
>  >::optional(const 
> std::optional
>  >&)’
>
>   { ::new(static_cast(__p)) _T1(std::forward<_Args>(__args)...); }
> ^~
>
> In file included from 
> /iothome/wuzx/workspace/llvm-comm/llvm/include/llvm/Support/Alignment.h:26:0,
>
>   from 
> /iothome/wuzx/workspace/llvm-comm/llvm/include/llvm/Support/TrailingObjects.h:50,
>   from 
> /iothome/wuzx/workspace/llvm-comm/clang/include/clang/AST/DeclGroup.h:16,
>   from /iothome/wuzx/workspace/llvm-comm/clang/include/clang/AST/Stmt.h:16,
>   from 
> /iothome/wuzx/workspace/llvm-comm/clang/include/clang/Analysis/FlowSensitive/Transfer.h:17,
>   from 
> /iothome/wuzx/workspace/llvm-comm/clang/lib/Analysis/FlowSensitive/Transfer.cpp:14:
>
> /usr/include/c++/7/optional:453:11: note: 
> ‘std::optional
>  >::optional(const 
> std::optional
>  >&)’ is implicitly deleted because the default definition would be 
> ill-formed:
>
>   class optional
> ^~~~
>
> /usr/include/c++/7/optional:453:11: error: use of deleted function ‘constexpr 
> std::_Enable_copy_move _Tag>:

[PATCH] D153058: [clang][CFG] Support construction of a weak topological ordering of the CFG.

2023-06-28 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun added a comment.

Could you rebase this patch to the latest tip of tree?




Comment at: clang/include/clang/Analysis/Analyses/IntervalPartition.h:73
+
+  // Whether this node is the head of a feedback edge within the interval.
+  bool IsFeedbackHead = false;

Is feedback edge a special terminology? I think we might simply call these back 
edges most of the time.



Comment at: clang/include/clang/Analysis/Analyses/IntervalPartition.h:83
 
-// Partitions `Cfg` into intervals and constructs a graph of the intervals,
+// Partitions `Cfg` into intervals and constructs a the graph of the intervals
 // based on the edges between nodes in these intervals.

typo?



Comment at: clang/include/clang/Analysis/Analyses/IntervalPartition.h:87
+
+// (Further) partitions `Graph` into intervals and constructs a the graph of 
the
+// intervals based on the edges between nodes (themselves intervals) in these

same typo here?



Comment at: clang/lib/Analysis/IntervalPartition.cpp:23-25
+namespace {
+template  using NodeData = CFGInterval::NodeData;
+} // namespace

What is the reason for putting a using statement in an anonymous namespace? 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153058

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


[PATCH] D153652: [Support] Don't set "all_exe" mode by default for file written by llvm::writeToOutput

2023-06-28 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 535309.
hokein added a comment.

compare the file-permission bits in unittest


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153652

Files:
  llvm/lib/Support/raw_ostream.cpp
  llvm/test/tools/llvm-dwarfutil/ELF/X86/mirror-permissions-unix.test
  llvm/unittests/Support/raw_ostream_test.cpp

Index: llvm/unittests/Support/raw_ostream_test.cpp
===
--- llvm/unittests/Support/raw_ostream_test.cpp
+++ llvm/unittests/Support/raw_ostream_test.cpp
@@ -504,6 +504,31 @@
   checkFileData(Path, "HelloWorld");
 }
 
+#ifndef _WIN32
+TEST(raw_ostreamTest, filePermissions) {
+  // Set umask to be permissive of all permissions.
+  unsigned OldMask = ::umask(0);
+
+  llvm::unittest::TempDir RootTestDirectory("writToOutput", /*Unique*/ true);
+  SmallString<128> Path(RootTestDirectory.path());
+  sys::path::append(Path, "test.txt");
+
+  ASSERT_THAT_ERROR(writeToOutput(Path,
+  [](raw_ostream &Out) -> Error {
+Out << "HelloWorld";
+return Error::success();
+  }),
+Succeeded());
+
+  ErrorOr Perms = llvm::sys::fs::getPermissions(Path);
+  ASSERT_TRUE(Perms) << "should be able to get permissions";
+  // Verify that writeToOutput doesn't set exe bit.
+  EXPECT_EQ(Perms.get(), llvm::sys::fs::all_read | llvm::sys::fs::all_write);
+
+  ::umask(OldMask);
+}
+#endif
+
 TEST(raw_ostreamTest, writeToNonexistingPath) {
   StringRef FileName = "/_bad/_path";
   std::string ErrorMessage = toString(createFileError(
Index: llvm/test/tools/llvm-dwarfutil/ELF/X86/mirror-permissions-unix.test
===
--- /dev/null
+++ llvm/test/tools/llvm-dwarfutil/ELF/X86/mirror-permissions-unix.test
@@ -0,0 +1,51 @@
+## The Unix version of this test must use umask(1) because
+## llvm-dwarfutil respects the umask in setting output permissions.
+## Setting the umask to 0 ensures deterministic permissions across
+## test environments.
+# UNSUPPORTED: system-windows
+# REQUIRES: shell
+
+# RUN: touch %t
+# RUN: chmod 0777 %t
+# RUN: ls -l %t | cut -f 1 -d ' ' > %t.0777
+# RUN: chmod 0666 %t
+# RUN: ls -l %t | cut -f 1 -d ' ' > %t.0666
+# RUN: chmod 0640 %t
+# RUN: ls -l %t | cut -f 1 -d ' ' > %t.0640
+
+## Set umask to be permissive of all permissions,
+## only test mirroring of permissions.
+# RUN: umask 0
+
+# RUN: yaml2obj %s -o %t
+
+# RUN: chmod 0777 %t
+# RUN: llvm-dwarfutil --no-garbage-collection %t %t1
+# RUN: ls -l %t1 | cut -f 1 -d ' ' > %t1.perms
+# RUN: cmp %t1.perms %t.0777
+# RUN: llvm-dwarfutil --garbage-collection --separate-debug-file %t %t2
+# RUN: ls -l %t2 | cut -f 1 -d ' ' > %t2.perms
+# RUN: cmp %t2.perms %t.0777
+
+# RUN: chmod 0666 %t
+# RUN: llvm-dwarfutil --no-garbage-collection %t %t1
+# RUN: ls -l %t1 | cut -f 1 -d ' ' > %t1.perms
+# RUN: cmp %t1.perms %t.0666
+# RUN: llvm-dwarfutil --garbage-collection --separate-debug-file %t %t2
+# RUN: ls -l %t2 | cut -f 1 -d ' ' > %t2.perms
+# RUN: cmp %t2.perms %t.0666
+
+# RUN: chmod 0640 %t
+# RUN: llvm-dwarfutil --no-garbage-collection %t %t1
+# RUN: ls -l %t1 | cut -f 1 -d ' ' > %t1.perms
+# RUN: cmp %t1.perms %t.0640
+# RUN: llvm-dwarfutil --garbage-collection --separate-debug-file %t %t2
+# RUN: ls -l %t2 | cut -f 1 -d ' ' > %t2.perms
+# RUN: cmp %t2.perms %t.0640
+
+--- !ELF
+FileHeader:
+  Class:   ELFCLASS64
+  Data:ELFDATA2LSB
+  Type:ET_EXEC
+  Machine: EM_X86_64
Index: llvm/lib/Support/raw_ostream.cpp
===
--- llvm/lib/Support/raw_ostream.cpp
+++ llvm/lib/Support/raw_ostream.cpp
@@ -1007,7 +1007,7 @@
 return Write(Out);
   }
 
-  unsigned Mode = sys::fs::all_read | sys::fs::all_write | sys::fs::all_exe;
+  unsigned Mode = sys::fs::all_read | sys::fs::all_write;
   Expected Temp =
   sys::fs::TempFile::create(OutputFileName + ".temp-stream-%%", Mode);
   if (!Temp)
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D153652: [Support] Don't set "all_exe" mode by default for file written by llvm::writeToOutput

2023-06-28 Thread Haojian Wu via Phabricator via cfe-commits
hokein added inline comments.



Comment at: llvm/unittests/Support/raw_ostream_test.cpp:500
+  ASSERT_TRUE(!!Perms);
+  EXPECT_EQ(0, *Perms & llvm::sys::fs::all_exe);
+

jhenderson wrote:
> hokein wrote:
> > jhenderson wrote:
> > > Here and below, rather than just checking the all_exe bit, let's check 
> > > the permissions are exactly what are expected (e.g. does it have the 
> > > read/write perms?). 
> > checking all existing bits is a bit tricky here (I tried it, then gave up):
> > 
> > - createTemporaryFile() creates a file with `owner_read | owner_write`
> > - writeToOutput() sets the written file to `all_read | all_write`
> > 
> > Both API don't provide a way to customize these bits, and they're internal 
> > details. We could test against them, but testing the implementation details 
> > seems subtle. And here we aim to verify the exe-bit not set by the 
> > `writeToOutput`, so I think just testing the exe-bit is not set should be 
> > enough. 
> This argument doesn't make much sense to me. Why are the `all_read` and 
> `all_write` bits implementation details that shouldn't be tested when the 
> lack of `all_exe` is?
> 
> This test is for testing `writeToOutput`. Part of `writeToOutput`'s behaviour 
> appears to be to create a file with the `all_read` and `all_write` bits set. 
> Therefore, we should be testing that behaviour. As there was already one 
> issue with the permission bits of the file this method creates, and you are 
> directly modifiyng a test to add permissions testing, I think it's justified 
> to request testing of the other bits.
OK, I changed the test to verify the all_read and all_write bits, please take 
another look.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153652

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


[PATCH] D153294: [clang] Do not create ExprWithCleanups while checking immediate invocation

2023-06-28 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

In D153294#4448342 , @Fznamznon wrote:

> I'm having a slight trouble with understanding why this part is required and 
> how to implement the test ...
>
> Also, simply adding a flag to `MaybeCreateExprWithCleanup` signaling that 
> we're processing an immediate invocation to not discard cleanups also passes 
> check-clang and fixes original memory leak problem. Maybe we should just do 
> that?

I also struggle to see how any of the cleanup objects may end up being inside 
`ExprWithCleanups` under immediate invocation.
Any use of block literals inside constant expressions results in an error and 
compound literals are handled like temporaries in C++ and don't create cleanup 
objects (see the reference above).

I would maybe guard the code doing the processing immediate invocations with 
`assert(LangOpts.CPlusPlus)` to sanity-check that we don't end up calling this 
in C in some very distant future.
I believe we should make the proposed change (add potentially redundant 
`ExprWithCleanups` without touching the cleanups objects or flags) without 
blocking on Richard's approval.
It definitely fixes the somewhat common problem we have now and potentially 
leaves behind a few corner cases with blocks which are much less likely (or 
even impossible) to occur in practice.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153294

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


[PATCH] D153857: [clang] Fix new-expression with elaborated-type-specifier

2023-06-28 Thread Mariya Podchishchaeva via Phabricator via cfe-commits
Fznamznon added a comment.

> What about
> template 
> struct A { };
>
>   void foo() {
> new struct A {};
>   }
>
> I think this should be allowed, right?

Yes, I think so. The patch helps to allow. Thanks, I'll add it to the test.

> MSVC rejects the first but accepts the second which I think is wrong but 
> worth testing:
>
> alignof(struct B {});
> sizeof(struct B{});

These don't have `new` so they are not affected by the patch ATM.
But why MSVC wrong? Operand of `alignof` is a `type-id` which is not 
`defining-type-id` meaning it shouldn't be parsed as type definition. So, 
`struct B{}` there is a reference to `struct B` with braced initializer, i.e. 
object creation. That is not a `type-id`, right? On the opposite, `sizeof` can 
accept either `type-id` or an expression, I guess this is why MSVC accepts.




Comment at: clang/include/clang/Parse/Parser.h:2359
 case DeclSpecContext::DSC_template_param:
+case DeclSpecContext::DSC_new:
   return ImplicitTypenameContext::Yes;

shafik wrote:
> Should this be below since `DeclaratorContext::CXXNew` was grouped w/ 
> `DSC_normal` normal before?
Not really. Since there was no `DeclSpecContext` for `new` expression, it was 
mostly handled as if it was `DSC_type_specifier`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153857

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


[clang] 51bb9b1 - OpenMP: Add missing test coverage for nothrow new/delete

2023-06-28 Thread Matt Arsenault via cfe-commits

Author: Matt Arsenault
Date: 2023-06-28T06:55:15-04:00
New Revision: 51bb9b12f87ea315f750490c39cd993507202861

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

LOG: OpenMP: Add missing test coverage for nothrow new/delete

Missing test from fd3437a4f791cb0520e19b87953141fc68543377

Added: 
clang/test/Headers/openmp_new_nothrow.cpp

Modified: 


Removed: 




diff  --git a/clang/test/Headers/openmp_new_nothrow.cpp 
b/clang/test/Headers/openmp_new_nothrow.cpp
new file mode 100644
index 0..2f1502ed44fe5
--- /dev/null
+++ b/clang/test/Headers/openmp_new_nothrow.cpp
@@ -0,0 +1,83 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py 
UTC_ARGS: --version 2
+// RUN: %clang_cc1 -std=c++03 -internal-isystem 
%S/../../lib/Headers/openmp_wrappers -include __clang_openmp_device_functions.h 
-internal-isystem %S/Inputs/include -verify -fopenmp -x c++ -triple 
nvptx64-nvidia-cuda -fopenmp-targets=nvptx64-nvidia-cuda -emit-llvm 
-fopenmp-is-device -o - %s | FileCheck -check-prefixes=CHECK,CXX03 %s
+// RUN: %clang_cc1 -std=c++11 -internal-isystem 
%S/../../lib/Headers/openmp_wrappers -include __clang_openmp_device_functions.h 
-internal-isystem %S/Inputs/include -verify -fopenmp -x c++ -triple 
nvptx64-nvidia-cuda -fopenmp-targets=nvptx64-nvidia-cuda -emit-llvm 
-fopenmp-is-device -o - %s | FileCheck -check-prefixes=CHECK,CXX11 %s
+
+
+// expected-no-diagnostics
+
+#include 
+
+#pragma omp begin declare target
+extern const std::nothrow_t nothrow;
+
+// CHECK-LABEL: define hidden noundef ptr @_Z17new_stuff_nothrowv
+// CHECK-SAME: () #[[ATTR0:[0-9]+]] {
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[CALL:%.*]] = call noalias noundef ptr 
@_ZnwmRKSt9nothrow_t(i64 noundef 4, ptr noundef nonnull align 1 
dereferenceable(1) @nothrow) #[[ATTR4:[0-9]+]]
+// CHECK-NEXT:ret ptr [[CALL]]
+//
+int* new_stuff_nothrow() {
+  return new (nothrow) int;
+}
+
+// CXX03-LABEL: define hidden noundef ptr @_Z23new_array_stuff_nothrowv
+// CXX03-SAME: () #[[ATTR0]] {
+// CXX03-NEXT:  entry:
+// CXX03-NEXT:[[CALL:%.*]] = call noalias noundef ptr 
@_ZnamRKSt9nothrow_t(i64 noundef 136, ptr noundef nonnull align 1 
dereferenceable(1) @nothrow) #[[ATTR4]]
+// CXX03-NEXT:ret ptr [[CALL]]
+//
+// CXX11-LABEL: define hidden noundef ptr @_Z23new_array_stuff_nothrowv
+// CXX11-SAME: () #[[ATTR0]] {
+// CXX11-NEXT:  entry:
+// CXX11-NEXT:[[CALL:%.*]] = call noalias noundef ptr 
@_ZnamRKSt9nothrow_t(i64 noundef 136, ptr noundef nonnull align 1 
dereferenceable(1) @nothrow) #[[ATTR7:[0-9]+]]
+// CXX11-NEXT:ret ptr [[CALL]]
+//
+int* new_array_stuff_nothrow() {
+  return new (nothrow) int[34];
+}
+
+// CXX03-LABEL: define hidden void @_Z20delete_stuff_nothrowPi
+// CXX03-SAME: (ptr noundef [[PTR:%.*]]) #[[ATTR0]] {
+// CXX03-NEXT:  entry:
+// CXX03-NEXT:[[PTR_ADDR:%.*]] = alloca ptr, align 8
+// CXX03-NEXT:store ptr [[PTR]], ptr [[PTR_ADDR]], align 8
+// CXX03-NEXT:[[TMP0:%.*]] = load ptr, ptr [[PTR_ADDR]], align 8
+// CXX03-NEXT:call void @_ZdlPvRKSt9nothrow_t(ptr noundef [[TMP0]], ptr 
noundef nonnull align 1 dereferenceable(1) @nothrow) #[[ATTR6:[0-9]+]]
+// CXX03-NEXT:ret void
+//
+// CXX11-LABEL: define hidden void @_Z20delete_stuff_nothrowPi
+// CXX11-SAME: (ptr noundef [[PTR:%.*]]) #[[ATTR0]] {
+// CXX11-NEXT:  entry:
+// CXX11-NEXT:[[PTR_ADDR:%.*]] = alloca ptr, align 8
+// CXX11-NEXT:store ptr [[PTR]], ptr [[PTR_ADDR]], align 8
+// CXX11-NEXT:[[TMP0:%.*]] = load ptr, ptr [[PTR_ADDR]], align 8
+// CXX11-NEXT:call void @_ZdlPvRKSt9nothrow_t(ptr noundef [[TMP0]], ptr 
noundef nonnull align 1 dereferenceable(1) @nothrow) #[[ATTR8:[0-9]+]]
+// CXX11-NEXT:ret void
+//
+void delete_stuff_nothrow(int* ptr) {
+  operator delete(ptr, nothrow);
+}
+
+// CXX03-LABEL: define hidden void @_Z26delete_array_stuff_nothrowPi
+// CXX03-SAME: (ptr noundef [[PTR:%.*]]) #[[ATTR0]] {
+// CXX03-NEXT:  entry:
+// CXX03-NEXT:[[PTR_ADDR:%.*]] = alloca ptr, align 8
+// CXX03-NEXT:store ptr [[PTR]], ptr [[PTR_ADDR]], align 8
+// CXX03-NEXT:[[TMP0:%.*]] = load ptr, ptr [[PTR_ADDR]], align 8
+// CXX03-NEXT:call void @_ZdaPvRKSt9nothrow_t(ptr noundef [[TMP0]], ptr 
noundef nonnull align 1 dereferenceable(1) @nothrow) #[[ATTR6]]
+// CXX03-NEXT:ret void
+//
+// CXX11-LABEL: define hidden void @_Z26delete_array_stuff_nothrowPi
+// CXX11-SAME: (ptr noundef [[PTR:%.*]]) #[[ATTR0]] {
+// CXX11-NEXT:  entry:
+// CXX11-NEXT:[[PTR_ADDR:%.*]] = alloca ptr, align 8
+// CXX11-NEXT:store ptr [[PTR]], ptr [[PTR_ADDR]], align 8
+// CXX11-NEXT:[[TMP0:%.*]] = load ptr, ptr [[PTR_ADDR]], align 8
+// CXX11-NEXT:call void @_ZdaPvRKSt9nothrow_t(ptr noundef [[TMP0]], ptr 
noundef nonnull align 1 dereferenceable(1) @nothrow) #[[ATTR8]]
+// C

[clang] 0e17174 - OpenMP: Fix nothrow new/delete for amdgpu

2023-06-28 Thread Matt Arsenault via cfe-commits

Author: Matt Arsenault
Date: 2023-06-28T06:55:16-04:00
New Revision: 0e17174d40b2d25a755d2ce9acf7c905f254746d

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

LOG: OpenMP: Fix nothrow new/delete for amdgpu

I tried #pragma omp begin declare variant device_type(nohost) but it
didn't work and I'm not really sure how it's supposed to work.

Added: 


Modified: 
clang/lib/Headers/openmp_wrappers/new
clang/test/Headers/openmp_new_nothrow.cpp

Removed: 




diff  --git a/clang/lib/Headers/openmp_wrappers/new 
b/clang/lib/Headers/openmp_wrappers/new
index 985ddc567f494..8bad3f19d6251 100644
--- a/clang/lib/Headers/openmp_wrappers/new
+++ b/clang/lib/Headers/openmp_wrappers/new
@@ -13,7 +13,7 @@
 // which do not use nothrow_t are provided without the  header.
 #include_next 
 
-#if defined(__NVPTX__) && defined(_OPENMP)
+#if (defined(__NVPTX__) || defined(__AMDGPU__)) && defined(_OPENMP)
 
 #include 
 

diff  --git a/clang/test/Headers/openmp_new_nothrow.cpp 
b/clang/test/Headers/openmp_new_nothrow.cpp
index 2f1502ed44fe5..8486de25ad655 100644
--- a/clang/test/Headers/openmp_new_nothrow.cpp
+++ b/clang/test/Headers/openmp_new_nothrow.cpp
@@ -1,6 +1,9 @@
 // NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py 
UTC_ARGS: --version 2
-// RUN: %clang_cc1 -std=c++03 -internal-isystem 
%S/../../lib/Headers/openmp_wrappers -include __clang_openmp_device_functions.h 
-internal-isystem %S/Inputs/include -verify -fopenmp -x c++ -triple 
nvptx64-nvidia-cuda -fopenmp-targets=nvptx64-nvidia-cuda -emit-llvm 
-fopenmp-is-device -o - %s | FileCheck -check-prefixes=CHECK,CXX03 %s
-// RUN: %clang_cc1 -std=c++11 -internal-isystem 
%S/../../lib/Headers/openmp_wrappers -include __clang_openmp_device_functions.h 
-internal-isystem %S/Inputs/include -verify -fopenmp -x c++ -triple 
nvptx64-nvidia-cuda -fopenmp-targets=nvptx64-nvidia-cuda -emit-llvm 
-fopenmp-is-device -o - %s | FileCheck -check-prefixes=CHECK,CXX11 %s
+// RUN: %clang_cc1 -std=c++03 -internal-isystem 
%S/../../lib/Headers/openmp_wrappers -include __clang_openmp_device_functions.h 
-internal-isystem %S/Inputs/include -verify -fopenmp -x c++ -triple 
nvptx64-nvidia-cuda -fopenmp-targets=nvptx64-nvidia-cuda -emit-llvm 
-fopenmp-is-device -o - %s | FileCheck -check-prefixes=NVPTX,NVPTX-CXX03 %s
+// RUN: %clang_cc1 -std=c++11 -internal-isystem 
%S/../../lib/Headers/openmp_wrappers -include __clang_openmp_device_functions.h 
-internal-isystem %S/Inputs/include -verify -fopenmp -x c++ -triple 
nvptx64-nvidia-cuda -fopenmp-targets=nvptx64-nvidia-cuda -emit-llvm 
-fopenmp-is-device -o - %s | FileCheck -check-prefixes=NVPTX,NVPTX-NVPTX-CXX11 
%s
+
+// RUN: %clang_cc1 -std=c++03 -internal-isystem 
%S/../../lib/Headers/openmp_wrappers -include __clang_openmp_device_functions.h 
-internal-isystem %S/Inputs/include -verify -fopenmp -x c++ -triple 
amdgcn-amd-amdhsa -fopenmp-targets=amdgcn-amd-amdhsa -emit-llvm 
-fopenmp-is-device -o - %s | FileCheck -check-prefixes=AMDGPU,AMDGPU-CXX03 %s
+// RUN: %clang_cc1 -std=c++11 -internal-isystem 
%S/../../lib/Headers/openmp_wrappers -include __clang_openmp_device_functions.h 
-internal-isystem %S/Inputs/include -verify -fopenmp -x c++ -triple 
amdgcn-amd-amdhsa -fopenmp-targets=amdgcn-amd-amdhsa -emit-llvm 
-fopenmp-is-device -o - %s | FileCheck -check-prefixes=AMDGPU,AMDGPU-CXX11 %s
 
 
 // expected-no-diagnostics
@@ -10,71 +13,159 @@
 #pragma omp begin declare target
 extern const std::nothrow_t nothrow;
 
-// CHECK-LABEL: define hidden noundef ptr @_Z17new_stuff_nothrowv
-// CHECK-SAME: () #[[ATTR0:[0-9]+]] {
-// CHECK-NEXT:  entry:
-// CHECK-NEXT:[[CALL:%.*]] = call noalias noundef ptr 
@_ZnwmRKSt9nothrow_t(i64 noundef 4, ptr noundef nonnull align 1 
dereferenceable(1) @nothrow) #[[ATTR4:[0-9]+]]
-// CHECK-NEXT:ret ptr [[CALL]]
+// NVPTX-LABEL: define hidden noundef ptr @_Z17new_stuff_nothrowv
+// NVPTX-SAME: () #[[ATTR0:[0-9]+]] {
+// NVPTX-NEXT:  entry:
+// NVPTX-NEXT:[[CALL:%.*]] = call noalias noundef ptr 
@_ZnwmRKSt9nothrow_t(i64 noundef 4, ptr noundef nonnull align 1 
dereferenceable(1) @nothrow) #[[ATTR4:[0-9]+]]
+// NVPTX-NEXT:ret ptr [[CALL]]
+//
+// AMDGPU-LABEL: define hidden noundef ptr @_Z17new_stuff_nothrowv
+// AMDGPU-SAME: () #[[ATTR0:[0-9]+]] {
+// AMDGPU-NEXT:  entry:
+// AMDGPU-NEXT:[[RETVAL:%.*]] = alloca ptr, align 8, addrspace(5)
+// AMDGPU-NEXT:[[RETVAL_ASCAST:%.*]] = addrspacecast ptr addrspace(5) 
[[RETVAL]] to ptr
+// AMDGPU-NEXT:[[CALL:%.*]] = call noalias noundef ptr 
@_ZnwmRKSt9nothrow_t(i64 noundef 4, ptr noundef nonnull align 1 
dereferenceable(1) addrspacecast (ptr addrspace(1) @nothrow to ptr)) 
#[[ATTR4:[0-9]+]]
+// AMDGPU-NEXT:ret ptr [[CALL]]
 //
 int* new_stuff_nothrow() {
   return new (nothrow) int;
 }
 
-// CXX03-

[PATCH] D152850: OpenMP: Add missing test coverage for nothrow new/delete

2023-06-28 Thread Matt Arsenault via Phabricator via cfe-commits
arsenm closed this revision.
arsenm added a comment.

51bb9b12f87ea315f750490c39cd993507202861 



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

https://reviews.llvm.org/D152850

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


[PATCH] D152851: OpenMP: Fix nothrow new/delete for amdgpu

2023-06-28 Thread Matt Arsenault via Phabricator via cfe-commits
arsenm closed this revision.
arsenm added a comment.

0e17174d40b2d25a755d2ce9acf7c905f254746d 



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

https://reviews.llvm.org/D152851

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


[PATCH] D153956: [clang][dataflow] Don't crash if copy constructor arg doesn't have a storage location.

2023-06-28 Thread Martin Böhme via Phabricator via cfe-commits
mboehme added a comment.

Pre-merge failures look unrelated


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153956

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


[PATCH] D153857: [clang] Fix new-expression with elaborated-type-specifier

2023-06-28 Thread Mariya Podchishchaeva via Phabricator via cfe-commits
Fznamznon updated this revision to Diff 535317.
Fznamznon added a comment.

Add comma and test


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153857

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Parse/Parser.h
  clang/lib/Parse/ParseDecl.cpp
  clang/lib/Parse/ParseExprCXX.cpp
  clang/test/CXX/dcl.dcl/dcl.spec/dcl.type/p3-0x.cpp
  clang/test/CXX/drs/dr19xx.cpp
  clang/test/CXX/drs/dr6xx.cpp
  clang/test/Parser/cxx11-type-specifier.cpp

Index: clang/test/Parser/cxx11-type-specifier.cpp
===
--- clang/test/Parser/cxx11-type-specifier.cpp
+++ clang/test/Parser/cxx11-type-specifier.cpp
@@ -7,16 +7,21 @@
 };
 enum E { e };
 
+template 
+struct Template { };
+
 void f() {
   try {
 (void) new constexpr int; // expected-error{{type name does not allow constexpr}}
   } catch (constexpr int) { // expected-error{{type name does not allow constexpr}}
   }
 
-  // These parse as type definitions, not as type references with braced
-  // initializers. Sad but true...
-  (void) new struct S {}; // expected-error{{'S' cannot be defined in a type specifier}}
-  (void) new enum E { e }; // expected-error{{'E' cannot be defined in a type specifier}}
+  (void) new struct S {};
+  (void) new enum E { e };
+  struct S *a = (1 == 1) ? new struct S : new struct S;
+  struct A *b = (1 == 1) ? new struct A : new struct A; // expected-error 2{{allocation of incomplete type}} // expected-note 2{{forward}}
+
+  (void) new Template {};
 }
 
 // And for trailing-type-specifier-seq
Index: clang/test/CXX/drs/dr6xx.cpp
===
--- clang/test/CXX/drs/dr6xx.cpp
+++ clang/test/CXX/drs/dr6xx.cpp
@@ -1078,9 +1078,10 @@
 (void)const_cast(0); // expected-error {{cannot be defined in a type specifier}}
 (void)sizeof(struct F*);
 (void)sizeof(struct F{}*); // expected-error {{cannot be defined in a type specifier}}
-(void)new struct G*;
-(void)new struct G{}*; // expected-error {{cannot be defined in a type specifier}}
+(void)new struct G*; // expected-note {{forward}}
+(void)new struct G{}*; // expected-error {{incomplete}}
 #if __cplusplus >= 201103L
+// expected-error@-2 {{expected expression}}
 (void)alignof(struct H*);
 (void)alignof(struct H{}*); // expected-error {{cannot be defined in a type specifier}}
 #endif
Index: clang/test/CXX/drs/dr19xx.cpp
===
--- clang/test/CXX/drs/dr19xx.cpp
+++ clang/test/CXX/drs/dr19xx.cpp
@@ -194,7 +194,7 @@
 enum E : int {1}; // expected-error {{expected identifier}} (not bit-field)
   };
   auto *p1 = new enum E : int; // expected-error {{only permitted as a standalone declaration}}
-  auto *p2 = new enum F : int {}; // expected-error {{cannot be defined in a type specifier}}
+  auto *p2 = new enum F : int {}; // expected-error {{only permitted as a standalone declaration}}
   auto *p3 = true ? new enum G : int {}; // expected-error {{forward reference}} expected-error {{incomplete}} expected-note {{declaration}}
   auto h() -> enum E : int {}; // expected-error {{only permitted as a standalone declaration}}
 
Index: clang/test/CXX/dcl.dcl/dcl.spec/dcl.type/p3-0x.cpp
===
--- clang/test/CXX/dcl.dcl/dcl.spec/dcl.type/p3-0x.cpp
+++ clang/test/CXX/dcl.dcl/dcl.spec/dcl.type/p3-0x.cpp
@@ -21,8 +21,8 @@
   for (struct S { S(int) {} } s : Undeclared); // expected-error{{types may not be defined in a for range declaration}}
// expected-error@-1{{use of undeclared identifier 'Undeclared'}}
 
-  new struct T {}; // expected-error {{'T' cannot be defined in a type specifier}}
-  new struct A {}; // expected-error {{'A' cannot be defined in a type specifier}}
+  new struct T {}; // expected-error {{allocation of incomplete type 'struct T'}} //expected-note{{forward declaration of 'T'}}
+  new struct A {};
 
   try {} catch (struct U {}) {} // expected-error {{'U' cannot be defined in a type specifier}}
 
Index: clang/lib/Parse/ParseExprCXX.cpp
===
--- clang/lib/Parse/ParseExprCXX.cpp
+++ clang/lib/Parse/ParseExprCXX.cpp
@@ -3231,7 +3231,7 @@
 // A new-type-id is a simplified type-id, where essentially the
 // direct-declarator is replaced by a direct-new-declarator.
 MaybeParseGNUAttributes(DeclaratorInfo);
-if (ParseCXXTypeSpecifierSeq(DS))
+if (ParseCXXTypeSpecifierSeq(DS, DeclaratorContext::CXXNew))
   DeclaratorInfo.setInvalidType(true);
 else {
   DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Index: clang/lib/Parse/ParseDecl.cpp
===
--- clang/lib/Parse/ParseDecl.cpp
+++ clang/lib/Parse/ParseDecl.cpp
@@ -2981,6 +298

[PATCH] D153612: [clang][analyzer] Add and change NoteTags in StdLibraryFunctionsChecker.

2023-06-28 Thread Donát Nagy via Phabricator via cfe-commits
donat.nagy added a comment.

The source code changes LGTM. I'll soon check the results on the open source 
projects and give a final approval based on that.

By the way, I think this commit and the "display notes only if interesting" 
follow-up change (D153776 ) should be merged 
at the same time (but I'd guess that you already planned to do it that way).




Comment at: 
clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp:1299
+// StdLibraryFunctionsChecker.
+ExplodedNode *Pred = const_cast(Node);
+if (!Case.getNote().empty()) {

balazske wrote:
> donat.nagy wrote:
> > balazske wrote:
> > > donat.nagy wrote:
> > > > Can you explain why is it safe to use `const_cast` here? (I don't see 
> > > > any concrete issue, but the engine has lots of invariants / unwritten 
> > > > rules and I fear that this might break one of them.)
> > > The node `Pred` should be modified only later when a successor is added 
> > > (`addTransition` has non-const parameter).
> > I understood that you //need// a non-const `ExplodedNode *` because 
> > `addTransition` expects it; I want to understand why you are //allowed to// 
> > `const_cast` it (why doesn't this confuse the engine logic).
> > 
> > Equivalent question from the other direction: Why did the author of 
> > `CheckerContext::getPredecessor()` specify that its return value is a 
> > //const// pointer to `ExplodedNode`?
> > 
> > If we can conclude that `const_cast` is valid in this kind of situation, 
> > then I'd also consider simply removing the "const" from the return type of 
> > `getPredecessor`.
> The `const_cast` is not needed at all if `Pred` and `Node` is made non-const, 
> and `getPredecessor` has a non-const version. The `Node` is saved because we 
> want to add transitions to it, it makes no sense to have it (a pointer to) 
> const. (Probably the const comes from a time when the `Node` was used only 
> for the lambda? In the lambda it could be const, if it matters.)
Sorry, it seems that I badly misread the source code of CheckerContext.h (I 
probably looked at the wrong line when I briefly jumped to the definition of 
`getPredecessor`). In fact, `getPredecessor` has only one version and it 
returns non-const `ExplodedNode *`.

This means that your code is (of course) completely valid.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153612

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


[PATCH] D153857: [clang] Fix new-expression with elaborated-type-specifier

2023-06-28 Thread Mariya Podchishchaeva via Phabricator via cfe-commits
Fznamznon added inline comments.



Comment at: clang/include/clang/Parse/Parser.h:2221
+DSC_association, // A _Generic selection expression's type association
+DSC_new  // C++ new operator
   };

aaron.ballman wrote:
> Adding the comma so the next person doesn't have to, and realigning to the 
> usual indentation
Added comma, but the indentation is what clang-format gave me. I'm afraid I 
won't pass the pre-commit with different .


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153857

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


[PATCH] D153690: [clang][Sema] Remove dead diagnostic for loss of __unaligned qualifier

2023-06-28 Thread Takuya Shimizu via Phabricator via cfe-commits
hazohelet added a comment.

In D153690#4453001 , @cjdb wrote:

> Excellent, thanks! LGTM, do you need assistance with merging?

Thanks for the review. I'll land this myself.


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

https://reviews.llvm.org/D153690

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


[clang] abc8367 - [clang][dataflow] Don't crash if copy constructor arg doesn't have a storage location.

2023-06-28 Thread Martin Braenne via cfe-commits

Author: Martin Braenne
Date: 2023-06-28T11:15:52Z
New Revision: abc8367413ff377b79e9743ca85252f209f81d65

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

LOG: [clang][dataflow] Don't crash if copy constructor arg doesn't have a 
storage location.

I accidentally used `cast` instead of `cast_or_null`.

Reviewed By: sammccall, xazax.hun

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

Added: 


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

Removed: 




diff  --git a/clang/lib/Analysis/FlowSensitive/Transfer.cpp 
b/clang/lib/Analysis/FlowSensitive/Transfer.cpp
index c09b6b9a99ac3..54b8b3a108dc0 100644
--- a/clang/lib/Analysis/FlowSensitive/Transfer.cpp
+++ b/clang/lib/Analysis/FlowSensitive/Transfer.cpp
@@ -598,7 +598,7 @@ class TransferVisitor : public 
ConstStmtVisitor {
   const Expr *Arg = S->getArg(0);
   assert(Arg != nullptr);
 
-  auto *ArgLoc = cast(
+  auto *ArgLoc = cast_or_null(
   Env.getStorageLocation(*Arg, SkipPast::Reference));
   if (ArgLoc == nullptr)
 return;

diff  --git a/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp 
b/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
index 51550adeea894..f41c3f2fdd2f7 100644
--- a/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
+++ b/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
@@ -2237,6 +2237,21 @@ TEST(TransferTest, CopyConstructorWithParens) {
   });
 }
 
+TEST(TransferTest, CopyConstructorArgIsRefReturnedByFunction) {
+  // This is a crash repro.
+  std::string Code = R"(
+struct S {};
+const S &returnsSRef();
+void target() {
+  S s(returnsSRef());
+}
+  )";
+  runDataflow(
+  Code,
+  [](const llvm::StringMap> &Results,
+ ASTContext &ASTCtx) {});
+}
+
 TEST(TransferTest, MoveConstructor) {
   std::string Code = R"(
 namespace std {



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


[PATCH] D153956: [clang][dataflow] Don't crash if copy constructor arg doesn't have a storage location.

2023-06-28 Thread Martin Böhme 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 rGabc8367413ff: [clang][dataflow] Don't crash if copy 
constructor arg doesn't have a storage… (authored by mboehme).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153956

Files:
  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
@@ -2237,6 +2237,21 @@
   });
 }
 
+TEST(TransferTest, CopyConstructorArgIsRefReturnedByFunction) {
+  // This is a crash repro.
+  std::string Code = R"(
+struct S {};
+const S &returnsSRef();
+void target() {
+  S s(returnsSRef());
+}
+  )";
+  runDataflow(
+  Code,
+  [](const llvm::StringMap> &Results,
+ ASTContext &ASTCtx) {});
+}
+
 TEST(TransferTest, MoveConstructor) {
   std::string Code = R"(
 namespace std {
Index: clang/lib/Analysis/FlowSensitive/Transfer.cpp
===
--- clang/lib/Analysis/FlowSensitive/Transfer.cpp
+++ clang/lib/Analysis/FlowSensitive/Transfer.cpp
@@ -598,7 +598,7 @@
   const Expr *Arg = S->getArg(0);
   assert(Arg != nullptr);
 
-  auto *ArgLoc = cast(
+  auto *ArgLoc = cast_or_null(
   Env.getStorageLocation(*Arg, SkipPast::Reference));
   if (ArgLoc == nullptr)
 return;


Index: clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
@@ -2237,6 +2237,21 @@
   });
 }
 
+TEST(TransferTest, CopyConstructorArgIsRefReturnedByFunction) {
+  // This is a crash repro.
+  std::string Code = R"(
+struct S {};
+const S &returnsSRef();
+void target() {
+  S s(returnsSRef());
+}
+  )";
+  runDataflow(
+  Code,
+  [](const llvm::StringMap> &Results,
+ ASTContext &ASTCtx) {});
+}
+
 TEST(TransferTest, MoveConstructor) {
   std::string Code = R"(
 namespace std {
Index: clang/lib/Analysis/FlowSensitive/Transfer.cpp
===
--- clang/lib/Analysis/FlowSensitive/Transfer.cpp
+++ clang/lib/Analysis/FlowSensitive/Transfer.cpp
@@ -598,7 +598,7 @@
   const Expr *Arg = S->getArg(0);
   assert(Arg != nullptr);
 
-  auto *ArgLoc = cast(
+  auto *ArgLoc = cast_or_null(
   Env.getStorageLocation(*Arg, SkipPast::Reference));
   if (ArgLoc == nullptr)
 return;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D153960: [clang][dataflow] Implement support for pointers to members.

2023-06-28 Thread Martin Böhme via Phabricator via cfe-commits
mboehme created this revision.
Herald added subscribers: martong, xazax.hun.
Herald added a reviewer: NoQ.
Herald added a project: All.
mboehme requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

The newly added tests crash without the other changes in this patch.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D153960

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
@@ -2523,6 +2523,54 @@
   });
 }
 
+TEST(TransferTest, PointerToMemberVariable) {
+  std::string Code = R"(
+struct S {
+  int i;
+};
+void target() {
+  int S::*P1 = &S::i;
+  int S::*P2 = &S::i;
+  // [[p]]
+}
+  )";
+  runDataflow(
+  Code,
+  [](const llvm::StringMap> &Results,
+ ASTContext &ASTCtx) {
+const Environment &Env = getEnvironmentAtAnnotation(Results, "p");
+
+auto &P1Val = getValueForDecl(ASTCtx, Env, "P1");
+auto &P2Val = getValueForDecl(ASTCtx, Env, "P2");
+
+ASSERT_EQ(&P1Val.getPointeeLoc(), &P2Val.getPointeeLoc());
+  });
+}
+
+TEST(TransferTest, PointerToMemberFunction) {
+  std::string Code = R"(
+struct S {
+  void Method();
+};
+void target() {
+  void (S::*P1)() = &S::Method;
+  void (S::*P2)() = &S::Method;
+  // [[p]]
+}
+  )";
+  runDataflow(
+  Code,
+  [](const llvm::StringMap> &Results,
+ ASTContext &ASTCtx) {
+const Environment &Env = getEnvironmentAtAnnotation(Results, "p");
+
+auto &P1Val = getValueForDecl(ASTCtx, Env, "P1");
+auto &P2Val = getValueForDecl(ASTCtx, Env, "P2");
+
+ASSERT_EQ(&P1Val.getPointeeLoc(), &P2Val.getPointeeLoc());
+  });
+}
+
 TEST(TransferTest, NullToMemberPointerCast) {
   std::string Code = R"(
 struct Foo {};
Index: clang/lib/Analysis/FlowSensitive/Transfer.cpp
===
--- clang/lib/Analysis/FlowSensitive/Transfer.cpp
+++ clang/lib/Analysis/FlowSensitive/Transfer.cpp
@@ -231,6 +231,15 @@
   void VisitDeclRefExpr(const DeclRefExpr *S) {
 const ValueDecl *VD = S->getDecl();
 assert(VD != nullptr);
+
+// `DeclRefExpr`s to fields and non-static methods aren't glvalues, and
+// there's also no sensible `Value` we can assign to them, so skip them.
+if (isa(VD))
+  return;
+if (auto *Method = dyn_cast(VD);
+Method && !Method->isStatic())
+  return;
+
 auto *DeclLoc = Env.getStorageLocation(*VD);
 if (DeclLoc == nullptr)
   return;
@@ -440,14 +449,18 @@
   break;
 }
 case UO_AddrOf: {
-  // Do not form a pointer to a reference. If `SubExpr` is assigned a
-  // `ReferenceValue` then form a value that points to the location of its
-  // pointee.
-  StorageLocation *PointeeLoc = Env.getStorageLocationStrict(*SubExpr);
-  if (PointeeLoc == nullptr)
-break;
+  StorageLocation *PointeeLoc = nullptr;
+  if (S->getType()->isMemberPointerType()) {
+if (auto *DeclRef = dyn_cast(SubExpr))
+  if (auto *D = DeclRef->getDecl())
+PointeeLoc = Env.getStorageLocation(*D);
+  } else {
+PointeeLoc = Env.getStorageLocationStrict(*SubExpr);
+  }
+
+  if (PointeeLoc)
+Env.setValueStrict(*S, Env.create(*PointeeLoc));
 
-  Env.setValueStrict(*S, Env.create(*PointeeLoc));
   break;
 }
 case UO_LNot: {
Index: clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
===
--- clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
+++ clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
@@ -168,6 +168,12 @@
 Funcs.insert(FD);
 }
 
+static void insertIfField(const Decl &D,
+  llvm::DenseSet &Fields) {
+  if (const auto *FD = dyn_cast(&D))
+Fields.insert(FD);
+}
+
 static void
 getFieldsGlobalsAndFuncs(const Decl &D,
  llvm::DenseSet &Fields,
@@ -204,13 +210,13 @@
   } else if (auto *E = dyn_cast(&S)) {
 insertIfGlobal(*E->getDecl(), Vars);
 insertIfFunction(*E->getDecl(), Funcs);
+insertIfField(*E->getDecl(), Fields);
   } else if (auto *E = dyn_cast(&S)) {
 // FIXME: should we be using `E->getFoundDecl()`?
 const ValueDecl *VD = E->getMemberDecl();
 insertIfGlobal(*VD, Vars);
 insertIfFunction(*VD, Funcs);
-if (const auto *FD = dyn_cast(VD))
-  Fields.insert(FD);
+insertIfField(*VD, Fields);
   }
 }
 
@@ -259,6 +265,14 @@
 auto &Loc = createStorageLocation(FD->getType());
 setStorageLocation(*FD, Loc);
   }
+

[PATCH] D153883: [Clang][OpenMP] Enable use of __kmpc_alloc_shared for VLAs defined in AMD GPU offloaded regions

2023-06-28 Thread Matt Arsenault via Phabricator via cfe-commits
arsenm added inline comments.



Comment at: clang/lib/CodeGen/CGDecl.cpp:1603
+// deallocation call of __kmpc_free_shared() is emitted later.
+if (getLangOpts().OpenMP && getTarget().getTriple().isAMDGCN()) {
+  // Emit call to __kmpc_alloc_shared() instead of the alloca.

ABataev wrote:
> doru1004 wrote:
> > jhuber6 wrote:
> > > ABataev wrote:
> > > > OpenMPIsDevice?
> > > Does NVPTX handle this already? If not, is there a compelling reason to 
> > > exclude NVPTX? Otherwise we should check if we are the OpenMP device.
> > Does NVPTX support dynamic allocas?
> It does not matter here, it depends on the runtime library implementations. 
> The compiler just shall provide proper runtime calls emission, everything 
> else is part of the runtime support.
I think I heard recent ptx introdced new instructions for it. amdgpu codegen 
just happens to be broken because we don't properly restore the stack 
afterwards. When I added the support we had no way of testing (and still don't 
really, __builtin_alloca doesn't handle non-0 stack address space correctly)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153883

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


[PATCH] D153962: [clang] Do not discard cleanups while processing immediate invocation

2023-06-28 Thread Mariya Podchishchaeva via Phabricator via cfe-commits
Fznamznon created this revision.
Herald added a project: All.
Fznamznon requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Since an immediate invocation is a full expression itself - it requires
an additional ExprWithCleanups node, but it can participate to a bigger
full expression which actually requires cleanups to be run after.

Thanks @ilya-biryukov for helping reducing the reproducer and confirming
that the analysis is correct.

Fixes https://github.com/llvm/llvm-project/issues/60709


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D153962

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Sema/Sema.h
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaExprCXX.cpp
  clang/test/CodeGenCXX/consteval-cleanup.cpp
  clang/test/SemaCXX/consteval-cleanup.cpp

Index: clang/test/SemaCXX/consteval-cleanup.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/consteval-cleanup.cpp
@@ -0,0 +1,42 @@
+// RUN: %clang_cc1 -Wno-unused-value -std=c++20 -ast-dump -verify %s -ast-dump | FileCheck %s
+
+// expected-no-diagnostics
+
+struct P {
+  consteval P() {}
+};
+
+struct A {
+  A(int v) { this->data = new int(v); }
+  ~A() { delete data; }
+private:
+  int *data;
+};
+
+void foo() {
+  for (;A(1), P(), false;);
+  // CHECK: foo
+  // CHECK: ExprWithCleanups
+  // CHECK-NEXT: BinaryOperator {{.*}} 'bool' ','
+  // CHECK-NEXT: BinaryOperator {{.*}} 'P':'P' ','
+  // CHECK-NEXT: CXXFunctionalCastExpr {{.*}} 'A':'A'
+  // CHECK-NEXT: CXXBindTemporaryExpr {{.*}} 'A':'A'
+  // CHECK-NEXT: CXXConstructExpr {{.*}} 'A':'A'
+  // CHECK: ConstantExpr {{.*}} 'P':'P'
+  // CHECK-NEXT: value:
+  // CHECK-NEXT: ExprWithCleanups
+}
+
+struct B {
+  int *p = new int(38);
+  consteval int get() { return *p; }
+  constexpr ~B() { delete p; }
+};
+
+void bar() {
+  // CHECK: bar
+  // CHECK: ConstantExpr
+  // CHECK-NEXT: value:
+  // CHECK-NEXT: ExprWithCleanups
+  int k = B().get();
+}
Index: clang/test/CodeGenCXX/consteval-cleanup.cpp
===
--- /dev/null
+++ clang/test/CodeGenCXX/consteval-cleanup.cpp
@@ -0,0 +1,21 @@
+// RUN: %clang_cc1 -std=c++20 -Wno-unused-value -triple x86_64-linux-gnu -emit-llvm %s -o - | FileCheck %s
+
+struct P {
+  consteval P() {}
+};
+
+struct A {
+  A(int v) { this->data = new int(v); }
+  ~A() { delete data; }
+private:
+  int *data;
+};
+
+void foo() {
+  for (;A(1), P(), false;);
+  // CHECK: foo
+  // CHECK: for.cond:
+  // CHECK: call void @_ZN1AC1Ei
+  // CHECK: call void @_ZN1AD1Ev
+  // CHECK: for.body
+}
Index: clang/lib/Sema/SemaExprCXX.cpp
===
--- clang/lib/Sema/SemaExprCXX.cpp
+++ clang/lib/Sema/SemaExprCXX.cpp
@@ -7346,15 +7346,16 @@
   return Bind;
 }
 
-ExprResult
-Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
+ExprResult Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr,
+ bool IsImmediateInvocation) {
   if (SubExpr.isInvalid())
 return ExprError();
 
-  return MaybeCreateExprWithCleanups(SubExpr.get());
+  return MaybeCreateExprWithCleanups(SubExpr.get(), IsImmediateInvocation);
 }
 
-Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
+Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr,
+bool IsImmediateInvocation) {
   assert(SubExpr && "subexpression can't be null!");
 
   CleanupVarDeclMarking();
@@ -7371,8 +7372,22 @@
 
   auto *E = ExprWithCleanups::Create(
   Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups);
-  DiscardCleanupsInEvaluationContext();
 
+  if (IsImmediateInvocation) {
+// Do not discard cleanups in case we're processing an immediate invocation
+// since an immediate invocation is a full expression itself - it requires
+// an additional ExprWithCleanups node, but it can participate to a bigger
+// full expression which actually requires cleanups to be run after.
+
+// ExprCleanupObjects contain BlockDecl or CompoundLiteralExpr nodes which
+// can't end up attached to a ExprWithCleanups created for an immediate
+// invocation, because BlockDecl is ObjC construct and compound literals
+// in C++ are just temporaries, so it is ok to not care about them.
+assert(LangOpts.CPlusPlus && "Immediate invocation outside of C++?");
+return E;
+  }
+
+  DiscardCleanupsInEvaluationContext();
   return E;
 }
 
Index: clang/lib/Sema/SemaExpr.cpp
===
--- clang/lib/Sema/SemaExpr.cpp
+++ clang/lib/Sema/SemaExpr.cpp
@@ -18183,7 +18183,7 @@
 return E;
   }
 
-  E = MaybeCreateExprWithCleanups(E);
+  E = MaybeCreateExprWithCleanups(E, /*IsImmediateInvocation=*/true);
 
   ConstantExpr *Res = ConstantExpr::Create(
   getASTContext(), E.get(),
Index: clang/include/clang/Sema/Sema.h
=

[PATCH] D153612: [clang][analyzer] Add and change NoteTags in StdLibraryFunctionsChecker.

2023-06-28 Thread Donát Nagy via Phabricator via cfe-commits
donat.nagy requested changes to this revision.
donat.nagy added a comment.
This revision now requires changes to proceed.

As I started to review the code of the follow-up commit D153776 
, I noticed a dangling `StringRef` bug which 
belongs to this review.

Moreover, as a minor remark I'd note that LLVM has a dedicated class for 
storing string literal constants (btw I learned this from @Szelethus yesterday).




Comment at: 
clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp:1303
+  // use it as a note tag.
+  StringRef Note = Case.getNote();
+  if (Summary.getInvalidationKd() == EvalCallAsPure) {

This variable will be captured and stored by the lambda functions, so it should 
own the memory area of  the string.

In the current code this did not cause problems because this StringRef points 
to the memory area of a string literal (which stays valid); but if later 
changes introduced dynamically generated note tags, then this code would dump 
random memory garbage.

By the way, a very similar issue survived almost four years in 
CheckerContext.h, I'm fixing it in D153889.



Comment at: 
clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp:1318
+  if (Node->succ_size() > 1)
+return Note.str();
+  return "";

Also update this when you change the type of `Note` to `std::string`.



Comment at: 
clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp:1687-1688
 
+  const char *GenericSuccessMsg = "Assuming that the call is successful";
+  const char *GenericFailureMsg = "Assuming that the call fails";
+

Consider using the `StringLiteral` subclass of `StringRef` which is designed 
for this kind of application (and determines the length of the string in 
compile time instead of calling `strlen` during a runtime `const char * → 
StringRef` conversion):
https://llvm.org/doxygen/classllvm_1_1StringLiteral.html
(After the suggested change, also update the code that uses these variables!)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153612

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


[PATCH] D153294: [clang] Do not create ExprWithCleanups while checking immediate invocation

2023-06-28 Thread Mariya Podchishchaeva via Phabricator via cfe-commits
Fznamznon added a comment.

> I believe we should make the proposed change (add potentially redundant 
> ExprWithCleanups without touching the cleanups objects or flags) without 
> blocking on Richard's approval.

I posted https://reviews.llvm.org/D153962 .


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153294

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


[PATCH] D153960: [clang][dataflow] Implement support for pointers to members.

2023-06-28 Thread Dmitri Gribenko via Phabricator via cfe-commits
gribozavr2 requested changes to this revision.
gribozavr2 added a comment.
This revision now requires changes to proceed.

Using PointerValue to model pointers to data members does not look right to me, 
because a pointer to data member is an offset within an object that we apply 
this pointer to, it is not a specific storage location.

I think we either shouldn't be modeling them at all (current implementation) 
and fix any crashes in the downstream code to allow non-modeled constructs in 
more places, or we should have a distinct kind of Value for pointers to members.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153960

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


[PATCH] D144911: adding bf16 support to NVPTX

2023-06-28 Thread Benjamin Kramer via Phabricator via cfe-commits
bkramer accepted this revision.
bkramer added a comment.
This revision is now accepted and ready to land.

I don't have much knowledge about the PTX ABI, but everything here makes 
perfect sense to me.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144911

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


[clang-tools-extra] 8ceb419 - [clangd] Fix some typos, NFC

2023-06-28 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2023-06-28T14:05:21+02:00
New Revision: 8ceb4190fe9baa617bc65e99f0296531c88a5a79

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

LOG: [clangd] Fix some typos, NFC

Added: 


Modified: 
clang-tools-extra/clangd/ClangdLSPServer.cpp
clang-tools-extra/clangd/Config.h
clang-tools-extra/clangd/ParsedAST.cpp
clang-tools-extra/clangd/Preamble.h
clang-tools-extra/clangd/TUScheduler.cpp
clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/ClangdLSPServer.cpp 
b/clang-tools-extra/clangd/ClangdLSPServer.cpp
index bf4c1a982834b..64489f78d843d 100644
--- a/clang-tools-extra/clangd/ClangdLSPServer.cpp
+++ b/clang-tools-extra/clangd/ClangdLSPServer.cpp
@@ -1720,7 +1720,7 @@ std::vector 
ClangdLSPServer::getFixes(llvm::StringRef File,
 }
 
 // A completion request is sent when the user types '>' or ':', but we only
-// want to trigger on '->' and '::'. We check the preceeding text to make
+// want to trigger on '->' and '::'. We check the preceding text to make
 // sure it matches what we expected.
 // Running the lexer here would be more robust (e.g. we can detect comments
 // and avoid triggering completion there), but we choose to err on the side

diff  --git a/clang-tools-extra/clangd/Config.h 
b/clang-tools-extra/clangd/Config.h
index 502dd01df1483..b46fedac3f88e 100644
--- a/clang-tools-extra/clangd/Config.h
+++ b/clang-tools-extra/clangd/Config.h
@@ -100,7 +100,7 @@ struct Config {
 
 /// Configures what clang-tidy checks to run and options to use with them.
 struct {
-  // A comma-seperated list of globs specify which clang-tidy checks to 
run.
+  // A comma-separated list of globs specify which clang-tidy checks to 
run.
   std::string Checks;
   llvm::StringMap CheckOptions;
 } ClangTidy;

diff  --git a/clang-tools-extra/clangd/ParsedAST.cpp 
b/clang-tools-extra/clangd/ParsedAST.cpp
index b810feab07581..02c8597c79613 100644
--- a/clang-tools-extra/clangd/ParsedAST.cpp
+++ b/clang-tools-extra/clangd/ParsedAST.cpp
@@ -706,7 +706,7 @@ ParsedAST::build(llvm::StringRef Filename, const 
ParseInputs &Inputs,
   ASTDiags.EndSourceFile();
 
   std::vector Diags = CompilerInvocationDiags;
-  // FIXME: Also skip generation of diagnostics alltogether to speed up ast
+  // FIXME: Also skip generation of diagnostics altogether to speed up ast
   // builds when we are patching a stale preamble.
   // Add diagnostics from the preamble, if any.
   if (Preamble)

diff  --git a/clang-tools-extra/clangd/Preamble.h 
b/clang-tools-extra/clangd/Preamble.h
index b3e53909ac73c..cbadae31dd02e 100644
--- a/clang-tools-extra/clangd/Preamble.h
+++ b/clang-tools-extra/clangd/Preamble.h
@@ -48,7 +48,7 @@
 namespace clang {
 namespace clangd {
 
-/// The captured AST conext.
+/// The captured AST context.
 /// Keeps necessary structs for an ASTContext and Preprocessor alive.
 /// This enables consuming them after context that produced the AST is gone.
 /// (e.g. indexing a preamble ast on a separate thread). ASTContext stored
@@ -186,7 +186,7 @@ class PreamblePatch {
 const SourceManager &SM);
 
   /// Adjusts CI (which compiles the modified inputs) to be used with the
-  /// baseline preamble. This is done by inserting an artifical include to the
+  /// baseline preamble. This is done by inserting an artificial include to the
   /// \p CI that contains new directives calculated in create.
   void apply(CompilerInvocation &CI) const;
 

diff  --git a/clang-tools-extra/clangd/TUScheduler.cpp 
b/clang-tools-extra/clangd/TUScheduler.cpp
index 968f4452e020e..46c469ff3f411 100644
--- a/clang-tools-extra/clangd/TUScheduler.cpp
+++ b/clang-tools-extra/clangd/TUScheduler.cpp
@@ -943,7 +943,7 @@ void ASTWorker::update(ParseInputs Inputs, WantDiagnostics 
WantDiags,
 // Emit diagnostics from (possibly) stale preamble while waiting for a
 // rebuild. Newly built preamble cannot emit diagnostics before this call
 // finishes (ast callbacks are called from astpeer thread), hence we
-// gurantee eventual consistency.
+// guarantee eventual consistency.
 if (LatestPreamble && WantDiags != WantDiagnostics::No)
   generateDiagnostics(std::move(Invocation), std::move(Inputs),
   std::move(CompilerInvocationDiags));

diff  --git a/clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp 
b/clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
index 4e2f0b6434c34..ef057158965d5 100644
--- a/clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
+++ b/clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
@@ -1629,7 +1629,7 @@ TEST_F(TUSchedulerTests, PreambleThrottle) {
 // We haven't released anything yet, w

[PATCH] D153960: [clang][dataflow] Implement support for pointers to members.

2023-06-28 Thread Sam McCall via Phabricator via cfe-commits
sammccall accepted this revision.
sammccall added a comment.

Per offline discussion, I think modelling pointer-to-member as PointerValue 
does make sense, though that's not completely obvious.
Can we document this on PointerValue? (And that it points to a StorageLocation 
for the decl, which has no value)




Comment at: clang/lib/Analysis/FlowSensitive/Transfer.cpp:236
+// `DeclRefExpr`s to fields and non-static methods aren't glvalues, and
+// there's also no sensible `Value` we can assign to them, so skip them.
+if (isa(VD))

I'm a bit confused by this. Why bail out rather than create the storage 
location?

`C::x` is going to be part of `&C::x`, and we're going to create the 
storagelocation by calling getStorageLocation() on line 456. So why not do it 
already?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153960

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


[PATCH] D153852: [clang][dataflow] Initialize fields of anonymous records correctly.

2023-06-28 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/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp:356
+  Member = cast(I);
+  MemberLoc = 
&cast(MemberLoc)->getChild(*Member);
+}

Is there a chance that there will be no such child if we hit one of our limits 
for modeling recursive data structures?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153852

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


[PATCH] D152054: [OpenMP] Codegen support for thread_limit on target directive

2023-06-28 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added inline comments.



Comment at: clang/lib/CodeGen/CGOpenMPRuntime.cpp:9818
+  D.hasClausesOfKind() ||
+  (CGM.getLangOpts().OpenMP >= 51 && D.getDirectiveKind() == OMPD_target &&
+   D.hasClausesOfKind());

What if D is combined target directive, i.e. D.getDirectiveKind() is something 
like OMPD_target_teams, etc.?



Comment at: clang/lib/CodeGen/CGStmtOpenMP.cpp:5143-5148
+S.getSingleClause()) {
+  // Emit __kmpc_set_thread_limit() to set the thread_limit for the task
+  // enclosing this target region. This will indirectly set the 
thread_limit
+  // for every applicable construct within target region.
+  CGF.CGM.getOpenMPRuntime().emitThreadLimitClause(
+  CGF, S.getSingleClause()->getThreadLimit(),

Avoid double call of S.getSingleClause(), store in local 
variable call result.



Comment at: clang/test/OpenMP/target_codegen.cpp:849
 // OMP51: [[CE:%.*]] = load {{.*}} [[CEA]]
-// OMP51: call i32 @__tgt_target_kernel({{.*}}, i64 -1, i32 -1, i32 [[CE]],
+// OMP51: call ptr @__kmpc_omp_task_alloc({{.*@.omp_task_entry.*}})
+// OMP51: call i32 [[OMP_TASK_ENTRY]]

It requires extra resource consumption, can you try to avoid creating outer 
task, if possible?



Comment at: openmp/runtime/src/kmp_ftn_entry.h:809
+return thread_limit;
+  else
+return thread->th.th_current_task->td_icvs.thread_limit;

No need for else here


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D152054

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


[PATCH] D153556: [OPENMP52] Initial support for doacross clause.

2023-06-28 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added inline comments.



Comment at: clang/lib/Parse/ParseOpenMP.cpp:4415-4439
+  } else if (Kind == OMPC_doacross) {
+// Handle dependence type for the doacross clause.
+ColonProtectionRAIIObject ColonRAII(*this);
+Data.ExtraModifier = getOpenMPSimpleClauseType(
+Kind, Tok.is(tok::identifier) ? PP.getSpelling(Tok) : "",
+getLangOpts());
+Data.ExtraModifierLoc = Tok.getLocation();

jyu2 wrote:
> ABataev wrote:
> > Can it be unified with depenbd clause parsing? (Maybe in a separate 
> > template function)
> I don't really has an idea on how to combine this two with template function. 
>  Since depend clause in ordered is deprecated in 52, and will be removed, 
> should we leave as this?
Even ff it will be removed in 52, it will still stay for OpenMP < 52. Would be 
good to try to unify it.



Comment at: clang/lib/Sema/SemaOpenMP.cpp:20694-20700
+auto *C = OMPDoacrossClause::Create(
+Context, StartLoc, LParenLoc, EndLoc,
+IsSource ? OMPC_DOACROSS_source : OMPC_DOACROSS_sink, DepLoc, ColonLoc,
+Vars, TotalDepCount.getZExtValue());
+if (DSAStack->isParentOrderedRegion())
+  DSAStack->addDoacrossDependClause(C, OpsOffs);
+return C;

Better to create clauses in ActOnDoAcross and ActOnDepend, this function better 
to return required data as a struct/class/bolean, etc.



Comment at: clang/lib/Sema/SemaOpenMP.cpp:20701
+return C;
+  } else {
+auto *C = OMPDependClause::Create(

No need for else


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

https://reviews.llvm.org/D153556

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


[PATCH] D153321: [OpenMP] Fix lvalue reference type generation in untied task loop

2023-06-28 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev accepted this revision.
ABataev added a comment.
This revision is now accepted and ready to land.

LG


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153321

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


[PATCH] D153953: Revert "[AMDGPU] Mark mbcnt as convergent"

2023-06-28 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl requested changes to this revision.
yaxunl added a comment.
This revision now requires changes to proceed.

Marking mbcnt as convergent, together with https://reviews.llvm.org/D144756 
prevent mbcnt to be merged, which fixed the reported issue.

Do you have an alternative fix for the issue?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153953

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


[PATCH] D150803: [WebAssembly] Support `annotate` clang attributes for marking functions.

2023-06-28 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman resigned from this revision.
aaron.ballman added a comment.
This revision is now accepted and ready to land.

In D150803#4454188 , @sbc100 wrote:

> In D150803#4454164 , @brendandahl 
> wrote:
>
>> In D150803#4440802 , 
>> @aaron.ballman wrote:
>>
>>> Marking as requested changes so it's clear there's more worth discussing, 
>>> so we don't accidentally land this.
>>
>> I've switched to using `annotate` now. Let me know if there's anything else.
>
> I guess the CL title and description now need updating?   Nice to see we no 
> longer need any clang changes here!

FWIW, I like this approach! I'm going to resign as a reviewer so that my 
"requested changes" marking no longer matters, but I'll still be subscribed to 
the review if folks need me to weigh in on anything for some reason.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D150803

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


[PATCH] D153582: [SystemZ][z/OS] Add required options/macro/etc for z/os compilation step

2023-06-28 Thread Sean via Phabricator via cfe-commits
SeanP updated this revision to Diff 535353.
SeanP added a comment.

Got old diff last time.


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

https://reviews.llvm.org/D153582

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Basic/Targets/OSTargets.h
  clang/lib/Basic/Targets/SystemZ.h
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Driver/ToolChains/ZOS.cpp
  clang/lib/Driver/ToolChains/ZOS.h
  clang/test/Driver/zos-comp-cxx.cpp
  clang/test/Driver/zos-comp.c
  clang/test/Driver/zos-driver-defaults.c
  clang/test/Preprocessor/init-s390x.c

Index: clang/test/Preprocessor/init-s390x.c
===
--- clang/test/Preprocessor/init-s390x.c
+++ clang/test/Preprocessor/init-s390x.c
@@ -183,17 +183,12 @@
 // RUN: %clang_cc1 -E -dM -ffreestanding -triple=s390x-none-zos -fno-signed-char < /dev/null | FileCheck -match-full-lines -check-prefix S390X-ZOS %s
 // RUN: %clang_cc1 -x c++ -std=gnu++14 -E -dM -ffreestanding -triple=s390x-none-zos -fno-signed-char < /dev/null | FileCheck -match-full-lines -check-prefix S390X-ZOS -check-prefix S390X-ZOS-GNUXX %s
 
-// S390X-ZOS-GNUXX: #define _EXT 1
 // S390X-ZOS:   #define _LONG_LONG 1
-// S390X-ZOS-GNUXX: #define _MI_BUILTIN 1
-// S390X-ZOS:   #define _OPEN_DEFAULT 1
-// S390X-ZOS:   #define _UNIX03_WITHDRAWN 1
-// S390X-ZOS-GNUXX: #define _XOPEN_SOURCE 600
 // S390X-ZOS:   #define __370__ 1
 // S390X-ZOS:   #define __64BIT__ 1
 // S390X-ZOS:   #define __BFP__ 1
 // S390X-ZOS:   #define __BOOL__ 1
-// S390X-ZOS-GNUXX: #define __DLL__ 1
+// S390X-ZOS:   #define __COMPILER_VER__ 0x5000
 // S390X-ZOS:   #define __LONGNAME__ 1
 // S390X-ZOS:   #define __MVS__ 1
 // S390X-ZOS:   #define __THW_370__ 1
Index: clang/test/Driver/zos-driver-defaults.c
===
--- clang/test/Driver/zos-driver-defaults.c
+++ clang/test/Driver/zos-driver-defaults.c
@@ -1,8 +1,23 @@
-// RUN: %clang -### --target=s390x-none-zos -fsyntax-only %s 2>&1 | FileCheck --check-prefix=CHECK-SHORT-ENUMS %s
+// RUN: %clang -### --target=s390x-none-zos -fsyntax-only %s 2>&1 | FileCheck --check-prefixes=CHECK-C-MACRO,CHECK-SHORT-ENUMS %s
+// RUN: %clang -### --target=s390x-none-zos -fsyntax-only %s 2>&1 | FileCheck --check-prefix=CHECK-ZOS-INCLUDES %s
 // RUN: %clang -### --target=s390x-none-zos -fno-short-enums -fsyntax-only %s 2>&1 | FileCheck %s
+// RUN: %clangxx -### --target=s390x-none-zos -fsyntax-only %s 2>&1 | FileCheck --check-prefixes=CHECK-C-MACRO,CHECK-CXX-MACRO %s
+// RUN: %clang -### --target=s390x-none-zos -x c++ -fsyntax-only %s 2>&1 | FileCheck --check-prefixes=CHECK-C-MACRO,CHECK-CXX-MACRO %s
+
+//CHECK-C-MACRO: -D_UNIX03_WITHDRAWN
+//CHECK-C-MACRO: -D_OPEN_DEFAULT
+
+//CHECK-CXX-MACRO: -D_XOPEN_SOURCE=600
+//CHECK-USER-CXX-MACRO-NOT: -D_XOPEN_SOURCE=600
+//CHECK-USER-CXX-MACRO: "-D" "_XOPEN_SOURCE=700"
 
 //CHECK-SHORT-ENUMS: -fshort-enums
 //CHECK-SHORT-ENUMS: -fno-signed-char
 
+//CHECK-ZOS-INCLUDES: clang{{.*}} "-cc1" "-triple" "s390x-none-zos"
+//CHECK-ZOS-INCLUDES-SAME: "-resource-dir" "[[RESOURCE_DIR:[^"]+]]"
+//CHECK-ZOS-INCLUDES-SAME: "-internal-isystem" "[[RESOURCE_DIR]]{{(/|)}}include{{(/|)}}zos_wrappers"
+//CHECK-ZOS-INCLUDES-SAME: "-internal-isystem" "[[RESOURCE_DIR]]{{(/|)}}include"
+//
 //CHECK-NOT: -fshort-enums
 //CHECK: -fno-signed-char
Index: clang/test/Driver/zos-comp.c
===
--- /dev/null
+++ clang/test/Driver/zos-comp.c
@@ -0,0 +1,75 @@
+// Tests that the z/OS toolchain adds system includes to its search path.
+
+// RUN: %clang -c -### %s --target=s390x-ibm-zos 2>&1 \
+// RUN:   | FileCheck %s
+
+// CHECK: "-D_UNIX03_WITHDRAWN"
+// CHECK-SAME: "-D_OPEN_DEFAULT"
+// CHECK-SAME: "-resource-dir" "[[RESOURCE_DIR:[^"]+]]"
+// CHECK-SAME: "-internal-isystem" "[[RESOURCE_DIR]]{{(/|)}}include{{(/|)}}zos_wrappers"
+// CHECK-SAME: "-internal-isystem" "[[RESOURCE_DIR]]{{(/|)}}include"
+// CHECK-SAME: "-internal-isystem" "/usr/include"
+// CHECK-SAME: "-fshort-enums"
+// CHECK-SAME: "-fno-signed-char"
+// CHECK-SAME: "-fno-signed-wchar"
+
+// RUN: %clang -c -### -mzos-sys-include=/ABC/DEF %s 2>&1 \
+// RUN:		--target=s390x-ibm-zos \
+// RUN:   | FileCheck --check-prefixes=CHECK2 %s
+
+// CHECK2: "-D_UNIX03_WITHDRAWN"
+// CHECK2-SAME: "-D_OPEN_DEFAULT"
+// CHECK2-SAME: "-resource-dir" "[[RESOURCE_DIR:[^"]+]]"
+// CHECK2-SAME: "-internal-isystem" "[[RESOURCE_DIR]]{{(/|)}}include{{(/|)}}zos_wrappers"
+// CHECK2-SAME: "-internal-isystem" "[[RESOURCE_DIR]]{{(/|)}}include"
+// CHECK2-SAME: "-internal-isystem" "/ABC/DEF"
+// CHECK2-NOT: "-internal-isystem" "/usr/include"
+// CHECK2-SAME: "-fshort-enums"
+// CHECK2-SAME: "-fno-signed-char"
+// CHECK2-SAME: "-fno-signed-wchar"
+
+// RUN: %clang -c -### -mzos-sys-include=/ABC/DEF:/ghi/jkl %s 2>&1 \
+// RUN:		--target=s390x-ibm-zos \
+// RUN:   | FileCheck --che

[PATCH] D153953: Revert "[AMDGPU] Mark mbcnt as convergent"

2023-06-28 Thread Sameer Sahasrabuddhe via Phabricator via cfe-commits
sameerds added a comment.

In D153953#4455794 , @yaxunl wrote:

> Marking mbcnt as convergent, together with https://reviews.llvm.org/D144756 
> prevent mbcnt to be merged, which fixed the reported issue.
>
> Do you have an alternative fix for the issue?

I completely disagree with this line of thought. The change to mbcnt is 
fundamentally incorrect and not related to the issue. There is no ground to ask 
for changes to this revision. Why was the change to mbcnt committed if was not 
an actual fix for anything?

Also, please note that the issue itself is invalid. I have put a comment in 
github explaining the same. The original program itself is invalid.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153953

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


[PATCH] D105759: Implement P2361 Unevaluated string literals

2023-06-28 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin updated this revision to Diff 535355.
cor3ntin added a comment.

Fix tests and handle variadic attributes.

- With that all normal attributes are handled. Only attributes with custop 
parsing code and those specified as an enum are left untouched.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105759

Files:
  clang-tools-extra/test/clang-tidy/checkers/modernize/unary-static-assert.cpp
  clang/include/clang/AST/Expr.h
  clang/include/clang/Basic/DiagnosticCommonKinds.td
  clang/include/clang/Basic/DiagnosticLexKinds.td
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Lex/LiteralSupport.h
  clang/include/clang/Parse/Parser.h
  clang/include/clang/Sema/ParsedAttr.h
  clang/include/clang/Sema/Sema.h
  clang/lib/AST/Expr.cpp
  clang/lib/Lex/LiteralSupport.cpp
  clang/lib/Lex/PPMacroExpansion.cpp
  clang/lib/Lex/Pragma.cpp
  clang/lib/Parse/ParseDecl.cpp
  clang/lib/Parse/ParseDeclCXX.cpp
  clang/lib/Parse/ParseExpr.cpp
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaExprCXX.cpp
  clang/lib/Sema/SemaInit.cpp
  clang/test/CXX/dcl.dcl/dcl.link/p2.cpp
  clang/test/CXX/dcl.dcl/p4-0x.cpp
  clang/test/FixIt/fixit-static-assert.cpp
  clang/test/Parser/MicrosoftExtensions.cpp
  clang/test/Parser/c2x-attributes.c
  clang/test/Parser/cxx-attributes.cpp
  clang/test/Parser/cxx0x-attributes.cpp
  clang/test/Sema/MicrosoftExtensions.c
  clang/test/Sema/annotate-type.c
  clang/test/Sema/annotate.c
  clang/test/Sema/attr-assume.c
  clang/test/Sema/attr-btf_tag.c
  clang/test/Sema/attr-btf_type_tag.c
  clang/test/Sema/attr-capabilities.c
  clang/test/Sema/attr-enforce-tcb-errors.cpp
  clang/test/Sema/attr-enforce-tcb-errors.m
  clang/test/Sema/attr-error.c
  clang/test/Sema/attr-handles.cpp
  clang/test/Sema/attr-section.c
  clang/test/Sema/attr-tls_model.c
  clang/test/Sema/attr-unavailable-message.c
  clang/test/Sema/attr-warning.c
  clang/test/Sema/diagnose_if.c
  clang/test/Sema/enable_if.c
  clang/test/SemaCXX/attr-deprecated-replacement-error.cpp
  clang/test/SemaCXX/attr-no-sanitize.cpp
  clang/test/SemaCXX/attr-section.cpp
  clang/test/SemaCXX/attr-weakref.cpp
  clang/test/SemaCXX/static-assert.cpp
  clang/test/SemaCXX/suppress.cpp
  clang/test/SemaObjC/attr-swift_bridge.m
  clang/test/SemaObjC/objc-asm-attribute-neg-test.m
  clang/test/SemaObjC/validate-attr-swift_attr.m
  clang/test/SemaTemplate/attributes.cpp
  clang/utils/TableGen/ClangAttrEmitter.cpp
  llvm/cmake/modules/HandleLLVMOptions.cmake

Index: llvm/cmake/modules/HandleLLVMOptions.cmake
===
--- llvm/cmake/modules/HandleLLVMOptions.cmake
+++ llvm/cmake/modules/HandleLLVMOptions.cmake
@@ -605,7 +605,7 @@
   # crash if LLVM is built with GCC and LTO enabled (#57740).  Until
   # these bugs are fixed, we need to disable dead store eliminations
   # based on object lifetime.
-  add_flag_if_supported("-fno-lifetime-dse" CMAKE_CXX_FLAGS)
+  # add_flag_if_supported("-fno-lifetime-dse" CMAKE_CXX_FLAGS)
 endif ( LLVM_COMPILER_IS_GCC_COMPATIBLE )
 
 # Modules enablement for GCC-compatible compilers:
Index: clang/utils/TableGen/ClangAttrEmitter.cpp
===
--- clang/utils/TableGen/ClangAttrEmitter.cpp
+++ clang/utils/TableGen/ClangAttrEmitter.cpp
@@ -2297,6 +2297,22 @@
  .Default(false);
 }
 
+static bool isStringLiteralArgument(const Record *Arg) {
+  return !Arg->getSuperClasses().empty() &&
+ llvm::StringSwitch(
+ Arg->getSuperClasses().back().first->getName())
+ .Case("StringArgument", true)
+ .Default(false);
+}
+
+static bool isVariadicStringLiteralArgument(const Record *Arg) {
+  return !Arg->getSuperClasses().empty() &&
+ llvm::StringSwitch(
+ Arg->getSuperClasses().back().first->getName())
+ .Case("VariadicStringArgument", true)
+ .Default(false);
+}
+
 static void emitClangAttrVariadicIdentifierArgList(RecordKeeper &Records,
raw_ostream &OS) {
   OS << "#if defined(CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST)\n";
@@ -2317,6 +2333,34 @@
   OS << "#endif // CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST\n\n";
 }
 
+// Emits the list of arguments that shoulkd be parsed as unevaluated string
+// literals for each attributes
+static void emitClangAttrUnevaluatedStringLiteralList(RecordKeeper &Records,
+  raw_ostream &OS) {
+  OS << "#if defined(CLANG_ATTR_STRING_LITERAL_ARG_LIST)\n";
+  std::vector Attrs = Records.getAllDerivedDefinitions("Attr");
+  for (const auto *Attr : Attrs) {
+std::vector Args = Attr->getValueAsListOfDefs("Args");
+uint32_t Bits = 0;
+for (uint32_t N = 0; N < Args.size(); N++) {
+  Bits |= (isStringLiteralArgument(Args[N]) << 

[PATCH] D152504: [clang][ThreadSafety] Analyze cleanup functions

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



Comment at: clang/lib/Analysis/ThreadSafety.cpp:2436
+CF.getVarDecl()->getLocation());
+  break;
+}

aaronpuchert wrote:
> aaronpuchert wrote:
> > tbaeder wrote:
> > > This handles the function call, but without the instance parameter. I was 
> > > wondering how to best do that.
> > Should you not simply pass `SxBuilder.createVariable(CF.getVarDecl())` as 
> > third parameter in analogy with the `AutomaticObjectDtor` case? It might 
> > also make sense to copy the attribute check.
> Can you write a test case that relies on passing the variable? Here is an 
> idea:
> ```
> void unlock_scope(Mutex **mu) __attribute__((release_capability(*mu))) {
>   mutex_exclusive_unlock(*mu);
> }
> 
> Mutex* const CLEANUP(unlock_scope) scope = &mu1;
> mutex_exclusive_lock(*scope);
> // Unlock should happen automatically.
> ```
> I think this is mildly more interesting than the cleanup function with an 
> unused parameter.
> 
> Unfortunately this is not quite as powerful as a scoped lock in C++, as we 
> don't track the identity `scope == &mu1`. So `guarded_by` won't work with 
> this. But we can at least see warnings on balanced locking/unlocking.
> 
> As for proper scoped locking, we could treat some variable initializations 
> like construction of a C++ scoped lock. But let's discuss this separately.
Yeah, it doesn't find the lock; I assume that's because the first parameter 
here is not an _actual_ this parameter; I'd have to handle the var decl as a 
regular parameter.


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

https://reviews.llvm.org/D152504

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


[PATCH] D105759: Implement P2361 Unevaluated string literals

2023-06-28 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin added a comment.

Note that I have confirmed that all the change attributes require a 
StringLiteral and go through `checkStringLiteralArgumentAttr`


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105759

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


[PATCH] D105759: Implement P2361 Unevaluated string literals

2023-06-28 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin updated this revision to Diff 535356.
cor3ntin added a comment.

revert accidental changes to cmake


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105759

Files:
  clang-tools-extra/test/clang-tidy/checkers/modernize/unary-static-assert.cpp
  clang/include/clang/AST/Expr.h
  clang/include/clang/Basic/DiagnosticCommonKinds.td
  clang/include/clang/Basic/DiagnosticLexKinds.td
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Lex/LiteralSupport.h
  clang/include/clang/Parse/Parser.h
  clang/include/clang/Sema/ParsedAttr.h
  clang/include/clang/Sema/Sema.h
  clang/lib/AST/Expr.cpp
  clang/lib/Lex/LiteralSupport.cpp
  clang/lib/Lex/PPMacroExpansion.cpp
  clang/lib/Lex/Pragma.cpp
  clang/lib/Parse/ParseDecl.cpp
  clang/lib/Parse/ParseDeclCXX.cpp
  clang/lib/Parse/ParseExpr.cpp
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaExprCXX.cpp
  clang/lib/Sema/SemaInit.cpp
  clang/test/CXX/dcl.dcl/dcl.link/p2.cpp
  clang/test/CXX/dcl.dcl/p4-0x.cpp
  clang/test/FixIt/fixit-static-assert.cpp
  clang/test/Parser/MicrosoftExtensions.cpp
  clang/test/Parser/c2x-attributes.c
  clang/test/Parser/cxx-attributes.cpp
  clang/test/Parser/cxx0x-attributes.cpp
  clang/test/Sema/MicrosoftExtensions.c
  clang/test/Sema/annotate-type.c
  clang/test/Sema/annotate.c
  clang/test/Sema/attr-assume.c
  clang/test/Sema/attr-btf_tag.c
  clang/test/Sema/attr-btf_type_tag.c
  clang/test/Sema/attr-capabilities.c
  clang/test/Sema/attr-enforce-tcb-errors.cpp
  clang/test/Sema/attr-enforce-tcb-errors.m
  clang/test/Sema/attr-error.c
  clang/test/Sema/attr-handles.cpp
  clang/test/Sema/attr-section.c
  clang/test/Sema/attr-tls_model.c
  clang/test/Sema/attr-unavailable-message.c
  clang/test/Sema/attr-warning.c
  clang/test/Sema/diagnose_if.c
  clang/test/Sema/enable_if.c
  clang/test/SemaCXX/attr-deprecated-replacement-error.cpp
  clang/test/SemaCXX/attr-no-sanitize.cpp
  clang/test/SemaCXX/attr-section.cpp
  clang/test/SemaCXX/attr-weakref.cpp
  clang/test/SemaCXX/static-assert.cpp
  clang/test/SemaCXX/suppress.cpp
  clang/test/SemaObjC/attr-swift_bridge.m
  clang/test/SemaObjC/objc-asm-attribute-neg-test.m
  clang/test/SemaObjC/validate-attr-swift_attr.m
  clang/test/SemaTemplate/attributes.cpp
  clang/utils/TableGen/ClangAttrEmitter.cpp

Index: clang/utils/TableGen/ClangAttrEmitter.cpp
===
--- clang/utils/TableGen/ClangAttrEmitter.cpp
+++ clang/utils/TableGen/ClangAttrEmitter.cpp
@@ -2297,6 +2297,22 @@
  .Default(false);
 }
 
+static bool isStringLiteralArgument(const Record *Arg) {
+  return !Arg->getSuperClasses().empty() &&
+ llvm::StringSwitch(
+ Arg->getSuperClasses().back().first->getName())
+ .Case("StringArgument", true)
+ .Default(false);
+}
+
+static bool isVariadicStringLiteralArgument(const Record *Arg) {
+  return !Arg->getSuperClasses().empty() &&
+ llvm::StringSwitch(
+ Arg->getSuperClasses().back().first->getName())
+ .Case("VariadicStringArgument", true)
+ .Default(false);
+}
+
 static void emitClangAttrVariadicIdentifierArgList(RecordKeeper &Records,
raw_ostream &OS) {
   OS << "#if defined(CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST)\n";
@@ -2317,6 +2333,34 @@
   OS << "#endif // CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST\n\n";
 }
 
+// Emits the list of arguments that shoulkd be parsed as unevaluated string
+// literals for each attributes
+static void emitClangAttrUnevaluatedStringLiteralList(RecordKeeper &Records,
+  raw_ostream &OS) {
+  OS << "#if defined(CLANG_ATTR_STRING_LITERAL_ARG_LIST)\n";
+  std::vector Attrs = Records.getAllDerivedDefinitions("Attr");
+  for (const auto *Attr : Attrs) {
+std::vector Args = Attr->getValueAsListOfDefs("Args");
+uint32_t Bits = 0;
+for (uint32_t N = 0; N < Args.size(); N++) {
+  Bits |= (isStringLiteralArgument(Args[N]) << N);
+  // If we have a variadic string argument, set all the remaining bits to 1
+  if (isVariadicStringLiteralArgument(Args[N])) {
+for (; N < sizeof(uint32_t); N++)
+  Bits |= (1 << N);
+break;
+  }
+}
+if (!Bits)
+  continue;
+// All these spellings have at least one string literal has argument.
+forEachUniqueSpelling(*Attr, [&](const FlattenedSpelling &S) {
+  OS << ".Case(\"" << S.name() << "\", " << Bits << ")\n";
+});
+  }
+  OS << "#endif // CLANG_ATTR_STRING_LITERAL_ARG_LIST\n\n";
+}
+
 // Emits the first-argument-is-identifier property for attributes.
 static void emitClangAttrIdentifierArgList(RecordKeeper &Records, raw_ostream &OS) {
   OS << "#if defined(CLANG_ATTR_IDENTIFIER_ARG_LIST)\n";
@@ -4615,6 +4659,7 @@
   emitSourceFileHead

[clang] 98390cc - [Clang] Reset FP options before function instantiations

2023-06-28 Thread Serge Pavlov via cfe-commits

Author: Serge Pavlov
Date: 2023-06-28T20:11:54+07:00
New Revision: 98390ccb80569e8fbb20e6c996b4b8cff87fbec6

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

LOG: [Clang] Reset FP options before function instantiations

Previously function template instantiations occurred with FP options
that were in effect at the end of translation unit. It was a problem
for late template parsing as these FP options were used as attributes of
AST nodes and may result in crash. To fix it FP options are set to the
state of the point of template definition.

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

Added: 


Modified: 
clang/include/clang/Sema/Sema.h
clang/lib/Parse/ParseTemplate.cpp
clang/lib/Sema/SemaTemplate.cpp
clang/test/CodeGen/fp-template.cpp

Removed: 




diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 55d1dcf6ee0c26..35bd3e253f668c 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -710,6 +710,12 @@ class Sema final {
 return result;
   }
 
+  void resetFPOptions(FPOptions FPO) {
+CurFPFeatures = FPO;
+FpPragmaStack.Stack.clear();
+FpPragmaStack.CurrentValue = FPO.getChangesFrom(FPOptions(LangOpts));
+  }
+
   // RAII object to push / pop sentinel slots for all MS #pragma stacks.
   // Actions should be performed only if we enter / exit a C++ method body.
   class PragmaStackSentinelRAII {
@@ -14001,6 +14007,8 @@ struct LateParsedTemplate {
   CachedTokens Toks;
   /// The template function declaration to be late parsed.
   Decl *D;
+  /// Floating-point options in the point of definition.
+  FPOptions FPO;
 };
 
 template <>

diff  --git a/clang/lib/Parse/ParseTemplate.cpp 
b/clang/lib/Parse/ParseTemplate.cpp
index d2e8a81ad521a9..776c66b436472e 100644
--- a/clang/lib/Parse/ParseTemplate.cpp
+++ b/clang/lib/Parse/ParseTemplate.cpp
@@ -1742,6 +1742,10 @@ void 
Parser::ParseLateTemplatedFuncDef(LateParsedTemplate &LPT) {
   Actions.PushDeclContext(Actions.getCurScope(), DC);
   }
 
+  // Parsing should occur with empty FP pragma stack and FP options used in the
+  // point of the template definition.
+  Actions.resetFPOptions(LPT.FPO);
+
   assert(!LPT.Toks.empty() && "Empty body!");
 
   // Append the current token at the end of the new token stream so that it

diff  --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp
index 063ddb418c4314..cb94edf67af594 100644
--- a/clang/lib/Sema/SemaTemplate.cpp
+++ b/clang/lib/Sema/SemaTemplate.cpp
@@ -11342,6 +11342,7 @@ void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, 
Decl *FnD,
   // Take tokens to avoid allocations
   LPT->Toks.swap(Toks);
   LPT->D = FnD;
+  LPT->FPO = getCurFPFeatures();
   LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
 
   FD->setLateTemplateParsed(true);

diff  --git a/clang/test/CodeGen/fp-template.cpp 
b/clang/test/CodeGen/fp-template.cpp
index 9e0fc0555e3365..e0ea8e4d12ad34 100644
--- a/clang/test/CodeGen/fp-template.cpp
+++ b/clang/test/CodeGen/fp-template.cpp
@@ -15,4 +15,40 @@ float func_01(float x, float y) {
 // CHECK-SAME:  (float noundef %{{.*}}, float noundef %{{.*}}) 
#[[ATTR01:[0-9]+]]{{.*}} {
 // CHECK:   call float @llvm.experimental.constrained.fadd.f32
 
+
+template 
+Ty templ_02(Ty x, Ty y) {
+  return x + y;
+}
+
+#pragma STDC FENV_ROUND FE_UPWARD
+
+template 
+Ty templ_03(Ty x, Ty y) {
+  return x - y;
+}
+
+#pragma STDC FENV_ROUND FE_TONEAREST
+
+float func_02(float x, float y) {
+  return templ_02(x, y);
+}
+
+// CHECK-LABEL: define {{.*}} float @_Z8templ_02IfET_S0_S0_
+// CHECK:   %add = fadd float %0, %1
+
+float func_03(float x, float y) {
+  return templ_03(x, y);
+}
+
+// CHECK-LABEL: define {{.*}} float @_Z8templ_03IfET_S0_S0_
+// CHECK:   call float @llvm.experimental.constrained.fsub.f32({{.*}}, 
metadata !"round.upward", metadata !"fpexcept.ignore")
+
+
+// This pragma sets non-default rounding mode before delayed parsing occurs. It
+// is used to check that the parsing uses FP options defined by command line
+// options or by pragma before the template definition but not by this pragma.
+#pragma STDC FENV_ROUND FE_TOWARDZERO
+
+
 // CHECK: attributes #[[ATTR01]] = { {{.*}}strictfp



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


[PATCH] D143241: [Clang] Reset FP options before function instantiations

2023-06-28 Thread Serge Pavlov 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 rG98390ccb8056: [Clang] Reset FP options before function 
instantiations (authored by sepavloff).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143241

Files:
  clang/include/clang/Sema/Sema.h
  clang/lib/Parse/ParseTemplate.cpp
  clang/lib/Sema/SemaTemplate.cpp
  clang/test/CodeGen/fp-template.cpp


Index: clang/test/CodeGen/fp-template.cpp
===
--- clang/test/CodeGen/fp-template.cpp
+++ clang/test/CodeGen/fp-template.cpp
@@ -15,4 +15,40 @@
 // CHECK-SAME:  (float noundef %{{.*}}, float noundef %{{.*}}) 
#[[ATTR01:[0-9]+]]{{.*}} {
 // CHECK:   call float @llvm.experimental.constrained.fadd.f32
 
+
+template 
+Ty templ_02(Ty x, Ty y) {
+  return x + y;
+}
+
+#pragma STDC FENV_ROUND FE_UPWARD
+
+template 
+Ty templ_03(Ty x, Ty y) {
+  return x - y;
+}
+
+#pragma STDC FENV_ROUND FE_TONEAREST
+
+float func_02(float x, float y) {
+  return templ_02(x, y);
+}
+
+// CHECK-LABEL: define {{.*}} float @_Z8templ_02IfET_S0_S0_
+// CHECK:   %add = fadd float %0, %1
+
+float func_03(float x, float y) {
+  return templ_03(x, y);
+}
+
+// CHECK-LABEL: define {{.*}} float @_Z8templ_03IfET_S0_S0_
+// CHECK:   call float @llvm.experimental.constrained.fsub.f32({{.*}}, 
metadata !"round.upward", metadata !"fpexcept.ignore")
+
+
+// This pragma sets non-default rounding mode before delayed parsing occurs. It
+// is used to check that the parsing uses FP options defined by command line
+// options or by pragma before the template definition but not by this pragma.
+#pragma STDC FENV_ROUND FE_TOWARDZERO
+
+
 // CHECK: attributes #[[ATTR01]] = { {{.*}}strictfp
Index: clang/lib/Sema/SemaTemplate.cpp
===
--- clang/lib/Sema/SemaTemplate.cpp
+++ clang/lib/Sema/SemaTemplate.cpp
@@ -11342,6 +11342,7 @@
   // Take tokens to avoid allocations
   LPT->Toks.swap(Toks);
   LPT->D = FnD;
+  LPT->FPO = getCurFPFeatures();
   LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
 
   FD->setLateTemplateParsed(true);
Index: clang/lib/Parse/ParseTemplate.cpp
===
--- clang/lib/Parse/ParseTemplate.cpp
+++ clang/lib/Parse/ParseTemplate.cpp
@@ -1742,6 +1742,10 @@
   Actions.PushDeclContext(Actions.getCurScope(), DC);
   }
 
+  // Parsing should occur with empty FP pragma stack and FP options used in the
+  // point of the template definition.
+  Actions.resetFPOptions(LPT.FPO);
+
   assert(!LPT.Toks.empty() && "Empty body!");
 
   // Append the current token at the end of the new token stream so that it
Index: clang/include/clang/Sema/Sema.h
===
--- clang/include/clang/Sema/Sema.h
+++ clang/include/clang/Sema/Sema.h
@@ -710,6 +710,12 @@
 return result;
   }
 
+  void resetFPOptions(FPOptions FPO) {
+CurFPFeatures = FPO;
+FpPragmaStack.Stack.clear();
+FpPragmaStack.CurrentValue = FPO.getChangesFrom(FPOptions(LangOpts));
+  }
+
   // RAII object to push / pop sentinel slots for all MS #pragma stacks.
   // Actions should be performed only if we enter / exit a C++ method body.
   class PragmaStackSentinelRAII {
@@ -14001,6 +14007,8 @@
   CachedTokens Toks;
   /// The template function declaration to be late parsed.
   Decl *D;
+  /// Floating-point options in the point of definition.
+  FPOptions FPO;
 };
 
 template <>


Index: clang/test/CodeGen/fp-template.cpp
===
--- clang/test/CodeGen/fp-template.cpp
+++ clang/test/CodeGen/fp-template.cpp
@@ -15,4 +15,40 @@
 // CHECK-SAME:  (float noundef %{{.*}}, float noundef %{{.*}}) #[[ATTR01:[0-9]+]]{{.*}} {
 // CHECK:   call float @llvm.experimental.constrained.fadd.f32
 
+
+template 
+Ty templ_02(Ty x, Ty y) {
+  return x + y;
+}
+
+#pragma STDC FENV_ROUND FE_UPWARD
+
+template 
+Ty templ_03(Ty x, Ty y) {
+  return x - y;
+}
+
+#pragma STDC FENV_ROUND FE_TONEAREST
+
+float func_02(float x, float y) {
+  return templ_02(x, y);
+}
+
+// CHECK-LABEL: define {{.*}} float @_Z8templ_02IfET_S0_S0_
+// CHECK:   %add = fadd float %0, %1
+
+float func_03(float x, float y) {
+  return templ_03(x, y);
+}
+
+// CHECK-LABEL: define {{.*}} float @_Z8templ_03IfET_S0_S0_
+// CHECK:   call float @llvm.experimental.constrained.fsub.f32({{.*}}, metadata !"round.upward", metadata !"fpexcept.ignore")
+
+
+// This pragma sets non-default rounding mode before delayed parsing occurs. It
+// is used to check that the parsing uses FP options defined by command line
+// options or by pragma before the template definition but not by this pragma.
+#pragma STDC FENV_ROUND FE_TOWARDZERO
+
+
 // CHECK: attributes #[[ATTR01]] = { {{.*}}strict

[PATCH] D153852: [clang][dataflow] Initialize fields of anonymous records correctly.

2023-06-28 Thread Martin Böhme via Phabricator via cfe-commits
mboehme marked an inline comment as done.
mboehme added inline comments.



Comment at: clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp:356
+  Member = cast(I);
+  MemberLoc = 
&cast(MemberLoc)->getChild(*Member);
+}

gribozavr2 wrote:
> Is there a chance that there will be no such child if we hit one of our 
> limits for modeling recursive data structures?
Happily, this isn't a concern. `AggregateStorageLocation`s always contain the 
same set of fields (the ones that are "modeled", i.e. accessed in some way). 
And this is a nice invariant to have.

Where we do the cutoff for modeling recursive data structures is that the 
storage location returned by `getChild()` may not have a `Value` associated 
with it.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153852

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


[PATCH] D153854: [clang][dataflow] Make `getThisPointeeStorageLocation()` return an `AggregateStorageLocation`.

2023-06-28 Thread Martin Böhme via Phabricator via cfe-commits
mboehme added a comment.

Pre-merge failure looks unrelated


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153854

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


[PATCH] D153960: [clang][dataflow] Implement support for pointers to members.

2023-06-28 Thread Martin Böhme via Phabricator via cfe-commits
mboehme added a comment.

In D153960#4455661 , @gribozavr2 
wrote:

> Using PointerValue to model pointers to data members does not look right to 
> me, because a pointer to data member is an offset within an object that we 
> apply this pointer to, it is not a specific storage location.
>
> I think we either shouldn't be modeling them at all (current implementation) 
> and fix any crashes in the downstream code to allow non-modeled constructs in 
> more places, or we should have a distinct kind of Value for pointers to 
> members.

After some offline discussion, I'll proceed by not modeling pointers to members 
at all for the time being (i.e. not associating them with a `Value`) but fixing 
the crashes.

Modeling pointers-to-members as a `PointerValue` works to the extent that it 
allows us to compare different pointers-to-members for equality, but where it 
breaks down is if we want to dereference them (assuming that we know 
unambiguously what value the pointer-to-member will have). At that point, what 
we would probably want is some `MemberPointerValue` that refers to the `Decl` 
for the field or member function being referenced.

I'll ping this patch once it's ready to review again.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153960

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


[PATCH] D153960: [clang][dataflow] Implement support for pointers to members.

2023-06-28 Thread Martin Böhme via Phabricator via cfe-commits
mboehme marked an inline comment as done.
mboehme added inline comments.



Comment at: clang/lib/Analysis/FlowSensitive/Transfer.cpp:236
+// `DeclRefExpr`s to fields and non-static methods aren't glvalues, and
+// there's also no sensible `Value` we can assign to them, so skip them.
+if (isa(VD))

sammccall wrote:
> I'm a bit confused by this. Why bail out rather than create the storage 
> location?
> 
> `C::x` is going to be part of `&C::x`, and we're going to create the 
> storagelocation by calling getStorageLocation() on line 456. So why not do it 
> already?
We can't associate a storage location with `*S` because it's not a glvalue, and 
only glvalues are allowed to be associated with storage locations. So we have 
to defer this work until we get to the `&` operator.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153960

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


[PATCH] D153969: [clang][ExprConstant] Fix crash on uninitialized base class subobject

2023-06-28 Thread Takuya Shimizu via Phabricator via cfe-commits
hazohelet created this revision.
hazohelet added reviewers: aaron.ballman, erichkeane, shafik, tbaeder.
Herald added a project: All.
hazohelet requested review of this revision.
Herald added a project: clang.

This patch fixes the reported regression caused by D146358 
 through adding notes about an uninitialized 
base class when we diagnose uninitialized constructor.

This also changes the wording from the old one in order to make it clear that 
the uninitialized subobject is a base class and its constructor is not called.
Wording changes:
BEFORE: `subobject of type 'Base' is not initialized`
AFTER: `constructor of base class 'Base' is not called`

BEFORE: `subobject declared here`
AFTER: `base class inherited here`

Fixes https://github.com/llvm/llvm-project/issues/63496


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D153969

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/DiagnosticASTKinds.td
  clang/lib/AST/ExprConstant.cpp
  clang/test/SemaCXX/constexpr-subobj-initialization.cpp


Index: clang/test/SemaCXX/constexpr-subobj-initialization.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/constexpr-subobj-initialization.cpp
@@ -0,0 +1,34 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+
+namespace baseclass_uninit {
+struct DelBase {
+  constexpr DelBase() = delete; // expected-note {{'DelBase' has been 
explicitly marked deleted here}}
+};
+
+struct Foo : DelBase {  // expected-note 2{{base class inherited here}}
+  constexpr Foo() {}; // expected-error {{call to deleted constructor of 
'DelBase'}}
+};
+constexpr Foo f; // expected-error {{must be initialized by a constant 
expression}} \
+ // expected-note {{constructor of base class 'DelBase' is not 
called}}
+struct Bar : Foo {
+  constexpr Bar() {};
+};
+constexpr Bar bar; // expected-error {{must be initialized by a constant 
expression}} \
+   // expected-note {{constructor of base class 'DelBase' is 
not called}}
+
+struct Base {};
+struct A : Base { // expected-note {{base class inherited here}}
+  constexpr A() : value() {} // expected-error {{member initializer 'value' 
does not name a non-static data member or base class}}
+};
+
+constexpr A a; // expected-error {{must be initialized by a constant 
expression}} \
+   // expected-note {{constructor of base class 'Base' is not 
called}}
+
+struct B : Base { // expected-note {{base class inherited here}}
+  constexpr B() : {} // expected-error {{expected class member or base class 
name}}
+};
+
+constexpr B b; // expected-error {{must be initialized by a constant 
expression}} \
+   // expected-note {{constructor of base class 'Base' is not 
called}}
+} // namespace baseclass_uninit
+
Index: clang/lib/AST/ExprConstant.cpp
===
--- clang/lib/AST/ExprConstant.cpp
+++ clang/lib/AST/ExprConstant.cpp
@@ -2415,9 +2415,16 @@
 if (const CXXRecordDecl *CD = dyn_cast(RD)) {
   unsigned BaseIndex = 0;
   for (const CXXBaseSpecifier &BS : CD->bases()) {
-if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(),
-   Value.getStructBase(BaseIndex), Kind,
-   /*SubobjectDecl=*/nullptr, CheckedTemps))
+const APValue &BaseValue = Value.getStructBase(BaseIndex);
+if (!BaseValue.hasValue()) {
+  Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized_base)
+  << BS.getType();
+  Info.Note(BS.getBeginLoc(), 
diag::note_constexpr_base_inherited_here);
+  return false;
+}
+if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), 
BaseValue,
+   Kind, /*SubobjectDecl=*/nullptr,
+   CheckedTemps))
   return false;
 ++BaseIndex;
   }
Index: clang/include/clang/Basic/DiagnosticASTKinds.td
===
--- clang/include/clang/Basic/DiagnosticASTKinds.td
+++ clang/include/clang/Basic/DiagnosticASTKinds.td
@@ -70,10 +70,14 @@
   "is not a constant expression">;
 def note_constexpr_uninitialized : Note<
   "subobject %0 is not initialized">;
+def note_constexpr_uninitialized_base : Note<
+  "constructor of base class %0 is not called">;
 def note_constexpr_static_local : Note<
   "control flows through the definition of a %select{static|thread_local}0 
variable">;
 def note_constexpr_subobject_declared_here : Note<
   "subobject declared here">;
+def note_constexpr_base_inherited_here : Note<
+  "base class inherited here">;
 def note_constexpr_array_index : Note<"cannot refer to element %0 of "
   "%select{array of %2 element%plural{1:|:s}2|non-array object}1 "
   "in a constant expression">;
Index: clang/docs/ReleaseNotes.rst
==

[PATCH] D153770: Fix test regression on 32-bit x86.

2023-06-28 Thread Zahira Ammarguellat via Phabricator via cfe-commits
zahiraam updated this revision to Diff 535368.

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

https://reviews.llvm.org/D153770

Files:
  clang/test/Sema/fp-eval-pragma-with-float-double_t-1.c
  clang/test/Sema/fp-eval-pragma-with-float-double_t-2.c
  clang/test/Sema/fp-eval-pragma-with-float-double_t-3.c

Index: clang/test/Sema/fp-eval-pragma-with-float-double_t-3.c
===
--- clang/test/Sema/fp-eval-pragma-with-float-double_t-3.c
+++ clang/test/Sema/fp-eval-pragma-with-float-double_t-3.c
@@ -1,15 +1,21 @@
-// RUN: %clang_cc1 -verify -fsyntax-only -verify -DNOERROR %s
-// RUN: %clang_cc1 -verify -fsyntax-only -x c++ -DCPP -DNOERROR %s
+// RUN: %clang_cc1 -verify -triple x86_64-linux-gnu -fsyntax-only -DNOERROR %s
+// RUN: %clang_cc1 -verify -triple x86_64-linux-gnu -fsyntax-only \
+// RUN: -x c++ -DCPP -DNOERROR %s
 
-// RUN: %clang_cc1 -verify -fsyntax-only -ffp-eval-method=extended -DNOERROR %s
-// RUN: %clang_cc1 -verify -fsyntax-only -x c++ -DCPP \
+// RUN: %clang_cc1 -verify -triple x86_64-linux-gnu -fsyntax-only \
+// RUN: -ffp-eval-method=extended -DNOERROR %s
+// RUN: %clang_cc1 -verify -triple x86_64-linux-gnu -fsyntax-only -x c++ -DCPP \
 // RUN: -ffp-eval-method=extended -DNOERROR %s
 
-// RUN: %clang_cc1 -verify -fsyntax-only -ffp-eval-method=source %s
-// RUN: %clang_cc1 -verify -fsyntax-only -x c++ -DCPP -ffp-eval-method=source %s
+// RUN: %clang_cc1 -verify -triple x86_64-linux-gnu -fsyntax-only \
+// RUN: -ffp-eval-method=source %s
+// RUN: %clang_cc1 -verify -triple x86_64-linux-gnu -fsyntax-only -x c++ -DCPP \
+// RUN: -ffp-eval-method=source %s
 
-// RUN: %clang_cc1 -verify -fsyntax-only -ffp-eval-method=double %s
-// RUN: %clang_cc1 -verify -fsyntax-only -x c++ -DCPP -ffp-eval-method=double %s
+// RUN: %clang_cc1 -verify -triple x86_64-linux-gnu -fsyntax-only \
+// RUN: -ffp-eval-method=double %s
+// RUN: %clang_cc1 -verify -triple x86_64-linux-gnu -fsyntax-only -x c++ -DCPP \
+// RUN: -ffp-eval-method=double %s
 
 
 #ifdef NOERROR
Index: clang/test/Sema/fp-eval-pragma-with-float-double_t-2.c
===
--- clang/test/Sema/fp-eval-pragma-with-float-double_t-2.c
+++ clang/test/Sema/fp-eval-pragma-with-float-double_t-2.c
@@ -1,14 +1,21 @@
-// RUN: %clang_cc1 -verify -fsyntax-only -DNOERROR %s
-// RUN: %clang_cc1 -verify -fsyntax-only -x c++ -DCPP -DNOERROR %s
+// RUN: %clang_cc1 -verify -triple x86_64-linux-gnu -fsyntax-only -DNOERROR %s
+// RUN: %clang_cc1 -verify -triple x86_64-linux-gnu -fsyntax-only \
+// RUN: -x c++ -DCPP -DNOERROR %s
 
-// RUN: %clang_cc1 -verify -fsyntax-only -ffp-eval-method=double -DNOERROR %s
-// RUN: %clang_cc1 -verify -fsyntax-only -x c++ -DCPP -ffp-eval-method=double -DNOERROR %s
+// RUN: %clang_cc1 -verify -triple x86_64-linux-gnu -fsyntax-only \
+// RUN: -ffp-eval-method=double -DNOERROR %s
+// RUN: %clang_cc1 -verify -triple x86_64-linux-gnu -fsyntax-only -x c++ -DCPP \
+// RUN: -ffp-eval-method=double -DNOERROR %s
 
-// RUN: %clang_cc1 -verify -fsyntax-only -ffp-eval-method=source %s
-// RUN: %clang_cc1 -verify -fsyntax-only -x c++ -DCPP -ffp-eval-method=source %s
+// RUN: %clang_cc1 -verify -triple x86_64-linux-gnu -fsyntax-only \
+// RUN: -ffp-eval-method=source %s
+// RUN: %clang_cc1 -verify -triple x86_64-linux-gnu -fsyntax-only -x c++ -DCPP \
+// RUN: -ffp-eval-method=source %s
 
-// RUN: %clang_cc1 -verify -fsyntax-only -ffp-eval-method=extended %s
-// RUN: %clang_cc1 -verify -fsyntax-only -x c++ -DCPP -ffp-eval-method=extended %s 
+// RUN: %clang_cc1 -verify -triple x86_64-linux-gnu -fsyntax-only \
+// RUN: -ffp-eval-method=extended %s
+// RUN: %clang_cc1 -verify -triple x86_64-linux-gnu -fsyntax-only -x c++ -DCPP \
+// RUN: -ffp-eval-method=extended %s
 
 #ifdef NOERROR
 // expected-no-diagnostics
Index: clang/test/Sema/fp-eval-pragma-with-float-double_t-1.c
===
--- clang/test/Sema/fp-eval-pragma-with-float-double_t-1.c
+++ clang/test/Sema/fp-eval-pragma-with-float-double_t-1.c
@@ -1,15 +1,21 @@
-// RUN: %clang_cc1 -verify -fsyntax-only -DNOERROR %s
-// RUN: %clang_cc1 -verify -fsyntax-only -x c++ -DCPP -DNOERROR %s
+// RUN: %clang_cc1 -verify -triple x86_64-linux-gnu -fsyntax-only -DNOERROR %s
+// RUN: %clang_cc1 -verify -triple x86_64-linux-gnu -fsyntax-only \
+// RUN: -x c++ -DCPP -DNOERROR %s
 
-// RUN: %clang_cc1 -verify -fsyntax-only -ffp-eval-method=source -DNOERROR %s
-// RUN: %clang_cc1 -verify -fsyntax-only -x c++ -DCPP -ffp-eval-method=source \
+// RUN: %clang_cc1 -verify -triple x86_64-linux-gnu -fsyntax-only \
+// RUN: -ffp-eval-method=source -DNOERROR %s
+// RUN: %clang_cc1 -verify -triple x86_64-linux-gnu -fsyntax-only -x c++ -DCPP \
+// RUN: -ffp-eval-method=source \
 // RUN: -DNOERROR %s
   
-// RUN: %clang_cc1 -verify -fsyntax-only -ffp-eval-method=double %s
-// RUN: %clang_cc1 -verify -fsyntax-only -x c++ -DCPP -ffp-eval-method=d

[PATCH] D105759: Implement P2361 Unevaluated string literals

2023-06-28 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added a comment.

Just 2 small nits, otherwise this all LGTM.




Comment at: clang/lib/Parse/ParseDecl.cpp:430
+}
+if (Expr.isInvalid()) {
+  SawError = true;

Please put a newline between unchained 'if' statements... it makes tehse really 
hard to read without it.

It happens a few times here.



Comment at: clang/lib/Sema/SemaDeclAttr.cpp:878
 
-  if (!isIntOrBool(AL.getArgAsExpr(0))) {
+  Expr *First = AL.getArgAsExpr(0);
+  if (!isIntOrBool(First)) {

Unrelated change here?  What is this for?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105759

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


[PATCH] D153969: [clang][ExprConstant] Fix crash on uninitialized base class subobject

2023-06-28 Thread Takuya Shimizu via Phabricator via cfe-commits
hazohelet added inline comments.



Comment at: clang/lib/AST/ExprConstant.cpp:2379
   if (!Value.hasValue()) {
 assert(SubobjectDecl && "SubobjectDecl shall be non-null");
 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized) << SubobjectDecl;

The reason I put the assertion here in the original patch was that there were 
not enough test cases to see what could cause null here, and I thought we could 
rethink later about this assertion's validness through crash reports like this. 
FWIW, I thought this assertion could be beneficial at that time because it had 
caught two internal bugs.

If reviewers do not agree with the assertion here anymore, we can fallback to 
the old diagnostic(`subobject of type 'A' is not initialized`) when we have 
invalid subobject, or revert the original patch.
Currently this patch is a partial fallback to the old diagnostic.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153969

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


[PATCH] D153667: [HIP]: Add gpu-link-output to control link job creation

2023-06-28 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl added a comment.

In D153667#4450724 , @jhuber6 wrote:

> In D153667#4450705 , @jrbyrnes 
> wrote:
>
>> In D153667#4450517 , @jhuber6 
>> wrote:
>>
>>> What's the difference here between this and the existing `--hip-link`?
>>
>> Hi @jhuber6
>>
>> The commit is poorly named, the main purpose is to introduce 
>> `-no-gpu-link-output.`
>>
>> We want a way to produce relocatable from source. In terms of the Driver, 
>> this means building actions and jobs for phases up to `phases::Assemble`. 
>> `-no- gpu-link-output` does this by overriding BuildActions to stop after 
>> `phases::Assemble` (similar to `-no-gpu-bundle-output`). `-gpu-link-output` 
>> is NFCI. COMGR would be the client of this, and it would be up to COMGR to 
>> handle linking of the relocatable.
>>
>> AFAICT, `-hip-link` allows for linking of offload-bundles, so it is 
>> conceptually different. We can get (somewhat) close to what we with 
>> `-emit-llvm -hip-link`, but that is probably more due to `-emit-llvm`. 
>> `-hip-link` by itself produces linker actions / jobs which what we are 
>> trying to avoid here.
>
> So, you run the backend and obtain a relocatable ELF, but do not link it via 
> `lld`? If I'm understanding this correctly, that would be the difference 
> between `-flto` and `-fno-lto`, or `-foffload-lto` and `-fno-offload-lto`, 
> AMDGPU always having `-flto` on currently. Also I recall AMDGPU / HIP 
> completely disabling the backend step at some point, so it only emits LLVM-IR.

For -fno-gpu-rdc case we do not use lto. Since -fno-gpu-rdc has one TU only, we 
use the non-lto backend to get relocatable object, and use lld for relocatable 
to shared object. This patch allows us to stop at the relocatable object since 
comgr needs that.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153667

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


[PATCH] D149248: [RISCV][MC] MC layer support for the experimental zacas extension

2023-06-28 Thread Alex Bradbury via Phabricator via cfe-commits
asb updated this revision to Diff 535372.
asb edited the summary of this revision.
asb added a comment.
Herald added a subscriber: wangpc.

Update to 1.0-rc1 (no code changes needed).


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

https://reviews.llvm.org/D149248

Files:
  clang/test/Preprocessor/riscv-target-features.c
  llvm/docs/RISCVUsage.rst
  llvm/docs/ReleaseNotes.rst
  llvm/lib/Support/RISCVISAInfo.cpp
  llvm/lib/Target/RISCV/AsmParser/RISCVAsmParser.cpp
  llvm/lib/Target/RISCV/RISCVFeatures.td
  llvm/lib/Target/RISCV/RISCVInstrInfoA.td
  llvm/test/CodeGen/RISCV/attributes.ll
  llvm/test/MC/RISCV/attribute-arch.s
  llvm/test/MC/RISCV/rv32zacas-invalid.s
  llvm/test/MC/RISCV/rv32zacas-valid.s
  llvm/test/MC/RISCV/rv64zacas-invalid.s
  llvm/test/MC/RISCV/rv64zacas-valid.s

Index: llvm/test/MC/RISCV/rv64zacas-valid.s
===
--- /dev/null
+++ llvm/test/MC/RISCV/rv64zacas-valid.s
@@ -0,0 +1,51 @@
+# RUN: llvm-mc %s -triple=riscv64 -mattr=+experimental-zacas -riscv-no-aliases -show-encoding \
+# RUN: | FileCheck -check-prefixes=CHECK-ASM,CHECK-ASM-AND-OBJ %s
+# RUN: llvm-mc -filetype=obj -triple=riscv64 -mattr=+experimental-zacas < %s \
+# RUN: | llvm-objdump --mattr=+experimental-zacas -M no-aliases -d -r - \
+# RUN: | FileCheck --check-prefix=CHECK-ASM-AND-OBJ %s
+# RUN: not llvm-mc -triple=riscv64 -mattr=+a -show-encoding %s 2>&1 \
+# RUN:| FileCheck %s --check-prefix=CHECK-ERROR
+
+# Odd register numbers for rd and rs2 are allowed for amocas.d on RV64.
+
+# CHECK-ASM-AND-OBJ: amocas.d a1, a3, (a5)
+# CHECK-ASM: encoding: [0xaf,0xb5,0xd7,0x28]
+# CHECK-ERROR: instruction requires the following: 'Zacas' (Atomic Compare-And-Swap Instructions){{$}}
+amocas.d a1, a3, (a5)
+# CHECK-ASM-AND-OBJ: amocas.d.aq a1, a3, (a5)
+# CHECK-ASM: encoding: [0xaf,0xb5,0xd7,0x2c]
+# CHECK-ERROR: instruction requires the following: 'Zacas' (Atomic Compare-And-Swap Instructions){{$}}
+amocas.d.aq a1, a3, (a5)
+# CHECK-ASM-AND-OBJ: amocas.d.rl a1, a3, (a5)
+# CHECK-ASM: encoding: [0xaf,0xb5,0xd7,0x2a]
+# CHECK-ERROR: instruction requires the following: 'Zacas' (Atomic Compare-And-Swap Instructions){{$}}
+amocas.d.rl a1, a3, (a5)
+# CHECK-ASM-AND-OBJ: amocas.d.aqrl a1, a3, (a5)
+# CHECK-ASM: encoding: [0xaf,0xb5,0xd7,0x2e]
+# CHECK-ERROR: instruction requires the following: 'Zacas' (Atomic Compare-And-Swap Instructions){{$}}
+amocas.d.aqrl a1, a3, (a5)
+
+# CHECK-ASM-AND-OBJ: amocas.q a0, a2, (a1)
+# CHECK-ASM: encoding: [0x2f,0xc5,0xc5,0x28]
+# CHECK-ERROR: instruction requires the following: 'Zacas' (Atomic Compare-And-Swap Instructions){{$}}
+amocas.q a0, a2, (a1)
+# CHECK-ASM-AND-OBJ: amocas.q a0, a2, (a1)
+# CHECK-ASM: encoding: [0x2f,0xc5,0xc5,0x28]
+# CHECK-ERROR: instruction requires the following: 'Zacas' (Atomic Compare-And-Swap Instructions){{$}}
+amocas.q a0, a2, 0(a1)
+# CHECK-ASM-AND-OBJ: amocas.q zero, zero, (a1)
+# CHECK-ASM: encoding: [0x2f,0xc0,0x05,0x28]
+# CHECK-ERROR: instruction requires the following: 'Zacas' (Atomic Compare-And-Swap Instructions){{$}}
+amocas.q zero, zero, (a1)
+# CHECK-ASM-AND-OBJ: amocas.q.aq zero, zero, (a1)
+# CHECK-ASM: encoding: [0x2f,0xc0,0x05,0x2c]
+# CHECK-ERROR: instruction requires the following: 'Zacas' (Atomic Compare-And-Swap Instructions){{$}}
+amocas.q.aq zero, zero, (a1)
+# CHECK-ASM-AND-OBJ: amocas.q.rl zero, zero, (a1)
+# CHECK-ASM: encoding: [0x2f,0xc0,0x05,0x2a]
+# CHECK-ERROR: instruction requires the following: 'Zacas' (Atomic Compare-And-Swap Instructions){{$}}
+amocas.q.rl zero, zero, (a1)
+# CHECK-ASM-AND-OBJ: amocas.q.aqrl zero, zero, (a1)
+# CHECK-ASM: encoding: [0x2f,0xc0,0x05,0x2e]
+# CHECK-ERROR: instruction requires the following: 'Zacas' (Atomic Compare-And-Swap Instructions){{$}}
+amocas.q.aqrl zero, zero, (a1)
Index: llvm/test/MC/RISCV/rv64zacas-invalid.s
===
--- /dev/null
+++ llvm/test/MC/RISCV/rv64zacas-invalid.s
@@ -0,0 +1,16 @@
+# RUN: not llvm-mc -triple riscv64 -mattr=+experimental-zacas < %s 2>&1 | FileCheck %s
+
+# Non-zero offsets not supported for the third operand (rs1).
+amocas.w a1, a3, 1(a5) # CHECK: :[[@LINE]]:18: error: optional integer offset must be 0
+amocas.d a1, a3, 2(a5) # CHECK: :[[@LINE]]:18: error: optional integer offset must be 0
+amocas.q a1, a3, 3(a5) # CHECK: :[[@LINE]]:18: error: optional integer offset must be 0
+
+# First and second operands (rd and rs2) of amocas.q must be even.
+amocas.q a1, a2, (a1) # CHECK: :[[@LINE]]:10: error: The destination register must be even.
+amocas.q a0, a1, (a1) # CHECK: :[[@LINE]]:14: error: The source register must be even.
+amocas.q.aq a1, a2, (a1) # CHECK: :[[@LINE]]:13: error: The destination register must be even.
+amocas.q.aq a0, a1, (a1) # CHECK: :[[@LINE]]:17: error: The source register must be even.
+amocas.q.rl a1, a2, (a1) # CHECK: :[[@LINE]]:13: error: The destination register must be even.
+amocas.q.rl a0, a1,

[PATCH] D153909: [AMDGPU] Always pass `-mcpu` to the `lld` linker

2023-06-28 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl accepted this revision.
yaxunl added a comment.
This revision is now accepted and ready to land.

LGTM. Thanks


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153909

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


[PATCH] D105759: Implement P2361 Unevaluated string literals

2023-06-28 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin updated this revision to Diff 535373.
cor3ntin added a comment.

Address Erich's comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105759

Files:
  clang-tools-extra/test/clang-tidy/checkers/modernize/unary-static-assert.cpp
  clang/include/clang/AST/Expr.h
  clang/include/clang/Basic/DiagnosticCommonKinds.td
  clang/include/clang/Basic/DiagnosticLexKinds.td
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Lex/LiteralSupport.h
  clang/include/clang/Parse/Parser.h
  clang/include/clang/Sema/ParsedAttr.h
  clang/include/clang/Sema/Sema.h
  clang/lib/AST/Expr.cpp
  clang/lib/Lex/LiteralSupport.cpp
  clang/lib/Lex/PPMacroExpansion.cpp
  clang/lib/Lex/Pragma.cpp
  clang/lib/Parse/ParseDecl.cpp
  clang/lib/Parse/ParseDeclCXX.cpp
  clang/lib/Parse/ParseExpr.cpp
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaExprCXX.cpp
  clang/lib/Sema/SemaInit.cpp
  clang/test/CXX/dcl.dcl/dcl.link/p2.cpp
  clang/test/CXX/dcl.dcl/p4-0x.cpp
  clang/test/FixIt/fixit-static-assert.cpp
  clang/test/Parser/MicrosoftExtensions.cpp
  clang/test/Parser/c2x-attributes.c
  clang/test/Parser/cxx-attributes.cpp
  clang/test/Parser/cxx0x-attributes.cpp
  clang/test/Sema/MicrosoftExtensions.c
  clang/test/Sema/annotate-type.c
  clang/test/Sema/annotate.c
  clang/test/Sema/attr-assume.c
  clang/test/Sema/attr-btf_tag.c
  clang/test/Sema/attr-btf_type_tag.c
  clang/test/Sema/attr-capabilities.c
  clang/test/Sema/attr-enforce-tcb-errors.cpp
  clang/test/Sema/attr-enforce-tcb-errors.m
  clang/test/Sema/attr-error.c
  clang/test/Sema/attr-handles.cpp
  clang/test/Sema/attr-section.c
  clang/test/Sema/attr-tls_model.c
  clang/test/Sema/attr-unavailable-message.c
  clang/test/Sema/attr-warning.c
  clang/test/Sema/diagnose_if.c
  clang/test/Sema/enable_if.c
  clang/test/SemaCXX/attr-deprecated-replacement-error.cpp
  clang/test/SemaCXX/attr-no-sanitize.cpp
  clang/test/SemaCXX/attr-section.cpp
  clang/test/SemaCXX/attr-weakref.cpp
  clang/test/SemaCXX/static-assert.cpp
  clang/test/SemaCXX/suppress.cpp
  clang/test/SemaObjC/attr-swift_bridge.m
  clang/test/SemaObjC/objc-asm-attribute-neg-test.m
  clang/test/SemaObjC/validate-attr-swift_attr.m
  clang/test/SemaTemplate/attributes.cpp
  clang/utils/TableGen/ClangAttrEmitter.cpp

Index: clang/utils/TableGen/ClangAttrEmitter.cpp
===
--- clang/utils/TableGen/ClangAttrEmitter.cpp
+++ clang/utils/TableGen/ClangAttrEmitter.cpp
@@ -2297,6 +2297,22 @@
  .Default(false);
 }
 
+static bool isStringLiteralArgument(const Record *Arg) {
+  return !Arg->getSuperClasses().empty() &&
+ llvm::StringSwitch(
+ Arg->getSuperClasses().back().first->getName())
+ .Case("StringArgument", true)
+ .Default(false);
+}
+
+static bool isVariadicStringLiteralArgument(const Record *Arg) {
+  return !Arg->getSuperClasses().empty() &&
+ llvm::StringSwitch(
+ Arg->getSuperClasses().back().first->getName())
+ .Case("VariadicStringArgument", true)
+ .Default(false);
+}
+
 static void emitClangAttrVariadicIdentifierArgList(RecordKeeper &Records,
raw_ostream &OS) {
   OS << "#if defined(CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST)\n";
@@ -2317,6 +2333,34 @@
   OS << "#endif // CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST\n\n";
 }
 
+// Emits the list of arguments that shoulkd be parsed as unevaluated string
+// literals for each attributes
+static void emitClangAttrUnevaluatedStringLiteralList(RecordKeeper &Records,
+  raw_ostream &OS) {
+  OS << "#if defined(CLANG_ATTR_STRING_LITERAL_ARG_LIST)\n";
+  std::vector Attrs = Records.getAllDerivedDefinitions("Attr");
+  for (const auto *Attr : Attrs) {
+std::vector Args = Attr->getValueAsListOfDefs("Args");
+uint32_t Bits = 0;
+for (uint32_t N = 0; N < Args.size(); N++) {
+  Bits |= (isStringLiteralArgument(Args[N]) << N);
+  // If we have a variadic string argument, set all the remaining bits to 1
+  if (isVariadicStringLiteralArgument(Args[N])) {
+for (; N < sizeof(uint32_t); N++)
+  Bits |= (1 << N);
+break;
+  }
+}
+if (!Bits)
+  continue;
+// All these spellings have at least one string literal has argument.
+forEachUniqueSpelling(*Attr, [&](const FlattenedSpelling &S) {
+  OS << ".Case(\"" << S.name() << "\", " << Bits << ")\n";
+});
+  }
+  OS << "#endif // CLANG_ATTR_STRING_LITERAL_ARG_LIST\n\n";
+}
+
 // Emits the first-argument-is-identifier property for attributes.
 static void emitClangAttrIdentifierArgList(RecordKeeper &Records, raw_ostream &OS) {
   OS << "#if defined(CLANG_ATTR_IDENTIFIER_ARG_LIST)\n";
@@ -4615,6 +4659,7 @@
   emitSourceFileHeader("Parser

[PATCH] D153701: [Clang] Implement P2718R0 "Lifetime extension in range-based for loops"

2023-06-28 Thread Yurong via Phabricator via cfe-commits
yronglin added a comment.

friendly ping~


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153701

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


[PATCH] D153667: [HIP]: Add gpu-link-output to control link job creation

2023-06-28 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 added a comment.

In D153667#4455943 , @yaxunl wrote:

> For -fno-gpu-rdc case we do not use lto. Since -fno-gpu-rdc has one TU only, 
> we use the non-lto backend to get relocatable object, and use lld for 
> relocatable to shared object. This patch allows us to stop at the relocatable 
> object since comgr needs that.

I see, so conceptually this is like `-Xarch-device -c` (if such a thing worked)?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153667

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


[clang] 7653011 - [AMDGPU] Always pass `-mcpu` to the `lld` linker

2023-06-28 Thread Joseph Huber via cfe-commits

Author: Joseph Huber
Date: 2023-06-28T08:52:37-05:00
New Revision: 765301183f58a28af65b112db44218dc224b9fec

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

LOG: [AMDGPU] Always pass `-mcpu` to the `lld` linker

Currently, AMDGPU more or less only supports linking with LTO. If the
user does not either pass `-flto` or `-Wl,-plugin-opt=mcpu=` manually
linking will fail because the architecture's aren't compatible. THis
patch simply passes `-mcpu` by default if it was specified. Should be a
no-op if it's not actually used.

Reviewed By: yaxunl

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

Added: 


Modified: 
clang/lib/Driver/ToolChains/AMDGPU.cpp
clang/test/Driver/amdgpu-toolchain.c

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/AMDGPU.cpp 
b/clang/lib/Driver/ToolChains/AMDGPU.cpp
index 7d1dda5529768c..b3fb7477c793c6 100644
--- a/clang/lib/Driver/ToolChains/AMDGPU.cpp
+++ b/clang/lib/Driver/ToolChains/AMDGPU.cpp
@@ -545,6 +545,9 @@ void amdgpu::Linker::ConstructJob(Compilation &C, const 
JobAction &JA,
   if (C.getDriver().isUsingLTO())
 addLTOOptions(getToolChain(), Args, CmdArgs, Output, Inputs[0],
   C.getDriver().getLTOMode() == LTOK_Thin);
+  else if (Args.hasArg(options::OPT_mcpu_EQ))
+CmdArgs.push_back(Args.MakeArgString(
+"-plugin-opt=mcpu=" + Args.getLastArgValue(options::OPT_mcpu_EQ)));
   CmdArgs.push_back("--no-undefined");
   CmdArgs.push_back("-shared");
   CmdArgs.push_back("-o");

diff  --git a/clang/test/Driver/amdgpu-toolchain.c 
b/clang/test/Driver/amdgpu-toolchain.c
index 288dbbedd49d50..1aa4775e7d9192 100644
--- a/clang/test/Driver/amdgpu-toolchain.c
+++ b/clang/test/Driver/amdgpu-toolchain.c
@@ -11,6 +11,8 @@
 // DWARF_VER: "-dwarf-version=5"
 
 // RUN: %clang -### --target=amdgcn-amd-amdhsa -mcpu=gfx906 -nogpulib \
-// RUN:   -L. -flto -fconvergent-functions %s 2>&1 | FileCheck 
-check-prefix=LTO %s
+// RUN:   -L. -flto -fconvergent-functions %s 2>&1 | FileCheck 
-check-prefixes=LTO,MCPU %s
+// RUN: %clang -### --target=amdgcn-amd-amdhsa -mcpu=gfx906 -nogpulib \
+// RUN:   -L. -fconvergent-functions %s 2>&1 | FileCheck -check-prefix=MCPU %s
 // LTO: clang{{.*}} "-flto=full"{{.*}}"-fconvergent-functions"
-// LTO: ld.lld{{.*}}"-L."{{.*}}"-plugin-opt=mcpu=gfx906"
+// MCPU: ld.lld{{.*}}"-L."{{.*}}"-plugin-opt=mcpu=gfx906"



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


[PATCH] D153909: [AMDGPU] Always pass `-mcpu` to the `lld` linker

2023-06-28 Thread Joseph Huber 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 rG765301183f58: [AMDGPU] Always pass `-mcpu` to the `lld` 
linker (authored by jhuber6).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153909

Files:
  clang/lib/Driver/ToolChains/AMDGPU.cpp
  clang/test/Driver/amdgpu-toolchain.c


Index: clang/test/Driver/amdgpu-toolchain.c
===
--- clang/test/Driver/amdgpu-toolchain.c
+++ clang/test/Driver/amdgpu-toolchain.c
@@ -11,6 +11,8 @@
 // DWARF_VER: "-dwarf-version=5"
 
 // RUN: %clang -### --target=amdgcn-amd-amdhsa -mcpu=gfx906 -nogpulib \
-// RUN:   -L. -flto -fconvergent-functions %s 2>&1 | FileCheck 
-check-prefix=LTO %s
+// RUN:   -L. -flto -fconvergent-functions %s 2>&1 | FileCheck 
-check-prefixes=LTO,MCPU %s
+// RUN: %clang -### --target=amdgcn-amd-amdhsa -mcpu=gfx906 -nogpulib \
+// RUN:   -L. -fconvergent-functions %s 2>&1 | FileCheck -check-prefix=MCPU %s
 // LTO: clang{{.*}} "-flto=full"{{.*}}"-fconvergent-functions"
-// LTO: ld.lld{{.*}}"-L."{{.*}}"-plugin-opt=mcpu=gfx906"
+// MCPU: ld.lld{{.*}}"-L."{{.*}}"-plugin-opt=mcpu=gfx906"
Index: clang/lib/Driver/ToolChains/AMDGPU.cpp
===
--- clang/lib/Driver/ToolChains/AMDGPU.cpp
+++ clang/lib/Driver/ToolChains/AMDGPU.cpp
@@ -545,6 +545,9 @@
   if (C.getDriver().isUsingLTO())
 addLTOOptions(getToolChain(), Args, CmdArgs, Output, Inputs[0],
   C.getDriver().getLTOMode() == LTOK_Thin);
+  else if (Args.hasArg(options::OPT_mcpu_EQ))
+CmdArgs.push_back(Args.MakeArgString(
+"-plugin-opt=mcpu=" + Args.getLastArgValue(options::OPT_mcpu_EQ)));
   CmdArgs.push_back("--no-undefined");
   CmdArgs.push_back("-shared");
   CmdArgs.push_back("-o");


Index: clang/test/Driver/amdgpu-toolchain.c
===
--- clang/test/Driver/amdgpu-toolchain.c
+++ clang/test/Driver/amdgpu-toolchain.c
@@ -11,6 +11,8 @@
 // DWARF_VER: "-dwarf-version=5"
 
 // RUN: %clang -### --target=amdgcn-amd-amdhsa -mcpu=gfx906 -nogpulib \
-// RUN:   -L. -flto -fconvergent-functions %s 2>&1 | FileCheck -check-prefix=LTO %s
+// RUN:   -L. -flto -fconvergent-functions %s 2>&1 | FileCheck -check-prefixes=LTO,MCPU %s
+// RUN: %clang -### --target=amdgcn-amd-amdhsa -mcpu=gfx906 -nogpulib \
+// RUN:   -L. -fconvergent-functions %s 2>&1 | FileCheck -check-prefix=MCPU %s
 // LTO: clang{{.*}} "-flto=full"{{.*}}"-fconvergent-functions"
-// LTO: ld.lld{{.*}}"-L."{{.*}}"-plugin-opt=mcpu=gfx906"
+// MCPU: ld.lld{{.*}}"-L."{{.*}}"-plugin-opt=mcpu=gfx906"
Index: clang/lib/Driver/ToolChains/AMDGPU.cpp
===
--- clang/lib/Driver/ToolChains/AMDGPU.cpp
+++ clang/lib/Driver/ToolChains/AMDGPU.cpp
@@ -545,6 +545,9 @@
   if (C.getDriver().isUsingLTO())
 addLTOOptions(getToolChain(), Args, CmdArgs, Output, Inputs[0],
   C.getDriver().getLTOMode() == LTOK_Thin);
+  else if (Args.hasArg(options::OPT_mcpu_EQ))
+CmdArgs.push_back(Args.MakeArgString(
+"-plugin-opt=mcpu=" + Args.getLastArgValue(options::OPT_mcpu_EQ)));
   CmdArgs.push_back("--no-undefined");
   CmdArgs.push_back("-shared");
   CmdArgs.push_back("-o");
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D139837: [Clang] Implements CTAD for aggregates P1816R0 and P2082R1

2023-06-28 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman accepted this revision.
aaron.ballman added a comment.

LGTM aside from some minor issues, thank you!




Comment at: clang/docs/ReleaseNotes.rst:98
+- Implemented `P1816R0: `_ and `P2082R1: 
`_,
+  which allows CTAD for aggregates (parenthesized aggregate-initialization is 
not supported).
 

Paren aggregate init is now supported, so this should be updated.



Comment at: clang/lib/Sema/SemaInit.cpp:3268-3269
 NumElements = numStructUnionElements(CurrentObjectType);
-  }
+  } else if (CurrentObjectType->isDependentType())
+NumElements = 1;
 

For local style consistency.



Comment at: clang/lib/Sema/SemaInit.cpp:10686
+
   auto tryToResolveOverload =
   [&](bool OnlyListConstructors) -> OverloadingResult {





Comment at: clang/lib/Sema/SemaTemplate.cpp:2577-2580
+  if (CXXRecordDecl *DefRecord = DeclRecord->getDefinition()) {
+TemplateDecl *DescribedTemplate = DefRecord->getDescribedClassTemplate();
+Template = DescribedTemplate ? DescribedTemplate : Template;
+  }

I think this is a bit more clear as to what's happening.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D139837

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


[PATCH] D153883: [Clang][OpenMP] Enable use of __kmpc_alloc_shared for VLAs defined in AMD GPU offloaded regions

2023-06-28 Thread Gheorghe-Teodor Bercea via Phabricator via cfe-commits
doru1004 added inline comments.



Comment at: clang/lib/CodeGen/CGDecl.cpp:1603
+// deallocation call of __kmpc_free_shared() is emitted later.
+if (getLangOpts().OpenMP && getTarget().getTriple().isAMDGCN()) {
+  // Emit call to __kmpc_alloc_shared() instead of the alloca.

arsenm wrote:
> ABataev wrote:
> > doru1004 wrote:
> > > jhuber6 wrote:
> > > > ABataev wrote:
> > > > > OpenMPIsDevice?
> > > > Does NVPTX handle this already? If not, is there a compelling reason to 
> > > > exclude NVPTX? Otherwise we should check if we are the OpenMP device.
> > > Does NVPTX support dynamic allocas?
> > It does not matter here, it depends on the runtime library implementations. 
> > The compiler just shall provide proper runtime calls emission, everything 
> > else is part of the runtime support.
> I think I heard recent ptx introdced new instructions for it. amdgpu codegen 
> just happens to be broken because we don't properly restore the stack 
> afterwards. When I added the support we had no way of testing (and still 
> don't really, __builtin_alloca doesn't handle non-0 stack address space 
> correctly)
If NVPTX supports that then there is no reason to have NVPTX avoid emitting 
allocas (i.e. the condition stays as it is right now) but I am willing to reach 
a consensus so please let me know what you would all prefer.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153883

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


[PATCH] D153131: [clang analysis][thread-safety] Handle return-by-reference...

2023-06-28 Thread Aaron Puchert via Phabricator via cfe-commits
aaronpuchert added a comment.

Tried this on our code base, and the number of new warnings seems acceptable. 
I'll still need to look through them in more detail, but there is one 
suspicious warning that boils down to this:

  > cat reference-bug.cpp
  struct __attribute__((capability("mutex"))) Mutex {} mu;
  int* p __attribute__((pt_guarded_by(mu)));
  
  int& f() {
return *p;
  }
  > clang-16 -fsyntax-only -Wthread-safety-analysis reference-bug.cpp
  > clang-16-D153131 -fsyntax-only -Wthread-safety-analysis reference-bug.cpp
  reference-bug.cpp:5:11: warning: writing the value pointed to by 'p' requires 
holding mutex 'mu' exclusively [-Wthread-safety-analysis]
return *p;
^
  1 warning generated.

That we're warning here is correct, but the warning message is a bit off (we're 
not quite writing here), and it's under `-Wthread-safety-analysis` instead of 
`-Wthread-safety-reference`.




Comment at: clang/include/clang/Basic/DiagnosticGroups.td:1046
 def ThreadSafetyPrecise: DiagGroup<"thread-safety-precise">;
 def ThreadSafetyReference  : DiagGroup<"thread-safety-reference">;
+def ThreadSafetyReturn : DiagGroup<"thread-safety-return">;

courbet wrote:
> aaronpuchert wrote:
> > courbet wrote:
> > > aaronpuchert wrote:
> > > > Why not under `-Wthread-safety-reference`, as it's return-by-reference 
> > > > that you're warning on? This seems too small for a separate flag to me.
> > > The main reason it so that we provide a soft transition period for users: 
> > > If we put that in `-Wthread-safety-reference`, we'll start breaking 
> > > compile for people who use `-Werror`, while a separate flag allows a 
> > > transition period where people opt into the new feature.
> > Transition flags can end up resulting in more churn, assuming that we 
> > eventually want to put this under `-Wthread-safety-reference`, because then 
> > you have two categories of users:
> > * those that opted in will eventually have to remove the flag again, and
> > * those that didn't will get hard errors on updating the compiler at that 
> > point.
> > Of course you might argue that the latter case can be prevented by 
> > carefully reading the release notes, but we know how often that happens.
> > 
> > I'd argue that if you're using `-Wthread-safety-reference`, you're already 
> > opting into warnings on escaping references, and not warning on `return` is 
> > a false negative.
> > 
> > A separate flag would make sense to me if we want to keep it, for example 
> > because this produces a substantial amount of false positives under some 
> > circumstances. Did you try this on a larger code base that's using the 
> > annotations? I could try it on our code, and maybe we can get some Googler 
> > to test it on theirs, which is also heavily using Thread Safety Analysis. 
> > (Though I'm not sure whether they use `-Wthread-safety-reference`.)
> I don't have a strong opinion for where the warning should go.  We are indeed 
> using `-Wthread-safety-reference`, though we're not enabling -Werror on 
> these, so adding more warnings is fine for us.
> 
> I've run the check on a small sample of our codebase (which I don;t claim to 
> be representative, I can do a larger analysis if needed). The warnings are 
> more or less evenly split between missing annotations and actual bugs. I 
> don't think any of the things I've seen qualify as false positives.
> 
> Among the missing annotations, most of the warnings are missing 
> `ABSL_EXCLUSIVE_LOCKS_REQUIRED` on the function. In a small number of cases, 
> the pattern is that a variable is lazily initialized under a lock and then 
> returned by reference:
> 
> ```
> struct LazyImmutableThing {
>   const Thing& Get() {
> {
>   MutexLock lock(&mutex_);
>   thing_->Initialize();
> }
> 
> return thing_;
>   }
>   
>   Mutex mutex_;
>   Thing thing_ GUARDED_BY(mutex_);
> };
> ```
> 
> I consider this to be a missing annotation as the returned value is 
> dynamically immutable, the proper fix would be `return 
> TS_UNCHECKED_READ(thing_)`.
> 
> 
> Most actual bugs are along the lines of:
> 
> ```
> struct S {
>   T& Get() const {
> MutexLock lock(&mutex_);
> return obj_;
>   }
> 
>   Mutex mutex_;
>   T obj_ GUARDED_BY(mutex_);
> };
> ```
> 
> though some are missing the guard altogether (`T& Get() const { return obj_; 
> }`).
> 
> There are a few possible fixes. In rough order of occurrence:
>  - Return by value as the copy is not too expensive and memory ordering does 
> not matter.
>  - Let the caller take the lock and annotate with 
> `ABSL_EXCLUSIVE_LOCKS_REQUIRED` when the `Get` method is not called too often.
>  - Let `Get` take a callback and process the value under the lock instead of 
> returning it (when ordering matters).
> 
> In a small number of cases, the pattern is that a variable is lazily 
> initialized under a lock and then returned by reference:

I wonder why that's safe, is the initialization gu

[PATCH] D129464: [Clang][CodeGen] Set FP options of builder at entry to compound statement

2023-06-28 Thread Serge Pavlov via Phabricator via cfe-commits
sepavloff added a comment.

After implementation of D142001  and D143241 
 this patch is not neded anymore.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129464

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


[PATCH] D105759: Implement P2361 Unevaluated string literals

2023-06-28 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin added inline comments.



Comment at: clang/lib/Sema/SemaDeclAttr.cpp:878
 
-  if (!isIntOrBool(AL.getArgAsExpr(0))) {
+  Expr *First = AL.getArgAsExpr(0);
+  if (!isIntOrBool(First)) {

erichkeane wrote:
> Unrelated change here?  What is this for?
Some test i failed to fully revert. good catch!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105759

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


[PATCH] D128648: [Clang][AArch64][SME] Add vector read/write (mova) intrinsics

2023-06-28 Thread Bryan Chan via Phabricator via cfe-commits
bryanpkc added a comment.

@sdesmalen Could you take a look at the patch stack again?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128648

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


[PATCH] D151567: [LLVM][Support] Report EISDIR when opening a directory on AIX

2023-06-28 Thread Alison Zhang via Phabricator via cfe-commits
azhan92 updated this revision to Diff 535389.
azhan92 added a comment.
Herald added subscribers: JDevlieghere, jdoerfert.

Remove unrelated changes.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151567

Files:
  llvm/lib/Support/CommandLine.cpp
  llvm/unittests/Support/CommandLineTest.cpp


Index: llvm/unittests/Support/CommandLineTest.cpp
===
--- llvm/unittests/Support/CommandLineTest.cpp
+++ llvm/unittests/Support/CommandLineTest.cpp
@@ -1060,7 +1060,6 @@
   ASSERT_STREQ(Argv[0], "clang");
   ASSERT_STREQ(Argv[1], AFileExp.c_str());
 
-#if !defined(_AIX) && !defined(__MVS__)
   std::string ADirExp = std::string("@") + std::string(ADir.path());
   Argv = {"clang", ADirExp.c_str()};
   Res = cl::ExpandResponseFiles(Saver, cl::TokenizeGNUCommandLine, Argv);
@@ -1068,7 +1067,6 @@
   ASSERT_EQ(2U, Argv.size());
   ASSERT_STREQ(Argv[0], "clang");
   ASSERT_STREQ(Argv[1], ADirExp.c_str());
-#endif
 }
 
 TEST(CommandLineTest, SetDefaultValue) {
Index: llvm/lib/Support/CommandLine.cpp
===
--- llvm/lib/Support/CommandLine.cpp
+++ llvm/lib/Support/CommandLine.cpp
@@ -1289,8 +1289,9 @@
 }
 
 ErrorOr Res = FS->status(FName);
+std::error_code EC;
 if (!Res || !Res->exists()) {
-  std::error_code EC = Res.getError();
+  EC = Res.getError();
   if (!InConfigFile) {
 // If the specified file does not exist, leave '@file' unexpanded, as
 // libiberty does.
@@ -1305,6 +1306,11 @@
"': " + EC.message());
 }
 const llvm::vfs::Status &FileStatus = Res.get();
+if (FileStatus.isDirectory()) {
+  EC = std::make_error_code(std::errc::is_a_directory);
+  return createStringError(EC, Twine("cannot not open file '") + FName +
+   "': " + EC.message());
+}
 
 auto IsEquivalent =
 [FileStatus, this](const ResponseFileRecord &RFile) -> ErrorOr {


Index: llvm/unittests/Support/CommandLineTest.cpp
===
--- llvm/unittests/Support/CommandLineTest.cpp
+++ llvm/unittests/Support/CommandLineTest.cpp
@@ -1060,7 +1060,6 @@
   ASSERT_STREQ(Argv[0], "clang");
   ASSERT_STREQ(Argv[1], AFileExp.c_str());
 
-#if !defined(_AIX) && !defined(__MVS__)
   std::string ADirExp = std::string("@") + std::string(ADir.path());
   Argv = {"clang", ADirExp.c_str()};
   Res = cl::ExpandResponseFiles(Saver, cl::TokenizeGNUCommandLine, Argv);
@@ -1068,7 +1067,6 @@
   ASSERT_EQ(2U, Argv.size());
   ASSERT_STREQ(Argv[0], "clang");
   ASSERT_STREQ(Argv[1], ADirExp.c_str());
-#endif
 }
 
 TEST(CommandLineTest, SetDefaultValue) {
Index: llvm/lib/Support/CommandLine.cpp
===
--- llvm/lib/Support/CommandLine.cpp
+++ llvm/lib/Support/CommandLine.cpp
@@ -1289,8 +1289,9 @@
 }
 
 ErrorOr Res = FS->status(FName);
+std::error_code EC;
 if (!Res || !Res->exists()) {
-  std::error_code EC = Res.getError();
+  EC = Res.getError();
   if (!InConfigFile) {
 // If the specified file does not exist, leave '@file' unexpanded, as
 // libiberty does.
@@ -1305,6 +1306,11 @@
"': " + EC.message());
 }
 const llvm::vfs::Status &FileStatus = Res.get();
+if (FileStatus.isDirectory()) {
+  EC = std::make_error_code(std::errc::is_a_directory);
+  return createStringError(EC, Twine("cannot not open file '") + FName +
+   "': " + EC.message());
+}
 
 auto IsEquivalent =
 [FileStatus, this](const ResponseFileRecord &RFile) -> ErrorOr {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D153890: [clang] Fix checking the equality comparator of base classes in __is_trivially_equality_comparable

2023-06-28 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin accepted this revision.
cor3ntin added a comment.
This revision is now accepted and ready to land.

Oh wow, nice catch!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153890

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


[PATCH] D151697: [clang] Add test for CWG1710 and related issues

2023-06-28 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin accepted this revision.
cor3ntin added a comment.
This revision is now accepted and ready to land.

Thanks.
These seem like important issues to fix. should we make a github issue to track 
them?




Comment at: clang/test/CXX/drs/dr17xx.cpp:10
+namespace dr1710 { // dr1710: no
+// FIXME: all of the following is well-formed
+template  struct D1 : T::template B::template C {};




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151697

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


[PATCH] D153883: [Clang][OpenMP] Enable use of __kmpc_alloc_shared for VLAs defined in AMD GPU offloaded regions

2023-06-28 Thread Matt Arsenault via Phabricator via cfe-commits
arsenm added inline comments.



Comment at: clang/lib/CodeGen/CGDecl.cpp:1603
+// deallocation call of __kmpc_free_shared() is emitted later.
+if (getLangOpts().OpenMP && getTarget().getTriple().isAMDGCN()) {
+  // Emit call to __kmpc_alloc_shared() instead of the alloca.

doru1004 wrote:
> arsenm wrote:
> > ABataev wrote:
> > > doru1004 wrote:
> > > > jhuber6 wrote:
> > > > > ABataev wrote:
> > > > > > OpenMPIsDevice?
> > > > > Does NVPTX handle this already? If not, is there a compelling reason 
> > > > > to exclude NVPTX? Otherwise we should check if we are the OpenMP 
> > > > > device.
> > > > Does NVPTX support dynamic allocas?
> > > It does not matter here, it depends on the runtime library 
> > > implementations. The compiler just shall provide proper runtime calls 
> > > emission, everything else is part of the runtime support.
> > I think I heard recent ptx introdced new instructions for it. amdgpu 
> > codegen just happens to be broken because we don't properly restore the 
> > stack afterwards. When I added the support we had no way of testing (and 
> > still don't really, __builtin_alloca doesn't handle non-0 stack address 
> > space correctly)
> If NVPTX supports that then there is no reason to have NVPTX avoid emitting 
> allocas (i.e. the condition stays as it is right now) but I am willing to 
> reach a consensus so please let me know what you would all prefer.
frontends seem to have a tradition of working around missing features in 
codegen, I think you should just pass through the correct IR and leave the 
backend bugs for the backends


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153883

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


[PATCH] D153058: [clang][CFG] Support construction of a weak topological ordering of the CFG.

2023-06-28 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel updated this revision to Diff 535397.
ymandel added a comment.

Rebase and address some comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153058

Files:
  clang/include/clang/Analysis/Analyses/IntervalPartition.h
  clang/lib/Analysis/IntervalPartition.cpp
  clang/unittests/Analysis/IntervalPartitionTest.cpp

Index: clang/unittests/Analysis/IntervalPartitionTest.cpp
===
--- clang/unittests/Analysis/IntervalPartitionTest.cpp
+++ clang/unittests/Analysis/IntervalPartitionTest.cpp
@@ -8,13 +8,119 @@
 
 #include "clang/Analysis/Analyses/IntervalPartition.h"
 #include "CFGBuildResult.h"
+#include "clang/Analysis/CFG.h"
+#include "llvm/Support/raw_ostream.h"
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
+#include 
+#include 
 
 namespace clang {
-namespace analysis {
+
+namespace {
+template  using NodeData = CFGInterval::NodeData;
+}  // namespace
+
+llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
+  const CFGInterval::IntervalData &D) {
+  OS << "Nodes{";
+  if (std::holds_alternative>(D)) {
+auto &BlockData = std::get>(D);
+for (const auto *B : BlockData.Nodes)
+  OS << B->getBlockID() << ", ";
+  } else {
+assert(std::holds_alternative>(D));
+auto &IntervalData = std::get>(D);
+for (const auto *B : IntervalData.Nodes)
+  OS << B->ID << ", ";
+  }
+  OS << "}";
+  return OS;
+}
+
+llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const CFGInterval &I) {
+  OS << "Interval{ID = " << I.ID << ", ";
+  OS << I.Data;
+  OS << ", Pre{";
+  for (const auto *P : I.Predecessors)
+OS << P->ID << ",";
+  OS << "}, Succ{";
+  for (const auto *P : I.Successors)
+OS << P->ID << ",";
+  OS << "}}\n";
+  return OS;
+}
+
+void PrintTo(const CFGInterval::IntervalData &D, std::ostream *OS) {
+  std::string Result;
+  llvm::raw_string_ostream StringOS(Result);
+  StringOS << D;
+  *OS << Result;
+}
+
+void PrintTo(const CFGInterval &I, std::ostream *OS) {
+  std::string Result;
+  llvm::raw_string_ostream StringOS(Result);
+  StringOS << I;
+  *OS << Result;
+}
+
 namespace {
 
+using ::clang::analysis::BuildCFG;
+using ::clang::analysis::BuildResult;
+using ::testing::ElementsAre;
+using ::testing::Field;
+using ::testing::IsEmpty;
+using ::testing::Optional;
+using ::testing::UnorderedElementsAre;
+
+MATCHER_P(BlockID, ID, "") { return arg->getBlockID == ID; }
+MATCHER_P(IntervalID, ID, "") { return arg->ID == ID; }
+
+template 
+auto BlockIDs(T... IDs) {
+  return UnorderedElementsAre(
+  ::testing::Property(&CFGBlock::getBlockID, IDs)...);
+}
+
+template 
+auto IntervalIDs(T... IDs) {
+  return UnorderedElementsAre(
+  ::testing::Field(&CFGInterval::ID, IDs)...);
+}
+
+MATCHER_P3(IsBlockInterval, ID, Preds, Succs, "") {
+  if (!std::holds_alternative>(arg.Data))
+return false;
+
+  return testing::Matches(ID)(arg.ID) &&
+ testing::Matches(Preds)(arg.Predecessors) &&
+ testing::Matches(Succs)(arg.Successors);
+}
+
+MATCHER_P4(IsBlockInterval, ID, Nodes, Preds, Succs, "") {
+  if (!std::holds_alternative>(arg.Data))
+return false;
+  auto &IntervalData = std::get>(arg.Data);
+
+  return testing::Matches(ID)(arg.ID) &&
+ testing::Matches(Nodes)(IntervalData.Nodes) &&
+ testing::Matches(Preds)(arg.Predecessors) &&
+ testing::Matches(Succs)(arg.Successors);
+}
+
+MATCHER_P4(IsNestedInterval, ID, Nodes, Preds, Succs, "") {
+  if (!std::holds_alternative>(arg.Data))
+return false;
+  auto &IntervalData = std::get>(arg.Data);
+
+  return testing::Matches(ID)(arg.ID) &&
+ testing::Matches(Nodes)(IntervalData.Nodes) &&
+ testing::Matches(Preds)(arg.Predecessors) &&
+ testing::Matches(Succs)(arg.Successors);
+}
+
 TEST(BuildInterval, PartitionSimpleOneInterval) {
 
   const char *Code = R"(void f() {
@@ -32,8 +138,8 @@
 
   auto &EntryBlock = cfg->getEntry();
 
-  CFGInterval I = buildInterval(*cfg, EntryBlock);
-  EXPECT_EQ(I.Blocks.size(), 3u);
+  std::vector I = buildInterval(&EntryBlock);
+  EXPECT_EQ(I.size(), 3u);
 }
 
 TEST(BuildInterval, PartitionIfThenOneInterval) {
@@ -56,12 +162,10 @@
 
   auto &EntryBlock = cfg->getEntry();
 
-  CFGInterval I = buildInterval(*cfg, EntryBlock);
-  EXPECT_EQ(I.Blocks.size(), 6u);
+  std::vector I = buildInterval(&EntryBlock);
+  EXPECT_EQ(I.size(), 6u);
 }
 
-using ::testing::UnorderedElementsAre;
-
 TEST(BuildInterval, PartitionWhileMultipleIntervals) {
 
   const char *Code = R"(void f() {
@@ -80,11 +184,11 @@
   CFGBlock *InitXBlock = *EntryBlock->succ_begin();
   CFGBlock *LoopHeadBlock = *InitXBlock->succ_begin();
 
-  CFGInterval I1 = buildInterval(*cfg, *EntryBlock);
-  EXPECT_THAT(I1.Blocks, UnorderedElementsAre(EntryBlock, InitXBlock));
+  std::vector I1 = buildInterval(EntryBlock);
+  EXPECT_THAT(I1, UnorderedElementsAre(EntryBlock, InitXBlock));
 
-  CFGInterva

[PATCH] D153960: [clang][dataflow] Implement support for pointers to members.

2023-06-28 Thread Martin Böhme via Phabricator via cfe-commits
mboehme updated this revision to Diff 535401.
mboehme marked an inline comment as done.
mboehme added a comment.

Don't produce values for pointers to members. For consistency, also make
the NullToMemberPointer cast not produce any values.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153960

Files:
  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
@@ -2523,10 +2523,56 @@
   });
 }
 
+TEST(TransferTest, PointerToMemberVariable) {
+  std::string Code = R"(
+struct S {
+  int i;
+};
+void target() {
+  int S::*MemberPointer = &S::i;
+  // [[p]]
+}
+  )";
+  runDataflow(
+  Code,
+  [](const llvm::StringMap> &Results,
+ ASTContext &ASTCtx) {
+const Environment &Env = getEnvironmentAtAnnotation(Results, "p");
+
+const ValueDecl *MemberPointerDecl =
+findValueDecl(ASTCtx, "MemberPointer");
+ASSERT_THAT(MemberPointerDecl, NotNull());
+ASSERT_THAT(Env.getValue(*MemberPointerDecl), IsNull());
+  });
+}
+
+TEST(TransferTest, PointerToMemberFunction) {
+  std::string Code = R"(
+struct S {
+  void Method();
+};
+void target() {
+  void (S::*MemberPointer)() = &S::Method;
+  // [[p]]
+}
+  )";
+  runDataflow(
+  Code,
+  [](const llvm::StringMap> &Results,
+ ASTContext &ASTCtx) {
+const Environment &Env = getEnvironmentAtAnnotation(Results, "p");
+
+const ValueDecl *MemberPointerDecl =
+findValueDecl(ASTCtx, "MemberPointer");
+ASSERT_THAT(MemberPointerDecl, NotNull());
+ASSERT_THAT(Env.getValue(*MemberPointerDecl), IsNull());
+  });
+}
+
 TEST(TransferTest, NullToMemberPointerCast) {
   std::string Code = R"(
 struct Foo {};
-void target(Foo *Foo) {
+void target() {
   int Foo::*MemberPointer = nullptr;
   // [[p]]
 }
@@ -2541,12 +2587,7 @@
 const ValueDecl *MemberPointerDecl =
 findValueDecl(ASTCtx, "MemberPointer");
 ASSERT_THAT(MemberPointerDecl, NotNull());
-
-const auto *MemberPointerVal =
-cast(Env.getValue(*MemberPointerDecl));
-
-const StorageLocation &MemberLoc = MemberPointerVal->getPointeeLoc();
-EXPECT_THAT(Env.getValue(MemberLoc), IsNull());
+ASSERT_THAT(Env.getValue(*MemberPointerDecl), IsNull());
   });
 }
 
Index: clang/lib/Analysis/FlowSensitive/Transfer.cpp
===
--- clang/lib/Analysis/FlowSensitive/Transfer.cpp
+++ clang/lib/Analysis/FlowSensitive/Transfer.cpp
@@ -231,6 +231,15 @@
   void VisitDeclRefExpr(const DeclRefExpr *S) {
 const ValueDecl *VD = S->getDecl();
 assert(VD != nullptr);
+
+// `DeclRefExpr`s to fields and non-static methods aren't glvalues, and
+// there's also no sensible `Value` we can assign to them, so skip them.
+if (isa(VD))
+  return;
+if (auto *Method = dyn_cast(VD);
+Method && !Method->isStatic())
+  return;
+
 auto *DeclLoc = Env.getStorageLocation(*VD);
 if (DeclLoc == nullptr)
   return;
@@ -397,8 +406,7 @@
   propagateValueOrStorageLocation(*SubExpr, *S, Env);
   break;
 }
-case CK_NullToPointer:
-case CK_NullToMemberPointer: {
+case CK_NullToPointer: {
   auto &Loc = Env.createStorageLocation(S->getType());
   Env.setStorageLocation(*S, Loc);
 
@@ -407,6 +415,10 @@
   Env.setValue(Loc, NullPointerVal);
   break;
 }
+case CK_NullToMemberPointer:
+  // FIXME: Implement pointers to members. For now, don't associate a value
+  // with this expression.
+  break;
 case CK_FunctionToPointerDecay:
 case CK_BuiltinFnToFnPtr: {
   StorageLocation *PointeeLoc =
@@ -440,14 +452,12 @@
   break;
 }
 case UO_AddrOf: {
-  // Do not form a pointer to a reference. If `SubExpr` is assigned a
-  // `ReferenceValue` then form a value that points to the location of its
-  // pointee.
-  StorageLocation *PointeeLoc = Env.getStorageLocationStrict(*SubExpr);
-  if (PointeeLoc == nullptr)
+  // FIXME: Model pointers to members.
+  if (S->getType()->isMemberPointerType())
 break;
 
-  Env.setValueStrict(*S, Env.create(*PointeeLoc));
+  if (StorageLocation *PointeeLoc = Env.getStorageLocationStrict(*SubExpr))
+Env.setValueStrict(*S, Env.create(*PointeeLoc));
   break;
 }
 case UO_LNot: {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D153960: [clang][dataflow] Implement support for pointers to members.

2023-06-28 Thread Martin Böhme via Phabricator via cfe-commits
mboehme added a comment.

PTAL




Comment at: clang/lib/Analysis/FlowSensitive/Transfer.cpp:447
-  StorageLocation *PointeeLoc = Env.getStorageLocationStrict(*SubExpr);
-  if (PointeeLoc == nullptr)
 break;

While I'm here, streamline the code for the not-pointer-to-member case.



Comment at: clang/unittests/Analysis/FlowSensitive/TransferTest.cpp:2529
 struct Foo {};
-void target(Foo *Foo) {
   int Foo::*MemberPointer = nullptr;

Noticed that the parameter here was unused, so I removed it.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153960

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


[PATCH] D153058: [clang][CFG] Support construction of a weak topological ordering of the CFG.

2023-06-28 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel updated this revision to Diff 535402.
ymandel added a comment.

Address more comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153058

Files:
  clang/include/clang/Analysis/Analyses/IntervalPartition.h
  clang/lib/Analysis/IntervalPartition.cpp
  clang/unittests/Analysis/IntervalPartitionTest.cpp

Index: clang/unittests/Analysis/IntervalPartitionTest.cpp
===
--- clang/unittests/Analysis/IntervalPartitionTest.cpp
+++ clang/unittests/Analysis/IntervalPartitionTest.cpp
@@ -8,13 +8,119 @@
 
 #include "clang/Analysis/Analyses/IntervalPartition.h"
 #include "CFGBuildResult.h"
+#include "clang/Analysis/CFG.h"
+#include "llvm/Support/raw_ostream.h"
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
+#include 
+#include 
 
 namespace clang {
-namespace analysis {
+
+namespace {
+template  using NodeData = CFGInterval::NodeData;
+}  // namespace
+
+llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
+  const CFGInterval::IntervalData &D) {
+  OS << "Nodes{";
+  if (std::holds_alternative>(D)) {
+auto &BlockData = std::get>(D);
+for (const auto *B : BlockData.Nodes)
+  OS << B->getBlockID() << ", ";
+  } else {
+assert(std::holds_alternative>(D));
+auto &IntervalData = std::get>(D);
+for (const auto *B : IntervalData.Nodes)
+  OS << B->ID << ", ";
+  }
+  OS << "}";
+  return OS;
+}
+
+llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const CFGInterval &I) {
+  OS << "Interval{ID = " << I.ID << ", ";
+  OS << I.Data;
+  OS << ", Pre{";
+  for (const auto *P : I.Predecessors)
+OS << P->ID << ",";
+  OS << "}, Succ{";
+  for (const auto *P : I.Successors)
+OS << P->ID << ",";
+  OS << "}}\n";
+  return OS;
+}
+
+void PrintTo(const CFGInterval::IntervalData &D, std::ostream *OS) {
+  std::string Result;
+  llvm::raw_string_ostream StringOS(Result);
+  StringOS << D;
+  *OS << Result;
+}
+
+void PrintTo(const CFGInterval &I, std::ostream *OS) {
+  std::string Result;
+  llvm::raw_string_ostream StringOS(Result);
+  StringOS << I;
+  *OS << Result;
+}
+
 namespace {
 
+using ::clang::analysis::BuildCFG;
+using ::clang::analysis::BuildResult;
+using ::testing::ElementsAre;
+using ::testing::Field;
+using ::testing::IsEmpty;
+using ::testing::Optional;
+using ::testing::UnorderedElementsAre;
+
+MATCHER_P(BlockID, ID, "") { return arg->getBlockID == ID; }
+MATCHER_P(IntervalID, ID, "") { return arg->ID == ID; }
+
+template 
+auto BlockIDs(T... IDs) {
+  return UnorderedElementsAre(
+  ::testing::Property(&CFGBlock::getBlockID, IDs)...);
+}
+
+template 
+auto IntervalIDs(T... IDs) {
+  return UnorderedElementsAre(
+  ::testing::Field(&CFGInterval::ID, IDs)...);
+}
+
+MATCHER_P3(IsBlockInterval, ID, Preds, Succs, "") {
+  if (!std::holds_alternative>(arg.Data))
+return false;
+
+  return testing::Matches(ID)(arg.ID) &&
+ testing::Matches(Preds)(arg.Predecessors) &&
+ testing::Matches(Succs)(arg.Successors);
+}
+
+MATCHER_P4(IsBlockInterval, ID, Nodes, Preds, Succs, "") {
+  if (!std::holds_alternative>(arg.Data))
+return false;
+  auto &IntervalData = std::get>(arg.Data);
+
+  return testing::Matches(ID)(arg.ID) &&
+ testing::Matches(Nodes)(IntervalData.Nodes) &&
+ testing::Matches(Preds)(arg.Predecessors) &&
+ testing::Matches(Succs)(arg.Successors);
+}
+
+MATCHER_P4(IsNestedInterval, ID, Nodes, Preds, Succs, "") {
+  if (!std::holds_alternative>(arg.Data))
+return false;
+  auto &IntervalData = std::get>(arg.Data);
+
+  return testing::Matches(ID)(arg.ID) &&
+ testing::Matches(Nodes)(IntervalData.Nodes) &&
+ testing::Matches(Preds)(arg.Predecessors) &&
+ testing::Matches(Succs)(arg.Successors);
+}
+
 TEST(BuildInterval, PartitionSimpleOneInterval) {
 
   const char *Code = R"(void f() {
@@ -32,8 +138,8 @@
 
   auto &EntryBlock = cfg->getEntry();
 
-  CFGInterval I = buildInterval(*cfg, EntryBlock);
-  EXPECT_EQ(I.Blocks.size(), 3u);
+  std::vector I = buildInterval(&EntryBlock);
+  EXPECT_EQ(I.size(), 3u);
 }
 
 TEST(BuildInterval, PartitionIfThenOneInterval) {
@@ -56,12 +162,10 @@
 
   auto &EntryBlock = cfg->getEntry();
 
-  CFGInterval I = buildInterval(*cfg, EntryBlock);
-  EXPECT_EQ(I.Blocks.size(), 6u);
+  std::vector I = buildInterval(&EntryBlock);
+  EXPECT_EQ(I.size(), 6u);
 }
 
-using ::testing::UnorderedElementsAre;
-
 TEST(BuildInterval, PartitionWhileMultipleIntervals) {
 
   const char *Code = R"(void f() {
@@ -80,11 +184,11 @@
   CFGBlock *InitXBlock = *EntryBlock->succ_begin();
   CFGBlock *LoopHeadBlock = *InitXBlock->succ_begin();
 
-  CFGInterval I1 = buildInterval(*cfg, *EntryBlock);
-  EXPECT_THAT(I1.Blocks, UnorderedElementsAre(EntryBlock, InitXBlock));
+  std::vector I1 = buildInterval(EntryBlock);
+  EXPECT_THAT(I1, UnorderedElementsAre(EntryBlock, InitXBlock));
 
-  CFGInterval I2 = buil

  1   2   3   >