[clang] [clang][ExprConst] Don't try to evaluate value-dependent DeclRefExprs (PR #67778)

2023-10-03 Thread Timm Baeder via cfe-commits
Timm =?utf-8?q?Bäder?= 
Message-ID:
In-Reply-To: 


https://github.com/tbaederr updated 
https://github.com/llvm/llvm-project/pull/67778

>From 1b6fcc49f5ef9b99b4b2f7019de6d8d24a03f232 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Tue, 3 Oct 2023 08:35:57 +0200
Subject: [PATCH 1/2] [clang][Interp] Add basic support for _BitInt

Make sure we pass the expected bitwidth around when casting to
IntAP/IntAPS and move the tests to their own file.
---
 clang/lib/AST/Interp/ByteCodeExprGen.cpp | 12 
 clang/lib/AST/Interp/Context.h   |  2 +
 clang/lib/AST/Interp/IntegralAP.h| 17 +++--
 clang/lib/AST/Interp/Interp.h| 58 +++-
 clang/lib/AST/Interp/InterpBuiltin.cpp   |  3 +-
 clang/lib/AST/Interp/Opcodes.td  | 30 +++-
 clang/test/AST/Interp/intap.cpp  | 88 
 clang/test/AST/Interp/literals.cpp   | 75 
 8 files changed, 199 insertions(+), 86 deletions(-)
 create mode 100644 clang/test/AST/Interp/intap.cpp

diff --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index e266804a4e75dea..f899c2fe22ecd8f 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -138,6 +138,13 @@ bool ByteCodeExprGen::VisitCastExpr(const 
CastExpr *CE) {
 if (!this->visit(SubExpr))
   return false;
 
+if (ToT == PT_IntAP)
+  return this->emitCastFloatingIntegralAP(Ctx.getBitWidth(CE->getType()),
+  CE);
+if (ToT == PT_IntAPS)
+  return this->emitCastFloatingIntegralAPS(Ctx.getBitWidth(CE->getType()),
+   CE);
+
 return this->emitCastFloatingIntegral(*ToT, CE);
   }
 
@@ -183,6 +190,11 @@ bool ByteCodeExprGen::VisitCastExpr(const 
CastExpr *CE) {
   return true;
 }
 
+if (ToT == PT_IntAP)
+  return this->emitCastAP(*FromT, Ctx.getBitWidth(CE->getType()), CE);
+if (ToT == PT_IntAPS)
+  return this->emitCastAPS(*FromT, Ctx.getBitWidth(CE->getType()), CE);
+
 return this->emitCast(*FromT, *ToT, CE);
   }
 
diff --git a/clang/lib/AST/Interp/Context.h b/clang/lib/AST/Interp/Context.h
index 958b50b1615ad18..6df61e93ad83abc 100644
--- a/clang/lib/AST/Interp/Context.h
+++ b/clang/lib/AST/Interp/Context.h
@@ -64,6 +64,8 @@ class Context final {
   unsigned getCharBit() const;
   /// Return the floating-point semantics for T.
   const llvm::fltSemantics &getFloatSemantics(QualType T) const;
+  /// Return the size of T in bits.
+  uint32_t getBitWidth(QualType T) const { return Ctx.getIntWidth(T); }
 
   /// Classifies an expression.
   std::optional classify(QualType T) const;
diff --git a/clang/lib/AST/Interp/IntegralAP.h 
b/clang/lib/AST/Interp/IntegralAP.h
index a8df431bef11784..363fcd2eacb2f23 100644
--- a/clang/lib/AST/Interp/IntegralAP.h
+++ b/clang/lib/AST/Interp/IntegralAP.h
@@ -37,8 +37,12 @@ template  class IntegralAP final {
   APSInt V;
 
   template  static T truncateCast(const APSInt &V) {
-return std::is_signed_v ? V.trunc(sizeof(T) * 8).getSExtValue()
-   : V.trunc(sizeof(T) * 8).getZExtValue();
+constexpr unsigned BitSize = sizeof(T) * 8;
+if (BitSize >= V.getBitWidth())
+  return std::is_signed_v ? V.getSExtValue() : V.getZExtValue();
+
+return std::is_signed_v ? V.trunc(BitSize).getSExtValue()
+   : V.trunc(BitSize).getZExtValue();
   }
 
 public:
@@ -89,10 +93,10 @@ template  class IntegralAP final {
   }
 
   template 
-  static IntegralAP from(Integral I) {
-// FIXME: Take bits parameter.
+  static IntegralAP from(Integral I, unsigned BitWidth) {
+llvm::errs() << __PRETTY_FUNCTION__ << ": " << BitWidth << "\n";
 APSInt Copy =
-APSInt(APInt(128, static_cast(I), InputSigned), !Signed);
+APSInt(APInt(BitWidth, static_cast(I), InputSigned), !Signed);
 Copy.setIsSigned(Signed);
 
 assert(Copy.isSigned() == Signed);
@@ -108,8 +112,7 @@ template  class IntegralAP final {
 return IntegralAP(0);
   }
 
-  // FIXME: This can't be static if the bitwidth depends on V.
-  static constexpr unsigned bitWidth() { return 128; }
+  constexpr unsigned bitWidth() const { return V.getBitWidth(); }
 
   APSInt toAPSInt(unsigned Bits = 0) const { return V; }
   APValue toAPValue() const { return APValue(V); }
diff --git a/clang/lib/AST/Interp/Interp.h b/clang/lib/AST/Interp/Interp.h
index 9d5ec3315415cf7..d3ee28c0315cda8 100644
--- a/clang/lib/AST/Interp/Interp.h
+++ b/clang/lib/AST/Interp/Interp.h
@@ -1561,6 +1561,22 @@ inline bool CastFP(InterpState &S, CodePtr OpPC, const 
llvm::fltSemantics *Sem,
   return true;
 }
 
+/// Like Cast(), but we cast to an arbitrary-bitwidth integral, so we need
+/// to know what bitwidth the result should be.
+template ::T>
+bool CastAP(InterpState &S, CodePtr OpPC, uint32_t BitWidth) {
+  S.Stk.push>(
+  IntegralAP::from(S.Stk.pop(), BitWidth

[clang] Avoid need for SLocEntryLoaded BitVector (PR #67960)

2023-10-03 Thread Giulio Eulisse via cfe-commits

https://github.com/ktf updated https://github.com/llvm/llvm-project/pull/67960

>From 9fde224de6baa5b1fb3713d810ce835d4456b457 Mon Sep 17 00:00:00 2001
From: Giulio Eulisse <10544+...@users.noreply.github.com>
Date: Fri, 29 Sep 2023 08:37:57 +0200
Subject: [PATCH 1/7] Avoid need for SLocEntryLoaded BitVector

The BitVector is currently used to keep track of which entries of
LoadedSLocEntryTable have been loaded. Such information can be stored in
the SLocEntry itself. Moreover, thanks to the fact that
LoadedSLocEntryTable is now a PagedVector, we can simply consider
elements of unmaterialised pages as not loaded.

This trades reducing the number of OffsetBits by one for reducing memory
usage of the SourceManager by LoadedSLocEntryTable.size()/8 bytes.
---
 clang/include/clang/Basic/SourceManager.h | 16 ++
 clang/lib/Basic/SourceManager.cpp | 27 ++-
 llvm/include/llvm/ADT/PagedVector.h   |  6 +
 3 files changed, 29 insertions(+), 20 deletions(-)

diff --git a/clang/include/clang/Basic/SourceManager.h 
b/clang/include/clang/Basic/SourceManager.h
index c1b24eec2759c71..d450280303d6785 100644
--- a/clang/include/clang/Basic/SourceManager.h
+++ b/clang/include/clang/Basic/SourceManager.h
@@ -474,9 +474,10 @@ static_assert(sizeof(FileInfo) <= sizeof(ExpansionInfo),
 /// SourceManager keeps an array of these objects, and they are uniquely
 /// identified by the FileID datatype.
 class SLocEntry {
-  static constexpr int OffsetBits = 8 * sizeof(SourceLocation::UIntTy) - 1;
+  static constexpr int OffsetBits = 8 * sizeof(SourceLocation::UIntTy) - 2;
   SourceLocation::UIntTy Offset : OffsetBits;
   SourceLocation::UIntTy IsExpansion : 1;
+  SourceLocation::UIntTy Loaded : 1;
   union {
 FileInfo File;
 ExpansionInfo Expansion;
@@ -489,6 +490,8 @@ class SLocEntry {
 
   bool isExpansion() const { return IsExpansion; }
   bool isFile() const { return !isExpansion(); }
+  [[nodiscard]] bool isLoaded() const { return Loaded; }
+  void setLoaded(bool Value) { Loaded = Value; }
 
   const FileInfo &getFile() const {
 assert(isFile() && "Not a file SLocEntry!");
@@ -716,13 +719,7 @@ class SourceManager : public RefCountedBase 
{
   /// The highest possible offset is 2^31-1 (2^63-1 for 64-bit source
   /// locations), so CurrentLoadedOffset starts at 2^31 (2^63 resp.).
   static const SourceLocation::UIntTy MaxLoadedOffset =
-  1ULL << (8 * sizeof(SourceLocation::UIntTy) - 1);
-
-  /// A bitmap that indicates whether the entries of LoadedSLocEntryTable
-  /// have already been loaded from the external source.
-  ///
-  /// Same indexing as LoadedSLocEntryTable.
-  llvm::BitVector SLocEntryLoaded;
+  1ULL << (8 * sizeof(SourceLocation::UIntTy) - 2);
 
   /// An external source for source location entries.
   ExternalSLocEntrySource *ExternalSLocEntries = nullptr;
@@ -1710,7 +1707,8 @@ class SourceManager : public 
RefCountedBase {
   const SrcMgr::SLocEntry &getLoadedSLocEntry(unsigned Index,
   bool *Invalid = nullptr) const {
 assert(Index < LoadedSLocEntryTable.size() && "Invalid index");
-if (SLocEntryLoaded[Index])
+if (LoadedSLocEntryTable.isMaterialized(Index) &&
+LoadedSLocEntryTable[Index].isLoaded())
   return LoadedSLocEntryTable[Index];
 return loadSLocEntry(Index, Invalid);
   }
diff --git a/clang/lib/Basic/SourceManager.cpp 
b/clang/lib/Basic/SourceManager.cpp
index 3066cc53dbfd878..20e3f1252ddf077 100644
--- a/clang/lib/Basic/SourceManager.cpp
+++ b/clang/lib/Basic/SourceManager.cpp
@@ -336,7 +336,6 @@ void SourceManager::clearIDTables() {
   MainFileID = FileID();
   LocalSLocEntryTable.clear();
   LoadedSLocEntryTable.clear();
-  SLocEntryLoaded.clear();
   LastLineNoFileIDQuery = FileID();
   LastLineNoContentCache = nullptr;
   LastFileIDLookup = FileID();
@@ -373,7 +372,8 @@ void SourceManager::initializeForReplay(const SourceManager 
&Old) {
 
   // Ensure all SLocEntries are loaded from the external source.
   for (unsigned I = 0, N = Old.LoadedSLocEntryTable.size(); I != N; ++I)
-if (!Old.SLocEntryLoaded[I])
+if (!Old.LoadedSLocEntryTable.isMaterialized(I) ||
+!Old.LoadedSLocEntryTable[I].isLoaded())
   Old.loadSLocEntry(I, nullptr);
 
   // Inherit any content cache data from the old source manager.
@@ -430,12 +430,14 @@ ContentCache &SourceManager::createMemBufferContentCache(
 
 const SrcMgr::SLocEntry &SourceManager::loadSLocEntry(unsigned Index,
   bool *Invalid) const {
-  assert(!SLocEntryLoaded[Index]);
+  assert(!LoadedSLocEntryTable.isMaterialized(Index) ||
+ !LoadedSLocEntryTable[Index].isLoaded());
   if (ExternalSLocEntries->ReadSLocEntry(-(static_cast(Index) + 2))) {
 if (Invalid)
   *Invalid = true;
 // If the file of the SLocEntry changed we could still have loaded it.
-if (!SLocEntryLoaded[Index]) {
+if (!LoadedSLocEntryTable.isMaterialized(Index) |

[clang] [clang][ASTImporter] Fix of possible crash "Did not find base!". (PR #67680)

2023-10-03 Thread Balázs Kéri via cfe-commits

balazske wrote:

The format checker job looks faulty, it fails in other patches too. I remember 
that clang-format was used on the code, because I usually don't add line breaks 
to long code lines.

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


[PATCH] D158413: [Lex] Introduce Preprocessor::LexTokensUntilEOF()

2023-10-03 Thread Jonas Hahnfeld via Phabricator via cfe-commits
Hahnfeld added a comment.

ping


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

https://reviews.llvm.org/D158413

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


[PATCH] D158414: [LexerTest] Use LexTokensUntilEOF() in StringifyArgs

2023-10-03 Thread Jonas Hahnfeld via Phabricator via cfe-commits
Hahnfeld added a comment.

ping


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

https://reviews.llvm.org/D158414

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


[clang] [RISCV] Add MC layer support for Zicfiss. (PR #66043)

2023-10-03 Thread Yeting Kuo via cfe-commits

https://github.com/yetingk updated 
https://github.com/llvm/llvm-project/pull/66043

>From 91bb1d9884276a37f93515a648aa6ece353fdc70 Mon Sep 17 00:00:00 2001
From: Yeting Kuo 
Date: Tue, 12 Sep 2023 12:28:00 +0800
Subject: [PATCH 1/2] [RISCV] Add MC layer support for Zicfiss.

The patch adds the instructions in Zicfiss extension. Zicfiss extension is
to support shadow stack for control flow integrity.

Differential Revision: https://reviews.llvm.org/D152793
---
 .../test/Preprocessor/riscv-target-features.c |   9 ++
 llvm/docs/RISCVUsage.rst  |   3 +
 llvm/lib/Support/RISCVISAInfo.cpp |   2 +
 .../RISCV/Disassembler/RISCVDisassembler.cpp  |  29 +
 llvm/lib/Target/RISCV/RISCVFeatures.td|   7 ++
 llvm/lib/Target/RISCV/RISCVInstrInfo.td   |   9 +-
 .../lib/Target/RISCV/RISCVInstrInfoZicfiss.td |  86 +++
 llvm/lib/Target/RISCV/RISCVRegisterInfo.cpp   |   3 +
 llvm/lib/Target/RISCV/RISCVRegisterInfo.td|   9 ++
 llvm/test/MC/RISCV/attribute-arch.s   |   3 +
 llvm/test/MC/RISCV/rv32zicfiss-invalid.s  |  20 
 llvm/test/MC/RISCV/rv32zicfiss-valid.s| 103 ++
 llvm/test/MC/RISCV/rv64zicfiss-invalid.s  |  20 
 llvm/test/MC/RISCV/rv64zicfiss-valid.s| 103 ++
 14 files changed, 402 insertions(+), 4 deletions(-)
 create mode 100644 llvm/lib/Target/RISCV/RISCVInstrInfoZicfiss.td
 create mode 100644 llvm/test/MC/RISCV/rv32zicfiss-invalid.s
 create mode 100644 llvm/test/MC/RISCV/rv32zicfiss-valid.s
 create mode 100644 llvm/test/MC/RISCV/rv64zicfiss-invalid.s
 create mode 100644 llvm/test/MC/RISCV/rv64zicfiss-valid.s

diff --git a/clang/test/Preprocessor/riscv-target-features.c 
b/clang/test/Preprocessor/riscv-target-features.c
index 02b67dc7944ba88..163eba81543ee5b 100644
--- a/clang/test/Preprocessor/riscv-target-features.c
+++ b/clang/test/Preprocessor/riscv-target-features.c
@@ -113,6 +113,7 @@
 // CHECK-NOT: __riscv_zfa {{.*$}}
 // CHECK-NOT: __riscv_zfbfmin {{.*$}}
 // CHECK-NOT: __riscv_zicfilp {{.*$}}
+// CHECK-NOT: __riscv_zicfiss {{.*$}}
 // CHECK-NOT: __riscv_zicond {{.*$}}
 // CHECK-NOT: __riscv_ztso {{.*$}}
 // CHECK-NOT: __riscv_zvbb {{.*$}}
@@ -1220,3 +1221,11 @@
 // RUN: -march=rv64i_zve32x_zvkt1p0 -x c -E -dM %s \
 // RUN: -o - | FileCheck --check-prefix=CHECK-ZVKT-EXT %s
 // CHECK-ZVKT-EXT: __riscv_zvkt 100{{$}}
+
+// RUN: %clang -target riscv32 -menable-experimental-extensions \
+// RUN: -march=rv32izicfiss0p3 -x c -E -dM %s \
+// RUN: -o - | FileCheck --check-prefix=CHECK-ZICFISS-EXT %s
+// RUN: %clang -target riscv64 -menable-experimental-extensions \
+// RUN: -march=rv64izicfiss0p3 -x c -E -dM %s \
+// RUN: -o - | FileCheck --check-prefix=CHECK-ZICFISS-EXT %s
+// CHECK-ZICFISS-EXT: __riscv_zicfiss 3000{{$}}
diff --git a/llvm/docs/RISCVUsage.rst b/llvm/docs/RISCVUsage.rst
index 8d12d58738c609a..31c55def0a7694a 100644
--- a/llvm/docs/RISCVUsage.rst
+++ b/llvm/docs/RISCVUsage.rst
@@ -205,6 +205,9 @@ The primary goal of experimental support is to assist in 
the process of ratifica
 ``experimental-zicfilp``
   LLVM implements the `0.2 draft specification 
`__.
 
+``experimental-zicfiss``
+  LLVM implements the `0.3.1 draft specification 
`__.
+
 ``experimental-zicond``
   LLVM implements the `1.0-rc1 draft specification 
`__.
 
diff --git a/llvm/lib/Support/RISCVISAInfo.cpp 
b/llvm/lib/Support/RISCVISAInfo.cpp
index a02c9842e85839a..c414b62c5f31092 100644
--- a/llvm/lib/Support/RISCVISAInfo.cpp
+++ b/llvm/lib/Support/RISCVISAInfo.cpp
@@ -170,6 +170,8 @@ static const RISCVSupportedExtension 
SupportedExperimentalExtensions[] = {
 {"zfbfmin", RISCVExtensionVersion{0, 8}},
 
 {"zicfilp", RISCVExtensionVersion{0, 2}},
+{"zicfiss", RISCVExtensionVersion{0, 3}},
+
 {"zicond", RISCVExtensionVersion{1, 0}},
 
 {"ztso", RISCVExtensionVersion{0, 1}},
diff --git a/llvm/lib/Target/RISCV/Disassembler/RISCVDisassembler.cpp 
b/llvm/lib/Target/RISCV/Disassembler/RISCVDisassembler.cpp
index d561d90d3088c1a..14b3122f0fecbdb 100644
--- a/llvm/lib/Target/RISCV/Disassembler/RISCVDisassembler.cpp
+++ b/llvm/lib/Target/RISCV/Disassembler/RISCVDisassembler.cpp
@@ -74,6 +74,17 @@ static DecodeStatus DecodeGPRRegisterClass(MCInst &Inst, 
uint32_t RegNo,
   return MCDisassembler::Success;
 }
 
+static DecodeStatus DecodeGPRRARegisterClass(MCInst &Inst, uint32_t RegNo,
+ uint64_t Address,
+ const MCDisassembler *Decoder) {
+  MCRegister Reg = RISCV::X0 + RegNo;
+  if (Reg != RISCV::X1 && Reg != RISCV::X5)
+return MCDisassembler::Fail;
+
+  Inst.addOperand(MCOperand::createReg(Reg));
+  return MCDisassembler::Success;
+}
+
 static DecodeStatus DecodeFPR16RegisterClass(MCInst &Inst, uint32_t RegNo,

[clang] [RISCV] Add MC layer support for Zicfiss. (PR #66043)

2023-10-03 Thread Yeting Kuo via cfe-commits


@@ -165,6 +167,10 @@ def SP : GPRRegisterClass<(add X2)>;
 def SR07 : GPRRegisterClass<(add (sequence "X%u", 8, 9),
  (sequence "X%u", 18, 23))>;
 
+def GPRRA : RegisterClass<"RISCV", [XLenVT], 32, (add X1, X5)> {

yetingk wrote:

Done.

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


[clang] [RISCV] Add MC layer support for Zicfiss. (PR #66043)

2023-10-03 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-llvm-support


Changes

The patch adds the instructions in Zicfiss extension. Zicfiss extension is to 
support shadow stack for control flow integrity. This patch is based on version 
[0.3.1].

[0.3.1]: https://github.com/riscv/riscv-cfi/releases/tag/v0.3.1

---

Patch is 23.46 KiB, truncated to 20.00 KiB below, full version: 
https://github.com/llvm/llvm-project/pull/66043.diff


14 Files Affected:

- (modified) clang/test/Preprocessor/riscv-target-features.c (+9) 
- (modified) llvm/docs/RISCVUsage.rst (+3) 
- (modified) llvm/lib/Support/RISCVISAInfo.cpp (+2) 
- (modified) llvm/lib/Target/RISCV/Disassembler/RISCVDisassembler.cpp (+29) 
- (modified) llvm/lib/Target/RISCV/RISCVFeatures.td (+7) 
- (modified) llvm/lib/Target/RISCV/RISCVInstrInfo.td (+5-4) 
- (added) llvm/lib/Target/RISCV/RISCVInstrInfoZicfiss.td (+86) 
- (modified) llvm/lib/Target/RISCV/RISCVRegisterInfo.cpp (+3) 
- (modified) llvm/lib/Target/RISCV/RISCVRegisterInfo.td (+9) 
- (modified) llvm/test/MC/RISCV/attribute-arch.s (+3) 
- (added) llvm/test/MC/RISCV/rv32zicfiss-invalid.s (+20) 
- (added) llvm/test/MC/RISCV/rv32zicfiss-valid.s (+103) 
- (added) llvm/test/MC/RISCV/rv64zicfiss-invalid.s (+20) 
- (added) llvm/test/MC/RISCV/rv64zicfiss-valid.s (+103) 


``diff
diff --git a/clang/test/Preprocessor/riscv-target-features.c 
b/clang/test/Preprocessor/riscv-target-features.c
index 02b67dc7944ba88..163eba81543ee5b 100644
--- a/clang/test/Preprocessor/riscv-target-features.c
+++ b/clang/test/Preprocessor/riscv-target-features.c
@@ -113,6 +113,7 @@
 // CHECK-NOT: __riscv_zfa {{.*$}}
 // CHECK-NOT: __riscv_zfbfmin {{.*$}}
 // CHECK-NOT: __riscv_zicfilp {{.*$}}
+// CHECK-NOT: __riscv_zicfiss {{.*$}}
 // CHECK-NOT: __riscv_zicond {{.*$}}
 // CHECK-NOT: __riscv_ztso {{.*$}}
 // CHECK-NOT: __riscv_zvbb {{.*$}}
@@ -1220,3 +1221,11 @@
 // RUN: -march=rv64i_zve32x_zvkt1p0 -x c -E -dM %s \
 // RUN: -o - | FileCheck --check-prefix=CHECK-ZVKT-EXT %s
 // CHECK-ZVKT-EXT: __riscv_zvkt 100{{$}}
+
+// RUN: %clang -target riscv32 -menable-experimental-extensions \
+// RUN: -march=rv32izicfiss0p3 -x c -E -dM %s \
+// RUN: -o - | FileCheck --check-prefix=CHECK-ZICFISS-EXT %s
+// RUN: %clang -target riscv64 -menable-experimental-extensions \
+// RUN: -march=rv64izicfiss0p3 -x c -E -dM %s \
+// RUN: -o - | FileCheck --check-prefix=CHECK-ZICFISS-EXT %s
+// CHECK-ZICFISS-EXT: __riscv_zicfiss 3000{{$}}
diff --git a/llvm/docs/RISCVUsage.rst b/llvm/docs/RISCVUsage.rst
index 8d12d58738c609a..31c55def0a7694a 100644
--- a/llvm/docs/RISCVUsage.rst
+++ b/llvm/docs/RISCVUsage.rst
@@ -205,6 +205,9 @@ The primary goal of experimental support is to assist in 
the process of ratifica
 ``experimental-zicfilp``
   LLVM implements the `0.2 draft specification 
`__.
 
+``experimental-zicfiss``
+  LLVM implements the `0.3.1 draft specification 
`__.
+
 ``experimental-zicond``
   LLVM implements the `1.0-rc1 draft specification 
`__.
 
diff --git a/llvm/lib/Support/RISCVISAInfo.cpp 
b/llvm/lib/Support/RISCVISAInfo.cpp
index a02c9842e85839a..c414b62c5f31092 100644
--- a/llvm/lib/Support/RISCVISAInfo.cpp
+++ b/llvm/lib/Support/RISCVISAInfo.cpp
@@ -170,6 +170,8 @@ static const RISCVSupportedExtension 
SupportedExperimentalExtensions[] = {
 {"zfbfmin", RISCVExtensionVersion{0, 8}},
 
 {"zicfilp", RISCVExtensionVersion{0, 2}},
+{"zicfiss", RISCVExtensionVersion{0, 3}},
+
 {"zicond", RISCVExtensionVersion{1, 0}},
 
 {"ztso", RISCVExtensionVersion{0, 1}},
diff --git a/llvm/lib/Target/RISCV/Disassembler/RISCVDisassembler.cpp 
b/llvm/lib/Target/RISCV/Disassembler/RISCVDisassembler.cpp
index d561d90d3088c1a..9f088b6f3bf6492 100644
--- a/llvm/lib/Target/RISCV/Disassembler/RISCVDisassembler.cpp
+++ b/llvm/lib/Target/RISCV/Disassembler/RISCVDisassembler.cpp
@@ -74,6 +74,17 @@ static DecodeStatus DecodeGPRRegisterClass(MCInst &Inst, 
uint32_t RegNo,
   return MCDisassembler::Success;
 }
 
+static DecodeStatus DecodeGPRX1X5RegisterClass(MCInst &Inst, uint32_t RegNo,
+   uint64_t Address,
+   const MCDisassembler *Decoder) {
+  MCRegister Reg = RISCV::X0 + RegNo;
+  if (Reg != RISCV::X1 && Reg != RISCV::X5)
+return MCDisassembler::Fail;
+
+  Inst.addOperand(MCOperand::createReg(Reg));
+  return MCDisassembler::Success;
+}
+
 static DecodeStatus DecodeFPR16RegisterClass(MCInst &Inst, uint32_t RegNo,
  uint64_t Address,
  const MCDisassembler *Decoder) {
@@ -370,6 +381,10 @@ static DecodeStatus decodeZcmpRlist(MCInst &Inst, unsigned 
Imm,
 static DecodeStatus decodeZcmpSpimm(MCInst &Inst, unsigned Imm,
 uint64_t Address, const void *Decoder);
 
+static 

[PATCH] D158413: [Lex] Introduce Preprocessor::LexTokensUntilEOF()

2023-10-03 Thread Vassil Vassilev via Phabricator via cfe-commits
v.g.vassilev added a comment.

This looks reasonable to me, but I'd wait for @aaron.ballman greenlight as he 
seems to have had more comments/ideas.




Comment at: clang/lib/Lex/Preprocessor.cpp:1000
+  std::vector toks;
+  while (1) {
+Token tok;

Hahnfeld wrote:
> aaron.ballman wrote:
> > v.g.vassilev wrote:
> > > aaron.ballman wrote:
> > > > Hahnfeld wrote:
> > > > > aaron.ballman wrote:
> > > > > > I'd prefer not to assume the token stream has an EOF token (perhaps 
> > > > > > the stream is one only being used to parse until the `eod` token 
> > > > > > instead), so if we can turn this into a non-infinite loop, that 
> > > > > > would make me more comfortable.
> > > > > I'm not sure I understand entirely. Do you want something like
> > > > > ```
> > > > > tok.isOneOf(tok::unknown, tok::eof, tok::eod)
> > > > > ```
> > > > > instead of `tok.is(tok::eof)`? Can this happen at the level of the 
> > > > > `Preprocessor`?
> > > > I was thinking something more along the lines of:
> > > > ```
> > > > if (Tokens) {
> > > >   for (Token Tok; !Tok.isOneOf(tok::eof, tok::eod); Lex(Tok))
> > > > Tokens->push_back(Tok);
> > > > }
> > > > ```
> > > > but I hadn't thought about `tok::unknown`; that might be a good one to 
> > > > also include given that clangd operates on partial sources.
> > > > 
> > > I was wondering if we could somehow merge this routine with 
> > > `Parser::SkipUntil` since they seem to be doing a very similar tasks.
> > That could perhaps end up looking reasonable (they do similar tasks aside 
> > from collecting the tokens that are being skipped). Do you need the 
> > interface to be on `Preprocessor` or `Parser` though (or does it not really 
> > matter for you)?
> > `tok.isOneOf(tok::unknown, tok::eof, tok::eod)`
> 
> I implemented this check, let me know if this looks reasonable. The code you 
> posted doesn't do what we need because we also want to lex if `Tokens` is 
> `nullptr`, so the hierarchy must be an `if` inside the loop.
> Given these additional token kinds, does `UntilEOF` still make sense or do we 
> want another name? Note that I'll leave `repl_input_end` to 
> https://reviews.llvm.org/D158415.
> 
> > I was wondering if we could somehow merge this routine with 
> > `Parser::SkipUntil` since they seem to be doing a very similar tasks.
> 
> I'm not sure this makes sense, given that `Parser::SkipUntil` requires some 
> knowledge about the structural input. At the very least, I'd prefer not to go 
> into that direction for this change.
I am not sure I understand the reasoning but I somewhat see that having 
Parser's `SkipUntil` be implemented with our new `Preprocessor::LexUntil...` 
would require a lot more work. How about adding a fixme note capturing this as 
a future possible refactoring?


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

https://reviews.llvm.org/D158413

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


[clang] [lld][ELF] Warn instead of error when linker script fails to find section (PR #68058)

2023-10-03 Thread Fangrui Song via cfe-commits

MaskRay wrote:

I can understand downgrading an error could be convenient for for (optimizing 
section layout or alleviate relocation overflow) but the motivation is a bit 
strange. GNU ld does use an error for this case and this change would not 
address `--fatal-warnings` builds. 
In the absence of an insertion anchor, discarding the effect of the output 
section descriptions could be benign in some cases but disruptive in other 
cases. I think an error is appropriate.

Have you tried defining the anchor sections in a relocatable object file that's 
always linked into the executable instead?
The relocatable object file can be used together with a global linker script.


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


[clang] [CodeGen] Allow mixed scalar type constraints for inline asm (PR #65465)

2023-10-03 Thread Dávid Ferenc Szabó via cfe-commits

https://github.com/dfszabo updated 
https://github.com/llvm/llvm-project/pull/65465

From ea6ac8788b383ba22073e631d12a80f421c36a1a Mon Sep 17 00:00:00 2001
From: dszabo 
Date: Mon, 18 Sep 2023 17:47:15 +0200
Subject: [PATCH] [CodeGen] Allow mixed scalar type constraints for inline asm

---
 .../SelectionDAG/SelectionDAGBuilder.cpp  |  7 ++--
 .../CodeGen/SelectionDAG/TargetLowering.cpp   |  7 ++--
 llvm/test/CodeGen/X86/inline-asm-int-to-fp.ll | 32 +++
 3 files changed, 42 insertions(+), 4 deletions(-)
 create mode 100644 llvm/test/CodeGen/X86/inline-asm-int-to-fp.ll

diff --git a/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp 
b/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp
index 7a85f19f3df5d3e..10e55e0cfe2ef5d 100644
--- a/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp
+++ b/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp
@@ -8841,8 +8841,11 @@ static void patchMatchingInput(const 
SDISelAsmOperandInfo &OpInfo,
   std::pair InputRC =
   TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
MatchingOpInfo.ConstraintVT);
-  if ((OpInfo.ConstraintVT.isInteger() !=
-   MatchingOpInfo.ConstraintVT.isInteger()) ||
+  const bool OutOpIsIntOrFP =
+  OpInfo.ConstraintVT.isInteger() || OpInfo.ConstraintVT.isFloatingPoint();
+  const bool InOpInfoIsIntOrFP = MatchingOpInfo.ConstraintVT.isInteger() ||
+ MatchingOpInfo.ConstraintVT.isFloatingPoint();
+  if ((OutOpIsIntOrFP != InOpInfoIsIntOrFP) ||
   (MatchRC.second != InputRC.second)) {
 // FIXME: error out in a more elegant fashion
 report_fatal_error("Unsupported asm: input constraint"
diff --git a/llvm/lib/CodeGen/SelectionDAG/TargetLowering.cpp 
b/llvm/lib/CodeGen/SelectionDAG/TargetLowering.cpp
index 23c1486f711d727..89d7bbd41f0be8f 100644
--- a/llvm/lib/CodeGen/SelectionDAG/TargetLowering.cpp
+++ b/llvm/lib/CodeGen/SelectionDAG/TargetLowering.cpp
@@ -5687,8 +5687,11 @@ TargetLowering::ParseConstraints(const DataLayout &DL,
 std::pair InputRC =
 getRegForInlineAsmConstraint(TRI, Input.ConstraintCode,
  Input.ConstraintVT);
-if ((OpInfo.ConstraintVT.isInteger() !=
- Input.ConstraintVT.isInteger()) ||
+const bool OutOpIsIntOrFP = OpInfo.ConstraintVT.isInteger() ||
+OpInfo.ConstraintVT.isFloatingPoint();
+const bool InOpIsIntOrFP = Input.ConstraintVT.isInteger() ||
+   Input.ConstraintVT.isFloatingPoint();
+if ((OutOpIsIntOrFP != InOpIsIntOrFP) ||
 (MatchRC.second != InputRC.second)) {
   report_fatal_error("Unsupported asm: input constraint"
  " with a matching output constraint of"
diff --git a/llvm/test/CodeGen/X86/inline-asm-int-to-fp.ll 
b/llvm/test/CodeGen/X86/inline-asm-int-to-fp.ll
new file mode 100644
index 000..9470553b2fbc43d
--- /dev/null
+++ b/llvm/test/CodeGen/X86/inline-asm-int-to-fp.ll
@@ -0,0 +1,32 @@
+; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py
+; RUN: llc -mtriple=x86_64-unknown-linux-gnu < %s | FileCheck %s
+
+; C source used for generating this test:
+
+; unsigned test(float f)
+; {
+;unsigned i;
+;asm volatile ("" : "=r" (i) : "0" (f));
+;return i;
+; }
+
+
+define i32 @test(float %f) {
+; CHECK-LABEL: test:
+; CHECK:   # %bb.0: # %entry
+; CHECK-NEXT:movss %xmm0, -{{[0-9]+}}(%rsp)
+; CHECK-NEXT:movl -{{[0-9]+}}(%rsp), %eax
+; CHECK-NEXT:#APP
+; CHECK-NEXT:#NO_APP
+; CHECK-NEXT:movl %eax, -{{[0-9]+}}(%rsp)
+; CHECK-NEXT:retq
+entry:
+  %f.addr = alloca float, align 4
+  %i = alloca i32, align 4
+  store float %f, ptr %f.addr, align 4
+  %0 = load float, ptr %f.addr, align 4
+  %1 = call i32 asm sideeffect "", "=r,0,~{dirflag},~{fpsr},~{flags}"(float %0)
+  store i32 %1, ptr %i, align 4
+  %2 = load i32, ptr %i, align 4
+  ret i32 %2
+}

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


[clang] [clang-repl] Emit const variables only once (PR #65257)

2023-10-03 Thread Jonas Hahnfeld via cfe-commits


@@ -0,0 +1,29 @@
+// UNSUPPORTED: system-aix
+// RUN: cat %s | clang-repl | FileCheck %s
+// RUN: cat %s | clang-repl -Xcc -O2 | FileCheck %s
+
+extern "C" int printf(const char*, ...);
+

hahnjo wrote:

`const A a(1);` is a file-scope constant, no? We don't need it for C because 
the special case in `LinkageComputer::getLVForNamespaceScopeDecl` only applies 
to C++ (my understanding is that `const` variables always have an identity in 
C).

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


[clang] [clang-repl][CUDA] Move CUDA module registration to beginning of global_ctors (PR #66658)

2023-10-03 Thread Jonas Hahnfeld via cfe-commits


@@ -794,7 +794,7 @@ void CodeGenModule::Release() {
   AddGlobalCtor(ObjCInitFunction);
   if (Context.getLangOpts().CUDA && CUDARuntime) {
 if (llvm::Function *CudaCtorFunction = CUDARuntime->finalizeModule())
-  AddGlobalCtor(CudaCtorFunction);
+  AddGlobalCtor(CudaCtorFunction, /*Priority=*/0);

hahnjo wrote:

I have the same fear as @Artem-B, higher than default priorities are also 
sometimes reserved. We really need to see what `nvcc` does here, but what I 
could imagine (at least how I would solve it) is putting the constructor with 
the same priority before all other constructors.

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


[clang] [RISCV] Implement shadow stack on shadow stack mode with Zicfiss. (PR #68075)

2023-10-03 Thread Yeting Kuo via cfe-commits

https://github.com/yetingk created 
https://github.com/llvm/llvm-project/pull/68075

There are two shadow stack implements with Zicfiss in [spec] now.
In Shadow stack mode, programs still store the return address to regular 
address.
In Control stack mode, programs only store the return address to shadow stack.
This patch only supports the shadow stack mode.

[spec]: 
https://github.com/riscv/riscv-cfi/blob/main/cfi_backward.adoc#push-to-and-pop-from-the-shadow-stack

>From 91bb1d9884276a37f93515a648aa6ece353fdc70 Mon Sep 17 00:00:00 2001
From: Yeting Kuo 
Date: Tue, 12 Sep 2023 12:28:00 +0800
Subject: [PATCH 1/3] [RISCV] Add MC layer support for Zicfiss.

The patch adds the instructions in Zicfiss extension. Zicfiss extension is
to support shadow stack for control flow integrity.

Differential Revision: https://reviews.llvm.org/D152793
---
 .../test/Preprocessor/riscv-target-features.c |   9 ++
 llvm/docs/RISCVUsage.rst  |   3 +
 llvm/lib/Support/RISCVISAInfo.cpp |   2 +
 .../RISCV/Disassembler/RISCVDisassembler.cpp  |  29 +
 llvm/lib/Target/RISCV/RISCVFeatures.td|   7 ++
 llvm/lib/Target/RISCV/RISCVInstrInfo.td   |   9 +-
 .../lib/Target/RISCV/RISCVInstrInfoZicfiss.td |  86 +++
 llvm/lib/Target/RISCV/RISCVRegisterInfo.cpp   |   3 +
 llvm/lib/Target/RISCV/RISCVRegisterInfo.td|   9 ++
 llvm/test/MC/RISCV/attribute-arch.s   |   3 +
 llvm/test/MC/RISCV/rv32zicfiss-invalid.s  |  20 
 llvm/test/MC/RISCV/rv32zicfiss-valid.s| 103 ++
 llvm/test/MC/RISCV/rv64zicfiss-invalid.s  |  20 
 llvm/test/MC/RISCV/rv64zicfiss-valid.s| 103 ++
 14 files changed, 402 insertions(+), 4 deletions(-)
 create mode 100644 llvm/lib/Target/RISCV/RISCVInstrInfoZicfiss.td
 create mode 100644 llvm/test/MC/RISCV/rv32zicfiss-invalid.s
 create mode 100644 llvm/test/MC/RISCV/rv32zicfiss-valid.s
 create mode 100644 llvm/test/MC/RISCV/rv64zicfiss-invalid.s
 create mode 100644 llvm/test/MC/RISCV/rv64zicfiss-valid.s

diff --git a/clang/test/Preprocessor/riscv-target-features.c 
b/clang/test/Preprocessor/riscv-target-features.c
index 02b67dc7944ba88..163eba81543ee5b 100644
--- a/clang/test/Preprocessor/riscv-target-features.c
+++ b/clang/test/Preprocessor/riscv-target-features.c
@@ -113,6 +113,7 @@
 // CHECK-NOT: __riscv_zfa {{.*$}}
 // CHECK-NOT: __riscv_zfbfmin {{.*$}}
 // CHECK-NOT: __riscv_zicfilp {{.*$}}
+// CHECK-NOT: __riscv_zicfiss {{.*$}}
 // CHECK-NOT: __riscv_zicond {{.*$}}
 // CHECK-NOT: __riscv_ztso {{.*$}}
 // CHECK-NOT: __riscv_zvbb {{.*$}}
@@ -1220,3 +1221,11 @@
 // RUN: -march=rv64i_zve32x_zvkt1p0 -x c -E -dM %s \
 // RUN: -o - | FileCheck --check-prefix=CHECK-ZVKT-EXT %s
 // CHECK-ZVKT-EXT: __riscv_zvkt 100{{$}}
+
+// RUN: %clang -target riscv32 -menable-experimental-extensions \
+// RUN: -march=rv32izicfiss0p3 -x c -E -dM %s \
+// RUN: -o - | FileCheck --check-prefix=CHECK-ZICFISS-EXT %s
+// RUN: %clang -target riscv64 -menable-experimental-extensions \
+// RUN: -march=rv64izicfiss0p3 -x c -E -dM %s \
+// RUN: -o - | FileCheck --check-prefix=CHECK-ZICFISS-EXT %s
+// CHECK-ZICFISS-EXT: __riscv_zicfiss 3000{{$}}
diff --git a/llvm/docs/RISCVUsage.rst b/llvm/docs/RISCVUsage.rst
index 8d12d58738c609a..31c55def0a7694a 100644
--- a/llvm/docs/RISCVUsage.rst
+++ b/llvm/docs/RISCVUsage.rst
@@ -205,6 +205,9 @@ The primary goal of experimental support is to assist in 
the process of ratifica
 ``experimental-zicfilp``
   LLVM implements the `0.2 draft specification 
`__.
 
+``experimental-zicfiss``
+  LLVM implements the `0.3.1 draft specification 
`__.
+
 ``experimental-zicond``
   LLVM implements the `1.0-rc1 draft specification 
`__.
 
diff --git a/llvm/lib/Support/RISCVISAInfo.cpp 
b/llvm/lib/Support/RISCVISAInfo.cpp
index a02c9842e85839a..c414b62c5f31092 100644
--- a/llvm/lib/Support/RISCVISAInfo.cpp
+++ b/llvm/lib/Support/RISCVISAInfo.cpp
@@ -170,6 +170,8 @@ static const RISCVSupportedExtension 
SupportedExperimentalExtensions[] = {
 {"zfbfmin", RISCVExtensionVersion{0, 8}},
 
 {"zicfilp", RISCVExtensionVersion{0, 2}},
+{"zicfiss", RISCVExtensionVersion{0, 3}},
+
 {"zicond", RISCVExtensionVersion{1, 0}},
 
 {"ztso", RISCVExtensionVersion{0, 1}},
diff --git a/llvm/lib/Target/RISCV/Disassembler/RISCVDisassembler.cpp 
b/llvm/lib/Target/RISCV/Disassembler/RISCVDisassembler.cpp
index d561d90d3088c1a..14b3122f0fecbdb 100644
--- a/llvm/lib/Target/RISCV/Disassembler/RISCVDisassembler.cpp
+++ b/llvm/lib/Target/RISCV/Disassembler/RISCVDisassembler.cpp
@@ -74,6 +74,17 @@ static DecodeStatus DecodeGPRRegisterClass(MCInst &Inst, 
uint32_t RegNo,
   return MCDisassembler::Success;
 }
 
+static DecodeStatus DecodeGPRRARegisterClass(MCInst &Inst, uint32_t RegNo,
+ uint64_t Address

[clang] [RISCV] Implement shadow stack on shadow stack mode with Zicfiss. (PR #68075)

2023-10-03 Thread Yeting Kuo via cfe-commits

yetingk wrote:

This is based on #66762.

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


[clang] [RISCV] Implement shadow stack on shadow stack mode with Zicfiss. (PR #68075)

2023-10-03 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-llvm-support


Changes

There are two shadow stack implements with Zicfiss in [spec] now.
In Shadow stack mode, programs still store the return address to regular 
address.
In Control stack mode, programs only store the return address to shadow stack.
This patch only supports the shadow stack mode.

[spec]: 
https://github.com/riscv/riscv-cfi/blob/main/cfi_backward.adoc#push-to-and-pop-from-the-shadow-stack

---

Patch is 31.33 KiB, truncated to 20.00 KiB below, full version: 
https://github.com/llvm/llvm-project/pull/68075.diff


16 Files Affected:

- (modified) clang/test/Preprocessor/riscv-target-features.c (+9) 
- (modified) llvm/docs/RISCVUsage.rst (+3) 
- (modified) llvm/lib/Support/RISCVISAInfo.cpp (+2) 
- (modified) llvm/lib/Target/RISCV/Disassembler/RISCVDisassembler.cpp (+29) 
- (modified) llvm/lib/Target/RISCV/RISCVFeatures.td (+7) 
- (modified) llvm/lib/Target/RISCV/RISCVFrameLowering.cpp (+12-2) 
- (modified) llvm/lib/Target/RISCV/RISCVInstrInfo.td (+5-4) 
- (added) llvm/lib/Target/RISCV/RISCVInstrInfoZicfiss.td (+86) 
- (modified) llvm/lib/Target/RISCV/RISCVRegisterInfo.cpp (+3) 
- (modified) llvm/lib/Target/RISCV/RISCVRegisterInfo.td (+9) 
- (modified) llvm/test/CodeGen/RISCV/shadowcallstack.ll (+130) 
- (modified) llvm/test/MC/RISCV/attribute-arch.s (+3) 
- (added) llvm/test/MC/RISCV/rv32zicfiss-invalid.s (+20) 
- (added) llvm/test/MC/RISCV/rv32zicfiss-valid.s (+103) 
- (added) llvm/test/MC/RISCV/rv64zicfiss-invalid.s (+20) 
- (added) llvm/test/MC/RISCV/rv64zicfiss-valid.s (+103) 


``diff
diff --git a/clang/test/Preprocessor/riscv-target-features.c 
b/clang/test/Preprocessor/riscv-target-features.c
index 02b67dc7944ba88..163eba81543ee5b 100644
--- a/clang/test/Preprocessor/riscv-target-features.c
+++ b/clang/test/Preprocessor/riscv-target-features.c
@@ -113,6 +113,7 @@
 // CHECK-NOT: __riscv_zfa {{.*$}}
 // CHECK-NOT: __riscv_zfbfmin {{.*$}}
 // CHECK-NOT: __riscv_zicfilp {{.*$}}
+// CHECK-NOT: __riscv_zicfiss {{.*$}}
 // CHECK-NOT: __riscv_zicond {{.*$}}
 // CHECK-NOT: __riscv_ztso {{.*$}}
 // CHECK-NOT: __riscv_zvbb {{.*$}}
@@ -1220,3 +1221,11 @@
 // RUN: -march=rv64i_zve32x_zvkt1p0 -x c -E -dM %s \
 // RUN: -o - | FileCheck --check-prefix=CHECK-ZVKT-EXT %s
 // CHECK-ZVKT-EXT: __riscv_zvkt 100{{$}}
+
+// RUN: %clang -target riscv32 -menable-experimental-extensions \
+// RUN: -march=rv32izicfiss0p3 -x c -E -dM %s \
+// RUN: -o - | FileCheck --check-prefix=CHECK-ZICFISS-EXT %s
+// RUN: %clang -target riscv64 -menable-experimental-extensions \
+// RUN: -march=rv64izicfiss0p3 -x c -E -dM %s \
+// RUN: -o - | FileCheck --check-prefix=CHECK-ZICFISS-EXT %s
+// CHECK-ZICFISS-EXT: __riscv_zicfiss 3000{{$}}
diff --git a/llvm/docs/RISCVUsage.rst b/llvm/docs/RISCVUsage.rst
index 8d12d58738c609a..31c55def0a7694a 100644
--- a/llvm/docs/RISCVUsage.rst
+++ b/llvm/docs/RISCVUsage.rst
@@ -205,6 +205,9 @@ The primary goal of experimental support is to assist in 
the process of ratifica
 ``experimental-zicfilp``
   LLVM implements the `0.2 draft specification 
`__.
 
+``experimental-zicfiss``
+  LLVM implements the `0.3.1 draft specification 
`__.
+
 ``experimental-zicond``
   LLVM implements the `1.0-rc1 draft specification 
`__.
 
diff --git a/llvm/lib/Support/RISCVISAInfo.cpp 
b/llvm/lib/Support/RISCVISAInfo.cpp
index a02c9842e85839a..c414b62c5f31092 100644
--- a/llvm/lib/Support/RISCVISAInfo.cpp
+++ b/llvm/lib/Support/RISCVISAInfo.cpp
@@ -170,6 +170,8 @@ static const RISCVSupportedExtension 
SupportedExperimentalExtensions[] = {
 {"zfbfmin", RISCVExtensionVersion{0, 8}},
 
 {"zicfilp", RISCVExtensionVersion{0, 2}},
+{"zicfiss", RISCVExtensionVersion{0, 3}},
+
 {"zicond", RISCVExtensionVersion{1, 0}},
 
 {"ztso", RISCVExtensionVersion{0, 1}},
diff --git a/llvm/lib/Target/RISCV/Disassembler/RISCVDisassembler.cpp 
b/llvm/lib/Target/RISCV/Disassembler/RISCVDisassembler.cpp
index d561d90d3088c1a..9f088b6f3bf6492 100644
--- a/llvm/lib/Target/RISCV/Disassembler/RISCVDisassembler.cpp
+++ b/llvm/lib/Target/RISCV/Disassembler/RISCVDisassembler.cpp
@@ -74,6 +74,17 @@ static DecodeStatus DecodeGPRRegisterClass(MCInst &Inst, 
uint32_t RegNo,
   return MCDisassembler::Success;
 }
 
+static DecodeStatus DecodeGPRX1X5RegisterClass(MCInst &Inst, uint32_t RegNo,
+   uint64_t Address,
+   const MCDisassembler *Decoder) {
+  MCRegister Reg = RISCV::X0 + RegNo;
+  if (Reg != RISCV::X1 && Reg != RISCV::X5)
+return MCDisassembler::Fail;
+
+  Inst.addOperand(MCOperand::createReg(Reg));
+  return MCDisassembler::Success;
+}
+
 static DecodeStatus DecodeFPR16RegisterClass(MCInst &Inst, uint32_t RegNo,
  uint64_t Address,
 

[PATCH] D126691: ASTContext: Provide a query for module initializer contents.

2023-10-03 Thread Iain Sandoe via Phabricator via cfe-commits
iains abandoned this revision.
iains added a comment.

although this was approved, we did not need to use it to implement the 
dependent changes.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126691

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


[clang] [Clang] Do not try to classify dependant call expression (PR #68078)

2023-10-03 Thread via cfe-commits

https://github.com/cor3ntin created 
https://github.com/llvm/llvm-project/pull/68078

when the callee is an object.

When implementing deducing this, we changed
`DeduceTemplateArgumentsFromCallArgument` to take an argument classification 
because we need to deduce the type of argument for which we might not have an 
expression yet.

However classifying a dependent call expression whose type is just some sort of 
record or elaborated type is not supported.

We avoid that by adding a `DeduceTemplateArgumentsFromCallArgument` that takes 
a `IsLvalue` boolean so that we don't have to call `Classify`.

The alternative might be to change `getCallReturnType` to support callees with 
type is a record type.

Fixes #68024

>From eb6c0c5c1778adfdba11d5d2e6196613d60c9e02 Mon Sep 17 00:00:00 2001
From: Corentin Jabot 
Date: Tue, 3 Oct 2023 09:55:08 +0200
Subject: [PATCH] [Clang] Do not try to classify dependant call expression when
 the callee is an object.

When implementing deducing this, we changed
`DeduceTemplateArgumentsFromCallArgument` to take an argument
classification because we need to deduce the type of
argument for which we might not have an expression yet.

However classifying a dependent call expression whose
type is just some sort of record or elaborated type is not
supported.

We avoid that by adding a `DeduceTemplateArgumentsFromCallArgument`
that takes a `IsLvalue` boolean so that we don't have to call `Classify`.

The alternative might be to change `getCallReturnType` to support
callees with type is a record type.

Fixes #68024
---
 clang/lib/Sema/SemaTemplateDeduction.cpp | 58 
 1 file changed, 39 insertions(+), 19 deletions(-)

diff --git a/clang/lib/Sema/SemaTemplateDeduction.cpp 
b/clang/lib/Sema/SemaTemplateDeduction.cpp
index 69b857d3510dc63..53975068751e128 100644
--- a/clang/lib/Sema/SemaTemplateDeduction.cpp
+++ b/clang/lib/Sema/SemaTemplateDeduction.cpp
@@ -3877,9 +3877,8 @@ ResolveOverloadForDeduction(Sema &S, 
TemplateParameterList *TemplateParams,
 /// overloaded function set that could not be resolved.
 static bool AdjustFunctionParmAndArgTypesForDeduction(
 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
-QualType &ParamType, QualType &ArgType,
-Expr::Classification ArgClassification, Expr *Arg, unsigned &TDF,
-TemplateSpecCandidateSet *FailedTSC = nullptr) {
+QualType &ParamType, QualType &ArgType, bool IsLValue, Expr *Arg,
+unsigned &TDF, TemplateSpecCandidateSet *FailedTSC = nullptr) {
   // C++0x [temp.deduct.call]p3:
   //   If P is a cv-qualified type, the top level cv-qualifiers of P's type
   //   are ignored for type deduction.
@@ -3914,7 +3913,7 @@ static bool AdjustFunctionParmAndArgTypesForDeduction(
 //   If P is a forwarding reference and the argument is an lvalue, the type
 //   "lvalue reference to A" is used in place of A for type deduction.
 if (isForwardingReference(QualType(ParamRefType, 0), FirstInnerIndex) &&
-ArgClassification.isLValue()) {
+IsLValue) {
   if (S.getLangOpts().OpenCL && !ArgType.hasAddressSpace())
 ArgType = S.Context.getAddrSpaceQualType(
 ArgType, S.Context.getDefaultOpenCLPointeeAddrSpace());
@@ -3973,6 +3972,15 @@ static bool
 hasDeducibleTemplateParameters(Sema &S, FunctionTemplateDecl *FunctionTemplate,
QualType T);
 
+static Sema::TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument(
+Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
+QualType ParamType, QualType ArgType, bool IsLValue, Expr *Arg,
+TemplateDeductionInfo &Info,
+SmallVectorImpl &Deduced,
+SmallVectorImpl &OriginalCallArgs,
+bool DecomposedParam, unsigned ArgIdx, unsigned TDF,
+TemplateSpecCandidateSet *FailedTSC = nullptr);
+
 static Sema::TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument(
 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
 QualType ParamType, QualType ArgType,
@@ -4022,9 +4030,8 @@ static Sema::TemplateDeductionResult 
DeduceFromInitializerList(
   if (ElTy->isDependentType()) {
 for (Expr *E : ILE->inits()) {
   if (auto Result = DeduceTemplateArgumentsFromCallArgument(
-  S, TemplateParams, 0, ElTy, E->getType(),
-  E->Classify(S.getASTContext()), E, Info, Deduced,
-  OriginalCallArgs, true, ArgIdx, TDF))
+  S, TemplateParams, 0, ElTy, E->getType(), E->isLValue(), E, Info,
+  Deduced, OriginalCallArgs, true, ArgIdx, TDF))
 return Result;
 }
   }
@@ -4055,8 +4062,7 @@ static Sema::TemplateDeductionResult 
DeduceFromInitializerList(
 ///single parameter / argument pair.
 static Sema::TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument(
 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
-QualType ParamType, QualType ArgType,
-Expr::Classification ArgClassificati

[clang] [Clang] Do not try to classify dependant call expression (PR #68078)

2023-10-03 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang


Changes

when the callee is an object.

When implementing deducing this, we changed
`DeduceTemplateArgumentsFromCallArgument` to take an argument classification 
because we need to deduce the type of argument for which we might not have an 
expression yet.

However classifying a dependent call expression whose type is just some sort of 
record or elaborated type is not supported.

We avoid that by adding a `DeduceTemplateArgumentsFromCallArgument` that takes 
a `IsLvalue` boolean so that we don't have to call `Classify`.

The alternative might be to change `getCallReturnType` to support callees with 
type is a record type.

Fixes #68024

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


1 Files Affected:

- (modified) clang/lib/Sema/SemaTemplateDeduction.cpp (+39-19) 


``diff
diff --git a/clang/lib/Sema/SemaTemplateDeduction.cpp 
b/clang/lib/Sema/SemaTemplateDeduction.cpp
index 69b857d3510dc63..53975068751e128 100644
--- a/clang/lib/Sema/SemaTemplateDeduction.cpp
+++ b/clang/lib/Sema/SemaTemplateDeduction.cpp
@@ -3877,9 +3877,8 @@ ResolveOverloadForDeduction(Sema &S, 
TemplateParameterList *TemplateParams,
 /// overloaded function set that could not be resolved.
 static bool AdjustFunctionParmAndArgTypesForDeduction(
 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
-QualType &ParamType, QualType &ArgType,
-Expr::Classification ArgClassification, Expr *Arg, unsigned &TDF,
-TemplateSpecCandidateSet *FailedTSC = nullptr) {
+QualType &ParamType, QualType &ArgType, bool IsLValue, Expr *Arg,
+unsigned &TDF, TemplateSpecCandidateSet *FailedTSC = nullptr) {
   // C++0x [temp.deduct.call]p3:
   //   If P is a cv-qualified type, the top level cv-qualifiers of P's type
   //   are ignored for type deduction.
@@ -3914,7 +3913,7 @@ static bool AdjustFunctionParmAndArgTypesForDeduction(
 //   If P is a forwarding reference and the argument is an lvalue, the type
 //   "lvalue reference to A" is used in place of A for type deduction.
 if (isForwardingReference(QualType(ParamRefType, 0), FirstInnerIndex) &&
-ArgClassification.isLValue()) {
+IsLValue) {
   if (S.getLangOpts().OpenCL && !ArgType.hasAddressSpace())
 ArgType = S.Context.getAddrSpaceQualType(
 ArgType, S.Context.getDefaultOpenCLPointeeAddrSpace());
@@ -3973,6 +3972,15 @@ static bool
 hasDeducibleTemplateParameters(Sema &S, FunctionTemplateDecl *FunctionTemplate,
QualType T);
 
+static Sema::TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument(
+Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
+QualType ParamType, QualType ArgType, bool IsLValue, Expr *Arg,
+TemplateDeductionInfo &Info,
+SmallVectorImpl &Deduced,
+SmallVectorImpl &OriginalCallArgs,
+bool DecomposedParam, unsigned ArgIdx, unsigned TDF,
+TemplateSpecCandidateSet *FailedTSC = nullptr);
+
 static Sema::TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument(
 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
 QualType ParamType, QualType ArgType,
@@ -4022,9 +4030,8 @@ static Sema::TemplateDeductionResult 
DeduceFromInitializerList(
   if (ElTy->isDependentType()) {
 for (Expr *E : ILE->inits()) {
   if (auto Result = DeduceTemplateArgumentsFromCallArgument(
-  S, TemplateParams, 0, ElTy, E->getType(),
-  E->Classify(S.getASTContext()), E, Info, Deduced,
-  OriginalCallArgs, true, ArgIdx, TDF))
+  S, TemplateParams, 0, ElTy, E->getType(), E->isLValue(), E, Info,
+  Deduced, OriginalCallArgs, true, ArgIdx, TDF))
 return Result;
 }
   }
@@ -4055,8 +4062,7 @@ static Sema::TemplateDeductionResult 
DeduceFromInitializerList(
 ///single parameter / argument pair.
 static Sema::TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument(
 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
-QualType ParamType, QualType ArgType,
-Expr::Classification ArgClassification, Expr *Arg,
+QualType ParamType, QualType ArgType, bool IsLValue, Expr *Arg,
 TemplateDeductionInfo &Info,
 SmallVectorImpl &Deduced,
 SmallVectorImpl &OriginalCallArgs,
@@ -4068,8 +4074,8 @@ static Sema::TemplateDeductionResult 
DeduceTemplateArgumentsFromCallArgument(
   //   If P is a reference type [...]
   //   If P is a cv-qualified type [...]
   if (AdjustFunctionParmAndArgTypesForDeduction(
-  S, TemplateParams, FirstInnerIndex, ParamType, ArgType,
-  ArgClassification, Arg, TDF, FailedTSC))
+  S, TemplateParams, FirstInnerIndex, ParamType, ArgType, IsLValue, 
Arg,
+  TDF, FailedTSC))
 return Sema::TDK_Success;
 
   //   If [...] the argument is a non-empty initializer list [...]
@@ -4089,6 +4095,22 @@ static Sema::TemplateDeductionResult 
DeduceTempl

[clang] [clang][ASTImporter] Fix crash when import `VarTemplateDecl` in record (PR #67522)

2023-10-03 Thread Qizhi Hu via cfe-commits

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

>From 9dc31bfb012c32da7a1bf511db04df9c6c480a78 Mon Sep 17 00:00:00 2001
From: huqizhi 
Date: Wed, 27 Sep 2023 15:32:10 +0800
Subject: [PATCH] [clang][ASTImporter] fix clash when import `VarTemplateDecl`
 in record

---
 clang/lib/AST/ASTImporter.cpp   |  3 +++
 clang/unittests/AST/ASTImporterTest.cpp | 33 +
 2 files changed, 36 insertions(+)

diff --git a/clang/lib/AST/ASTImporter.cpp b/clang/lib/AST/ASTImporter.cpp
index c7c2aecc8b179a4..a8ce1c469b6329c 100644
--- a/clang/lib/AST/ASTImporter.cpp
+++ b/clang/lib/AST/ASTImporter.cpp
@@ -6240,6 +6240,9 @@ ExpectedDecl 
ASTNodeImporter::VisitVarTemplateDecl(VarTemplateDecl *D) {
   // FIXME Check for ODR error if the two definitions have
   // different initializers?
   return Importer.MapImported(D, FoundDef);
+if (FoundTemplate->getDeclContext()->isRecord() &&
+D->getDeclContext()->isRecord())
+  return Importer.MapImported(D, FoundTemplate);
 
 FoundByLookup = FoundTemplate;
 break;
diff --git a/clang/unittests/AST/ASTImporterTest.cpp 
b/clang/unittests/AST/ASTImporterTest.cpp
index c90b5aaeb624306..8cbd5436c7093ae 100644
--- a/clang/unittests/AST/ASTImporterTest.cpp
+++ b/clang/unittests/AST/ASTImporterTest.cpp
@@ -4988,6 +4988,39 @@ TEST_P(ASTImporterOptionSpecificTestBase,
   }
 }
 
+TEST_P(ImportFriendClasses, RecordVarTemplateDecl) {
+  Decl *ToTU = getToTuDecl(
+  R"(
+  template 
+  class A {
+  public:
+template 
+static constexpr bool X = true;
+  };
+  )",
+  Lang_CXX14);
+
+  auto *Fwd = FirstDeclMatcher().match(
+  ToTU, varTemplateDecl(hasName("X")));
+  Decl *FromTU = getTuDecl(
+  R"(
+  template 
+  class A {
+  public:
+template 
+static constexpr bool X = true;
+  };
+  )",
+  Lang_CXX14, "input1.cc");
+  auto *FromA = FirstDeclMatcher().match(
+  FromTU, varTemplateDecl(hasName("X")));
+  auto *ToA = Import(FromA, Lang_CXX11);
+  EXPECT_TRUE(ToA);
+  EXPECT_EQ(Fwd->getTemplatedDecl(), ToA->getTemplatedDecl());
+  EXPECT_EQ(Fwd->getTemplatedDecl()->getDefinition(),
+ToA->getTemplatedDecl()->getDefinition());
+}
+
 TEST_P(ASTImporterOptionSpecificTestBase, VarTemplateParameterDeclContext) {
   constexpr auto Code =
   R"(

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


[libunwind] [mlir][OpenMP] Added translation for `omp.teams` to LLVM IR (PR #68042)

2023-10-03 Thread Kiran Chandramohan via cfe-commits


@@ -0,0 +1,136 @@
+// RUN: mlir-translate -mlir-to-llvmir -split-input-file %s | FileCheck %s
+
+llvm.func @foo()
+
+// CHECK-LABEL: @omp_teams_simple
+// CHECK: call void {{.*}} @__kmpc_fork_teams(ptr @{{.+}}, i32 0, ptr 
[[wrapperfn:.+]])

kiranchandramohan wrote:

Could you convert the captured variables (eg. wrapperfn) to caps? This is to 
distinguish them easily from code.

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


[clang] [mlir][OpenMP] Added translation for `omp.teams` to LLVM IR (PR #68042)

2023-10-03 Thread Kiran Chandramohan via cfe-commits

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

LGTM.

Will the wrapper function stay or be removed?

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


[libunwind] [mlir][OpenMP] Added translation for `omp.teams` to LLVM IR (PR #68042)

2023-10-03 Thread Kiran Chandramohan via cfe-commits

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

LGTM.

Will the wrapper function stay or be removed?

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


[clang] [mlir][OpenMP] Added translation for `omp.teams` to LLVM IR (PR #68042)

2023-10-03 Thread Kiran Chandramohan via cfe-commits


@@ -0,0 +1,136 @@
+// RUN: mlir-translate -mlir-to-llvmir -split-input-file %s | FileCheck %s
+
+llvm.func @foo()
+
+// CHECK-LABEL: @omp_teams_simple
+// CHECK: call void {{.*}} @__kmpc_fork_teams(ptr @{{.+}}, i32 0, ptr 
[[wrapperfn:.+]])

kiranchandramohan wrote:

Could you convert the captured variables (eg. wrapperfn) to caps? This is to 
distinguish them easily from code.

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


[clang] [clang] remove ClassScopeFunctionSpecializationDecl (PR #66636)

2023-10-03 Thread Krystian Stasiowski via cfe-commits

https://github.com/sdkrystian updated 
https://github.com/llvm/llvm-project/pull/66636

>From d11d546f3190936ba45c57b4825073026d817878 Mon Sep 17 00:00:00 2001
From: Krystian Stasiowski 
Date: Fri, 25 Aug 2023 14:07:32 -0400
Subject: [PATCH 1/5] [clang] remove ClassScopeFunctionSpecializationDecl

---
 .../clang-tidy/modernize/UseEmplaceCheck.cpp  |   2 +-
 .../clangd/SemanticHighlighting.cpp   |   9 --
 clang/include/clang/AST/ASTNodeTraverser.h|   7 +-
 clang/include/clang/AST/Decl.h|  10 +-
 clang/include/clang/AST/DeclTemplate.h| 150 +++---
 clang/include/clang/AST/RecursiveASTVisitor.h |  19 ++-
 clang/include/clang/Basic/DeclNodes.td|   1 -
 .../clang/Basic/DiagnosticSemaKinds.td|   8 +-
 clang/include/clang/Sema/Sema.h   |   6 +-
 clang/include/clang/Sema/Template.h   |   2 -
 .../include/clang/Serialization/ASTBitCodes.h |   4 -
 .../clang/Serialization/ASTRecordReader.h |   2 +
 clang/lib/AST/ASTImporter.cpp |  26 ++-
 clang/lib/AST/Decl.cpp|  71 ++---
 clang/lib/AST/DeclBase.cpp|   2 -
 clang/lib/AST/DeclTemplate.cpp|  13 --
 clang/lib/AST/ODRHash.cpp |   4 +
 clang/lib/CodeGen/CGDecl.cpp  |   1 -
 clang/lib/Index/IndexSymbol.cpp   |   1 -
 clang/lib/Sema/SemaDecl.cpp   | 112 ++---
 clang/lib/Sema/SemaTemplate.cpp   |  14 +-
 .../lib/Sema/SemaTemplateInstantiateDecl.cpp  | 121 +++---
 clang/lib/Serialization/ASTCommon.cpp |   1 -
 clang/lib/Serialization/ASTReader.cpp |  19 ++-
 clang/lib/Serialization/ASTReaderDecl.cpp |  59 ++-
 clang/lib/Serialization/ASTWriter.cpp |   1 -
 clang/lib/Serialization/ASTWriterDecl.cpp |  42 ++---
 .../Checkers/SmartPtrModeling.cpp |   2 +-
 clang/test/AST/ast-dump-decl.cpp  |   9 +-
 clang/test/CXX/drs/dr7xx.cpp  |   5 +
 .../test/SemaTemplate/instantiate-method.cpp  |   7 +-
 clang/tools/libclang/CIndex.cpp   |   1 -
 32 files changed, 290 insertions(+), 441 deletions(-)

diff --git a/clang-tools-extra/clang-tidy/modernize/UseEmplaceCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseEmplaceCheck.cpp
index 554abcd900e329c..06ae1f4e257528f 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseEmplaceCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/UseEmplaceCheck.cpp
@@ -67,7 +67,7 @@ AST_MATCHER_P(CallExpr, hasLastArgument,
 // function had parameters defined (this is useful to check if there is only 
one
 // variadic argument).
 AST_MATCHER(CXXMemberCallExpr, hasSameNumArgsAsDeclNumParams) {
-  if (Node.getMethodDecl()->isFunctionTemplateSpecialization())
+  if (Node.getMethodDecl()->getPrimaryTemplate())
 return Node.getNumArgs() == Node.getMethodDecl()
 ->getPrimaryTemplate()
 ->getTemplatedDecl()
diff --git a/clang-tools-extra/clangd/SemanticHighlighting.cpp 
b/clang-tools-extra/clangd/SemanticHighlighting.cpp
index 45c01634e2e38d1..7649e37e1f96663 100644
--- a/clang-tools-extra/clangd/SemanticHighlighting.cpp
+++ b/clang-tools-extra/clangd/SemanticHighlighting.cpp
@@ -715,13 +715,6 @@ class CollectExtraHighlightings
 return true;
   }
 
-  bool VisitClassScopeFunctionSpecializationDecl(
-  ClassScopeFunctionSpecializationDecl *D) {
-if (auto *Args = D->getTemplateArgsAsWritten())
-  H.addAngleBracketTokens(Args->getLAngleLoc(), Args->getRAngleLoc());
-return true;
-  }
-
   bool VisitDeclRefExpr(DeclRefExpr *E) {
 H.addAngleBracketTokens(E->getLAngleLoc(), E->getRAngleLoc());
 return true;
@@ -752,8 +745,6 @@ class CollectExtraHighlightings
 }
 if (auto *Args = D->getTemplateSpecializationArgsAsWritten())
   H.addAngleBracketTokens(Args->getLAngleLoc(), Args->getRAngleLoc());
-if (auto *I = D->getDependentSpecializationInfo())
-  H.addAngleBracketTokens(I->getLAngleLoc(), I->getRAngleLoc());
 return true;
   }
 
diff --git a/clang/include/clang/AST/ASTNodeTraverser.h 
b/clang/include/clang/AST/ASTNodeTraverser.h
index 1151a756ff377b6..c3d233d3ab4a259 100644
--- a/clang/include/clang/AST/ASTNodeTraverser.h
+++ b/clang/include/clang/AST/ASTNodeTraverser.h
@@ -428,6 +428,8 @@ class ASTNodeTraverser
   void VisitFunctionDecl(const FunctionDecl *D) {
 if (const auto *FTSI = D->getTemplateSpecializationInfo())
   dumpTemplateArgumentList(*FTSI->TemplateArguments);
+else if (const auto *DFTSI = D->getDependentSpecializationInfo())
+  dumpASTTemplateArgumentListInfo(DFTSI->TemplateArgumentsAsWritten);
 
 if (D->param_begin())
   for (const auto *Parameter : D->parameters())
@@ -578,11 +580,6 @@ class ASTNodeTraverser
 dumpTemplateParameters(D->getTemplateParameters());
   }
 
-  void VisitClassScopeFunctionSpecializationDecl(
-  const ClassScopeFunctionSpe

[clang] Add Documentation for Execution Results Handling in Clang-Repl (PR #65650)

2023-10-03 Thread Pavel Kalugin via cfe-commits


@@ -213,6 +213,411 @@ concept helps support advanced use cases such as template 
instantiations on dema
 automatic language interoperability. It also helps static languages such as 
C/C++ become
 apt for data science.
 
+Execution Results Handling in Clang-Repl
+
+
+Execution Results Handling features discussed below help extend the Clang-Repl
+functionality by creating an interface between the execution results of a
+program and the compiled program.
+
+1. **Capture Execution Results**: This feature helps capture the execution 
results
+of a program and bring them back to the compiled program.
+
+2. **Dump Captured Execution Results**: This feature helps create a temporary 
dump
+for Value Printing/Automatic Printf, that is, to display the value and type of
+the captured data.
+
+
+1. Capture Execution Results
+
+
+In many cases, it is useful to bring back the program execution result to the
+compiled program. This result can be stored in an object of type **Value**.
+
+How Execution Results are captured (Value Synthesis):
+-
+
+The synthesizer chooses which expression to synthesize, and then it replaces
+the original expression with the synthesized expression. Depending on the
+expression type, it may choose to save an object (``LastValue``) of type 
'value'
+while allocating memory to it (``SetValueWithAlloc()``), or not (
+``SetValueNoAlloc()``).
+
+.. graphviz::
+:name: valuesynthesis
+:caption: Value Synthesis
+:alt: Shows how an object of type 'Value' is synthesized
+:align: center
+
+ digraph "valuesynthesis" {
+ rankdir="LR";
+ graph [fontname="Verdana", fontsize="12"];
+ node [fontname="Verdana", fontsize="12"];
+ edge [fontname="Sans", fontsize="9"];
+
+ start [label=" Create an Object \n 'Last Value' \n of type 'Value' ", 
shape="note", fontcolor=white, fillcolor="#ff", style=filled];
+ assign [label=" Assign the result \n to the 'LastValue' \n (based on 
respective \n Memory Allocation \n scenario) ", shape="box"]
+ print [label=" Pretty Print \n the Value Object ", shape="Msquare", 
fillcolor="yellow", style=filled];
+ start -> assign;
+ assign -> print;
+
+   subgraph SynthesizeExpression {
+ synth [label=" SynthesizeExpr() ", shape="note", fontcolor=white, 
fillcolor="#ff", style=filled];
+ mem [label=" New Memory \n Allocation? ", shape="diamond"];
+ withaloc [label=" SetValueWithAlloc() ", shape="box"];
+ noaloc [label=" SetValueNoAlloc() ", shape="box"];
+ right [label=" 1. RValue Structure \n (a temporary value)", 
shape="box"];
+ left2 [label=" 2. LValue Structure \n (a variable with \n an 
address)", shape="box"];
+ left3 [label=" 3. Built-In Type \n (int, float, etc.)", 
shape="box"];
+ output [label=" move to 'Assign' step ", shape="box"];
+
+ synth -> mem;
+ mem -> withaloc [label="Yes"];
+ mem -> noaloc [label="No"];
+ withaloc -> right;
+ noaloc -> left2;
+ noaloc -> left3;
+ right -> output;
+ left2 -> output;
+ left3 -> output;
+  }
+output -> assign
+  }
+
+Where is the captured result stored?
+
+
+``LastValue`` holds the last result of the value printing. It is a class member
+because it can be accessed even after subsequent inputs.
+
+**Note:** If no value printing happens, then it is in an invalid state.
+
+Improving Efficiency and User Experience
+
+
+The Value object is essentially used to create a mapping between an expression
+'type' and the allocated 'memory'. Built-in types (bool, char, int,
+float, double, etc.) are copyable. Their their memory allocation size is known

pavel-the-best wrote:

their their?

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


[PATCH] D148381: [Clang] Implement the 'counted_by' attribute

2023-10-03 Thread Bill Wendling via Phabricator via cfe-commits
void added inline comments.



Comment at: clang/lib/Sema/SemaDeclAttr.cpp:8420-8428
+if (Result.getResultKind() == LookupResult::Found) {
+  SourceRange SR = CBA->getCountedByFieldLoc();
+  Diag(SR.getBegin(),
+   diag::err_flexible_array_counted_by_attr_field_not_found_in_struct)
+  << CBA->getCountedByField() << SR;
+
+  SR = Result.getAsSingle()->getSourceRange();

aaron.ballman wrote:
> The logic here still seems incorrect. I was expecting the code to look more 
> like this:
> ```
> bool Sema::CheckCountedByAttr(Scope *S, const FieldDecl *FD) {
>   const RecordDecl *RD = FD->getParent();
>   const auto *CBA = FD->getAttr();
>   const IdentifierInfo *FieldName = CBA->getCountedByField();
>   DeclarationNameInfo NameInfo(FieldName,
>CBA->getCountedByFieldLoc().getBegin());
>   LookupResult Result(*this, NameInfo, Sema::LookupMemberName);
> 
>   LookupName(Result, S);
>   if (Result.empty()) {
> CXXScopeSpec SS;
> DeclFilterCCC Filter(const_cast(FieldName));
> if (DiagnoseEmptyLookup(S, SS, Result, Filter, nullptr, std::nullopt,
> const_cast(FD->getDeclContext(
>   return true;
>   }
> 
>   const FieldDecl *Field = Result.getAsSingle();
>   LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel =
>   Context.getLangOpts().getStrictFlexArraysLevel();
>   ...
> ```
> I tested this locally on code like:
> ```
> struct not_a_fam {
>   int foo;
>   int fam[] __attribute__((counted_by(fob)));
> };
> ```
> and get a diagnostic like: 
> ```
> C:\Users\aballman\OneDrive - Intel Corporation\Desktop\test.c:3:39: error: 
> use of undeclared identifier 'fob'; did you
>   mean 'foo'?
> 3 |   int fam[] __attribute__((counted_by(fob)));
>   |   ^~~
>   |   foo
> C:\Users\aballman\OneDrive - Intel Corporation\Desktop\test.c:2:7: note: 
> 'foo' declared here
> 2 |   int foo;
>   |   ^
> 1 error generated.
> ```
> Note, I had to add a constructor to `DeclFilterCCC` to expose the base class 
> constructor, and modify `DiagnoseEmptyLookup()` like this:
> ```
> diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
> index 2ed31a90c5dc..3c4ade391a5e 100644
> --- a/clang/lib/Sema/SemaExpr.cpp
> +++ b/clang/lib/Sema/SemaExpr.cpp
> @@ -2458,7 +2458,8 @@ bool Sema::DiagnoseDependentMemberLookup(const 
> LookupResult &R) {
>  bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
> CorrectionCandidateCallback &CCC,
> TemplateArgumentListInfo 
> *ExplicitTemplateArgs,
> -   ArrayRef Args, TypoExpr **Out) {
> +   ArrayRef Args, DeclContext *LookupCtx,
> +   TypoExpr **Out) {
>DeclarationName Name = R.getLookupName();
> 
>unsigned diagnostic = diag::err_undeclared_var_use;
> @@ -2474,7 +2475,9 @@ bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec 
> &SS, LookupResult &R,
>// unqualified lookup.  This is useful when (for example) the
>// original lookup would not have found something because it was a
>// dependent name.
> -  DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
> +  DeclContext *DC =
> +  LookupCtx ? LookupCtx : (SS.isEmpty() ? CurContext : nullptr);
> +  DeclContext *OrigLookupCtx = DC;
>while (DC) {
>  if (isa(DC)) {
>LookupQualifiedName(R, DC);
> @@ -2517,12 +2520,12 @@ bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec 
> &SS, LookupResult &R,
>emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
>  diagnostic, diagnostic_suggest);
>  },
> -nullptr, CTK_ErrorRecovery);
> +nullptr, CTK_ErrorRecovery, OrigLookupCtx);
>  if (*Out)
>return true;
> -  } else if (S &&
> - (Corrected = CorrectTypo(R.getLookupNameInfo(), 
> R.getLookupKind(),
> -  S, &SS, CCC, CTK_ErrorRecovery))) {
> +  } else if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(),
> +   R.getLookupKind(), S, &SS, CCC,
> +   CTK_ErrorRecovery, 
> OrigLookupCtx))) {
>  std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
>  bool DroppedSpecifier =
>  Corrected.WillReplaceSpecifier() && Name.getAsString() == 
> CorrectedStr;
> @@ -2812,7 +2815,7 @@ Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
>  // a template name, but we happen to have always already looked up the 
> name
>  // before we get here if it must be a template name.
>  if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
> -std::nullopt, &TE)) {
> +std::nullopt, nullptr, 

[clang] [clang][Interp] IntegralAP zero-init (PR #68081)

2023-10-03 Thread Timm Baeder via cfe-commits

https://github.com/tbaederr created 
https://github.com/llvm/llvm-project/pull/68081

Not adding any tests since I'm waiting for 
https://github.com/llvm/llvm-project/pull/68069/

>From dabd2ea3311929d446499e94fc2647e18183ea8d Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Tue, 3 Oct 2023 11:05:27 +0200
Subject: [PATCH] [clang][Interp] IntegralAP zero-init

---
 clang/lib/AST/Interp/ByteCodeExprGen.cpp |  4 ++--
 clang/lib/AST/Interp/IntegralAP.h|  9 +
 clang/lib/AST/Interp/Interp.h| 10 ++
 clang/lib/AST/Interp/Opcodes.td  | 15 ++-
 4 files changed, 31 insertions(+), 7 deletions(-)

diff --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index e266804a4e75dea..9a2bbe5c1841208 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -1642,9 +1642,9 @@ bool 
ByteCodeExprGen::visitZeroInitializer(QualType QT,
   case PT_Uint64:
 return this->emitZeroUint64(E);
   case PT_IntAP:
+return this->emitZeroIntAP(128, E); // FIXME: Ctx.getBitWidth()
   case PT_IntAPS:
-assert(false);
-return false;
+return this->emitZeroIntAPS(128, E); // FIXME: Ctx.getBitWidth()
   case PT_Ptr:
 return this->emitNullPtr(E);
   case PT_FnPtr:
diff --git a/clang/lib/AST/Interp/IntegralAP.h 
b/clang/lib/AST/Interp/IntegralAP.h
index a8df431bef11784..bca39884ac1de88 100644
--- a/clang/lib/AST/Interp/IntegralAP.h
+++ b/clang/lib/AST/Interp/IntegralAP.h
@@ -100,12 +100,13 @@ template  class IntegralAP final {
   }
   static IntegralAP from(const Boolean &B) {
 assert(false);
-return IntegralAP::zero();
+return IntegralAP::zero(1);
   }
 
-  static IntegralAP zero() {
-assert(false);
-return IntegralAP(0);
+  static IntegralAP zero(int32_t BitWidth) {
+APSInt V =
+APSInt(APInt(BitWidth, static_cast(0), Signed), !Signed);
+return IntegralAP(V);
   }
 
   // FIXME: This can't be static if the bitwidth depends on V.
diff --git a/clang/lib/AST/Interp/Interp.h b/clang/lib/AST/Interp/Interp.h
index 9d5ec3315415cf7..f768deca62b8b0a 100644
--- a/clang/lib/AST/Interp/Interp.h
+++ b/clang/lib/AST/Interp/Interp.h
@@ -1622,6 +1622,16 @@ bool Zero(InterpState &S, CodePtr OpPC) {
   return true;
 }
 
+static inline bool ZeroIntAP(InterpState &S, CodePtr OpPC, uint32_t BitWidth) {
+  S.Stk.push>(IntegralAP::zero(BitWidth));
+  return true;
+}
+
+static inline bool ZeroIntAPS(InterpState &S, CodePtr OpPC, uint32_t BitWidth) 
{
+  S.Stk.push>(IntegralAP::zero(BitWidth));
+  return true;
+}
+
 template ::T>
 inline bool Null(InterpState &S, CodePtr OpPC) {
   S.Stk.push();
diff --git a/clang/lib/AST/Interp/Opcodes.td b/clang/lib/AST/Interp/Opcodes.td
index 9fc4938bb37bde8..d78431c56645629 100644
--- a/clang/lib/AST/Interp/Opcodes.td
+++ b/clang/lib/AST/Interp/Opcodes.td
@@ -72,6 +72,11 @@ def IntegerTypeClass : TypeClass {
Uint32, Sint64, Uint64, IntAP, IntAPS];
 }
 
+def FixedSizeIntegralTypeClass : TypeClass {
+  let Types = [Sint8, Uint8, Sint16, Uint16, Sint32,
+   Uint32, Sint64, Uint64, Bool];
+}
+
 def NumberTypeClass : TypeClass {
   let Types = !listconcat(IntegerTypeClass.Types, [Float]);
 }
@@ -243,10 +248,18 @@ def ConstBool : ConstOpcode;
 
 // [] -> [Integer]
 def Zero : Opcode {
-  let Types = [AluTypeClass];
+  let Types = [FixedSizeIntegralTypeClass];
   let HasGroup = 1;
 }
 
+def ZeroIntAP : Opcode {
+  let Args = [ArgUint32];
+}
+
+def ZeroIntAPS : Opcode {
+  let Args = [ArgUint32];
+}
+
 // [] -> [Pointer]
 def Null : Opcode {
   let Types = [PtrTypeClass];

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


[clang] [clang][Interp] IntegralAP zero-init (PR #68081)

2023-10-03 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang


Changes

Not adding any tests since I'm waiting for 
https://github.com/llvm/llvm-project/pull/68069/

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


4 Files Affected:

- (modified) clang/lib/AST/Interp/ByteCodeExprGen.cpp (+2-2) 
- (modified) clang/lib/AST/Interp/IntegralAP.h (+5-4) 
- (modified) clang/lib/AST/Interp/Interp.h (+10) 
- (modified) clang/lib/AST/Interp/Opcodes.td (+14-1) 


``diff
diff --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index e266804a4e75dea..9a2bbe5c1841208 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -1642,9 +1642,9 @@ bool 
ByteCodeExprGen::visitZeroInitializer(QualType QT,
   case PT_Uint64:
 return this->emitZeroUint64(E);
   case PT_IntAP:
+return this->emitZeroIntAP(128, E); // FIXME: Ctx.getBitWidth()
   case PT_IntAPS:
-assert(false);
-return false;
+return this->emitZeroIntAPS(128, E); // FIXME: Ctx.getBitWidth()
   case PT_Ptr:
 return this->emitNullPtr(E);
   case PT_FnPtr:
diff --git a/clang/lib/AST/Interp/IntegralAP.h 
b/clang/lib/AST/Interp/IntegralAP.h
index a8df431bef11784..bca39884ac1de88 100644
--- a/clang/lib/AST/Interp/IntegralAP.h
+++ b/clang/lib/AST/Interp/IntegralAP.h
@@ -100,12 +100,13 @@ template  class IntegralAP final {
   }
   static IntegralAP from(const Boolean &B) {
 assert(false);
-return IntegralAP::zero();
+return IntegralAP::zero(1);
   }
 
-  static IntegralAP zero() {
-assert(false);
-return IntegralAP(0);
+  static IntegralAP zero(int32_t BitWidth) {
+APSInt V =
+APSInt(APInt(BitWidth, static_cast(0), Signed), !Signed);
+return IntegralAP(V);
   }
 
   // FIXME: This can't be static if the bitwidth depends on V.
diff --git a/clang/lib/AST/Interp/Interp.h b/clang/lib/AST/Interp/Interp.h
index 9d5ec3315415cf7..f768deca62b8b0a 100644
--- a/clang/lib/AST/Interp/Interp.h
+++ b/clang/lib/AST/Interp/Interp.h
@@ -1622,6 +1622,16 @@ bool Zero(InterpState &S, CodePtr OpPC) {
   return true;
 }
 
+static inline bool ZeroIntAP(InterpState &S, CodePtr OpPC, uint32_t BitWidth) {
+  S.Stk.push>(IntegralAP::zero(BitWidth));
+  return true;
+}
+
+static inline bool ZeroIntAPS(InterpState &S, CodePtr OpPC, uint32_t BitWidth) 
{
+  S.Stk.push>(IntegralAP::zero(BitWidth));
+  return true;
+}
+
 template ::T>
 inline bool Null(InterpState &S, CodePtr OpPC) {
   S.Stk.push();
diff --git a/clang/lib/AST/Interp/Opcodes.td b/clang/lib/AST/Interp/Opcodes.td
index 9fc4938bb37bde8..d78431c56645629 100644
--- a/clang/lib/AST/Interp/Opcodes.td
+++ b/clang/lib/AST/Interp/Opcodes.td
@@ -72,6 +72,11 @@ def IntegerTypeClass : TypeClass {
Uint32, Sint64, Uint64, IntAP, IntAPS];
 }
 
+def FixedSizeIntegralTypeClass : TypeClass {
+  let Types = [Sint8, Uint8, Sint16, Uint16, Sint32,
+   Uint32, Sint64, Uint64, Bool];
+}
+
 def NumberTypeClass : TypeClass {
   let Types = !listconcat(IntegerTypeClass.Types, [Float]);
 }
@@ -243,10 +248,18 @@ def ConstBool : ConstOpcode;
 
 // [] -> [Integer]
 def Zero : Opcode {
-  let Types = [AluTypeClass];
+  let Types = [FixedSizeIntegralTypeClass];
   let HasGroup = 1;
 }
 
+def ZeroIntAP : Opcode {
+  let Args = [ArgUint32];
+}
+
+def ZeroIntAPS : Opcode {
+  let Args = [ArgUint32];
+}
+
 // [] -> [Pointer]
 def Null : Opcode {
   let Types = [PtrTypeClass];

``




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


[clang] [Clang] Do not try to classify dependant call expression (PR #68078)

2023-10-03 Thread via cfe-commits

https://github.com/cor3ntin updated 
https://github.com/llvm/llvm-project/pull/68078

>From a14d189cfd513d4b2c8353fbab1a53927d2feaf5 Mon Sep 17 00:00:00 2001
From: Corentin Jabot 
Date: Tue, 3 Oct 2023 09:55:08 +0200
Subject: [PATCH] [Clang] Do not try to classify dependant call expression when
 the callee is an object.

When implementing deducing this, we changed
`DeduceTemplateArgumentsFromCallArgument` to take an argument
classification because we need to deduce the type of
argument for which we might not have an expression yet.

However classifying a dependent call expression whose
type is just some sort of record or elaborated type is not
supported.

We avoid that by adding a `DeduceTemplateArgumentsFromCallArgument`
that takes a `IsLvalue` boolean so that we don't have to call `Classify`.

The alternative might be to change `getCallReturnType` to support
callees with type is a record type.

Fixes #68024
---
 clang/lib/Sema/SemaTemplateDeduction.cpp  | 58 +--
 .../SemaTemplate/temp_arg_nontype_cxx1z.cpp   | 12 
 2 files changed, 51 insertions(+), 19 deletions(-)

diff --git a/clang/lib/Sema/SemaTemplateDeduction.cpp 
b/clang/lib/Sema/SemaTemplateDeduction.cpp
index 69b857d3510dc63..53975068751e128 100644
--- a/clang/lib/Sema/SemaTemplateDeduction.cpp
+++ b/clang/lib/Sema/SemaTemplateDeduction.cpp
@@ -3877,9 +3877,8 @@ ResolveOverloadForDeduction(Sema &S, 
TemplateParameterList *TemplateParams,
 /// overloaded function set that could not be resolved.
 static bool AdjustFunctionParmAndArgTypesForDeduction(
 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
-QualType &ParamType, QualType &ArgType,
-Expr::Classification ArgClassification, Expr *Arg, unsigned &TDF,
-TemplateSpecCandidateSet *FailedTSC = nullptr) {
+QualType &ParamType, QualType &ArgType, bool IsLValue, Expr *Arg,
+unsigned &TDF, TemplateSpecCandidateSet *FailedTSC = nullptr) {
   // C++0x [temp.deduct.call]p3:
   //   If P is a cv-qualified type, the top level cv-qualifiers of P's type
   //   are ignored for type deduction.
@@ -3914,7 +3913,7 @@ static bool AdjustFunctionParmAndArgTypesForDeduction(
 //   If P is a forwarding reference and the argument is an lvalue, the type
 //   "lvalue reference to A" is used in place of A for type deduction.
 if (isForwardingReference(QualType(ParamRefType, 0), FirstInnerIndex) &&
-ArgClassification.isLValue()) {
+IsLValue) {
   if (S.getLangOpts().OpenCL && !ArgType.hasAddressSpace())
 ArgType = S.Context.getAddrSpaceQualType(
 ArgType, S.Context.getDefaultOpenCLPointeeAddrSpace());
@@ -3973,6 +3972,15 @@ static bool
 hasDeducibleTemplateParameters(Sema &S, FunctionTemplateDecl *FunctionTemplate,
QualType T);
 
+static Sema::TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument(
+Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
+QualType ParamType, QualType ArgType, bool IsLValue, Expr *Arg,
+TemplateDeductionInfo &Info,
+SmallVectorImpl &Deduced,
+SmallVectorImpl &OriginalCallArgs,
+bool DecomposedParam, unsigned ArgIdx, unsigned TDF,
+TemplateSpecCandidateSet *FailedTSC = nullptr);
+
 static Sema::TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument(
 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
 QualType ParamType, QualType ArgType,
@@ -4022,9 +4030,8 @@ static Sema::TemplateDeductionResult 
DeduceFromInitializerList(
   if (ElTy->isDependentType()) {
 for (Expr *E : ILE->inits()) {
   if (auto Result = DeduceTemplateArgumentsFromCallArgument(
-  S, TemplateParams, 0, ElTy, E->getType(),
-  E->Classify(S.getASTContext()), E, Info, Deduced,
-  OriginalCallArgs, true, ArgIdx, TDF))
+  S, TemplateParams, 0, ElTy, E->getType(), E->isLValue(), E, Info,
+  Deduced, OriginalCallArgs, true, ArgIdx, TDF))
 return Result;
 }
   }
@@ -4055,8 +4062,7 @@ static Sema::TemplateDeductionResult 
DeduceFromInitializerList(
 ///single parameter / argument pair.
 static Sema::TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument(
 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
-QualType ParamType, QualType ArgType,
-Expr::Classification ArgClassification, Expr *Arg,
+QualType ParamType, QualType ArgType, bool IsLValue, Expr *Arg,
 TemplateDeductionInfo &Info,
 SmallVectorImpl &Deduced,
 SmallVectorImpl &OriginalCallArgs,
@@ -4068,8 +4074,8 @@ static Sema::TemplateDeductionResult 
DeduceTemplateArgumentsFromCallArgument(
   //   If P is a reference type [...]
   //   If P is a cv-qualified type [...]
   if (AdjustFunctionParmAndArgTypesForDeduction(
-  S, TemplateParams, FirstInnerIndex, ParamType, ArgType,
-  ArgClassification, Arg, TDF, FailedTSC))
+  S, TemplateParams, FirstInne

[clang] Bugfix for chosing the correct deduction guide (PR #66487)

2023-10-03 Thread Botond István Hprváth via cfe-commits

HoBoIs wrote:

The paper where this came from is: https://wg21.link/P0620R0. most of this 
paper was already implemented.
Where is the paper tracking doc I need to update? 
https://clang.llvm.org/cxx_status.html claims this paper is implemented. 
Sorry if the following questions are trivial, I'm new to this.
In the release note should I put it under [Bug Fixes to C++ 
Support](https://github.com/llvm/llvm-project/blob/main/clang/docs/ReleaseNotes.rst#bug-fixes-to-c-support)
 or [Bug Fixes in This 
Version](https://github.com/llvm/llvm-project/blob/main/clang/docs/ReleaseNotes.rst#id88)?
 

Where should I reference the standard in the PR? In the Description?

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


[clang] [clang] Implement constexpr bit_cast for vectors (PR #66894)

2023-10-03 Thread via cfe-commits


@@ -7304,6 +7382,21 @@ class BufferToAPValueConverter {
 return ArrayValue;
   }
 
+  std::optional visit(const VectorType *Ty, CharUnits Offset) {
+SmallVector Bytes;
+if (!Buffer.readObject(Offset, Info.Ctx.getTypeSizeInChars(Ty), Bytes))
+  return std::nullopt;

DaMatrix wrote:

I've nearly got it working, except now we have another fun thing: pointing the 
`CK_BitCast` at my new implementation which tracks uninitialized padding bits 
prevents that test case in `const-init.c` from being constant-evaluated, so it 
proceeds to generate bitcode for it instead. Unfortunately, this doesn't work 
either because some bit casting code in LLVM itself seems to assume that a 
vector of `long double` is tightly packed, triggering this assertion:  
https://github.com/llvm/llvm-project/blob/8768741800aae37a825864e2ee782484ed073ce9/llvm/lib/IR/Instructions.cpp#L3299-L3302

This can actually be reproduced anywhere a vector is bit_casted to or from a 
vector of long double. 
[Example](https://godbolt.org/#g:!((g:!((g:!((h:codeEditor,i:(filename:'1',fontScale:14,fontUsePx:'0',j:1,lang:c%2B%2B,selection:(endColumn:1,endLineNumber:3,positionColumn:1,positionLineNumber:3,selectionStartColumn:1,selectionStartLineNumber:3,startColumn:1,startLineNumber:3),source:'using+fp80_vec+%3D+long+double+__attribute__((vector_size(32)))%3B%0Ausing+int16_vec+%3D+short+__attribute__((vector_size(32)))%3B%0A%0Afp80_vec+bit_cast_vec(int16_vec+vec)+%7B%0Areturn+(fp80_vec)vec%3B%0A%7D%0A'),l:'5',n:'0',o:'C%2B%2B+source+%231',t:'0')),k:37.545691906005224,l:'4',n:'0',o:'',s:0,t:'0'),(g:!((g:!((h:compiler,i:(compiler:clang170assert,deviceViewOpen:'1',filters:(b:'0',binary:'1',binaryObject:'1',commentOnly:'0',debugCalls:'1',demangle:'0',directives:'0',execute:'1',intel:'0',libraryCode:'0',trim:'1'),flagsViewOpen:'1',fontScale:14,fontUsePx:'0',j:1,lang:c%2B%2B,libs:!(),options:'-emit-llvm+-march%3Dskylake',overrides:!(),selection:(endColumn:1,endLineNumber:1,positionColumn:1,positionLineNumber:1,selectionStartColumn:1,selectionStartLineNumber:1,startColumn:1,startLineNumber:1),source:1),l:'5',n:'0',o:'+x86-64+clang+17.0.1+(assertions)+(Editor+%231)',t:'0')),k:50,l:'4',m:31.542857142857144,n:'0',o:'',s:0,t:'0'),(g:!((h:output,i:(compilerName:'x86-64+clang+17.0.1+(assertions)',editorid:1,fontScale:14,fontUsePx:'0',j:1,wrap:'1'),l:'5',n:'0',o:'Output+of+x86-64+clang+17.0.1+(assertions)+(Compiler+%231)',t:'0')),header:(),l:'4',m:68.45714285714286,n:'0',o:'',s:0,t:'0')),k:62.45430809399477,l:'3',n:'0',o:'',t:'0')),l:'2',n:'0',o:'',t:'0')),version:4)

This obviously needs to be fixed as well; should I do that here or make a 
separate PR for that?

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


[clang] [clang][ASTImporter] Fix crash when import `VarTemplateDecl` in record (PR #67522)

2023-10-03 Thread Balázs Kéri via cfe-commits


@@ -4988,6 +4988,39 @@ TEST_P(ASTImporterOptionSpecificTestBase,
   }
 }
 
+TEST_P(ImportFriendClasses, RecordVarTemplateDecl) {
+  Decl *ToTU = getToTuDecl(
+  R"(
+  template 
+  class A {
+  public:
+template 
+static constexpr bool X = true;
+  };
+  )",
+  Lang_CXX14);
+
+  auto *Fwd = FirstDeclMatcher().match(

balazske wrote:

Name `Fwd` seems not to match with the meaning.of the variable.

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


[clang] [clang][ASTImporter] Fix crash when import `VarTemplateDecl` in record (PR #67522)

2023-10-03 Thread Balázs Kéri via cfe-commits


@@ -4988,6 +4988,39 @@ TEST_P(ASTImporterOptionSpecificTestBase,
   }
 }
 
+TEST_P(ImportFriendClasses, RecordVarTemplateDecl) {
+  Decl *ToTU = getToTuDecl(
+  R"(
+  template 
+  class A {
+  public:
+template 
+static constexpr bool X = true;
+  };
+  )",
+  Lang_CXX14);
+
+  auto *Fwd = FirstDeclMatcher().match(
+  ToTU, varTemplateDecl(hasName("X")));
+  Decl *FromTU = getTuDecl(
+  R"(
+  template 
+  class A {
+  public:
+template 
+static constexpr bool X = true;
+  };
+  )",
+  Lang_CXX14, "input1.cc");
+  auto *FromA = FirstDeclMatcher().match(

balazske wrote:

`FromA` and `ToA` looks again not correct, these should be `FromX` and `ToX`.

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


[clang] [clang-repl] Emit const variables only once (PR #65257)

2023-10-03 Thread Vassil Vassilev via cfe-commits


@@ -0,0 +1,29 @@
+// UNSUPPORTED: system-aix
+// RUN: cat %s | clang-repl | FileCheck %s
+// RUN: cat %s | clang-repl -Xcc -O2 | FileCheck %s
+
+extern "C" int printf(const char*, ...);
+

vgvassilev wrote:

> const A a(1); is a file-scope constant, no?

Yes, missed that.

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


[clang] [clang-repl] Emit const variables only once (PR #65257)

2023-10-03 Thread Vassil Vassilev via cfe-commits

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

LGTM. Let's move forward here and rely on a further post-commit review if 
necessary.

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


[clang] [clang-repl] Emit const variables only once (PR #65257)

2023-10-03 Thread Vassil Vassilev via cfe-commits

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


[clang] [clang][ASTImporter] Fix crash when import `VarTemplateDecl` in record (PR #67522)

2023-10-03 Thread Balázs Kéri via cfe-commits


@@ -4988,6 +4988,39 @@ TEST_P(ASTImporterOptionSpecificTestBase,
   }
 }
 
+TEST_P(ImportFriendClasses, RecordVarTemplateDecl) {
+  Decl *ToTU = getToTuDecl(
+  R"(
+  template 
+  class A {
+  public:
+template 
+static constexpr bool X = true;
+  };
+  )",
+  Lang_CXX14);
+
+  auto *Fwd = FirstDeclMatcher().match(
+  ToTU, varTemplateDecl(hasName("X")));
+  Decl *FromTU = getTuDecl(
+  R"(
+  template 
+  class A {
+  public:
+template 
+static constexpr bool X = true;
+  };
+  )",
+  Lang_CXX14, "input1.cc");
+  auto *FromA = FirstDeclMatcher().match(
+  FromTU, varTemplateDecl(hasName("X")));
+  auto *ToA = Import(FromA, Lang_CXX11);
+  EXPECT_TRUE(ToA);
+  EXPECT_EQ(Fwd->getTemplatedDecl(), ToA->getTemplatedDecl());

balazske wrote:

Is not a check `EXPECT_EQ(ToA, Fwd)` better here?

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


[clang] [clang-repl] Emit const variables only once (PR #65257)

2023-10-03 Thread Jonas Hahnfeld via cfe-commits

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


[clang] 05137ec - [clang-repl] Emit const variables only once (#65257)

2023-10-03 Thread via cfe-commits

Author: Jonas Hahnfeld
Date: 2023-10-03T11:58:23+02:00
New Revision: 05137ecfca0bd2f7fa6cd30c771dfacbb8188785

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

LOG: [clang-repl] Emit const variables only once (#65257)

Disable internal linkage for const variables if IncrementalExtensions
are enabled. Otherwise the variables are emitted multiple times, with
multiple constructions at unique memory locations, during every PTU.

Added: 
clang/test/Interpreter/const.cpp

Modified: 
clang/lib/AST/ASTContext.cpp

Removed: 




diff  --git a/clang/lib/AST/ASTContext.cpp b/clang/lib/AST/ASTContext.cpp
index 8917662c5336825..e3e4578ffd49e19 100644
--- a/clang/lib/AST/ASTContext.cpp
+++ b/clang/lib/AST/ASTContext.cpp
@@ -11768,6 +11768,16 @@ GVALinkage ASTContext::GetGVALinkageForFunction(const 
FunctionDecl *FD) const {
 
 static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
  const VarDecl *VD) {
+  // As an extension for interactive REPLs, make sure constant variables are
+  // only emitted once instead of LinkageComputer::getLVForNamespaceScopeDecl
+  // marking them as internal.
+  if (Context.getLangOpts().CPlusPlus &&
+  Context.getLangOpts().IncrementalExtensions &&
+  VD->getType().isConstQualified() &&
+  !VD->getType().isVolatileQualified() && !VD->isInline() &&
+  !isa(VD) && 
!VD->getDescribedVarTemplate())
+return GVA_DiscardableODR;
+
   if (!VD->isExternallyVisible())
 return GVA_Internal;
 

diff  --git a/clang/test/Interpreter/const.cpp 
b/clang/test/Interpreter/const.cpp
new file mode 100644
index 000..a4b610f1a19d842
--- /dev/null
+++ b/clang/test/Interpreter/const.cpp
@@ -0,0 +1,29 @@
+// UNSUPPORTED: system-aix
+// RUN: cat %s | clang-repl | FileCheck %s
+// RUN: cat %s | clang-repl -Xcc -O2 | FileCheck %s
+
+extern "C" int printf(const char*, ...);
+
+struct A { int val; A(int v); ~A(); void f() const; };
+A::A(int v) : val(v) { printf("A(%d), this = %p\n", val, this); }
+A::~A() { printf("~A, this = %p, val = %d\n", this, val); }
+void A::f() const { printf("f: this = %p, val = %d\n", this, val); }
+
+const A a(1);
+// CHECK: A(1), this = [[THIS:0x[0-9a-f]+]]
+// The constructor must only be called once!
+// CHECK-NOT: A(1)
+
+a.f();
+// CHECK-NEXT: f: this = [[THIS]], val = 1
+a.f();
+// CHECK-NEXT: f: this = [[THIS]], val = 1
+
+%quit
+// There must still be no other constructor!
+// CHECK-NOT: A(1)
+
+// At the end, we expect exactly one destructor call
+// CHECK: ~A
+// CHECK-SAME: this = [[THIS]], val = 1
+// CHECK-NOT: ~A



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


[clang] [clang][ASTImporter] Fix crash when import `VarTemplateDecl` in record (PR #67522)

2023-10-03 Thread Qizhi Hu via cfe-commits

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

>From 4a14372fc7856adb5a6d2c2c04eaec8c3a518075 Mon Sep 17 00:00:00 2001
From: huqizhi 
Date: Wed, 27 Sep 2023 15:32:10 +0800
Subject: [PATCH] [clang][ASTImporter] fix clash when import `VarTemplateDecl`
 in record

---
 clang/lib/AST/ASTImporter.cpp   |  3 +++
 clang/unittests/AST/ASTImporterTest.cpp | 31 +
 2 files changed, 34 insertions(+)

diff --git a/clang/lib/AST/ASTImporter.cpp b/clang/lib/AST/ASTImporter.cpp
index c7c2aecc8b179a4..a8ce1c469b6329c 100644
--- a/clang/lib/AST/ASTImporter.cpp
+++ b/clang/lib/AST/ASTImporter.cpp
@@ -6240,6 +6240,9 @@ ExpectedDecl 
ASTNodeImporter::VisitVarTemplateDecl(VarTemplateDecl *D) {
   // FIXME Check for ODR error if the two definitions have
   // different initializers?
   return Importer.MapImported(D, FoundDef);
+if (FoundTemplate->getDeclContext()->isRecord() &&
+D->getDeclContext()->isRecord())
+  return Importer.MapImported(D, FoundTemplate);
 
 FoundByLookup = FoundTemplate;
 break;
diff --git a/clang/unittests/AST/ASTImporterTest.cpp 
b/clang/unittests/AST/ASTImporterTest.cpp
index c90b5aaeb624306..ac27d932ce919d4 100644
--- a/clang/unittests/AST/ASTImporterTest.cpp
+++ b/clang/unittests/AST/ASTImporterTest.cpp
@@ -4988,6 +4988,37 @@ TEST_P(ASTImporterOptionSpecificTestBase,
   }
 }
 
+TEST_P(ImportFriendClasses, RecordVarTemplateDecl) {
+  Decl *ToTU = getToTuDecl(
+  R"(
+  template 
+  class A {
+  public:
+template 
+static constexpr bool X = true;
+  };
+  )",
+  Lang_CXX14);
+
+  auto *ToTUX = FirstDeclMatcher().match(
+  ToTU, varTemplateDecl(hasName("X")));
+  Decl *FromTU = getTuDecl(
+  R"(
+  template 
+  class A {
+  public:
+template 
+static constexpr bool X = true;
+  };
+  )",
+  Lang_CXX14, "input1.cc");
+  auto *FromX = FirstDeclMatcher().match(
+  FromTU, varTemplateDecl(hasName("X")));
+  auto *ToX = Import(FromX, Lang_CXX11);
+  EXPECT_TRUE(ToX);
+  EXPECT_EQ(ToTUX, ToX);
+}
+
 TEST_P(ASTImporterOptionSpecificTestBase, VarTemplateParameterDeclContext) {
   constexpr auto Code =
   R"(

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


[clang] Add Documentation for Execution Results Handling in Clang-Repl (PR #65650)

2023-10-03 Thread Vassil Vassilev via cfe-commits


@@ -213,6 +213,411 @@ concept helps support advanced use cases such as template 
instantiations on dema
 automatic language interoperability. It also helps static languages such as 
C/C++ become
 apt for data science.
 
+Execution Results Handling in Clang-Repl
+
+
+Execution Results Handling features discussed below help extend the Clang-Repl
+functionality by creating an interface between the execution results of a
+program and the compiled program.
+
+1. **Capture Execution Results**: This feature helps capture the execution 
results
+of a program and bring them back to the compiled program.
+
+2. **Dump Captured Execution Results**: This feature helps create a temporary 
dump
+for Value Printing/Automatic Printf, that is, to display the value and type of
+the captured data.
+
+
+1. Capture Execution Results
+
+
+In many cases, it is useful to bring back the program execution result to the
+compiled program. This result can be stored in an object of type **Value**.
+
+How Execution Results are captured (Value Synthesis):
+-
+
+The synthesizer chooses which expression to synthesize, and then it replaces
+the original expression with the synthesized expression. Depending on the
+expression type, it may choose to save an object (``LastValue``) of type 
'value'
+while allocating memory to it (``SetValueWithAlloc()``), or not (
+``SetValueNoAlloc()``).
+
+.. graphviz::
+:name: valuesynthesis
+:caption: Value Synthesis
+:alt: Shows how an object of type 'Value' is synthesized
+:align: center
+
+ digraph "valuesynthesis" {
+ rankdir="LR";
+ graph [fontname="Verdana", fontsize="12"];
+ node [fontname="Verdana", fontsize="12"];
+ edge [fontname="Sans", fontsize="9"];
+
+ start [label=" Create an Object \n 'Last Value' \n of type 'Value' ", 
shape="note", fontcolor=white, fillcolor="#ff", style=filled];
+ assign [label=" Assign the result \n to the 'LastValue' \n (based on 
respective \n Memory Allocation \n scenario) ", shape="box"]
+ print [label=" Pretty Print \n the Value Object ", shape="Msquare", 
fillcolor="yellow", style=filled];
+ start -> assign;
+ assign -> print;
+
+   subgraph SynthesizeExpression {
+ synth [label=" SynthesizeExpr() ", shape="note", fontcolor=white, 
fillcolor="#ff", style=filled];
+ mem [label=" New Memory \n Allocation? ", shape="diamond"];
+ withaloc [label=" SetValueWithAlloc() ", shape="box"];
+ noaloc [label=" SetValueNoAlloc() ", shape="box"];
+ right [label=" 1. RValue Structure \n (a temporary value)", 
shape="box"];
+ left2 [label=" 2. LValue Structure \n (a variable with \n an 
address)", shape="box"];
+ left3 [label=" 3. Built-In Type \n (int, float, etc.)", 
shape="box"];
+ output [label=" move to 'Assign' step ", shape="box"];
+
+ synth -> mem;
+ mem -> withaloc [label="Yes"];
+ mem -> noaloc [label="No"];
+ withaloc -> right;
+ noaloc -> left2;
+ noaloc -> left3;
+ right -> output;
+ left2 -> output;
+ left3 -> output;
+  }
+output -> assign
+  }
+
+Where is the captured result stored?
+
+
+``LastValue`` holds the last result of the value printing. It is a class member
+because it can be accessed even after subsequent inputs.
+
+**Note:** If no value printing happens, then it is in an invalid state.
+
+Improving Efficiency and User Experience
+
+
+The Value object is essentially used to create a mapping between an expression
+'type' and the allocated 'memory'. Built-in types (bool, char, int,
+float, double, etc.) are copyable. Their their memory allocation size is known

vgvassilev wrote:

```suggestion
float, double, etc.) are copyable. Their memory allocation size is known
```

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


[clang] Add Documentation for Execution Results Handling in Clang-Repl (PR #65650)

2023-10-03 Thread Vassil Vassilev via cfe-commits

vgvassilev wrote:

@Krishna-13-cyber, can you rebase this PR?

@gribozavr ping.

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


[clang] [clang][ASTImporter] Fix crash when import `VarTemplateDecl` in record (PR #67522)

2023-10-03 Thread Qizhi Hu via cfe-commits


@@ -4988,6 +4988,39 @@ TEST_P(ASTImporterOptionSpecificTestBase,
   }
 }
 
+TEST_P(ImportFriendClasses, RecordVarTemplateDecl) {
+  Decl *ToTU = getToTuDecl(
+  R"(
+  template 
+  class A {
+  public:
+template 
+static constexpr bool X = true;
+  };
+  )",
+  Lang_CXX14);
+
+  auto *Fwd = FirstDeclMatcher().match(
+  ToTU, varTemplateDecl(hasName("X")));
+  Decl *FromTU = getTuDecl(
+  R"(
+  template 
+  class A {
+  public:
+template 
+static constexpr bool X = true;
+  };
+  )",
+  Lang_CXX14, "input1.cc");
+  auto *FromA = FirstDeclMatcher().match(
+  FromTU, varTemplateDecl(hasName("X")));
+  auto *ToA = Import(FromA, Lang_CXX11);
+  EXPECT_TRUE(ToA);
+  EXPECT_EQ(Fwd->getTemplatedDecl(), ToA->getTemplatedDecl());

jcsxky wrote:

Yes, thanks for your suggestion. And other variable naming also has been 
updated.

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


[clang] [analyzer][clangsa] Add new option to alpha.security.cert.InvalidPtrChecker (PR #67663)

2023-10-03 Thread Endre Fülöp via cfe-commits

https://github.com/gamesh411 updated 
https://github.com/llvm/llvm-project/pull/67663

From 9f7f577c95d7e9fb7e2f929215ff217ca2d7ed53 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Endre=20F=C3=BCl=C3=B6p?= 
Date: Fri, 8 Sep 2023 14:20:00 +0200
Subject: [PATCH 1/8] [analyzer][clangsa] Add new option to
 alpha.security.cert.InvalidPtrChecker

The invalidation of pointer pointers returned by subsequent calls to genenv is
suggested by the POSIX standard, but is too strict from a practical point of
view. A new checker option 'InvalidatingGetEnv' is introduced, and is set to a
more lax default value, which does not consider consecutive getenv calls
invalidating.
The handling of the main function's possible specification where an environment
pointer is also pecified as a third parameter is also considered now.

Differential Revision: https://reviews.llvm.org/D154603
---
 .../clang/StaticAnalyzer/Checkers/Checkers.td |  9 ++
 .../Checkers/cert/InvalidPtrChecker.cpp   | 86 ++-
 clang/test/Analysis/analyzer-config.c |  1 +
 .../Analysis/cert/env34-c-cert-examples.c | 40 -
 clang/test/Analysis/cert/env34-c.c|  1 +
 clang/test/Analysis/invalid-ptr-checker.c | 50 +++
 6 files changed, 163 insertions(+), 24 deletions(-)
 create mode 100644 clang/test/Analysis/invalid-ptr-checker.c

diff --git a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td 
b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
index 65c1595eb6245dd..b4f65c934bf483b 100644
--- a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
+++ b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
@@ -997,6 +997,15 @@ let ParentPackage = ENV in {
 
   def InvalidPtrChecker : Checker<"InvalidPtr">,
   HelpText<"Finds usages of possibly invalidated pointers">,
+  CheckerOptions<[
+CmdLineOption,
+  ]>,
   Documentation;
 
 } // end "alpha.cert.env"
diff --git a/clang/lib/StaticAnalyzer/Checkers/cert/InvalidPtrChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/cert/InvalidPtrChecker.cpp
index aae1a17bc0ae53e..8849eb1148564b7 100644
--- a/clang/lib/StaticAnalyzer/Checkers/cert/InvalidPtrChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/cert/InvalidPtrChecker.cpp
@@ -38,6 +38,15 @@ class InvalidPtrChecker
 CheckerContext &C) const;
 
   // SEI CERT ENV31-C
+
+  // If set to true, consider getenv calls as invalidating operations on the
+  // environment variable buffer. This is implied in the standard, but in
+  // practice does not cause problems (in the commonly used environments).
+  bool InvalidatingGetEnv = false;
+
+  // GetEnv can be treated invalidating and non-invalidating as well.
+  const CallDescription GetEnvCall{{"getenv"}, 1};
+
   const CallDescriptionMap EnvpInvalidatingFunctions = {
   {{{"setenv"}, 3}, &InvalidPtrChecker::EnvpInvalidatingCall},
   {{{"unsetenv"}, 1}, &InvalidPtrChecker::EnvpInvalidatingCall},
@@ -51,7 +60,6 @@ class InvalidPtrChecker
 
   // SEI CERT ENV34-C
   const CallDescriptionMap PreviousCallInvalidatingFunctions = {
-  {{{"getenv"}, 1}, 
&InvalidPtrChecker::postPreviousReturnInvalidatingCall},
   {{{"setlocale"}, 2},
&InvalidPtrChecker::postPreviousReturnInvalidatingCall},
   {{{"strerror"}, 1},
@@ -62,6 +70,10 @@ class InvalidPtrChecker
&InvalidPtrChecker::postPreviousReturnInvalidatingCall},
   };
 
+  // The private members of this checker corresponding to commandline options
+  // are set in this function.
+  friend void ento::registerInvalidPtrChecker(CheckerManager &);
+
 public:
   // Obtain the environment pointer from 'main()' (if present).
   void checkBeginFunction(CheckerContext &C) const;
@@ -84,7 +96,10 @@ class InvalidPtrChecker
 REGISTER_SET_WITH_PROGRAMSTATE(InvalidMemoryRegions, const MemRegion *)
 
 // Stores the region of the environment pointer of 'main' (if present).
-REGISTER_TRAIT_WITH_PROGRAMSTATE(EnvPtrRegion, const MemRegion *)
+REGISTER_TRAIT_WITH_PROGRAMSTATE(MainEnvPtrRegion, const MemRegion *)
+
+// Stores the regions of environments returned by getenv calls.
+REGISTER_SET_WITH_PROGRAMSTATE(GetenvEnvPtrRegions, const MemRegion *)
 
 // Stores key-value pairs, where key is function declaration and value is
 // pointer to memory region returned by previous call of this function
@@ -95,22 +110,35 @@ void InvalidPtrChecker::EnvpInvalidatingCall(const 
CallEvent &Call,
  CheckerContext &C) const {
   StringRef FunctionName = Call.getCalleeIdentifier()->getName();
   ProgramStateRef State = C.getState();
-  const MemRegion *SymbolicEnvPtrRegion = State->get();
-  if (!SymbolicEnvPtrRegion)
-return;
 
-  State = State->add(SymbolicEnvPtrRegion);
+  auto PlaceInvalidationNote = [&C, FunctionName,
+&State](const MemRegion *Region,
+StringRef Message, ExplodedNode *Pred) 
{
+State = State->add(Region);
+
+// Make cop

[clang] [clang] Implement constexpr bit_cast for vectors (PR #66894)

2023-10-03 Thread via cfe-commits

https://github.com/DaMatrix updated 
https://github.com/llvm/llvm-project/pull/66894

>From c05ee51f4d930014ac7ff4adb7232ecdaceec7f9 Mon Sep 17 00:00:00 2001
From: DaPorkchop_ 
Date: Sun, 13 Aug 2023 22:39:12 +0200
Subject: [PATCH] [clang] Implement constexpr bit_cast for vectors

---
 .../include/clang/Basic/DiagnosticASTKinds.td |   3 +
 clang/lib/AST/ExprConstant.cpp| 247 +++---
 .../SemaCXX/constexpr-builtin-bit-cast.cpp|  61 +
 3 files changed, 217 insertions(+), 94 deletions(-)

diff --git a/clang/include/clang/Basic/DiagnosticASTKinds.td 
b/clang/include/clang/Basic/DiagnosticASTKinds.td
index d2656310e79c9b8..3f06e18783dd558 100644
--- a/clang/include/clang/Basic/DiagnosticASTKinds.td
+++ b/clang/include/clang/Basic/DiagnosticASTKinds.td
@@ -326,6 +326,9 @@ def note_constexpr_bit_cast_invalid_type : Note<
   "%select{type|member}1 is not allowed in a constant expression">;
 def note_constexpr_bit_cast_invalid_subtype : Note<
   "invalid type %0 is a %select{member|base}1 of %2">;
+def note_constexpr_bit_cast_invalid_vector : Note<
+  "bit_cast involving type %0 is not allowed in a constant expression; "
+  "element size %1 * element count %2 is not a multiple of the byte size %3">;
 def note_constexpr_bit_cast_indet_dest : Note<
   "indeterminate value can only initialize an object of type 'unsigned char'"
   "%select{, 'char',|}1 or 'std::byte'; %0 is invalid">;
diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index fea06b97259fe31..fdfb2c3f4431ad4 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -2732,53 +2732,6 @@ static bool truncateBitfieldValue(EvalInfo &Info, const 
Expr *E,
   return true;
 }
 
-static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
-  llvm::APInt &Res) {
-  APValue SVal;
-  if (!Evaluate(SVal, Info, E))
-return false;
-  if (SVal.isInt()) {
-Res = SVal.getInt();
-return true;
-  }
-  if (SVal.isFloat()) {
-Res = SVal.getFloat().bitcastToAPInt();
-return true;
-  }
-  if (SVal.isVector()) {
-QualType VecTy = E->getType();
-unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
-QualType EltTy = VecTy->castAs()->getElementType();
-unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
-bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
-Res = llvm::APInt::getZero(VecSize);
-for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
-  APValue &Elt = SVal.getVectorElt(i);
-  llvm::APInt EltAsInt;
-  if (Elt.isInt()) {
-EltAsInt = Elt.getInt();
-  } else if (Elt.isFloat()) {
-EltAsInt = Elt.getFloat().bitcastToAPInt();
-  } else {
-// Don't try to handle vectors of anything other than int or float
-// (not sure if it's possible to hit this case).
-Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
-return false;
-  }
-  unsigned BaseEltSize = EltAsInt.getBitWidth();
-  if (BigEndian)
-Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
-  else
-Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
-}
-return true;
-  }
-  // Give up if the input isn't an int, float, or vector.  For example, we
-  // reject "(v4i16)(intptr_t)&a".
-  Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
-  return false;
-}
-
 /// Perform the given integer operation, which is known to need at most 
BitWidth
 /// bits, and check for overflow in the original type (if that type was not an
 /// unsigned type).
@@ -7005,10 +6958,11 @@ class APValueToBufferConverter {
   return visitArray(Val, Ty, Offset);
 case APValue::Struct:
   return visitRecord(Val, Ty, Offset);
+case APValue::Vector:
+  return visitVector(Val, Ty, Offset);
 
 case APValue::ComplexInt:
 case APValue::ComplexFloat:
-case APValue::Vector:
 case APValue::FixedPoint:
   // FIXME: We should support these.
 
@@ -7095,6 +7049,61 @@ class APValueToBufferConverter {
 return true;
   }
 
+  bool visitVector(const APValue &Val, QualType Ty, CharUnits Offset) {
+const VectorType *VTy = Ty->castAs();
+QualType EltTy = VTy->getElementType();
+unsigned NElts = VTy->getNumElements();
+unsigned EltSize =
+VTy->isExtVectorBoolType() ? 1 : Info.Ctx.getTypeSize(EltTy);
+
+if ((NElts * EltSize) % Info.Ctx.getCharWidth() != 0) {
+  // The vector's size in bits is not a multiple of the target's byte size,
+  // so its layout is unspecified. For now, we'll simply treat these cases
+  // as unsupported (this should only be possible with OpenCL bool vectors
+  // whose element count isn't a multiple of the byte size).
+  Info.FFDiag(BCE->getBeginLoc(),
+  diag::note_constexpr_bit_cast_invalid_vector)
+  << Ty.getCanonicalType() << EltSize << NElts
+  << Info.Ctx.getCharWidth();
+  return false;
+}
+
+if (VTy->isExtV

[clang] [clang][codegen] Add a verifier IR pass before any further passes. (PR #68015)

2023-10-03 Thread Matheus Izvekov via cfe-commits

mizvekov wrote:

The latest revision now has the new pass under control of the same flag.

I will drop the matter of whether we do it for release builds by default, for 
this MR at least, because otherwise this is a useful change.

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


[clang] [analyzer][clangsa] Add new option to alpha.security.cert.InvalidPtrChecker (PR #67663)

2023-10-03 Thread Endre Fülöp via cfe-commits

https://github.com/gamesh411 updated 
https://github.com/llvm/llvm-project/pull/67663

From 9f7f577c95d7e9fb7e2f929215ff217ca2d7ed53 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Endre=20F=C3=BCl=C3=B6p?= 
Date: Fri, 8 Sep 2023 14:20:00 +0200
Subject: [PATCH 1/8] [analyzer][clangsa] Add new option to
 alpha.security.cert.InvalidPtrChecker

The invalidation of pointer pointers returned by subsequent calls to genenv is
suggested by the POSIX standard, but is too strict from a practical point of
view. A new checker option 'InvalidatingGetEnv' is introduced, and is set to a
more lax default value, which does not consider consecutive getenv calls
invalidating.
The handling of the main function's possible specification where an environment
pointer is also pecified as a third parameter is also considered now.

Differential Revision: https://reviews.llvm.org/D154603
---
 .../clang/StaticAnalyzer/Checkers/Checkers.td |  9 ++
 .../Checkers/cert/InvalidPtrChecker.cpp   | 86 ++-
 clang/test/Analysis/analyzer-config.c |  1 +
 .../Analysis/cert/env34-c-cert-examples.c | 40 -
 clang/test/Analysis/cert/env34-c.c|  1 +
 clang/test/Analysis/invalid-ptr-checker.c | 50 +++
 6 files changed, 163 insertions(+), 24 deletions(-)
 create mode 100644 clang/test/Analysis/invalid-ptr-checker.c

diff --git a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td 
b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
index 65c1595eb6245dd..b4f65c934bf483b 100644
--- a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
+++ b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
@@ -997,6 +997,15 @@ let ParentPackage = ENV in {
 
   def InvalidPtrChecker : Checker<"InvalidPtr">,
   HelpText<"Finds usages of possibly invalidated pointers">,
+  CheckerOptions<[
+CmdLineOption,
+  ]>,
   Documentation;
 
 } // end "alpha.cert.env"
diff --git a/clang/lib/StaticAnalyzer/Checkers/cert/InvalidPtrChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/cert/InvalidPtrChecker.cpp
index aae1a17bc0ae53e..8849eb1148564b7 100644
--- a/clang/lib/StaticAnalyzer/Checkers/cert/InvalidPtrChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/cert/InvalidPtrChecker.cpp
@@ -38,6 +38,15 @@ class InvalidPtrChecker
 CheckerContext &C) const;
 
   // SEI CERT ENV31-C
+
+  // If set to true, consider getenv calls as invalidating operations on the
+  // environment variable buffer. This is implied in the standard, but in
+  // practice does not cause problems (in the commonly used environments).
+  bool InvalidatingGetEnv = false;
+
+  // GetEnv can be treated invalidating and non-invalidating as well.
+  const CallDescription GetEnvCall{{"getenv"}, 1};
+
   const CallDescriptionMap EnvpInvalidatingFunctions = {
   {{{"setenv"}, 3}, &InvalidPtrChecker::EnvpInvalidatingCall},
   {{{"unsetenv"}, 1}, &InvalidPtrChecker::EnvpInvalidatingCall},
@@ -51,7 +60,6 @@ class InvalidPtrChecker
 
   // SEI CERT ENV34-C
   const CallDescriptionMap PreviousCallInvalidatingFunctions = {
-  {{{"getenv"}, 1}, 
&InvalidPtrChecker::postPreviousReturnInvalidatingCall},
   {{{"setlocale"}, 2},
&InvalidPtrChecker::postPreviousReturnInvalidatingCall},
   {{{"strerror"}, 1},
@@ -62,6 +70,10 @@ class InvalidPtrChecker
&InvalidPtrChecker::postPreviousReturnInvalidatingCall},
   };
 
+  // The private members of this checker corresponding to commandline options
+  // are set in this function.
+  friend void ento::registerInvalidPtrChecker(CheckerManager &);
+
 public:
   // Obtain the environment pointer from 'main()' (if present).
   void checkBeginFunction(CheckerContext &C) const;
@@ -84,7 +96,10 @@ class InvalidPtrChecker
 REGISTER_SET_WITH_PROGRAMSTATE(InvalidMemoryRegions, const MemRegion *)
 
 // Stores the region of the environment pointer of 'main' (if present).
-REGISTER_TRAIT_WITH_PROGRAMSTATE(EnvPtrRegion, const MemRegion *)
+REGISTER_TRAIT_WITH_PROGRAMSTATE(MainEnvPtrRegion, const MemRegion *)
+
+// Stores the regions of environments returned by getenv calls.
+REGISTER_SET_WITH_PROGRAMSTATE(GetenvEnvPtrRegions, const MemRegion *)
 
 // Stores key-value pairs, where key is function declaration and value is
 // pointer to memory region returned by previous call of this function
@@ -95,22 +110,35 @@ void InvalidPtrChecker::EnvpInvalidatingCall(const 
CallEvent &Call,
  CheckerContext &C) const {
   StringRef FunctionName = Call.getCalleeIdentifier()->getName();
   ProgramStateRef State = C.getState();
-  const MemRegion *SymbolicEnvPtrRegion = State->get();
-  if (!SymbolicEnvPtrRegion)
-return;
 
-  State = State->add(SymbolicEnvPtrRegion);
+  auto PlaceInvalidationNote = [&C, FunctionName,
+&State](const MemRegion *Region,
+StringRef Message, ExplodedNode *Pred) 
{
+State = State->add(Region);
+
+// Make cop

[clang] [flang][Driver] Support -rpath, -shared, and -static in the frontend (PR #66702)

2023-10-03 Thread David Truby via cfe-commits

DavidTruby wrote:

Sorry I haven’t had a chance to look at this yet but I can help you resolve the 
Windows issues here. 

Windows does support static libraries and that’s the default for the runtime at 
the moment, I’ve not actually tried linking the flang runtime dynamically on 
Windows so that may be the issue. There’s an additional hurdle on Windows as 
well that libraries statically or dynamically linked against libc are not ABI 
compatible, so I’m not sure how these flags might interact with that without 
taking a look

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


[clang] [clang] Document -Wglobal-constructors behavior (PR #68084)

2023-10-03 Thread via cfe-commits

https://github.com/serge-sans-paille created 
https://github.com/llvm/llvm-project/pull/68084

It's a drop in the ocean considering the lack of documentation of our 
diagnostics, but it's a start.

>From 9d8da7e0221ec408db68d84f3edd4aec58883eb1 Mon Sep 17 00:00:00 2001
From: serge-sans-paille 
Date: Tue, 3 Oct 2023 10:54:14 +0200
Subject: [PATCH] [clang] Document -Wglobal-constructors behavior

It's a drop in the ocean considering the lack of documentation of our
diagnostics, but it's a start.
---
 clang/include/clang/Basic/DiagnosticGroups.td | 6 +-
 1 file changed, 5 insertions(+), 1 deletion(-)

diff --git a/clang/include/clang/Basic/DiagnosticGroups.td 
b/clang/include/clang/Basic/DiagnosticGroups.td
index 0b09c002191848a..55e15e68764c42b 100644
--- a/clang/include/clang/Basic/DiagnosticGroups.td
+++ b/clang/include/clang/Basic/DiagnosticGroups.td
@@ -416,7 +416,11 @@ def : DiagGroup<"c++2a-compat-pedantic", 
[CXX20CompatPedantic]>;
 def ExitTimeDestructors : DiagGroup<"exit-time-destructors">;
 def FlexibleArrayExtensions : DiagGroup<"flexible-array-extensions">;
 def FourByteMultiChar : DiagGroup<"four-char-constants">;
-def GlobalConstructors : DiagGroup<"global-constructors">;
+def GlobalConstructors : DiagGroup<"global-constructors"> {
+ code Documentation = [{
+Emit a warning for each variable declaration that generates code run at 
startup.
+ }];
+}
 def BitwiseConditionalParentheses: 
DiagGroup<"bitwise-conditional-parentheses">;
 def BitwiseOpParentheses: DiagGroup<"bitwise-op-parentheses">;
 def LogicalOpParentheses: DiagGroup<"logical-op-parentheses">;

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


[clang] [clang] Document -Wglobal-constructors behavior (PR #68084)

2023-10-03 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang


Changes

It's a drop in the ocean considering the lack of documentation of our 
diagnostics, but it's a start.

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


1 Files Affected:

- (modified) clang/include/clang/Basic/DiagnosticGroups.td (+5-1) 


``diff
diff --git a/clang/include/clang/Basic/DiagnosticGroups.td 
b/clang/include/clang/Basic/DiagnosticGroups.td
index 0b09c002191848a..55e15e68764c42b 100644
--- a/clang/include/clang/Basic/DiagnosticGroups.td
+++ b/clang/include/clang/Basic/DiagnosticGroups.td
@@ -416,7 +416,11 @@ def : DiagGroup<"c++2a-compat-pedantic", 
[CXX20CompatPedantic]>;
 def ExitTimeDestructors : DiagGroup<"exit-time-destructors">;
 def FlexibleArrayExtensions : DiagGroup<"flexible-array-extensions">;
 def FourByteMultiChar : DiagGroup<"four-char-constants">;
-def GlobalConstructors : DiagGroup<"global-constructors">;
+def GlobalConstructors : DiagGroup<"global-constructors"> {
+ code Documentation = [{
+Emit a warning for each variable declaration that generates code run at 
startup.
+ }];
+}
 def BitwiseConditionalParentheses: 
DiagGroup<"bitwise-conditional-parentheses">;
 def BitwiseOpParentheses: DiagGroup<"bitwise-op-parentheses">;
 def LogicalOpParentheses: DiagGroup<"logical-op-parentheses">;

``




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


[clang] [clang][Sema] Fix a bug when instantiating a lambda with requires clause (PR #65193)

2023-10-03 Thread via cfe-commits

https://github.com/0x59616e updated 
https://github.com/llvm/llvm-project/pull/65193

>From 3eafb85ff74271456cba24ea5892dd5660c1d332 Mon Sep 17 00:00:00 2001
From: Sheng 
Date: Wed, 30 Aug 2023 11:44:23 +0800
Subject: [PATCH 1/5] [clang][Sema] Fix a bug when instantiating a lambda with
 requires clause

Instantiating a lambda at a scope different from its definition
scope will paralyze clang if the trailing require clause
refers to local variables of that definition scope.

This patch fixes this by re-adding the local variables to
`LocalInstantiationScope`.

Fixes #64462
---
 clang/lib/Sema/SemaConcept.cpp | 59 ++
 clang/test/SemaCXX/pr64462.cpp | 20 
 2 files changed, 79 insertions(+)
 create mode 100644 clang/test/SemaCXX/pr64462.cpp

diff --git a/clang/lib/Sema/SemaConcept.cpp b/clang/lib/Sema/SemaConcept.cpp
index d1fa8e7831225b7..e48e0f743927a17 100644
--- a/clang/lib/Sema/SemaConcept.cpp
+++ b/clang/lib/Sema/SemaConcept.cpp
@@ -567,6 +567,58 @@ bool Sema::addInstantiatedCapturesToScope(
   return false;
 }
 
+static void addDeclsFromParentScope(Sema &S, FunctionDecl *FD,
+LocalInstantiationScope &Scope) {
+  assert(isLambdaCallOperator(FD) && "FD must be a lambda call operator");
+
+  LambdaScopeInfo *LSI = cast(S.getFunctionScopes().back());
+
+  auto captureVar = [&](VarDecl *VD) {
+LSI->addCapture(VD, /*isBlock=*/false, /*isByref=*/false,
+/*isNested=*/false, VD->getBeginLoc(), SourceLocation(),
+VD->getType(), /*Invalid=*/false);
+  };
+
+  FD = dyn_cast(FD->getParent()->getParent());
+
+  if (!FD || !FD->isTemplateInstantiation())
+return;
+
+  FunctionDecl *Pattern = FD->getPrimaryTemplate()->getTemplatedDecl();
+
+  for (unsigned I = 0; I < Pattern->getNumParams(); ++I) {
+ParmVarDecl *PVD = Pattern->getParamDecl(I);
+if (!PVD->isParameterPack()) {
+  Scope.InstantiatedLocal(PVD, FD->getParamDecl(I));
+  captureVar(FD->getParamDecl(I));
+  continue;
+}
+
+Scope.MakeInstantiatedLocalArgPack(PVD);
+
+for (ParmVarDecl *Inst : FD->parameters().drop_front(I)) {
+  Scope.InstantiatedLocalPackArg(PVD, Inst);
+  captureVar(Inst);
+}
+  }
+
+  for (auto *decl : Pattern->decls()) {
+if (!isa(decl) || isa(decl))
+  continue;
+
+IdentifierInfo *II = cast(decl)->getIdentifier();
+auto it = llvm::find_if(FD->decls(), [&](Decl *inst) {
+  VarDecl *VD = dyn_cast(inst);
+  return VD && VD->isLocalVarDecl() && VD->getIdentifier() == II;
+});
+
+assert(it != FD->decls().end() && "Cannot find the instantiated 
variable.");
+
+Scope.InstantiatedLocal(decl, *it);
+captureVar(cast(*it));
+  }
+}
+
 bool Sema::SetupConstraintScope(
 FunctionDecl *FD, std::optional> TemplateArgs,
 MultiLevelTemplateArgumentList MLTAL, LocalInstantiationScope &Scope) {
@@ -684,6 +736,7 @@ bool Sema::CheckFunctionConstraints(const FunctionDecl *FD,
   CtxToSave = CtxToSave->getNonTransparentContext();
   }
 
+  const bool shouldAddDeclsFromParentScope = !CtxToSave->Encloses(CurContext);
   ContextRAII SavedContext{*this, CtxToSave};
   LocalInstantiationScope Scope(*this, !ForOverloadResolution ||
isLambdaCallOperator(FD));
@@ -705,6 +758,9 @@ bool Sema::CheckFunctionConstraints(const FunctionDecl *FD,
   LambdaScopeForCallOperatorInstantiationRAII LambdaScope(
   *this, const_cast(FD), *MLTAL, Scope);
 
+  if (isLambdaCallOperator(FD) && shouldAddDeclsFromParentScope)
+addDeclsFromParentScope(*this, const_cast(FD), Scope);
+
   return CheckConstraintSatisfaction(
   FD, {FD->getTrailingRequiresClause()}, *MLTAL,
   SourceRange(UsageLoc.isValid() ? UsageLoc : FD->getLocation()),
@@ -896,6 +952,9 @@ bool Sema::CheckInstantiatedFunctionTemplateConstraints(
   LambdaScopeForCallOperatorInstantiationRAII LambdaScope(
   *this, const_cast(Decl), *MLTAL, Scope);
 
+  if (isLambdaCallOperator(Decl))
+addDeclsFromParentScope(*this, Decl, Scope);
+
   llvm::SmallVector Converted;
   return CheckConstraintSatisfaction(Template, TemplateAC, Converted, *MLTAL,
  PointOfInstantiation, Satisfaction);
diff --git a/clang/test/SemaCXX/pr64462.cpp b/clang/test/SemaCXX/pr64462.cpp
new file mode 100644
index 000..cc8b5510d1a823a
--- /dev/null
+++ b/clang/test/SemaCXX/pr64462.cpp
@@ -0,0 +1,20 @@
+// RUN: %clang_cc1 -verify -std=c++20 -fsyntax-only %s
+
+auto c1(auto f, auto ...fs) {
+  constexpr bool a = true;
+  // expected-note@+2{{because substituted constraint expression is 
ill-formed: no matching function for call to 'c1'}}
+  // expected-note@+1{{candidate template ignored: constraints not satisfied 
[with auto:1 = bool}}
+  return [](auto) requires a && (c1(fs...)) {};
+}
+
+auto c2(auto f, auto ...fs) {
+  constexpr bool a = true;
+  // expected-note@+2{{because substituted constraint expression is 
ill-formed: n

[clang] [clang][Sema] Fix a bug when instantiating a lambda with requires clause (PR #65193)

2023-10-03 Thread via cfe-commits

https://github.com/0x59616e updated 
https://github.com/llvm/llvm-project/pull/65193

>From 3eafb85ff74271456cba24ea5892dd5660c1d332 Mon Sep 17 00:00:00 2001
From: Sheng 
Date: Wed, 30 Aug 2023 11:44:23 +0800
Subject: [PATCH 1/5] [clang][Sema] Fix a bug when instantiating a lambda with
 requires clause

Instantiating a lambda at a scope different from its definition
scope will paralyze clang if the trailing require clause
refers to local variables of that definition scope.

This patch fixes this by re-adding the local variables to
`LocalInstantiationScope`.

Fixes #64462
---
 clang/lib/Sema/SemaConcept.cpp | 59 ++
 clang/test/SemaCXX/pr64462.cpp | 20 
 2 files changed, 79 insertions(+)
 create mode 100644 clang/test/SemaCXX/pr64462.cpp

diff --git a/clang/lib/Sema/SemaConcept.cpp b/clang/lib/Sema/SemaConcept.cpp
index d1fa8e7831225b7..e48e0f743927a17 100644
--- a/clang/lib/Sema/SemaConcept.cpp
+++ b/clang/lib/Sema/SemaConcept.cpp
@@ -567,6 +567,58 @@ bool Sema::addInstantiatedCapturesToScope(
   return false;
 }
 
+static void addDeclsFromParentScope(Sema &S, FunctionDecl *FD,
+LocalInstantiationScope &Scope) {
+  assert(isLambdaCallOperator(FD) && "FD must be a lambda call operator");
+
+  LambdaScopeInfo *LSI = cast(S.getFunctionScopes().back());
+
+  auto captureVar = [&](VarDecl *VD) {
+LSI->addCapture(VD, /*isBlock=*/false, /*isByref=*/false,
+/*isNested=*/false, VD->getBeginLoc(), SourceLocation(),
+VD->getType(), /*Invalid=*/false);
+  };
+
+  FD = dyn_cast(FD->getParent()->getParent());
+
+  if (!FD || !FD->isTemplateInstantiation())
+return;
+
+  FunctionDecl *Pattern = FD->getPrimaryTemplate()->getTemplatedDecl();
+
+  for (unsigned I = 0; I < Pattern->getNumParams(); ++I) {
+ParmVarDecl *PVD = Pattern->getParamDecl(I);
+if (!PVD->isParameterPack()) {
+  Scope.InstantiatedLocal(PVD, FD->getParamDecl(I));
+  captureVar(FD->getParamDecl(I));
+  continue;
+}
+
+Scope.MakeInstantiatedLocalArgPack(PVD);
+
+for (ParmVarDecl *Inst : FD->parameters().drop_front(I)) {
+  Scope.InstantiatedLocalPackArg(PVD, Inst);
+  captureVar(Inst);
+}
+  }
+
+  for (auto *decl : Pattern->decls()) {
+if (!isa(decl) || isa(decl))
+  continue;
+
+IdentifierInfo *II = cast(decl)->getIdentifier();
+auto it = llvm::find_if(FD->decls(), [&](Decl *inst) {
+  VarDecl *VD = dyn_cast(inst);
+  return VD && VD->isLocalVarDecl() && VD->getIdentifier() == II;
+});
+
+assert(it != FD->decls().end() && "Cannot find the instantiated 
variable.");
+
+Scope.InstantiatedLocal(decl, *it);
+captureVar(cast(*it));
+  }
+}
+
 bool Sema::SetupConstraintScope(
 FunctionDecl *FD, std::optional> TemplateArgs,
 MultiLevelTemplateArgumentList MLTAL, LocalInstantiationScope &Scope) {
@@ -684,6 +736,7 @@ bool Sema::CheckFunctionConstraints(const FunctionDecl *FD,
   CtxToSave = CtxToSave->getNonTransparentContext();
   }
 
+  const bool shouldAddDeclsFromParentScope = !CtxToSave->Encloses(CurContext);
   ContextRAII SavedContext{*this, CtxToSave};
   LocalInstantiationScope Scope(*this, !ForOverloadResolution ||
isLambdaCallOperator(FD));
@@ -705,6 +758,9 @@ bool Sema::CheckFunctionConstraints(const FunctionDecl *FD,
   LambdaScopeForCallOperatorInstantiationRAII LambdaScope(
   *this, const_cast(FD), *MLTAL, Scope);
 
+  if (isLambdaCallOperator(FD) && shouldAddDeclsFromParentScope)
+addDeclsFromParentScope(*this, const_cast(FD), Scope);
+
   return CheckConstraintSatisfaction(
   FD, {FD->getTrailingRequiresClause()}, *MLTAL,
   SourceRange(UsageLoc.isValid() ? UsageLoc : FD->getLocation()),
@@ -896,6 +952,9 @@ bool Sema::CheckInstantiatedFunctionTemplateConstraints(
   LambdaScopeForCallOperatorInstantiationRAII LambdaScope(
   *this, const_cast(Decl), *MLTAL, Scope);
 
+  if (isLambdaCallOperator(Decl))
+addDeclsFromParentScope(*this, Decl, Scope);
+
   llvm::SmallVector Converted;
   return CheckConstraintSatisfaction(Template, TemplateAC, Converted, *MLTAL,
  PointOfInstantiation, Satisfaction);
diff --git a/clang/test/SemaCXX/pr64462.cpp b/clang/test/SemaCXX/pr64462.cpp
new file mode 100644
index 000..cc8b5510d1a823a
--- /dev/null
+++ b/clang/test/SemaCXX/pr64462.cpp
@@ -0,0 +1,20 @@
+// RUN: %clang_cc1 -verify -std=c++20 -fsyntax-only %s
+
+auto c1(auto f, auto ...fs) {
+  constexpr bool a = true;
+  // expected-note@+2{{because substituted constraint expression is 
ill-formed: no matching function for call to 'c1'}}
+  // expected-note@+1{{candidate template ignored: constraints not satisfied 
[with auto:1 = bool}}
+  return [](auto) requires a && (c1(fs...)) {};
+}
+
+auto c2(auto f, auto ...fs) {
+  constexpr bool a = true;
+  // expected-note@+2{{because substituted constraint expression is 
ill-formed: n

[clang] [clang][Sema] Fix a bug when instantiating a lambda with requires clause (PR #65193)

2023-10-03 Thread via cfe-commits

0x59616e wrote:

The typo and the style issues have been fixed. Thank you. Now I'm going to 
rebase to main and add release note.

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


[clang] [clang][Sema] Fix a bug when instantiating a lambda with requires clause (PR #65193)

2023-10-03 Thread via cfe-commits

https://github.com/0x59616e updated 
https://github.com/llvm/llvm-project/pull/65193

>From 8abb437d97382f517bcbf0b5c4a542172c5ae144 Mon Sep 17 00:00:00 2001
From: Sheng 
Date: Wed, 30 Aug 2023 11:44:23 +0800
Subject: [PATCH 1/6] [clang][Sema] Fix a bug when instantiating a lambda with
 requires clause

Instantiating a lambda at a scope different from its definition
scope will paralyze clang if the trailing require clause
refers to local variables of that definition scope.

This patch fixes this by re-adding the local variables to
`LocalInstantiationScope`.

Fixes #64462
---
 clang/lib/Sema/SemaConcept.cpp | 59 ++
 clang/test/SemaCXX/pr64462.cpp | 20 
 2 files changed, 79 insertions(+)
 create mode 100644 clang/test/SemaCXX/pr64462.cpp

diff --git a/clang/lib/Sema/SemaConcept.cpp b/clang/lib/Sema/SemaConcept.cpp
index 036548b68247bfa..41af513969c6615 100644
--- a/clang/lib/Sema/SemaConcept.cpp
+++ b/clang/lib/Sema/SemaConcept.cpp
@@ -584,6 +584,58 @@ bool Sema::addInstantiatedCapturesToScope(
   return false;
 }
 
+static void addDeclsFromParentScope(Sema &S, FunctionDecl *FD,
+LocalInstantiationScope &Scope) {
+  assert(isLambdaCallOperator(FD) && "FD must be a lambda call operator");
+
+  LambdaScopeInfo *LSI = cast(S.getFunctionScopes().back());
+
+  auto captureVar = [&](VarDecl *VD) {
+LSI->addCapture(VD, /*isBlock=*/false, /*isByref=*/false,
+/*isNested=*/false, VD->getBeginLoc(), SourceLocation(),
+VD->getType(), /*Invalid=*/false);
+  };
+
+  FD = dyn_cast(FD->getParent()->getParent());
+
+  if (!FD || !FD->isTemplateInstantiation())
+return;
+
+  FunctionDecl *Pattern = FD->getPrimaryTemplate()->getTemplatedDecl();
+
+  for (unsigned I = 0; I < Pattern->getNumParams(); ++I) {
+ParmVarDecl *PVD = Pattern->getParamDecl(I);
+if (!PVD->isParameterPack()) {
+  Scope.InstantiatedLocal(PVD, FD->getParamDecl(I));
+  captureVar(FD->getParamDecl(I));
+  continue;
+}
+
+Scope.MakeInstantiatedLocalArgPack(PVD);
+
+for (ParmVarDecl *Inst : FD->parameters().drop_front(I)) {
+  Scope.InstantiatedLocalPackArg(PVD, Inst);
+  captureVar(Inst);
+}
+  }
+
+  for (auto *decl : Pattern->decls()) {
+if (!isa(decl) || isa(decl))
+  continue;
+
+IdentifierInfo *II = cast(decl)->getIdentifier();
+auto it = llvm::find_if(FD->decls(), [&](Decl *inst) {
+  VarDecl *VD = dyn_cast(inst);
+  return VD && VD->isLocalVarDecl() && VD->getIdentifier() == II;
+});
+
+assert(it != FD->decls().end() && "Cannot find the instantiated 
variable.");
+
+Scope.InstantiatedLocal(decl, *it);
+captureVar(cast(*it));
+  }
+}
+
 bool Sema::SetupConstraintScope(
 FunctionDecl *FD, std::optional> TemplateArgs,
 MultiLevelTemplateArgumentList MLTAL, LocalInstantiationScope &Scope) {
@@ -701,6 +753,7 @@ bool Sema::CheckFunctionConstraints(const FunctionDecl *FD,
   CtxToSave = CtxToSave->getNonTransparentContext();
   }
 
+  const bool shouldAddDeclsFromParentScope = !CtxToSave->Encloses(CurContext);
   ContextRAII SavedContext{*this, CtxToSave};
   LocalInstantiationScope Scope(*this, !ForOverloadResolution ||
isLambdaCallOperator(FD));
@@ -722,6 +775,9 @@ bool Sema::CheckFunctionConstraints(const FunctionDecl *FD,
   LambdaScopeForCallOperatorInstantiationRAII LambdaScope(
   *this, const_cast(FD), *MLTAL, Scope);
 
+  if (isLambdaCallOperator(FD) && shouldAddDeclsFromParentScope)
+addDeclsFromParentScope(*this, const_cast(FD), Scope);
+
   return CheckConstraintSatisfaction(
   FD, {FD->getTrailingRequiresClause()}, *MLTAL,
   SourceRange(UsageLoc.isValid() ? UsageLoc : FD->getLocation()),
@@ -913,6 +969,9 @@ bool Sema::CheckInstantiatedFunctionTemplateConstraints(
   LambdaScopeForCallOperatorInstantiationRAII LambdaScope(
   *this, const_cast(Decl), *MLTAL, Scope);
 
+  if (isLambdaCallOperator(Decl))
+addDeclsFromParentScope(*this, Decl, Scope);
+
   llvm::SmallVector Converted;
   return CheckConstraintSatisfaction(Template, TemplateAC, Converted, *MLTAL,
  PointOfInstantiation, Satisfaction);
diff --git a/clang/test/SemaCXX/pr64462.cpp b/clang/test/SemaCXX/pr64462.cpp
new file mode 100644
index 000..cc8b5510d1a823a
--- /dev/null
+++ b/clang/test/SemaCXX/pr64462.cpp
@@ -0,0 +1,20 @@
+// RUN: %clang_cc1 -verify -std=c++20 -fsyntax-only %s
+
+auto c1(auto f, auto ...fs) {
+  constexpr bool a = true;
+  // expected-note@+2{{because substituted constraint expression is 
ill-formed: no matching function for call to 'c1'}}
+  // expected-note@+1{{candidate template ignored: constraints not satisfied 
[with auto:1 = bool}}
+  return [](auto) requires a && (c1(fs...)) {};
+}
+
+auto c2(auto f, auto ...fs) {
+  constexpr bool a = true;
+  // expected-note@+2{{because substituted constraint expression is 
ill-formed: n

[clang] [NFC][clang] change remaining context-dependent type nodes to ContextualFoldingSet (PR #67751)

2023-10-03 Thread Matheus Izvekov via cfe-commits

mizvekov wrote:

@shafik from the last message, it seemed like this is good to go, but you 
didn't approve, so I am wondering if you forgot.

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


[clang] [RISCV][AArch64] Don't allow -mvscale-min/max options to be passed to the clang driver. (PR #68065)

2023-10-03 Thread Paul Walker via cfe-commits

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


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


[clang] b6ee41f - [clang-repl] Relax regular expression for new const.cpp test

2023-10-03 Thread Jonas Hahnfeld via cfe-commits

Author: Jonas Hahnfeld
Date: 2023-10-03T13:10:31+02:00
New Revision: b6ee41f83c6ea361bfafc2168e9223379b32773f

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

LOG: [clang-repl] Relax regular expression for new const.cpp test

This should fix the failing test on Windows:
https://lab.llvm.org/buildbot/#/builders/216/builds/28266

Added: 


Modified: 
clang/test/Interpreter/const.cpp

Removed: 




diff  --git a/clang/test/Interpreter/const.cpp 
b/clang/test/Interpreter/const.cpp
index a4b610f1a19d842..b3206f6e3fda96f 100644
--- a/clang/test/Interpreter/const.cpp
+++ b/clang/test/Interpreter/const.cpp
@@ -10,7 +10,7 @@ A::~A() { printf("~A, this = %p, val = %d\n", this, val); }
 void A::f() const { printf("f: this = %p, val = %d\n", this, val); }
 
 const A a(1);
-// CHECK: A(1), this = [[THIS:0x[0-9a-f]+]]
+// CHECK: A(1), this = [[THIS:.+]]
 // The constructor must only be called once!
 // CHECK-NOT: A(1)
 



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


[clang] [Clang] Fix constant evaluating a captured variable in a lambda (PR #68090)

2023-10-03 Thread via cfe-commits

https://github.com/cor3ntin created 
https://github.com/llvm/llvm-project/pull/68090

with an explicit parameter.

Fixes #68070

>From d3c5351c0bddd0bf9cd743471beafbf18bbab77c Mon Sep 17 00:00:00 2001
From: Corentin Jabot 
Date: Tue, 3 Oct 2023 13:19:50 +0200
Subject: [PATCH] [Clang] Fix constant evaluating a captured variable in a
 lambda

with an explicit parameter.

Fixes #68070
---
 clang/lib/AST/ExprConstant.cpp |  8 +++-
 .../SemaCXX/cxx2b-deducing-this-constexpr.cpp  | 18 ++
 2 files changed, 25 insertions(+), 1 deletion(-)

diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index a142ea7c47a4730..e8bf037c879c640 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -8366,8 +8366,14 @@ bool LValueExprEvaluator::VisitVarDecl(const Expr *E, 
const VarDecl *VD) {
   return false;
 
 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
+  auto *MD = cast(Info.CurrentCall->Callee);
   // Start with 'Result' referring to the complete closure object...
-  Result = *Info.CurrentCall->This;
+  if (MD->isExplicitObjectMemberFunction()) {
+APValue *RefValue =
+Info.getParamSlot(Info.CurrentCall->Arguments, 
MD->getParamDecl(0));
+Result.setFrom(Info.Ctx, *RefValue);
+  } else
+Result = *Info.CurrentCall->This;
   // ... then update it to refer to the field of the closure object
   // that represents the capture.
   if (!HandleLValueMember(Info, E, Result, FD))
diff --git a/clang/test/SemaCXX/cxx2b-deducing-this-constexpr.cpp 
b/clang/test/SemaCXX/cxx2b-deducing-this-constexpr.cpp
index 44de0d711674ba8..9dbea17dd2cae34 100644
--- a/clang/test/SemaCXX/cxx2b-deducing-this-constexpr.cpp
+++ b/clang/test/SemaCXX/cxx2b-deducing-this-constexpr.cpp
@@ -54,3 +54,21 @@ consteval void test() {
 static_assert(*s == 42);
 static_assert((s << 11) == 31);
 }
+
+namespace GH68070 {
+
+constexpr auto f = [x = 3](this Self&& self) {
+return x;
+};
+
+auto g = [x = 3](this Self&& self) {
+return x;
+};
+
+int test() {
+  constexpr int a = f();
+  static_assert(a == 3);
+  return f() + g();
+}
+
+}

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


[clang] Use platform specific calls to get the executable absolute path (PR #68091)

2023-10-03 Thread Liviu Ionescu via cfe-commits

https://github.com/ilg-ul created 
https://github.com/llvm/llvm-project/pull/68091

This patch fixes #66704.

>From f3812174546270051c4a2903b9a99408bf5b7ba0 Mon Sep 17 00:00:00 2001
From: Liviu Ionescu 
Date: Tue, 3 Oct 2023 14:07:48 +0300
Subject: [PATCH 1/2] [clang][driver] Use platform specific calls to get the
 executable absolute path (#66704)

In clang/tools/driver/driver.cpp, the function SetInstallDir() tries to 
determine the
location where the toolchain is installed, basically by taking the parent 
folder of
the executable absolute path. This is not correct when the compiler is invoked
via a link, since it returns the parent of the link.

This leads to subtle errors, for example on macOS it silently picks the wrong
system headers.
---
 clang/tools/driver/driver.cpp | 61 +++
 1 file changed, 61 insertions(+)

diff --git a/clang/tools/driver/driver.cpp b/clang/tools/driver/driver.cpp
index 531b5b4a61c1804..c8ad167cba0a423 100644
--- a/clang/tools/driver/driver.cpp
+++ b/clang/tools/driver/driver.cpp
@@ -57,6 +57,15 @@ using namespace clang;
 using namespace clang::driver;
 using namespace llvm::opt;
 
+#if defined(__linux__)
+#include 
+#elif defined(__APPLE__)
+#include 
+#include 
+#elif defined(__MINGW32__)
+#include 
+#endif
+
 std::string GetExecutablePath(const char *Argv0, bool CanonicalPrefixes) {
   if (!CanonicalPrefixes) {
 SmallString<128> ExecutablePath(Argv0);
@@ -331,6 +340,56 @@ static void SetInstallDir(SmallVectorImpl 
&argv,
   // path being a symlink.
   SmallString<128> InstalledPath(argv[0]);
 
+#if defined(__linux__)
+
+  char ProcessAbsolutePath[PATH_MAX];
+
+  int len = readlink("/proc/self/exe", ProcessAbsolutePath,
+ sizeof(ProcessAbsolutePath) - 1);
+  if ( len <= 0 ) {
+llvm::errs() << "Internal error: readlink(\"/proc/self/exe\") failed with "
+ << strerror(errno) << "\n";
+exit(1);
+  }
+
+  ProcessAbsolutePath[len] = 0;
+  InstalledPath = ProcessAbsolutePath;
+
+#elif defined(__APPLE__)
+
+  // The size must be higher than PROC_PIDPATHINFO_SIZE, otherwise the call
+  // fails with ENOMEM (12) - Cannot allocate memory.
+  // https://opensource.apple.com/source/Libc/Libc-498/darwin/libproc.c
+  char ProcessAbsolutePath[PROC_PIDPATHINFO_SIZE+1];
+
+  int len = proc_pidpath(getpid(), ProcessAbsolutePath,
+ sizeof(ProcessAbsolutePath) - 1);
+  if ( len <= 0 ) {
+llvm::errs() << "Internal error: proc_pidpath() failed with "
+ << strerror(errno) << "\n";
+exit(1);
+  }
+
+  ProcessAbsolutePath[len] = 0;
+  InstalledPath = ProcessAbsolutePath;
+
+#elif defined(__MINGW32__)
+
+  char ProcessAbsolutePath[PATH_MAX];
+
+  len = GetModuleFileName(NULL, ProcessAbsolutePath,
+  sizeof(ProcessAbsolutePath) - 1);
+  if ( len <= 0 ) {
+llvm::errs() << "Internal error: GetModuleFileName() failed with "
+ << strerror(errno) << "\n";
+exit(1);
+  }
+
+  ProcessAbsolutePath[len] = 0;
+  InstalledPath = ProcessAbsolutePath;
+
+#else
+
   // Do a PATH lookup, if there are no directory components.
   if (llvm::sys::path::filename(InstalledPath) == InstalledPath)
 if (llvm::ErrorOr Tmp = llvm::sys::findProgramByName(
@@ -341,6 +400,8 @@ static void SetInstallDir(SmallVectorImpl 
&argv,
   if (CanonicalPrefixes)
 llvm::sys::fs::make_absolute(InstalledPath);
 
+#endif
+
   StringRef InstalledPathParent(llvm::sys::path::parent_path(InstalledPath));
   if (llvm::sys::fs::exists(InstalledPathParent))
 TheDriver.setInstalledDir(InstalledPathParent);

>From eb7b122d5e6ce160d3f0880aac44a2df720d182f Mon Sep 17 00:00:00 2001
From: Liviu Ionescu 
Date: Tue, 3 Oct 2023 14:16:30 +0300
Subject: [PATCH 2/2] clang-format driver.cpp patch

---
 clang/tools/driver/driver.cpp | 8 
 1 file changed, 4 insertions(+), 4 deletions(-)

diff --git a/clang/tools/driver/driver.cpp b/clang/tools/driver/driver.cpp
index c8ad167cba0a423..45e1469aafca95e 100644
--- a/clang/tools/driver/driver.cpp
+++ b/clang/tools/driver/driver.cpp
@@ -346,7 +346,7 @@ static void SetInstallDir(SmallVectorImpl 
&argv,
 
   int len = readlink("/proc/self/exe", ProcessAbsolutePath,
  sizeof(ProcessAbsolutePath) - 1);
-  if ( len <= 0 ) {
+  if (len <= 0) {
 llvm::errs() << "Internal error: readlink(\"/proc/self/exe\") failed with "
  << strerror(errno) << "\n";
 exit(1);
@@ -360,11 +360,11 @@ static void SetInstallDir(SmallVectorImpl 
&argv,
   // The size must be higher than PROC_PIDPATHINFO_SIZE, otherwise the call
   // fails with ENOMEM (12) - Cannot allocate memory.
   // https://opensource.apple.com/source/Libc/Libc-498/darwin/libproc.c
-  char ProcessAbsolutePath[PROC_PIDPATHINFO_SIZE+1];
+  char ProcessAbsolutePath[PROC_PIDPATHINFO_SIZE + 1];
 
   int len = proc_pidpath(getpid(), ProcessAbsolutePath,
  sizeof(ProcessAbsolutePath) - 1);
-  if ( len <= 0 ) {
+  if (len <= 0) {

[clang] [Clang] Fix constant evaluating a captured variable in a lambda (PR #68090)

2023-10-03 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang


Changes

with an explicit parameter.

Fixes #68070

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


2 Files Affected:

- (modified) clang/lib/AST/ExprConstant.cpp (+7-1) 
- (modified) clang/test/SemaCXX/cxx2b-deducing-this-constexpr.cpp (+18) 


``diff
diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index a142ea7c47a4730..e8bf037c879c640 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -8366,8 +8366,14 @@ bool LValueExprEvaluator::VisitVarDecl(const Expr *E, 
const VarDecl *VD) {
   return false;
 
 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
+  auto *MD = cast(Info.CurrentCall->Callee);
   // Start with 'Result' referring to the complete closure object...
-  Result = *Info.CurrentCall->This;
+  if (MD->isExplicitObjectMemberFunction()) {
+APValue *RefValue =
+Info.getParamSlot(Info.CurrentCall->Arguments, 
MD->getParamDecl(0));
+Result.setFrom(Info.Ctx, *RefValue);
+  } else
+Result = *Info.CurrentCall->This;
   // ... then update it to refer to the field of the closure object
   // that represents the capture.
   if (!HandleLValueMember(Info, E, Result, FD))
diff --git a/clang/test/SemaCXX/cxx2b-deducing-this-constexpr.cpp 
b/clang/test/SemaCXX/cxx2b-deducing-this-constexpr.cpp
index 44de0d711674ba8..9dbea17dd2cae34 100644
--- a/clang/test/SemaCXX/cxx2b-deducing-this-constexpr.cpp
+++ b/clang/test/SemaCXX/cxx2b-deducing-this-constexpr.cpp
@@ -54,3 +54,21 @@ consteval void test() {
 static_assert(*s == 42);
 static_assert((s << 11) == 31);
 }
+
+namespace GH68070 {
+
+constexpr auto f = [x = 3](this Self&& self) {
+return x;
+};
+
+auto g = [x = 3](this Self&& self) {
+return x;
+};
+
+int test() {
+  constexpr int a = f();
+  static_assert(a == 3);
+  return f() + g();
+}
+
+}

``




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


[clang] Use platform specific calls to get the executable absolute path (PR #68091)

2023-10-03 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang


Changes

This patch fixes #66704.

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


1 Files Affected:

- (modified) clang/tools/driver/driver.cpp (+61) 


``diff
diff --git a/clang/tools/driver/driver.cpp b/clang/tools/driver/driver.cpp
index 531b5b4a61c1804..45e1469aafca95e 100644
--- a/clang/tools/driver/driver.cpp
+++ b/clang/tools/driver/driver.cpp
@@ -57,6 +57,15 @@ using namespace clang;
 using namespace clang::driver;
 using namespace llvm::opt;
 
+#if defined(__linux__)
+#include 
+#elif defined(__APPLE__)
+#include 
+#include 
+#elif defined(__MINGW32__)
+#include 
+#endif
+
 std::string GetExecutablePath(const char *Argv0, bool CanonicalPrefixes) {
   if (!CanonicalPrefixes) {
 SmallString<128> ExecutablePath(Argv0);
@@ -331,6 +340,56 @@ static void SetInstallDir(SmallVectorImpl 
&argv,
   // path being a symlink.
   SmallString<128> InstalledPath(argv[0]);
 
+#if defined(__linux__)
+
+  char ProcessAbsolutePath[PATH_MAX];
+
+  int len = readlink("/proc/self/exe", ProcessAbsolutePath,
+ sizeof(ProcessAbsolutePath) - 1);
+  if (len <= 0) {
+llvm::errs() << "Internal error: readlink(\"/proc/self/exe\") failed with "
+ << strerror(errno) << "\n";
+exit(1);
+  }
+
+  ProcessAbsolutePath[len] = 0;
+  InstalledPath = ProcessAbsolutePath;
+
+#elif defined(__APPLE__)
+
+  // The size must be higher than PROC_PIDPATHINFO_SIZE, otherwise the call
+  // fails with ENOMEM (12) - Cannot allocate memory.
+  // https://opensource.apple.com/source/Libc/Libc-498/darwin/libproc.c
+  char ProcessAbsolutePath[PROC_PIDPATHINFO_SIZE + 1];
+
+  int len = proc_pidpath(getpid(), ProcessAbsolutePath,
+ sizeof(ProcessAbsolutePath) - 1);
+  if (len <= 0) {
+llvm::errs() << "Internal error: proc_pidpath() failed with "
+ << strerror(errno) << "\n";
+exit(1);
+  }
+
+  ProcessAbsolutePath[len] = 0;
+  InstalledPath = ProcessAbsolutePath;
+
+#elif defined(__MINGW32__)
+
+  char ProcessAbsolutePath[PATH_MAX];
+
+  len = GetModuleFileName(NULL, ProcessAbsolutePath,
+  sizeof(ProcessAbsolutePath) - 1);
+  if (len <= 0) {
+llvm::errs() << "Internal error: GetModuleFileName() failed with "
+ << strerror(errno) << "\n";
+exit(1);
+  }
+
+  ProcessAbsolutePath[len] = 0;
+  InstalledPath = ProcessAbsolutePath;
+
+#else
+
   // Do a PATH lookup, if there are no directory components.
   if (llvm::sys::path::filename(InstalledPath) == InstalledPath)
 if (llvm::ErrorOr Tmp = llvm::sys::findProgramByName(
@@ -341,6 +400,8 @@ static void SetInstallDir(SmallVectorImpl 
&argv,
   if (CanonicalPrefixes)
 llvm::sys::fs::make_absolute(InstalledPath);
 
+#endif
+
   StringRef InstalledPathParent(llvm::sys::path::parent_path(InstalledPath));
   if (llvm::sys::fs::exists(InstalledPathParent))
 TheDriver.setInstalledDir(InstalledPathParent);

``




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


[clang] [clang][driver] Use platform specific calls to get the executable absolute path (PR #68091)

2023-10-03 Thread Liviu Ionescu via cfe-commits

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


[clang] 4812eec - [clang-repl] XFAIL new const.cpp test on Windows

2023-10-03 Thread Jonas Hahnfeld via cfe-commits

Author: Jonas Hahnfeld
Date: 2023-10-03T13:30:01+02:00
New Revision: 4812eecd7106200c0330d6371afbe036f577244a

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

LOG: [clang-repl] XFAIL new const.cpp test on Windows

Still failing after the previous commit:
https://lab.llvm.org/buildbot/#/builders/216/builds/28268

Added: 


Modified: 
clang/test/Interpreter/const.cpp

Removed: 




diff  --git a/clang/test/Interpreter/const.cpp 
b/clang/test/Interpreter/const.cpp
index b3206f6e3fda96f..4b6ce65e3643e64 100644
--- a/clang/test/Interpreter/const.cpp
+++ b/clang/test/Interpreter/const.cpp
@@ -1,4 +1,7 @@
 // UNSUPPORTED: system-aix
+// see https://github.com/llvm/llvm-project/issues/68092
+// XFAIL: system-windows
+
 // RUN: cat %s | clang-repl | FileCheck %s
 // RUN: cat %s | clang-repl -Xcc -O2 | FileCheck %s
 



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


[PATCH] D158540: Improve error message for constexpr constructors of virtual base classes

2023-10-03 Thread Nouman Amir via Phabricator via cfe-commits
NoumanAmir657 updated this revision to Diff 557555.

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

https://reviews.llvm.org/D158540

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/test/CXX/dcl.dcl/dcl.spec/dcl.constexpr/p3.cpp


Index: clang/test/CXX/dcl.dcl/dcl.spec/dcl.constexpr/p3.cpp
===
--- clang/test/CXX/dcl.dcl/dcl.spec/dcl.constexpr/p3.cpp
+++ clang/test/CXX/dcl.dcl/dcl.spec/dcl.constexpr/p3.cpp
@@ -283,3 +283,12 @@
 return r;
   }
 }
+
+struct Base {
+ constexpr Base() = default;
+};
+struct Derived : virtual Base { // expected-note 3{{virtual base class 
declared here}}
+  constexpr Derived() = default; // expected-error {{default constructor 
cannot be 'constexpr' in a class with virtual base class}}
+  constexpr Derived(const Derived&) = default; // expected-error {{copy 
constructor cannot be 'constexpr' in a class with virtual base class}}
+  constexpr Derived(Derived&&) = default; // expected-error {{move constructor 
cannot be 'constexpr' in a class with virtual base class}}
+};
\ No newline at end of file
Index: clang/lib/Sema/SemaDeclCXX.cpp
===
--- clang/lib/Sema/SemaDeclCXX.cpp
+++ clang/lib/Sema/SemaDeclCXX.cpp
@@ -7814,10 +7814,17 @@
   : isa(MD))) &&
   MD->isConstexpr() && !Constexpr &&
   MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
-Diag(MD->getBeginLoc(), MD->isConsteval()
-? diag::err_incorrect_defaulted_consteval
-: diag::err_incorrect_defaulted_constexpr)
-<< CSM;
+if (!MD->isConsteval() && RD->getNumVBases()) {
+  Diag(MD->getBeginLoc(), diag::err_incorrect_defaulted_constexpr_with_vb)
+  << CSM;
+  for (const auto &I : RD->vbases())
+Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here);
+} else {
+  Diag(MD->getBeginLoc(), MD->isConsteval()
+  ? diag::err_incorrect_defaulted_consteval
+  : diag::err_incorrect_defaulted_constexpr)
+  << CSM;
+}
 // FIXME: Explain why the special member can't be constexpr.
 HadError = true;
   }
Index: clang/include/clang/Basic/DiagnosticSemaKinds.td
===
--- clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -9416,6 +9416,8 @@
 def err_incorrect_defaulted_constexpr : Error<
   "defaulted definition of %sub{select_special_member_kind}0 "
   "is not constexpr">;
+def err_incorrect_defaulted_constexpr_with_vb: Error<
+  "%sub{select_special_member_kind}0 cannot be 'constexpr' in a class with 
virtual base class">;
 def err_incorrect_defaulted_consteval : Error<
   "defaulted declaration of %sub{select_special_member_kind}0 "
   "cannot be consteval because implicit definition is not constexpr">;
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -208,6 +208,8 @@
   (`#54678: `_).
 - Clang now prints its 'note' diagnostic in cyan instead of black, to be more 
compatible
   with terminals with dark background colors. This is also more consistent 
with GCC.
+- Clang now displays an improved diagnostic and a note when defaulted special 
+  member is a contexpr in a class with virtual base class
 
 Bug Fixes in This Version
 -


Index: clang/test/CXX/dcl.dcl/dcl.spec/dcl.constexpr/p3.cpp
===
--- clang/test/CXX/dcl.dcl/dcl.spec/dcl.constexpr/p3.cpp
+++ clang/test/CXX/dcl.dcl/dcl.spec/dcl.constexpr/p3.cpp
@@ -283,3 +283,12 @@
 return r;
   }
 }
+
+struct Base {
+ constexpr Base() = default;
+};
+struct Derived : virtual Base { // expected-note 3{{virtual base class declared here}}
+  constexpr Derived() = default; // expected-error {{default constructor cannot be 'constexpr' in a class with virtual base class}}
+  constexpr Derived(const Derived&) = default; // expected-error {{copy constructor cannot be 'constexpr' in a class with virtual base class}}
+  constexpr Derived(Derived&&) = default; // expected-error {{move constructor cannot be 'constexpr' in a class with virtual base class}}
+};
\ No newline at end of file
Index: clang/lib/Sema/SemaDeclCXX.cpp
===
--- clang/lib/Sema/SemaDeclCXX.cpp
+++ clang/lib/Sema/SemaDeclCXX.cpp
@@ -7814,10 +7814,17 @@
   : isa(MD))) &&
   MD->isConstexpr() && !Constexpr &&
   MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
-Diag(MD->getBeginLoc()

[clang] Bugfix for chosing the correct deduction guide (PR #66487)

2023-10-03 Thread Botond István Hprváth via cfe-commits

HoBoIs wrote:

Deduction guides were added in C++17, and This paper is also in C++17, so I 
don't think we need to check for versions in the code (I don't create any 
deduction guides I just use them so before C++17 my code is never used).

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


[clang] [Clang] Fix constant evaluating a captured variable in a lambda (PR #68090)

2023-10-03 Thread Timm Baeder via cfe-commits


@@ -8366,8 +8366,14 @@ bool LValueExprEvaluator::VisitVarDecl(const Expr *E, 
const VarDecl *VD) {
   return false;
 
 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
+  auto *MD = cast(Info.CurrentCall->Callee);
   // Start with 'Result' referring to the complete closure object...
-  Result = *Info.CurrentCall->This;
+  if (MD->isExplicitObjectMemberFunction()) {

tbaederr wrote:

```suggestion
  if (const auto *MD = cast(Info.CurrentCall->Callee);
  MD && MD->isExplicitObjectMemberFunction()) {
```

Does that work?

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


[clang] [Clang] Fix constant evaluating a captured variable in a lambda (PR #68090)

2023-10-03 Thread Timm Baeder via cfe-commits


@@ -8366,8 +8366,14 @@ bool LValueExprEvaluator::VisitVarDecl(const Expr *E, 
const VarDecl *VD) {
   return false;
 
 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
+  auto *MD = cast(Info.CurrentCall->Callee);
   // Start with 'Result' referring to the complete closure object...
-  Result = *Info.CurrentCall->This;
+  if (MD->isExplicitObjectMemberFunction()) {
+APValue *RefValue =
+Info.getParamSlot(Info.CurrentCall->Arguments, 
MD->getParamDecl(0));
+Result.setFrom(Info.Ctx, *RefValue);
+  } else
+Result = *Info.CurrentCall->This;

tbaederr wrote:

Shouldn't the `CurrentCall->this` be set to the first argument for explicit 
member functions, somewhere where the  stack frame is created?

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


[clang] [OpenMP] Improve omp offload profiler (PR #68016)

2023-10-03 Thread via cfe-commits

https://github.com/fel-cab updated 
https://github.com/llvm/llvm-project/pull/68016

>From dd44de067c26ba94b6561c5ed7fa4a5d812a3d1a Mon Sep 17 00:00:00 2001
From: Felipe Cabarcas 
Date: Mon, 18 Sep 2023 12:07:12 +
Subject: [PATCH 01/11] testing Profiler features

---
 openmp/libomptarget/src/interface.cpp | 5 -
 openmp/libomptarget/src/private.h | 3 ++-
 2 files changed, 6 insertions(+), 2 deletions(-)

diff --git a/openmp/libomptarget/src/interface.cpp 
b/openmp/libomptarget/src/interface.cpp
index 5f21b16b3fbfb1e..f64e1e268a3952e 100644
--- a/openmp/libomptarget/src/interface.cpp
+++ b/openmp/libomptarget/src/interface.cpp
@@ -252,7 +252,10 @@ static inline int targetKernel(ident_t *Loc, int64_t 
DeviceId, int32_t NumTeams,
   static_assert(std::is_convertible_v,
 "Target AsyncInfoTy must be convertible to AsyncInfoTy.");
 
-  TIMESCOPE_WITH_IDENT(Loc);
+  //TIMESCOPE_WITH_IDENT(Loc);
+  TIMESCOPE();
+  //TIMESCOPE_WITH_NAME_AND_IDENT("Hello", Loc);
+  //TIMESCOPE_WITH_RTM_AND_IDENT("Hello", Loc);
 
   DP("Entering target region for device %" PRId64 " with entry point " DPxMOD
  "\n",
diff --git a/openmp/libomptarget/src/private.h 
b/openmp/libomptarget/src/private.h
index cbce15b63a3eba2..dc6cd3944233955 100644
--- a/openmp/libomptarget/src/private.h
+++ b/openmp/libomptarget/src/private.h
@@ -433,7 +433,8 @@ class ExponentialBackoff {
   SourceInfo SI(IDENT);
\
   std::string ProfileLocation = SI.getProfileLocation();   
\
   std::string RTM = RegionTypeMsg; 
\
-  llvm::TimeTraceScope TimeScope(__FUNCTION__, ProfileLocation + RTM)
+  llvm::TimeTraceScope TimeScope(ProfileLocation, ProfileLocation + RTM)
+  //llvm::TimeTraceScope TimeScope(__FUNCTION__, ProfileLocation + RTM)
 #else
 #define TIMESCOPE()
 #define TIMESCOPE_WITH_IDENT(IDENT)

>From 92586bca6364100c7511ad38a30f41b0f86dea9c Mon Sep 17 00:00:00 2001
From: Felipe Cabarcas 
Date: Tue, 19 Sep 2023 12:02:53 +
Subject: [PATCH 02/11] Improve Profiler 1

---
 llvm/lib/Support/TimeProfiler.cpp |  2 +-
 openmp/libomptarget/src/interface.cpp | 17 +
 openmp/libomptarget/src/omptarget.cpp | 10 +-
 openmp/libomptarget/src/private.h |  5 +++--
 4 files changed, 18 insertions(+), 16 deletions(-)

diff --git a/llvm/lib/Support/TimeProfiler.cpp 
b/llvm/lib/Support/TimeProfiler.cpp
index 4d625b3eb5b1709..e1458116f64ab47 100644
--- a/llvm/lib/Support/TimeProfiler.cpp
+++ b/llvm/lib/Support/TimeProfiler.cpp
@@ -227,7 +227,7 @@ struct llvm::TimeTraceProfiler {
 J.attribute("ph", "X");
 J.attribute("ts", 0);
 J.attribute("dur", DurUs);
-J.attribute("name", "Total " + Total.first);
+J.attribute("name", "Total: " + Total.first);
 J.attributeObject("args", [&] {
   J.attribute("count", int64_t(Count));
   J.attribute("avg ms", int64_t(DurUs / Count / 1000));
diff --git a/openmp/libomptarget/src/interface.cpp 
b/openmp/libomptarget/src/interface.cpp
index f64e1e268a3952e..b8892cbe689107f 100644
--- a/openmp/libomptarget/src/interface.cpp
+++ b/openmp/libomptarget/src/interface.cpp
@@ -33,14 +33,14 @@ using namespace llvm::omp::target::ompt;
 

 /// adds requires flags
 EXTERN void __tgt_register_requires(int64_t Flags) {
-  TIMESCOPE();
+  //TIMESCOPE();
   PM->RTLs.registerRequires(Flags);
 }
 
 

 /// adds a target shared library to the target execution image
 EXTERN void __tgt_register_lib(__tgt_bin_desc *Desc) {
-  TIMESCOPE();
+  //TIMESCOPE();
   if (PM->maybeDelayRegisterLib(Desc))
 return;
 
@@ -61,7 +61,7 @@ EXTERN void __tgt_init_all_rtls() { PM->RTLs.initAllRTLs(); }
 

 /// unloads a target shared library
 EXTERN void __tgt_unregister_lib(__tgt_bin_desc *Desc) {
-  TIMESCOPE();
+  //TIMESCOPE();
   PM->RTLs.unregisterLib(Desc);
   for (auto &RTL : PM->RTLs.UsedRTLs) {
 if (RTL->unregister_lib) {
@@ -82,7 +82,8 @@ targetData(ident_t *Loc, int64_t DeviceId, int32_t ArgNum, 
void **ArgsBase,
   static_assert(std::is_convertible_v,
 "TargetAsyncInfoTy must be convertible to AsyncInfoTy.");
 
-  TIMESCOPE_WITH_RTM_AND_IDENT(RegionTypeMsg, Loc);
+  //TIMESCOPE_WITH_RTM_AND_IDENT(RegionTypeMsg, Loc);
+  TIMESCOPE_WITH_RTM_AND_IDENT("targetData", Loc);
 
   DP("Entering data %s region for device %" PRId64 " with %d mappings\n",
  RegionName, DeviceId, ArgNum);
@@ -253,9 +254,9 @@ static inline int targetKernel(ident_t *Loc, int64_t 
DeviceId, int32_t NumTeams,
 "Target AsyncInfoTy must be convertible to AsyncInfoTy.");
 
   //TIMESCOPE_WITH_IDENT(Loc);
-  TIMESCOPE();
+  //TIMESCOPE();
   //TIMESCOPE_WITH_NAME_AND_IDENT("Hello", Loc);
-

[clang-tools-extra] [OpenMP] Improve omp offload profiler (PR #68016)

2023-10-03 Thread via cfe-commits

https://github.com/fel-cab updated 
https://github.com/llvm/llvm-project/pull/68016

>From dd44de067c26ba94b6561c5ed7fa4a5d812a3d1a Mon Sep 17 00:00:00 2001
From: Felipe Cabarcas 
Date: Mon, 18 Sep 2023 12:07:12 +
Subject: [PATCH 01/11] testing Profiler features

---
 openmp/libomptarget/src/interface.cpp | 5 -
 openmp/libomptarget/src/private.h | 3 ++-
 2 files changed, 6 insertions(+), 2 deletions(-)

diff --git a/openmp/libomptarget/src/interface.cpp 
b/openmp/libomptarget/src/interface.cpp
index 5f21b16b3fbfb1e..f64e1e268a3952e 100644
--- a/openmp/libomptarget/src/interface.cpp
+++ b/openmp/libomptarget/src/interface.cpp
@@ -252,7 +252,10 @@ static inline int targetKernel(ident_t *Loc, int64_t 
DeviceId, int32_t NumTeams,
   static_assert(std::is_convertible_v,
 "Target AsyncInfoTy must be convertible to AsyncInfoTy.");
 
-  TIMESCOPE_WITH_IDENT(Loc);
+  //TIMESCOPE_WITH_IDENT(Loc);
+  TIMESCOPE();
+  //TIMESCOPE_WITH_NAME_AND_IDENT("Hello", Loc);
+  //TIMESCOPE_WITH_RTM_AND_IDENT("Hello", Loc);
 
   DP("Entering target region for device %" PRId64 " with entry point " DPxMOD
  "\n",
diff --git a/openmp/libomptarget/src/private.h 
b/openmp/libomptarget/src/private.h
index cbce15b63a3eba2..dc6cd3944233955 100644
--- a/openmp/libomptarget/src/private.h
+++ b/openmp/libomptarget/src/private.h
@@ -433,7 +433,8 @@ class ExponentialBackoff {
   SourceInfo SI(IDENT);
\
   std::string ProfileLocation = SI.getProfileLocation();   
\
   std::string RTM = RegionTypeMsg; 
\
-  llvm::TimeTraceScope TimeScope(__FUNCTION__, ProfileLocation + RTM)
+  llvm::TimeTraceScope TimeScope(ProfileLocation, ProfileLocation + RTM)
+  //llvm::TimeTraceScope TimeScope(__FUNCTION__, ProfileLocation + RTM)
 #else
 #define TIMESCOPE()
 #define TIMESCOPE_WITH_IDENT(IDENT)

>From 92586bca6364100c7511ad38a30f41b0f86dea9c Mon Sep 17 00:00:00 2001
From: Felipe Cabarcas 
Date: Tue, 19 Sep 2023 12:02:53 +
Subject: [PATCH 02/11] Improve Profiler 1

---
 llvm/lib/Support/TimeProfiler.cpp |  2 +-
 openmp/libomptarget/src/interface.cpp | 17 +
 openmp/libomptarget/src/omptarget.cpp | 10 +-
 openmp/libomptarget/src/private.h |  5 +++--
 4 files changed, 18 insertions(+), 16 deletions(-)

diff --git a/llvm/lib/Support/TimeProfiler.cpp 
b/llvm/lib/Support/TimeProfiler.cpp
index 4d625b3eb5b1709..e1458116f64ab47 100644
--- a/llvm/lib/Support/TimeProfiler.cpp
+++ b/llvm/lib/Support/TimeProfiler.cpp
@@ -227,7 +227,7 @@ struct llvm::TimeTraceProfiler {
 J.attribute("ph", "X");
 J.attribute("ts", 0);
 J.attribute("dur", DurUs);
-J.attribute("name", "Total " + Total.first);
+J.attribute("name", "Total: " + Total.first);
 J.attributeObject("args", [&] {
   J.attribute("count", int64_t(Count));
   J.attribute("avg ms", int64_t(DurUs / Count / 1000));
diff --git a/openmp/libomptarget/src/interface.cpp 
b/openmp/libomptarget/src/interface.cpp
index f64e1e268a3952e..b8892cbe689107f 100644
--- a/openmp/libomptarget/src/interface.cpp
+++ b/openmp/libomptarget/src/interface.cpp
@@ -33,14 +33,14 @@ using namespace llvm::omp::target::ompt;
 

 /// adds requires flags
 EXTERN void __tgt_register_requires(int64_t Flags) {
-  TIMESCOPE();
+  //TIMESCOPE();
   PM->RTLs.registerRequires(Flags);
 }
 
 

 /// adds a target shared library to the target execution image
 EXTERN void __tgt_register_lib(__tgt_bin_desc *Desc) {
-  TIMESCOPE();
+  //TIMESCOPE();
   if (PM->maybeDelayRegisterLib(Desc))
 return;
 
@@ -61,7 +61,7 @@ EXTERN void __tgt_init_all_rtls() { PM->RTLs.initAllRTLs(); }
 

 /// unloads a target shared library
 EXTERN void __tgt_unregister_lib(__tgt_bin_desc *Desc) {
-  TIMESCOPE();
+  //TIMESCOPE();
   PM->RTLs.unregisterLib(Desc);
   for (auto &RTL : PM->RTLs.UsedRTLs) {
 if (RTL->unregister_lib) {
@@ -82,7 +82,8 @@ targetData(ident_t *Loc, int64_t DeviceId, int32_t ArgNum, 
void **ArgsBase,
   static_assert(std::is_convertible_v,
 "TargetAsyncInfoTy must be convertible to AsyncInfoTy.");
 
-  TIMESCOPE_WITH_RTM_AND_IDENT(RegionTypeMsg, Loc);
+  //TIMESCOPE_WITH_RTM_AND_IDENT(RegionTypeMsg, Loc);
+  TIMESCOPE_WITH_RTM_AND_IDENT("targetData", Loc);
 
   DP("Entering data %s region for device %" PRId64 " with %d mappings\n",
  RegionName, DeviceId, ArgNum);
@@ -253,9 +254,9 @@ static inline int targetKernel(ident_t *Loc, int64_t 
DeviceId, int32_t NumTeams,
 "Target AsyncInfoTy must be convertible to AsyncInfoTy.");
 
   //TIMESCOPE_WITH_IDENT(Loc);
-  TIMESCOPE();
+  //TIMESCOPE();
   //TIMESCOPE_WITH_NAME_AND_IDENT("Hello", Loc);
-

[libunwind] [OpenMP] Improve omp offload profiler (PR #68016)

2023-10-03 Thread via cfe-commits

https://github.com/fel-cab updated 
https://github.com/llvm/llvm-project/pull/68016

>From dd44de067c26ba94b6561c5ed7fa4a5d812a3d1a Mon Sep 17 00:00:00 2001
From: Felipe Cabarcas 
Date: Mon, 18 Sep 2023 12:07:12 +
Subject: [PATCH 01/11] testing Profiler features

---
 openmp/libomptarget/src/interface.cpp | 5 -
 openmp/libomptarget/src/private.h | 3 ++-
 2 files changed, 6 insertions(+), 2 deletions(-)

diff --git a/openmp/libomptarget/src/interface.cpp 
b/openmp/libomptarget/src/interface.cpp
index 5f21b16b3fbfb1e..f64e1e268a3952e 100644
--- a/openmp/libomptarget/src/interface.cpp
+++ b/openmp/libomptarget/src/interface.cpp
@@ -252,7 +252,10 @@ static inline int targetKernel(ident_t *Loc, int64_t 
DeviceId, int32_t NumTeams,
   static_assert(std::is_convertible_v,
 "Target AsyncInfoTy must be convertible to AsyncInfoTy.");
 
-  TIMESCOPE_WITH_IDENT(Loc);
+  //TIMESCOPE_WITH_IDENT(Loc);
+  TIMESCOPE();
+  //TIMESCOPE_WITH_NAME_AND_IDENT("Hello", Loc);
+  //TIMESCOPE_WITH_RTM_AND_IDENT("Hello", Loc);
 
   DP("Entering target region for device %" PRId64 " with entry point " DPxMOD
  "\n",
diff --git a/openmp/libomptarget/src/private.h 
b/openmp/libomptarget/src/private.h
index cbce15b63a3eba2..dc6cd3944233955 100644
--- a/openmp/libomptarget/src/private.h
+++ b/openmp/libomptarget/src/private.h
@@ -433,7 +433,8 @@ class ExponentialBackoff {
   SourceInfo SI(IDENT);
\
   std::string ProfileLocation = SI.getProfileLocation();   
\
   std::string RTM = RegionTypeMsg; 
\
-  llvm::TimeTraceScope TimeScope(__FUNCTION__, ProfileLocation + RTM)
+  llvm::TimeTraceScope TimeScope(ProfileLocation, ProfileLocation + RTM)
+  //llvm::TimeTraceScope TimeScope(__FUNCTION__, ProfileLocation + RTM)
 #else
 #define TIMESCOPE()
 #define TIMESCOPE_WITH_IDENT(IDENT)

>From 92586bca6364100c7511ad38a30f41b0f86dea9c Mon Sep 17 00:00:00 2001
From: Felipe Cabarcas 
Date: Tue, 19 Sep 2023 12:02:53 +
Subject: [PATCH 02/11] Improve Profiler 1

---
 llvm/lib/Support/TimeProfiler.cpp |  2 +-
 openmp/libomptarget/src/interface.cpp | 17 +
 openmp/libomptarget/src/omptarget.cpp | 10 +-
 openmp/libomptarget/src/private.h |  5 +++--
 4 files changed, 18 insertions(+), 16 deletions(-)

diff --git a/llvm/lib/Support/TimeProfiler.cpp 
b/llvm/lib/Support/TimeProfiler.cpp
index 4d625b3eb5b1709..e1458116f64ab47 100644
--- a/llvm/lib/Support/TimeProfiler.cpp
+++ b/llvm/lib/Support/TimeProfiler.cpp
@@ -227,7 +227,7 @@ struct llvm::TimeTraceProfiler {
 J.attribute("ph", "X");
 J.attribute("ts", 0);
 J.attribute("dur", DurUs);
-J.attribute("name", "Total " + Total.first);
+J.attribute("name", "Total: " + Total.first);
 J.attributeObject("args", [&] {
   J.attribute("count", int64_t(Count));
   J.attribute("avg ms", int64_t(DurUs / Count / 1000));
diff --git a/openmp/libomptarget/src/interface.cpp 
b/openmp/libomptarget/src/interface.cpp
index f64e1e268a3952e..b8892cbe689107f 100644
--- a/openmp/libomptarget/src/interface.cpp
+++ b/openmp/libomptarget/src/interface.cpp
@@ -33,14 +33,14 @@ using namespace llvm::omp::target::ompt;
 

 /// adds requires flags
 EXTERN void __tgt_register_requires(int64_t Flags) {
-  TIMESCOPE();
+  //TIMESCOPE();
   PM->RTLs.registerRequires(Flags);
 }
 
 

 /// adds a target shared library to the target execution image
 EXTERN void __tgt_register_lib(__tgt_bin_desc *Desc) {
-  TIMESCOPE();
+  //TIMESCOPE();
   if (PM->maybeDelayRegisterLib(Desc))
 return;
 
@@ -61,7 +61,7 @@ EXTERN void __tgt_init_all_rtls() { PM->RTLs.initAllRTLs(); }
 

 /// unloads a target shared library
 EXTERN void __tgt_unregister_lib(__tgt_bin_desc *Desc) {
-  TIMESCOPE();
+  //TIMESCOPE();
   PM->RTLs.unregisterLib(Desc);
   for (auto &RTL : PM->RTLs.UsedRTLs) {
 if (RTL->unregister_lib) {
@@ -82,7 +82,8 @@ targetData(ident_t *Loc, int64_t DeviceId, int32_t ArgNum, 
void **ArgsBase,
   static_assert(std::is_convertible_v,
 "TargetAsyncInfoTy must be convertible to AsyncInfoTy.");
 
-  TIMESCOPE_WITH_RTM_AND_IDENT(RegionTypeMsg, Loc);
+  //TIMESCOPE_WITH_RTM_AND_IDENT(RegionTypeMsg, Loc);
+  TIMESCOPE_WITH_RTM_AND_IDENT("targetData", Loc);
 
   DP("Entering data %s region for device %" PRId64 " with %d mappings\n",
  RegionName, DeviceId, ArgNum);
@@ -253,9 +254,9 @@ static inline int targetKernel(ident_t *Loc, int64_t 
DeviceId, int32_t NumTeams,
 "Target AsyncInfoTy must be convertible to AsyncInfoTy.");
 
   //TIMESCOPE_WITH_IDENT(Loc);
-  TIMESCOPE();
+  //TIMESCOPE();
   //TIMESCOPE_WITH_NAME_AND_IDENT("Hello", Loc);
-

[clang] 9a40858 - [HIP][Clang][Driver] Add Driver support for `hipstdpar`

2023-10-03 Thread Alex Voicu via cfe-commits

Author: Alex Voicu
Date: 2023-10-03T13:14:46+01:00
New Revision: 9a408588d1b8b7899eff593c537de539a4a12651

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

LOG: [HIP][Clang][Driver] Add Driver support for `hipstdpar`

This patch adds the Driver changes needed for enabling HIP parallel algorithm 
offload on AMDGPU targets. What this change does can be summed up as follows:

- add two flags, one for enabling `hipstdpar` compilation, the second enabling 
the optional allocation interposition mode;
- the flags correspond to new LangOpt members;
- if we are compiling or linking with --hipstdpar, we enable HIP; in the 
compilation case C and C++ inputs are treated as HIP inputs;
- the ROCm / AMDGPU driver is augmented to look for and include an 
implementation detail forwarding header; we error out if the user requested 
`hipstdpar` but the header or its dependencies cannot be found.

Tests for the behaviour described above are also added.

Reviewed by: MaskRay, yaxunl

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

Added: 
clang/test/Driver/Inputs/hipstdpar/hipstdpar_lib.hpp
clang/test/Driver/Inputs/hipstdpar/rocprim/.keep
clang/test/Driver/Inputs/hipstdpar/thrust/.keep
clang/test/Driver/hipstdpar.c

Modified: 
clang/include/clang/Basic/DiagnosticDriverKinds.td
clang/include/clang/Basic/LangOptions.def
clang/include/clang/Driver/Options.td
clang/lib/Driver/Driver.cpp
clang/lib/Driver/ToolChains/AMDGPU.cpp
clang/lib/Driver/ToolChains/Clang.cpp
clang/lib/Driver/ToolChains/HIPAMD.cpp
clang/lib/Driver/ToolChains/ROCm.h

Removed: 




diff  --git a/clang/include/clang/Basic/DiagnosticDriverKinds.td 
b/clang/include/clang/Basic/DiagnosticDriverKinds.td
index 2a48c063e243ee0..91a95def4f80de4 100644
--- a/clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ b/clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -70,6 +70,16 @@ def err_drv_no_rocm_device_lib : Error<
 def err_drv_no_hip_runtime : Error<
   "cannot find HIP runtime; provide its path via '--rocm-path', or pass "
   "'-nogpuinc' to build without HIP runtime">;
+def err_drv_no_hipstdpar_lib : Error<
+  "cannot find HIP Standard Parallelism Acceleration library; provide it via "
+  "'--hipstdpar-path'">;
+def err_drv_no_hipstdpar_thrust_lib : Error<
+  "cannot find rocThrust, which is required by the HIP Standard Parallelism "
+  "Acceleration library; provide it via "
+  "'--hipstdpar-thrust-path'">;
+def err_drv_no_hipstdpar_prim_lib : Error<
+  "cannot find rocPrim, which is required by the HIP Standard Parallelism "
+  "Acceleration library; provide it via '--hipstdpar-prim-path'">;
 
 def err_drv_no_hipspv_device_lib : Error<
   "cannot find HIP device library%select{| for %1}0; provide its path via "

diff  --git a/clang/include/clang/Basic/LangOptions.def 
b/clang/include/clang/Basic/LangOptions.def
index 28c9bcec3ee60f1..c0ea4ecb9806a5b 100644
--- a/clang/include/clang/Basic/LangOptions.def
+++ b/clang/include/clang/Basic/LangOptions.def
@@ -280,6 +280,8 @@ ENUM_LANGOPT(SYCLVersion  , SYCLMajorVersion, 2, SYCL_None, 
"Version of the SYCL
 
 LANGOPT(HIPUseNewLaunchAPI, 1, 0, "Use new kernel launching API for HIP")
 LANGOPT(OffloadUniformBlock, 1, 0, "Assume that kernels are launched with 
uniform block sizes (default true for CUDA/HIP and false otherwise)")
+LANGOPT(HIPStdPar, 1, 0, "Enable Standard Parallel Algorithm Acceleration for 
HIP (experimental)")
+LANGOPT(HIPStdParInterposeAlloc, 1, 0, "Replace allocations / deallocations 
with HIP RT calls when Standard Parallel Algorithm Acceleration for HIP is 
enabled (Experimental)")
 
 LANGOPT(SizedDeallocation , 1, 0, "sized deallocation")
 LANGOPT(AlignedAllocation , 1, 0, "aligned allocation")

diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index ee4e23f335e7875..ff2130c93f28ea0 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -1258,6 +1258,32 @@ def rocm_path_EQ : Joined<["--"], "rocm-path=">, 
Group,
   HelpText<"ROCm installation path, used for finding and automatically linking 
required bitcode libraries.">;
 def hip_path_EQ : Joined<["--"], "hip-path=">, Group,
   HelpText<"HIP runtime installation path, used for finding HIP version and 
adding HIP include path.">;
+def hipstdpar : Flag<["--"], "hipstdpar">,
+  Visibility<[ClangOption, CC1Option]>,
+  Group,
+  HelpText<"Enable HIP acceleration for standard parallel algorithms">,
+  MarshallingInfoFlag>;
+def hipstdpar_interpose_alloc : Flag<["--"], "hipstdpar-interpose-alloc">,
+  Visibility<[ClangOption, CC1Option]>,
+  Group,
+  HelpText<"Replace all memory allocation / deallocation calls with "
+   "hipManagedMalloc / hipFree equivalents">,
+  MarshallingInfo

[PATCH] D155775: [HIP][Clang][Driver][RFC] Add driver support for C++ Parallel Algorithm Offload

2023-10-03 Thread Alex Voicu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG9a408588d1b8: [HIP][Clang][Driver] Add Driver support for 
`hipstdpar` (authored by AlexVlx).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155775

Files:
  clang/include/clang/Basic/DiagnosticDriverKinds.td
  clang/include/clang/Basic/LangOptions.def
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/Driver.cpp
  clang/lib/Driver/ToolChains/AMDGPU.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Driver/ToolChains/HIPAMD.cpp
  clang/lib/Driver/ToolChains/ROCm.h
  clang/test/Driver/Inputs/hipstdpar/hipstdpar_lib.hpp
  clang/test/Driver/Inputs/hipstdpar/rocprim/.keep
  clang/test/Driver/Inputs/hipstdpar/thrust/.keep
  clang/test/Driver/hipstdpar.c

Index: clang/test/Driver/hipstdpar.c
===
--- /dev/null
+++ clang/test/Driver/hipstdpar.c
@@ -0,0 +1,18 @@
+// RUN: not %clang -### --hipstdpar -nogpulib -nogpuinc --compile %s 2>&1 | \
+// RUN:   FileCheck --check-prefix=HIPSTDPAR-MISSING-LIB %s
+// RUN: %clang -### --hipstdpar --hipstdpar-path=%S/Inputs/hipstdpar \
+// RUN:   --hipstdpar-thrust-path=%S/Inputs/hipstdpar/thrust \
+// RUN:   --hipstdpar-prim-path=%S/Inputs/hipstdpar/rocprim \
+// RUN:   -nogpulib -nogpuinc --compile %s 2>&1 | \
+// RUN:   FileCheck --check-prefix=HIPSTDPAR-COMPILE %s
+// RUN: touch %t.o
+// RUN: %clang -### --hipstdpar %t.o 2>&1 | FileCheck --check-prefix=HIPSTDPAR-LINK %s
+
+// HIPSTDPAR-MISSING-LIB: error: cannot find HIP Standard Parallelism Acceleration library; provide it via '--hipstdpar-path'
+// HIPSTDPAR-COMPILE: "-x" "hip"
+// HIPSTDPAR-COMPILE: "-idirafter" "{{.*/thrust}}"
+// HIPSTDPAR-COMPILE: "-idirafter" "{{.*/rocprim}}"
+// HIPSTDPAR-COMPILE: "-idirafter" "{{.*/Inputs/hipstdpar}}"
+// HIPSTDPAR-COMPILE: "-include" "hipstdpar_lib.hpp"
+// HIPSTDPAR-LINK: "-rpath"
+// HIPSTDPAR-LINK: "-l{{.*hip.*}}"
Index: clang/lib/Driver/ToolChains/ROCm.h
===
--- clang/lib/Driver/ToolChains/ROCm.h
+++ clang/lib/Driver/ToolChains/ROCm.h
@@ -77,6 +77,9 @@
   const Driver &D;
   bool HasHIPRuntime = false;
   bool HasDeviceLibrary = false;
+  bool HasHIPStdParLibrary = false;
+  bool HasRocThrustLibrary = false;
+  bool HasRocPrimLibrary = false;
 
   // Default version if not detected or specified.
   const unsigned DefaultVersionMajor = 3;
@@ -96,6 +99,13 @@
   std::vector RocmDeviceLibPathArg;
   // HIP runtime path specified by --hip-path.
   StringRef HIPPathArg;
+  // HIP Standard Parallel Algorithm acceleration library specified by
+  // --hipstdpar-path
+  StringRef HIPStdParPathArg;
+  // rocThrust algorithm library specified by --hipstdpar-thrust-path
+  StringRef HIPRocThrustPathArg;
+  // rocPrim algorithm library specified by --hipstdpar-prim-path
+  StringRef HIPRocPrimPathArg;
   // HIP version specified by --hip-version.
   StringRef HIPVersionArg;
   // Wheter -nogpulib is specified.
@@ -180,6 +190,9 @@
   /// Check whether we detected a valid ROCm device library.
   bool hasDeviceLibrary() const { return HasDeviceLibrary; }
 
+  /// Check whether we detected a valid HIP STDPAR Acceleration library.
+  bool hasHIPStdParLibrary() const { return HasHIPStdParLibrary; }
+
   /// Print information about the detected ROCm installation.
   void print(raw_ostream &OS) const;
 
Index: clang/lib/Driver/ToolChains/HIPAMD.cpp
===
--- clang/lib/Driver/ToolChains/HIPAMD.cpp
+++ clang/lib/Driver/ToolChains/HIPAMD.cpp
@@ -113,6 +113,8 @@
 "--no-undefined",
 "-shared",
 "-plugin-opt=-amdgpu-internalize-symbols"};
+  if (Args.hasArg(options::OPT_hipstdpar))
+LldArgs.push_back("-plugin-opt=-amdgpu-enable-hipstdpar");
 
   auto &TC = getToolChain();
   auto &D = TC.getDriver();
@@ -242,6 +244,8 @@
   if (!DriverArgs.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc,
   false))
 CC1Args.append({"-mllvm", "-amdgpu-internalize-symbols"});
+  if (DriverArgs.hasArgNoClaim(options::OPT_hipstdpar))
+CC1Args.append({"-mllvm", "-amdgpu-enable-hipstdpar"});
 
   StringRef MaxThreadsPerBlock =
   DriverArgs.getLastArgValue(options::OPT_gpu_max_threads_per_block_EQ);
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -6580,6 +6580,8 @@
   CmdArgs.push_back("-fhip-new-launch-api");
 Args.addOptInFlag(CmdArgs, options::OPT_fgpu_allow_device_init,
   options::OPT_fno_gpu_allow_device_init);
+Args.AddLastArg(CmdArgs, options::OPT_hipstdpar);
+Args.AddLastArg(CmdArgs, options::OPT_hipstdpar_interpose_alloc);
 Args.addOptInFla

[PATCH] D158540: Improve error message for constexpr constructors of virtual base classes

2023-10-03 Thread Nouman Amir via Phabricator via cfe-commits
NoumanAmir657 updated this revision to Diff 557557.

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

https://reviews.llvm.org/D158540

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/test/CXX/dcl.dcl/dcl.spec/dcl.constexpr/p3.cpp


Index: clang/test/CXX/dcl.dcl/dcl.spec/dcl.constexpr/p3.cpp
===
--- clang/test/CXX/dcl.dcl/dcl.spec/dcl.constexpr/p3.cpp
+++ clang/test/CXX/dcl.dcl/dcl.spec/dcl.constexpr/p3.cpp
@@ -283,3 +283,12 @@
 return r;
   }
 }
+
+struct Base {
+ constexpr Base() = default;
+};
+struct Derived : virtual Base { // expected-note 3{{virtual base class 
declared here}}
+  constexpr Derived() = default; // expected-error {{default constructor 
cannot be 'constexpr' in a class with virtual base class}}
+  constexpr Derived(const Derived&) = default; // expected-error {{copy 
constructor cannot be 'constexpr' in a class with virtual base class}}
+  constexpr Derived(Derived&&) = default; // expected-error {{move constructor 
cannot be 'constexpr' in a class with virtual base class}}
+};
\ No newline at end of file
Index: clang/lib/Sema/SemaDeclCXX.cpp
===
--- clang/lib/Sema/SemaDeclCXX.cpp
+++ clang/lib/Sema/SemaDeclCXX.cpp
@@ -7814,10 +7814,17 @@
   : isa(MD))) &&
   MD->isConstexpr() && !Constexpr &&
   MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
-Diag(MD->getBeginLoc(), MD->isConsteval()
-? diag::err_incorrect_defaulted_consteval
-: diag::err_incorrect_defaulted_constexpr)
-<< CSM;
+if (!MD->isConsteval() && RD->getNumVBases()) {
+  Diag(MD->getBeginLoc(), 
diag::err_incorrect_defaulted_constexpr_with_vb)
+  << CSM;
+  for (const auto &I : RD->vbases())
+Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here);
+} else {
+  Diag(MD->getBeginLoc(), MD->isConsteval()
+  ? diag::err_incorrect_defaulted_consteval
+  : 
diag::err_incorrect_defaulted_constexpr)
+  << CSM;
+}
 // FIXME: Explain why the special member can't be constexpr.
 HadError = true;
   }
Index: clang/include/clang/Basic/DiagnosticSemaKinds.td
===
--- clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -9416,6 +9416,8 @@
 def err_incorrect_defaulted_constexpr : Error<
   "defaulted definition of %sub{select_special_member_kind}0 "
   "is not constexpr">;
+def err_incorrect_defaulted_constexpr_with_vb: Error<
+  "%sub{select_special_member_kind}0 cannot be 'constexpr' in a class with 
virtual base class">;
 def err_incorrect_defaulted_consteval : Error<
   "defaulted declaration of %sub{select_special_member_kind}0 "
   "cannot be consteval because implicit definition is not constexpr">;
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -208,7 +208,9 @@
   (`#54678: `_).
 - Clang now prints its 'note' diagnostic in cyan instead of black, to be more 
compatible
   with terminals with dark background colors. This is also more consistent 
with GCC.
-
+- Clang now displays an improved diagnostic and a note when defaulted special 
+  member is a constexpr in a class with virtual base class
+  
 Bug Fixes in This Version
 -
 - Fixed an issue where a class template specialization whose declaration is


Index: clang/test/CXX/dcl.dcl/dcl.spec/dcl.constexpr/p3.cpp
===
--- clang/test/CXX/dcl.dcl/dcl.spec/dcl.constexpr/p3.cpp
+++ clang/test/CXX/dcl.dcl/dcl.spec/dcl.constexpr/p3.cpp
@@ -283,3 +283,12 @@
 return r;
   }
 }
+
+struct Base {
+ constexpr Base() = default;
+};
+struct Derived : virtual Base { // expected-note 3{{virtual base class declared here}}
+  constexpr Derived() = default; // expected-error {{default constructor cannot be 'constexpr' in a class with virtual base class}}
+  constexpr Derived(const Derived&) = default; // expected-error {{copy constructor cannot be 'constexpr' in a class with virtual base class}}
+  constexpr Derived(Derived&&) = default; // expected-error {{move constructor cannot be 'constexpr' in a class with virtual base class}}
+};
\ No newline at end of file
Index: clang/lib/Sema/SemaDeclCXX.cpp
===
--- clang/lib/Sema/SemaDeclCXX.cpp
+++ clang/lib/Sema/SemaDeclCXX.cpp
@@ -7814,10 +7814,17 @@
   : isa(MD))) &&
  

[clang] [Clang] Fix constant evaluating a captured variable in a lambda (PR #68090)

2023-10-03 Thread via cfe-commits

https://github.com/cor3ntin updated 
https://github.com/llvm/llvm-project/pull/68090

>From d3c5351c0bddd0bf9cd743471beafbf18bbab77c Mon Sep 17 00:00:00 2001
From: Corentin Jabot 
Date: Tue, 3 Oct 2023 13:19:50 +0200
Subject: [PATCH 1/2] [Clang] Fix constant evaluating a captured variable in a
 lambda

with an explicit parameter.

Fixes #68070
---
 clang/lib/AST/ExprConstant.cpp |  8 +++-
 .../SemaCXX/cxx2b-deducing-this-constexpr.cpp  | 18 ++
 2 files changed, 25 insertions(+), 1 deletion(-)

diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index a142ea7c47a4730..e8bf037c879c640 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -8366,8 +8366,14 @@ bool LValueExprEvaluator::VisitVarDecl(const Expr *E, 
const VarDecl *VD) {
   return false;
 
 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
+  auto *MD = cast(Info.CurrentCall->Callee);
   // Start with 'Result' referring to the complete closure object...
-  Result = *Info.CurrentCall->This;
+  if (MD->isExplicitObjectMemberFunction()) {
+APValue *RefValue =
+Info.getParamSlot(Info.CurrentCall->Arguments, 
MD->getParamDecl(0));
+Result.setFrom(Info.Ctx, *RefValue);
+  } else
+Result = *Info.CurrentCall->This;
   // ... then update it to refer to the field of the closure object
   // that represents the capture.
   if (!HandleLValueMember(Info, E, Result, FD))
diff --git a/clang/test/SemaCXX/cxx2b-deducing-this-constexpr.cpp 
b/clang/test/SemaCXX/cxx2b-deducing-this-constexpr.cpp
index 44de0d711674ba8..9dbea17dd2cae34 100644
--- a/clang/test/SemaCXX/cxx2b-deducing-this-constexpr.cpp
+++ b/clang/test/SemaCXX/cxx2b-deducing-this-constexpr.cpp
@@ -54,3 +54,21 @@ consteval void test() {
 static_assert(*s == 42);
 static_assert((s << 11) == 31);
 }
+
+namespace GH68070 {
+
+constexpr auto f = [x = 3](this Self&& self) {
+return x;
+};
+
+auto g = [x = 3](this Self&& self) {
+return x;
+};
+
+int test() {
+  constexpr int a = f();
+  static_assert(a == 3);
+  return f() + g();
+}
+
+}

>From 535fda1ccf5804f2c350b58ced8ee5e98c6583bd Mon Sep 17 00:00:00 2001
From: Corentin Jabot 
Date: Tue, 3 Oct 2023 14:17:54 +0200
Subject: [PATCH 2/2] Address Timm's feedback

---
 clang/lib/AST/ExprConstant.cpp | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index e8bf037c879c640..d77597d063eb2a8 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -8366,9 +8366,9 @@ bool LValueExprEvaluator::VisitVarDecl(const Expr *E, 
const VarDecl *VD) {
   return false;
 
 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
-  auto *MD = cast(Info.CurrentCall->Callee);
   // Start with 'Result' referring to the complete closure object...
-  if (MD->isExplicitObjectMemberFunction()) {
+  if (auto *MD = cast(Info.CurrentCall->Callee);
+  MD->isExplicitObjectMemberFunction()) {
 APValue *RefValue =
 Info.getParamSlot(Info.CurrentCall->Arguments, 
MD->getParamDecl(0));
 Result.setFrom(Info.Ctx, *RefValue);

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


[clang] c0f8748 - [HIP][Clang][Preprocessor] Add Preprocessor support for `hipstdpar`

2023-10-03 Thread Alex Voicu via cfe-commits

Author: Alex Voicu
Date: 2023-10-03T13:18:31+01:00
New Revision: c0f8748d448be69748fee73014a60ada22b41b0d

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

LOG: [HIP][Clang][Preprocessor] Add Preprocessor support for `hipstdpar`

This patch adds the Driver changes needed for enabling HIP parallel algorithm 
offload on AMDGPU targets. This change merely adds two macros to inform user 
space if we are compiling in `hipstdpar` mode and, respectively, if the 
optional allocation interposition mode has been requested, as well as 
associated minimal tests. The macros can be used by the runtime implementation 
of offload to drive conditional compilation, and are only defined if the HIP 
language has been enabled.

Reviewed by: yaxunl

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

Added: 


Modified: 
clang/lib/Frontend/InitPreprocessor.cpp
clang/test/Preprocessor/predefined-macros.c

Removed: 




diff  --git a/clang/lib/Frontend/InitPreprocessor.cpp 
b/clang/lib/Frontend/InitPreprocessor.cpp
index 9e4d4d398a21da5..9e1e02e04ca7a00 100644
--- a/clang/lib/Frontend/InitPreprocessor.cpp
+++ b/clang/lib/Frontend/InitPreprocessor.cpp
@@ -585,6 +585,11 @@ static void InitializeStandardPredefinedMacros(const 
TargetInfo &TI,
 Builder.defineMacro("__HIP_MEMORY_SCOPE_WORKGROUP", "3");
 Builder.defineMacro("__HIP_MEMORY_SCOPE_AGENT", "4");
 Builder.defineMacro("__HIP_MEMORY_SCOPE_SYSTEM", "5");
+if (LangOpts.HIPStdPar) {
+  Builder.defineMacro("__HIPSTDPAR__");
+  if (LangOpts.HIPStdParInterposeAlloc)
+Builder.defineMacro("__HIPSTDPAR_INTERPOSE_ALLOC__");
+}
 if (LangOpts.CUDAIsDevice) {
   Builder.defineMacro("__HIP_DEVICE_COMPILE__");
   if (!TI.hasHIPImageSupport()) {

diff  --git a/clang/test/Preprocessor/predefined-macros.c 
b/clang/test/Preprocessor/predefined-macros.c
index d77b699674af4e1..c4a9672f0814aad 100644
--- a/clang/test/Preprocessor/predefined-macros.c
+++ b/clang/test/Preprocessor/predefined-macros.c
@@ -290,3 +290,20 @@
 // RUN:   -fcuda-is-device -fgpu-default-stream=per-thread \
 // RUN:   | FileCheck -match-full-lines %s --check-prefix=CHECK-PTH
 // CHECK-PTH: #define HIP_API_PER_THREAD_DEFAULT_STREAM 1
+
+// RUN: %clang_cc1 %s -E -dM -o - -x hip --hipstdpar -triple 
x86_64-unknown-linux-gnu \
+// RUN:   | FileCheck -match-full-lines %s --check-prefix=CHECK-HIPSTDPAR
+// CHECK-HIPSTDPAR: #define __HIPSTDPAR__ 1
+// CHECK-HIPSTDPAR-NOT: #define __HIPSTDPAR_INTERPOSE_ALLOC__ 1
+
+// RUN: %clang_cc1 %s -E -dM -o - -x hip --hipstdpar 
--hipstdpar-interpose-alloc \
+// RUN:  -triple x86_64-unknown-linux-gnu | FileCheck -match-full-lines %s \
+// RUN:  --check-prefix=CHECK-HIPSTDPAR-INTERPOSE
+// CHECK-HIPSTDPAR-INTERPOSE: #define __HIPSTDPAR_INTERPOSE_ALLOC__ 1
+// CHECK-HIPSTDPAR-INTERPOSE: #define __HIPSTDPAR__ 1
+
+// RUN: %clang_cc1 %s -E -dM -o - -x hip --hipstdpar 
--hipstdpar-interpose-alloc \
+// RUN:  -triple amdgcn-amd-amdhsa -fcuda-is-device | FileCheck 
-match-full-lines \
+// RUN:  %s --check-prefix=CHECK-HIPSTDPAR-INTERPOSE-DEV-NEG
+// CHECK-HIPSTDPAR-INTERPOSE-DEV-NEG: #define __HIPSTDPAR__ 1
+// CHECK-HIPSTDPAR-INTERPOSE-DEV-NEG-NOT: #define 
__HIPSTDPAR_INTERPOSE_ALLOC__ 1
\ No newline at end of file



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


[PATCH] D155826: [HIP][Clang][Preprocessor][RFC] Add preprocessor support for C++ Parallel Algorithm Offload

2023-10-03 Thread Alex Voicu 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 rGc0f8748d448b: [HIP][Clang][Preprocessor] Add Preprocessor 
support for `hipstdpar` (authored by AlexVlx).

Changed prior to commit:
  https://reviews.llvm.org/D155826?vs=552952&id=557558#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155826

Files:
  clang/lib/Frontend/InitPreprocessor.cpp
  clang/test/Preprocessor/predefined-macros.c


Index: clang/test/Preprocessor/predefined-macros.c
===
--- clang/test/Preprocessor/predefined-macros.c
+++ clang/test/Preprocessor/predefined-macros.c
@@ -290,3 +290,20 @@
 // RUN:   -fcuda-is-device -fgpu-default-stream=per-thread \
 // RUN:   | FileCheck -match-full-lines %s --check-prefix=CHECK-PTH
 // CHECK-PTH: #define HIP_API_PER_THREAD_DEFAULT_STREAM 1
+
+// RUN: %clang_cc1 %s -E -dM -o - -x hip --hipstdpar -triple 
x86_64-unknown-linux-gnu \
+// RUN:   | FileCheck -match-full-lines %s --check-prefix=CHECK-HIPSTDPAR
+// CHECK-HIPSTDPAR: #define __HIPSTDPAR__ 1
+// CHECK-HIPSTDPAR-NOT: #define __HIPSTDPAR_INTERPOSE_ALLOC__ 1
+
+// RUN: %clang_cc1 %s -E -dM -o - -x hip --hipstdpar 
--hipstdpar-interpose-alloc \
+// RUN:  -triple x86_64-unknown-linux-gnu | FileCheck -match-full-lines %s \
+// RUN:  --check-prefix=CHECK-HIPSTDPAR-INTERPOSE
+// CHECK-HIPSTDPAR-INTERPOSE: #define __HIPSTDPAR_INTERPOSE_ALLOC__ 1
+// CHECK-HIPSTDPAR-INTERPOSE: #define __HIPSTDPAR__ 1
+
+// RUN: %clang_cc1 %s -E -dM -o - -x hip --hipstdpar 
--hipstdpar-interpose-alloc \
+// RUN:  -triple amdgcn-amd-amdhsa -fcuda-is-device | FileCheck 
-match-full-lines \
+// RUN:  %s --check-prefix=CHECK-HIPSTDPAR-INTERPOSE-DEV-NEG
+// CHECK-HIPSTDPAR-INTERPOSE-DEV-NEG: #define __HIPSTDPAR__ 1
+// CHECK-HIPSTDPAR-INTERPOSE-DEV-NEG-NOT: #define 
__HIPSTDPAR_INTERPOSE_ALLOC__ 1
\ No newline at end of file
Index: clang/lib/Frontend/InitPreprocessor.cpp
===
--- clang/lib/Frontend/InitPreprocessor.cpp
+++ clang/lib/Frontend/InitPreprocessor.cpp
@@ -585,6 +585,11 @@
 Builder.defineMacro("__HIP_MEMORY_SCOPE_WORKGROUP", "3");
 Builder.defineMacro("__HIP_MEMORY_SCOPE_AGENT", "4");
 Builder.defineMacro("__HIP_MEMORY_SCOPE_SYSTEM", "5");
+if (LangOpts.HIPStdPar) {
+  Builder.defineMacro("__HIPSTDPAR__");
+  if (LangOpts.HIPStdParInterposeAlloc)
+Builder.defineMacro("__HIPSTDPAR_INTERPOSE_ALLOC__");
+}
 if (LangOpts.CUDAIsDevice) {
   Builder.defineMacro("__HIP_DEVICE_COMPILE__");
   if (!TI.hasHIPImageSupport()) {


Index: clang/test/Preprocessor/predefined-macros.c
===
--- clang/test/Preprocessor/predefined-macros.c
+++ clang/test/Preprocessor/predefined-macros.c
@@ -290,3 +290,20 @@
 // RUN:   -fcuda-is-device -fgpu-default-stream=per-thread \
 // RUN:   | FileCheck -match-full-lines %s --check-prefix=CHECK-PTH
 // CHECK-PTH: #define HIP_API_PER_THREAD_DEFAULT_STREAM 1
+
+// RUN: %clang_cc1 %s -E -dM -o - -x hip --hipstdpar -triple x86_64-unknown-linux-gnu \
+// RUN:   | FileCheck -match-full-lines %s --check-prefix=CHECK-HIPSTDPAR
+// CHECK-HIPSTDPAR: #define __HIPSTDPAR__ 1
+// CHECK-HIPSTDPAR-NOT: #define __HIPSTDPAR_INTERPOSE_ALLOC__ 1
+
+// RUN: %clang_cc1 %s -E -dM -o - -x hip --hipstdpar --hipstdpar-interpose-alloc \
+// RUN:  -triple x86_64-unknown-linux-gnu | FileCheck -match-full-lines %s \
+// RUN:  --check-prefix=CHECK-HIPSTDPAR-INTERPOSE
+// CHECK-HIPSTDPAR-INTERPOSE: #define __HIPSTDPAR_INTERPOSE_ALLOC__ 1
+// CHECK-HIPSTDPAR-INTERPOSE: #define __HIPSTDPAR__ 1
+
+// RUN: %clang_cc1 %s -E -dM -o - -x hip --hipstdpar --hipstdpar-interpose-alloc \
+// RUN:  -triple amdgcn-amd-amdhsa -fcuda-is-device | FileCheck -match-full-lines \
+// RUN:  %s --check-prefix=CHECK-HIPSTDPAR-INTERPOSE-DEV-NEG
+// CHECK-HIPSTDPAR-INTERPOSE-DEV-NEG: #define __HIPSTDPAR__ 1
+// CHECK-HIPSTDPAR-INTERPOSE-DEV-NEG-NOT: #define __HIPSTDPAR_INTERPOSE_ALLOC__ 1
\ No newline at end of file
Index: clang/lib/Frontend/InitPreprocessor.cpp
===
--- clang/lib/Frontend/InitPreprocessor.cpp
+++ clang/lib/Frontend/InitPreprocessor.cpp
@@ -585,6 +585,11 @@
 Builder.defineMacro("__HIP_MEMORY_SCOPE_WORKGROUP", "3");
 Builder.defineMacro("__HIP_MEMORY_SCOPE_AGENT", "4");
 Builder.defineMacro("__HIP_MEMORY_SCOPE_SYSTEM", "5");
+if (LangOpts.HIPStdPar) {
+  Builder.defineMacro("__HIPSTDPAR__");
+  if (LangOpts.HIPStdParInterposeAlloc)
+Builder.defineMacro("__HIPSTDPAR_INTERPOSE_ALLOC__");
+}
 if (LangOpts.CUDAIsDevice) {
   Builder.defineMacro("__HIP_DEVICE_COMPILE__");
   if (!TI.hasHIPImageSupport()) {
___
cfe-commits mailin

[clang] [Clang] Fix constant evaluating a captured variable in a lambda (PR #68090)

2023-10-03 Thread via cfe-commits


@@ -8366,8 +8366,14 @@ bool LValueExprEvaluator::VisitVarDecl(const Expr *E, 
const VarDecl *VD) {
   return false;
 
 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
+  auto *MD = cast(Info.CurrentCall->Callee);
   // Start with 'Result' referring to the complete closure object...
-  Result = *Info.CurrentCall->This;
+  if (MD->isExplicitObjectMemberFunction()) {
+APValue *RefValue =
+Info.getParamSlot(Info.CurrentCall->Arguments, 
MD->getParamDecl(0));
+Result.setFrom(Info.Ctx, *RefValue);
+  } else
+Result = *Info.CurrentCall->This;

cor3ntin wrote:

I'd rather not pretend that there is a `this` object even though it would not 
correspond to an actual this pointer (and evaluating `this` is ill formed. I 
imagine it might make things more difficult to maintain in the future

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


[clang] Extension: allow recursive macros (PR #65851)

2023-10-03 Thread via cfe-commits

https://github.com/kelbon updated 
https://github.com/llvm/llvm-project/pull/65851

>From d10ce5dd9e49fe85eac2e1f93a65cb27b511a71f Mon Sep 17 00:00:00 2001
From: Kelbon Nik 
Date: Sat, 9 Sep 2023 17:51:15 +0400
Subject: [PATCH 01/17] add define2 pp directive

---
 clang/include/clang/Basic/TokenKinds.def |  1 +
 clang/include/clang/Lex/MacroInfo.h  | 19 +--
 clang/include/clang/Lex/Preprocessor.h   |  2 +-
 clang/lib/Basic/IdentifierTable.cpp  |  2 ++
 clang/lib/Format/WhitespaceManager.cpp   |  2 +-
 clang/lib/Lex/MacroInfo.cpp  |  3 ++-
 clang/lib/Lex/PPDirectives.cpp   | 16 +++-
 7 files changed, 27 insertions(+), 18 deletions(-)

diff --git a/clang/include/clang/Basic/TokenKinds.def 
b/clang/include/clang/Basic/TokenKinds.def
index 72e8df8c793a7b6..b227a6a5632f496 100644
--- a/clang/include/clang/Basic/TokenKinds.def
+++ b/clang/include/clang/Basic/TokenKinds.def
@@ -115,6 +115,7 @@ PPKEYWORD(__include_macros)
 
 // C99 6.10.3 - Macro Replacement.
 PPKEYWORD(define)
+PPKEYWORD(define2)
 PPKEYWORD(undef)
 
 // C99 6.10.4 - Line Control.
diff --git a/clang/include/clang/Lex/MacroInfo.h 
b/clang/include/clang/Lex/MacroInfo.h
index 00c1c3866bbd9ca..4f0c8e987610e50 100644
--- a/clang/include/clang/Lex/MacroInfo.h
+++ b/clang/include/clang/Lex/MacroInfo.h
@@ -102,6 +102,10 @@ class MacroInfo {
   /// like \#define A A.
   bool IsDisabled : 1;
 
+  // True if 'define2' used,
+  // ignores 'IsDisabled' and enables expansion anyway
+  bool AllowRecurse : 1;
+
   /// True if this macro is either defined in the main file and has
   /// been used, or if it is not defined in the main file.
   ///
@@ -278,18 +282,13 @@ class MacroInfo {
   /// Return true if this macro is enabled.
   ///
   /// In other words, that we are not currently in an expansion of this macro.
-  bool isEnabled() const { return !IsDisabled; }
-
-  void EnableMacro() {
-assert(IsDisabled && "Cannot enable an already-enabled macro!");
-IsDisabled = false;
-  }
+  bool isEnabled() const { return AllowRecurse || !IsDisabled; }
+  void setAllowRecursive(bool Allow) { AllowRecurse = Allow; }
+  bool isAllowRecurse() const { return AllowRecurse; }
 
-  void DisableMacro() {
-assert(!IsDisabled && "Cannot disable an already-disabled macro!");
-IsDisabled = true;
-  }
+  void EnableMacro() { IsDisabled = false; }
 
+  void DisableMacro() { IsDisabled = true; }
   /// Determine whether this macro was used for a header guard.
   bool isUsedForHeaderGuard() const { return UsedForHeaderGuard; }
 
diff --git a/clang/include/clang/Lex/Preprocessor.h 
b/clang/include/clang/Lex/Preprocessor.h
index 575d08b83fd3a02..01eac0939fe9e21 100644
--- a/clang/include/clang/Lex/Preprocessor.h
+++ b/clang/include/clang/Lex/Preprocessor.h
@@ -2754,7 +2754,7 @@ class Preprocessor {
   void replayPreambleConditionalStack();
 
   // Macro handling.
-  void HandleDefineDirective(Token &Tok, bool ImmediatelyAfterHeaderGuard);
+  void HandleDefineDirective(Token &Tok, bool ImmediatelyAfterHeaderGuard, 
bool AllowRecurse);
   void HandleUndefDirective();
 
   // Conditional Inclusion.
diff --git a/clang/lib/Basic/IdentifierTable.cpp 
b/clang/lib/Basic/IdentifierTable.cpp
index e5599d545541085..7300825ff6b826a 100644
--- a/clang/lib/Basic/IdentifierTable.cpp
+++ b/clang/lib/Basic/IdentifierTable.cpp
@@ -431,6 +431,8 @@ tok::PPKeywordKind IdentifierInfo::getPPKeywordID() const {
   unsigned Len = getLength();
   if (Len < 2) return tok::pp_not_keyword;
   const char *Name = getNameStart();
+  if (std::string_view(Name, Len) == "define2")
+return tok::pp_define2;
   switch (HASH(Len, Name[0], Name[2])) {
   default: return tok::pp_not_keyword;
   CASE( 2, 'i', '\0', if);
diff --git a/clang/lib/Format/WhitespaceManager.cpp 
b/clang/lib/Format/WhitespaceManager.cpp
index b7bd8d27dc976b1..d8ab76d6761553e 100644
--- a/clang/lib/Format/WhitespaceManager.cpp
+++ b/clang/lib/Format/WhitespaceManager.cpp
@@ -743,7 +743,7 @@ void WhitespaceManager::alignConsecutiveMacros() {
 if (!Current || Current->isNot(tok::identifier))
   return false;
 
-if (!Current->Previous || Current->Previous->isNot(tok::pp_define))
+if (!Current->Previous || !Current->Previous->isOneOf(tok::pp_define, 
tok::pp_define2))
   return false;
 
 // For a macro function, 0 spaces are required between the
diff --git a/clang/lib/Lex/MacroInfo.cpp b/clang/lib/Lex/MacroInfo.cpp
index 39bb0f44eff25ba..9c3619c7c909304 100644
--- a/clang/lib/Lex/MacroInfo.cpp
+++ b/clang/lib/Lex/MacroInfo.cpp
@@ -50,7 +50,7 @@ static_assert(MacroInfoSizeChecker::AsExpected,
 MacroInfo::MacroInfo(SourceLocation DefLoc)
 : Location(DefLoc), IsDefinitionLengthCached(false), IsFunctionLike(false),
   IsC99Varargs(false), IsGNUVarargs(false), IsBuiltinMacro(false),
-  HasCommaPasting(false), IsDisabled(false), IsUsed(false),
+  HasCommaPasting(false), IsDisabled(false), AllowRecurse(false), 
IsUsed(false),
   IsAllowRedefinitions

[clang] [OpenMP] Improve omp offload profiler (PR #68016)

2023-10-03 Thread via cfe-commits


@@ -79,15 +79,15 @@ struct TimeTraceProfilerEntry {
   // Calculate timings for FlameGraph. Cast time points to microsecond 
precision

fel-cab wrote:

Removed this file from this PR

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


[libunwind] [OpenMP] Improve omp offload profiler (PR #68016)

2023-10-03 Thread via cfe-commits


@@ -79,15 +79,15 @@ struct TimeTraceProfilerEntry {
   // Calculate timings for FlameGraph. Cast time points to microsecond 
precision

fel-cab wrote:

Removed this file from this PR

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


[clang-tools-extra] [OpenMP] Improve omp offload profiler (PR #68016)

2023-10-03 Thread via cfe-commits


@@ -79,15 +79,15 @@ struct TimeTraceProfilerEntry {
   // Calculate timings for FlameGraph. Cast time points to microsecond 
precision

fel-cab wrote:

Removed this file from this PR

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


[clang] Bugfix for chosing the correct deduction guide (PR #66487)

2023-10-03 Thread Botond István Hprváth via cfe-commits

https://github.com/HoBoIs updated 
https://github.com/llvm/llvm-project/pull/66487

From 258462cc65403af147bb47cbeb95210df8e18cd3 Mon Sep 17 00:00:00 2001
From: hobois 
Date: Fri, 15 Sep 2023 09:28:21 +0200
Subject: [PATCH] Choose the correct deduction guide

If there are two guides, one of them generated from a non-templated constructor
and the other from a templated constructor, then the standard gives priority to
the first. Clang detected ambiguity before, now the correct guide is chosen.

As an unrelated minor change, fix the issue #64020, which could've led to
incorrect behavior if further development inserted code after a call to
isAddressSpaceSubsetOf() which specified the two parameters in the wrong order.
---
 clang/lib/Sema/SemaOverload.cpp | 17 -
 clang/lib/Sema/SemaTemplateInstantiateDecl.cpp  |  2 +-
 .../over.match.class.deduct/p2.cpp  | 10 ++
 3 files changed, 27 insertions(+), 2 deletions(-)

diff --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index 45a9e5dc98c032d..1bb81238520173a 100644
--- a/clang/lib/Sema/SemaOverload.cpp
+++ b/clang/lib/Sema/SemaOverload.cpp
@@ -10153,6 +10153,21 @@ bool clang::isBetterOverloadCandidate(
   //  -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
   if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy)
 return true;
+  if (Guide2->getDeductionCandidateKind() == DeductionCandidate::Copy)
+return false;
+
+  //  --F1 is generated from a non-template constructor and F2 is generated
+  //  from a constructor template
+  const auto *Constructor1 = Guide1->getCorrespondingConstructor();
+  const auto *Constructor2 = Guide2->getCorrespondingConstructor();
+  if (Constructor1 && Constructor2) {
+bool isC1Templated = Constructor1->getTemplatedKind() !=
+ FunctionDecl::TemplatedKind::TK_NonTemplate;
+bool isC2Templated = Constructor2->getTemplatedKind() !=
+ FunctionDecl::TemplatedKind::TK_NonTemplate;
+if (isC1Templated != isC2Templated)
+  return isC2Templated;
+  }
 }
   }
 
@@ -10196,7 +10211,7 @@ bool clang::isBetterOverloadCandidate(
 if (AS1 != AS2) {
   if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1))
 return true;
-  if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1))
+  if (Qualifiers::isAddressSpaceSupersetOf(AS1, AS2))
 return false;
 }
   }
diff --git a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp 
b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
index 9e5f85b0f9166bd..b9c4a9db842b9ee 100644
--- a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
@@ -2129,7 +2129,7 @@ Decl *TemplateDeclInstantiator::VisitFunctionDecl(
 Function = CXXDeductionGuideDecl::Create(
 SemaRef.Context, DC, D->getInnerLocStart(),
 InstantiatedExplicitSpecifier, NameInfo, T, TInfo,
-D->getSourceRange().getEnd(), /*Ctor=*/nullptr,
+D->getSourceRange().getEnd(), DGuide->getCorrespondingConstructor(),
 DGuide->getDeductionCandidateKind());
 Function->setAccess(D->getAccess());
   } else {
diff --git 
a/clang/test/CXX/over/over.match/over.match.funcs/over.match.class.deduct/p2.cpp
 
b/clang/test/CXX/over/over.match/over.match.funcs/over.match.class.deduct/p2.cpp
index 4eac0a1ac510f1d..d939d724dc7a0fd 100644
--- 
a/clang/test/CXX/over/over.match/over.match.funcs/over.match.class.deduct/p2.cpp
+++ 
b/clang/test/CXX/over/over.match/over.match.funcs/over.match.class.deduct/p2.cpp
@@ -85,3 +85,13 @@ int main() {
 
 
 }
+
+namespace deduceTemplatedConstructor{
+template  struct A {
+  A(T, T, int);
+  template
+A(int, T, U);
+};
+
+A x(1, 2, 3);   // no-error
+}

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


[libclc] [LIBCLC] Teach prepare-builtins how to handle text based IR (PR #66993)

2023-10-03 Thread Jakub Chlanda via cfe-commits

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


[libclc] 5ec9faf - [LIBCLC] Teach prepare-builtins how to handle text based IR (#66993)

2023-10-03 Thread via cfe-commits

Author: Jakub Chlanda
Date: 2023-10-03T14:28:01+02:00
New Revision: 5ec9faf007cc2589682cd28a10aa5a351f6aebda

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

LOG: [LIBCLC] Teach prepare-builtins how to handle text based IR (#66993)

Added: 


Modified: 
libclc/utils/prepare-builtins.cpp

Removed: 




diff  --git a/libclc/utils/prepare-builtins.cpp 
b/libclc/utils/prepare-builtins.cpp
index 550b5971913f48a..ebdbc68cfee3b3c 100644
--- a/libclc/utils/prepare-builtins.cpp
+++ b/libclc/utils/prepare-builtins.cpp
@@ -5,23 +5,27 @@
 #include "llvm/Bitcode/ReaderWriter.h"
 #endif
 
+#include "llvm/Config/llvm-config.h"
 #include "llvm/IR/Function.h"
 #include "llvm/IR/GlobalVariable.h"
 #include "llvm/IR/LLVMContext.h"
 #include "llvm/IR/Module.h"
+#include "llvm/IRReader/IRReader.h"
 #include "llvm/Support/CommandLine.h"
+#include "llvm/Support/ErrorOr.h"
+#include "llvm/Support/FileSystem.h"
 #include "llvm/Support/ManagedStatic.h"
 #include "llvm/Support/MemoryBuffer.h"
-#include "llvm/Support/FileSystem.h"
-#include "llvm/Support/raw_ostream.h"
-#include "llvm/Support/ErrorOr.h"
+#include "llvm/Support/SourceMgr.h"
 #include "llvm/Support/ToolOutputFile.h"
-#include "llvm/Config/llvm-config.h"
+#include "llvm/Support/raw_ostream.h"
 
 #include 
 
 using namespace llvm;
 
+static ExitOnError ExitOnErr;
+
 static cl::opt
 InputFilename(cl::Positional, cl::desc(""), cl::init("-"));
 
@@ -29,6 +33,9 @@ static cl::opt
 OutputFilename("o", cl::desc("Output filename"),
cl::value_desc("filename"));
 
+static cl::opt TextualOut("S", cl::desc("Emit LLVM textual assembly"),
+cl::init(false));
+
 int main(int argc, char **argv) {
   LLVMContext Context;
   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
@@ -45,17 +52,15 @@ int main(int argc, char **argv) {
   ErrorMessage = ec.message();
 } else {
   std::unique_ptr &BufferPtr = BufferOrErr.get();
-  ErrorOr> ModuleOrErr =
+  SMDiagnostic Err;
+  std::unique_ptr MPtr =
 #if HAVE_LLVM > 0x0390
-  expectedToErrorOrAndEmitErrors(Context,
-  parseBitcodeFile(BufferPtr.get()->getMemBufferRef(), Context));
+  ExitOnErr(Expected>(
+  parseIR(BufferPtr.get()->getMemBufferRef(), Err, Context)));
 #else
-  parseBitcodeFile(BufferPtr.get()->getMemBufferRef(), Context);
+  parseIR(BufferPtr.get()->getMemBufferRef(), Err, Context);
 #endif
-  if (std::error_code ec = ModuleOrErr.getError())
-ErrorMessage = ec.message();
-
-  M = ModuleOrErr.get().release();
+  M = MPtr.release();
 }
   }
 
@@ -105,14 +110,16 @@ int main(int argc, char **argv) {
 exit(1);
   }
 
+  if (TextualOut)
+M->print(Out->os(), nullptr, true);
+  else
 #if HAVE_LLVM >= 0x0700
-  WriteBitcodeToFile(*M, Out->os());
+WriteBitcodeToFile(*M, Out->os());
 #else
-  WriteBitcodeToFile(M, Out->os());
+WriteBitcodeToFile(M, Out->os());
 #endif
 
   // Declare success.
   Out->keep();
   return 0;
 }
-



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


[clang] 4d680f5 - [HIP][Clang][Sema] Add Sema support for `hipstdpar`

2023-10-03 Thread Alex Voicu via cfe-commits

Author: Alex Voicu
Date: 2023-10-03T13:29:12+01:00
New Revision: 4d680f56475ce17d8fb793655eb3d77ac8aee1b9

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

LOG: [HIP][Clang][Sema] Add Sema support for `hipstdpar`

This patch adds the Sema changes needed for enabling HIP parallel algorithm 
offload on AMDGPU targets. This change impacts the CUDA / HIP language specific 
checks, and only manifests if compiling in `hipstdpar` mode. In this case, we 
essentially do three things:

1. Allow device side callers to call host side callees - since the user visible 
HLL would be standard C++, with no annotations / restriction mechanisms, we 
cannot unambiguously establish that such a call is an error, so we 
conservatively allow all such calls, deferring actual cleanup to a subsequent 
pass over IR;
2. Allow host formed lambdas to capture by reference;
3. Allow device functions to use host global variables.

Reviewed by: yaxunl

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

Added: 
clang/test/SemaHipStdPar/device-can-call-host.cpp

Modified: 
clang/lib/Sema/SemaCUDA.cpp
clang/lib/Sema/SemaExpr.cpp
clang/lib/Sema/SemaStmtAsm.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaCUDA.cpp b/clang/lib/Sema/SemaCUDA.cpp
index 88f5484575db17a..3336dbf474df019 100644
--- a/clang/lib/Sema/SemaCUDA.cpp
+++ b/clang/lib/Sema/SemaCUDA.cpp
@@ -249,6 +249,15 @@ Sema::IdentifyCUDAPreference(const FunctionDecl *Caller,
   (CallerTarget == CFT_Global && CalleeTarget == CFT_Device))
 return CFP_Native;
 
+  // HipStdPar mode is special, in that assessing whether a device side call to
+  // a host target is deferred to a subsequent pass, and cannot unambiguously 
be
+  // adjudicated in the AST, hence we optimistically allow them to pass here.
+  if (getLangOpts().HIPStdPar &&
+  (CallerTarget == CFT_Global || CallerTarget == CFT_Device ||
+   CallerTarget == CFT_HostDevice) &&
+  CalleeTarget == CFT_Host)
+return CFP_HostDevice;
+
   // (d) HostDevice behavior depends on compilation mode.
   if (CallerTarget == CFT_HostDevice) {
 // It's OK to call a compilation-mode matching function from an HD one.
@@ -895,7 +904,7 @@ void Sema::CUDACheckLambdaCapture(CXXMethodDecl *Callee,
   if (!ShouldCheck || !Capture.isReferenceCapture())
 return;
   auto DiagKind = SemaDiagnosticBuilder::K_Deferred;
-  if (Capture.isVariableCapture()) {
+  if (Capture.isVariableCapture() && !getLangOpts().HIPStdPar) {
 SemaDiagnosticBuilder(DiagKind, Capture.getLocation(),
   diag::err_capture_bad_target, Callee, *this)
 << Capture.getVariable();

diff  --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index 2ed31a90c5dc1da..797b71bffbb451e 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -19157,7 +19157,7 @@ MarkVarDeclODRUsed(ValueDecl *V, SourceLocation Loc, 
Sema &SemaRef,
   // Diagnose ODR-use of host global variables in device functions.
   // Reference of device global variables in host functions is allowed
   // through shadow variables therefore it is not diagnosed.
-  if (SemaRef.LangOpts.CUDAIsDevice) {
+  if (SemaRef.LangOpts.CUDAIsDevice && !SemaRef.LangOpts.HIPStdPar) {
 SemaRef.targetDiag(Loc, diag::err_ref_bad_target)
 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget;
 SemaRef.targetDiag(Var->getLocation(),

diff  --git a/clang/lib/Sema/SemaStmtAsm.cpp b/clang/lib/Sema/SemaStmtAsm.cpp
index 2acb269f042399b..83351b703c1536c 100644
--- a/clang/lib/Sema/SemaStmtAsm.cpp
+++ b/clang/lib/Sema/SemaStmtAsm.cpp
@@ -271,7 +271,8 @@ StmtResult Sema::ActOnGCCAsmStmt(SourceLocation AsmLoc, 
bool IsSimple,
   OutputName = Names[i]->getName();
 
 TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName);
-if (!Context.getTargetInfo().validateOutputConstraint(Info)) {
+if (!Context.getTargetInfo().validateOutputConstraint(Info) &&
+!(LangOpts.HIPStdPar && LangOpts.CUDAIsDevice)) {
   targetDiag(Literal->getBeginLoc(),
  diag::err_asm_invalid_output_constraint)
   << Info.getConstraintStr();

diff  --git a/clang/test/SemaHipStdPar/device-can-call-host.cpp 
b/clang/test/SemaHipStdPar/device-can-call-host.cpp
new file mode 100644
index 000..3fedc179251d281
--- /dev/null
+++ b/clang/test/SemaHipStdPar/device-can-call-host.cpp
@@ -0,0 +1,93 @@
+// RUN: %clang_cc1 -x hip %s --hipstdpar -triple amdgcn-amd-amdhsa --std=c++17 
\
+// RUN:   -fcuda-is-device -emit-llvm -o /dev/null -verify
+
+// Note: These would happen implicitly, within the implementation of the
+//   accelerator specific algorithm library, and not from user code.
+
+// Calls from the accelerator side to implicitly host

[PATCH] D155833: [HIP][Clang][Sema][RFC] Add Sema support for C++ Parallel Algorithm Offload

2023-10-03 Thread Alex Voicu 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 rG4d680f56475c: [HIP][Clang][Sema] Add Sema support for 
`hipstdpar` (authored by AlexVlx).

Changed prior to commit:
  https://reviews.llvm.org/D155833?vs=552568&id=557559#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155833

Files:
  clang/lib/Sema/SemaCUDA.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaStmtAsm.cpp
  clang/test/SemaHipStdPar/device-can-call-host.cpp

Index: clang/test/SemaHipStdPar/device-can-call-host.cpp
===
--- /dev/null
+++ clang/test/SemaHipStdPar/device-can-call-host.cpp
@@ -0,0 +1,93 @@
+// RUN: %clang_cc1 -x hip %s --hipstdpar -triple amdgcn-amd-amdhsa --std=c++17 \
+// RUN:   -fcuda-is-device -emit-llvm -o /dev/null -verify
+
+// Note: These would happen implicitly, within the implementation of the
+//   accelerator specific algorithm library, and not from user code.
+
+// Calls from the accelerator side to implicitly host (i.e. unannotated)
+// functions are fine.
+
+// expected-no-diagnostics
+
+#define __device__ __attribute__((device))
+#define __global__ __attribute__((global))
+
+extern "C" void host_fn() {}
+
+struct Dummy {};
+
+struct S {
+  S() {}
+  ~S() { host_fn(); }
+
+  int x;
+};
+
+struct T {
+  __device__ void hd() { host_fn(); }
+
+  __device__ void hd3();
+
+  void h() {}
+
+  void operator+();
+  void operator-(const T&) {}
+
+  operator Dummy() { return Dummy(); }
+};
+
+__device__ void T::hd3() { host_fn(); }
+
+template  __device__ void hd2() { host_fn(); }
+
+__global__ void kernel() { hd2(); }
+
+__device__ void hd() { host_fn(); }
+
+template  __device__ void hd3() { host_fn(); }
+__device__ void device_fn() { hd3(); }
+
+__device__ void local_var() {
+  S s;
+}
+
+__device__ void explicit_destructor(S *s) {
+  s->~S();
+}
+
+__device__ void hd_member_fn() {
+  T t;
+
+  t.hd();
+}
+
+__device__ void h_member_fn() {
+  T t;
+  t.h();
+}
+
+__device__ void unaryOp() {
+  T t;
+  (void) +t;
+}
+
+__device__ void binaryOp() {
+  T t;
+  (void) (t - t);
+}
+
+__device__ void implicitConversion() {
+  T t;
+  Dummy d = t;
+}
+
+template 
+struct TmplStruct {
+  template  __device__ void fn() {}
+};
+
+template <>
+template <>
+__device__ void TmplStruct::fn() { host_fn(); }
+
+__device__ void double_specialization() { TmplStruct().fn(); }
Index: clang/lib/Sema/SemaStmtAsm.cpp
===
--- clang/lib/Sema/SemaStmtAsm.cpp
+++ clang/lib/Sema/SemaStmtAsm.cpp
@@ -271,7 +271,8 @@
   OutputName = Names[i]->getName();
 
 TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName);
-if (!Context.getTargetInfo().validateOutputConstraint(Info)) {
+if (!Context.getTargetInfo().validateOutputConstraint(Info) &&
+!(LangOpts.HIPStdPar && LangOpts.CUDAIsDevice)) {
   targetDiag(Literal->getBeginLoc(),
  diag::err_asm_invalid_output_constraint)
   << Info.getConstraintStr();
Index: clang/lib/Sema/SemaExpr.cpp
===
--- clang/lib/Sema/SemaExpr.cpp
+++ clang/lib/Sema/SemaExpr.cpp
@@ -19157,7 +19157,7 @@
   // Diagnose ODR-use of host global variables in device functions.
   // Reference of device global variables in host functions is allowed
   // through shadow variables therefore it is not diagnosed.
-  if (SemaRef.LangOpts.CUDAIsDevice) {
+  if (SemaRef.LangOpts.CUDAIsDevice && !SemaRef.LangOpts.HIPStdPar) {
 SemaRef.targetDiag(Loc, diag::err_ref_bad_target)
 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget;
 SemaRef.targetDiag(Var->getLocation(),
Index: clang/lib/Sema/SemaCUDA.cpp
===
--- clang/lib/Sema/SemaCUDA.cpp
+++ clang/lib/Sema/SemaCUDA.cpp
@@ -249,6 +249,15 @@
   (CallerTarget == CFT_Global && CalleeTarget == CFT_Device))
 return CFP_Native;
 
+  // HipStdPar mode is special, in that assessing whether a device side call to
+  // a host target is deferred to a subsequent pass, and cannot unambiguously be
+  // adjudicated in the AST, hence we optimistically allow them to pass here.
+  if (getLangOpts().HIPStdPar &&
+  (CallerTarget == CFT_Global || CallerTarget == CFT_Device ||
+   CallerTarget == CFT_HostDevice) &&
+  CalleeTarget == CFT_Host)
+return CFP_HostDevice;
+
   // (d) HostDevice behavior depends on compilation mode.
   if (CallerTarget == CFT_HostDevice) {
 // It's OK to call a compilation-mode matching function from an HD one.
@@ -895,7 +904,7 @@
   if (!ShouldCheck || !Capture.isReferenceCapture())
 return;
   auto DiagKind = SemaDiagnosticBuilder::K_Deferred;
-  if (Capture.isVariableCapture()) {
+  if (Capture.isVariableC

[clang-tools-extra] Bugfix for chosing the correct deduction guide (PR #66487)

2023-10-03 Thread Botond István Hprváth via cfe-commits

https://github.com/HoBoIs updated 
https://github.com/llvm/llvm-project/pull/66487

From 258462cc65403af147bb47cbeb95210df8e18cd3 Mon Sep 17 00:00:00 2001
From: hobois 
Date: Fri, 15 Sep 2023 09:28:21 +0200
Subject: [PATCH 1/2] Choose the correct deduction guide

If there are two guides, one of them generated from a non-templated constructor
and the other from a templated constructor, then the standard gives priority to
the first. Clang detected ambiguity before, now the correct guide is chosen.

As an unrelated minor change, fix the issue #64020, which could've led to
incorrect behavior if further development inserted code after a call to
isAddressSpaceSubsetOf() which specified the two parameters in the wrong order.
---
 clang/lib/Sema/SemaOverload.cpp | 17 -
 clang/lib/Sema/SemaTemplateInstantiateDecl.cpp  |  2 +-
 .../over.match.class.deduct/p2.cpp  | 10 ++
 3 files changed, 27 insertions(+), 2 deletions(-)

diff --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index 45a9e5dc98c032d..1bb81238520173a 100644
--- a/clang/lib/Sema/SemaOverload.cpp
+++ b/clang/lib/Sema/SemaOverload.cpp
@@ -10153,6 +10153,21 @@ bool clang::isBetterOverloadCandidate(
   //  -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
   if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy)
 return true;
+  if (Guide2->getDeductionCandidateKind() == DeductionCandidate::Copy)
+return false;
+
+  //  --F1 is generated from a non-template constructor and F2 is generated
+  //  from a constructor template
+  const auto *Constructor1 = Guide1->getCorrespondingConstructor();
+  const auto *Constructor2 = Guide2->getCorrespondingConstructor();
+  if (Constructor1 && Constructor2) {
+bool isC1Templated = Constructor1->getTemplatedKind() !=
+ FunctionDecl::TemplatedKind::TK_NonTemplate;
+bool isC2Templated = Constructor2->getTemplatedKind() !=
+ FunctionDecl::TemplatedKind::TK_NonTemplate;
+if (isC1Templated != isC2Templated)
+  return isC2Templated;
+  }
 }
   }
 
@@ -10196,7 +10211,7 @@ bool clang::isBetterOverloadCandidate(
 if (AS1 != AS2) {
   if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1))
 return true;
-  if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1))
+  if (Qualifiers::isAddressSpaceSupersetOf(AS1, AS2))
 return false;
 }
   }
diff --git a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp 
b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
index 9e5f85b0f9166bd..b9c4a9db842b9ee 100644
--- a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
@@ -2129,7 +2129,7 @@ Decl *TemplateDeclInstantiator::VisitFunctionDecl(
 Function = CXXDeductionGuideDecl::Create(
 SemaRef.Context, DC, D->getInnerLocStart(),
 InstantiatedExplicitSpecifier, NameInfo, T, TInfo,
-D->getSourceRange().getEnd(), /*Ctor=*/nullptr,
+D->getSourceRange().getEnd(), DGuide->getCorrespondingConstructor(),
 DGuide->getDeductionCandidateKind());
 Function->setAccess(D->getAccess());
   } else {
diff --git 
a/clang/test/CXX/over/over.match/over.match.funcs/over.match.class.deduct/p2.cpp
 
b/clang/test/CXX/over/over.match/over.match.funcs/over.match.class.deduct/p2.cpp
index 4eac0a1ac510f1d..d939d724dc7a0fd 100644
--- 
a/clang/test/CXX/over/over.match/over.match.funcs/over.match.class.deduct/p2.cpp
+++ 
b/clang/test/CXX/over/over.match/over.match.funcs/over.match.class.deduct/p2.cpp
@@ -85,3 +85,13 @@ int main() {
 
 
 }
+
+namespace deduceTemplatedConstructor{
+template  struct A {
+  A(T, T, int);
+  template
+A(int, T, U);
+};
+
+A x(1, 2, 3);   // no-error
+}

From 91af52e8d1519df1b3928b02efec9e8c0f324a71 Mon Sep 17 00:00:00 2001
From: hobois 
Date: Tue, 3 Oct 2023 14:22:24 +0200
Subject: [PATCH 2/2] Added the fix to relasenotes

---
 clang/docs/ReleaseNotes.rst | 3 +++
 1 file changed, 3 insertions(+)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 6be824771c583be..e0a412796f365be 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -282,6 +282,9 @@ Bug Fixes in This Version
   Fixes (`#67603 `_)
 - Fixes a crash caused by a multidimensional array being captured by a lambda
   (`#67722 `_).
+- Fixed a bug where clang couldn't choose the correct deduction guide from
+  two implicitly generated deduction guides. One of them generated from a
+  non-templated constructor and the other from a templated constructor.
 
 Bug Fixes to Compiler Builtins
 ^^

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


[clang] [clang][driver] Use platform specific calls to get the executable absolute path (PR #68091)

2023-10-03 Thread Vlad Serebrennikov via cfe-commits

Endilll wrote:

You have failed tests on Linux CI:
```
Failed Tests (4):
  Clang :: Driver/mingw-sysroot.cpp
  Clang :: Driver/no-canonical-prefixes.c
  Clang :: Driver/program-path-priority.c
  Clang :: Driver/rocm-detect.hip
```
Windows CI has another test in Clang interpreter failing, but that might be not 
related to you.
You should be able to reproduce those test failures with `clang --build . -t 
check-clang-driver` (or `ninja check-clang-driver`).

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


[clang] [clang-repl] Emit const variables only once (PR #65257)

2023-10-03 Thread Jonas Hahnfeld via cfe-commits

hahnjo wrote:

Note that this currently doesn't seem to work on Windows: 
https://github.com/llvm/llvm-project/issues/68092

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


[clang] 3e3cf77 - [HIP][Clang][Driver] Fix build failure introduced by https://reviews.llvm.org/rG9a408588d1b8b7899eff593c537de539a4a12651

2023-10-03 Thread Alex Voicu via cfe-commits

Author: Alex Voicu
Date: 2023-10-03T13:45:32+01:00
New Revision: 3e3cf77cbebab237b3f9379fc07d4b1af391f874

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

LOG: [HIP][Clang][Driver] Fix build failure introduced by 
https://reviews.llvm.org/rG9a408588d1b8b7899eff593c537de539a4a12651

Added: 
clang/test/Driver/Inputs/hipstdpar/rocprim/rocprim/.keep
clang/test/Driver/Inputs/hipstdpar/thrust/thrust/.keep

Modified: 


Removed: 




diff  --git a/clang/test/Driver/Inputs/hipstdpar/rocprim/rocprim/.keep 
b/clang/test/Driver/Inputs/hipstdpar/rocprim/rocprim/.keep
new file mode 100644
index 000..e69de29bb2d1d64

diff  --git a/clang/test/Driver/Inputs/hipstdpar/thrust/thrust/.keep 
b/clang/test/Driver/Inputs/hipstdpar/thrust/thrust/.keep
new file mode 100644
index 000..e69de29bb2d1d64



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


[clang] Add Documentation for Execution Results Handling in Clang-Repl (PR #65650)

2023-10-03 Thread Krishna Narayanan via cfe-commits

https://github.com/Krishna-13-cyber updated 
https://github.com/llvm/llvm-project/pull/65650

>From 145ff3877b588aebd811f26b6d596257ea889957 Mon Sep 17 00:00:00 2001
From: Krishna-13-cyber 
Date: Thu, 7 Sep 2023 22:35:53 +0530
Subject: [PATCH 1/2] Add Documentation for Execution Results Handling in
 Clang-Repl

---
 clang/docs/CMakeLists.txt |   7 +
 clang/docs/ClangRepl.rst  | 405 ++
 clang/docs/conf.py|   1 +
 3 files changed, 413 insertions(+)

diff --git a/clang/docs/CMakeLists.txt b/clang/docs/CMakeLists.txt
index 4163dd2d90ad5b3..356814f994c32cd 100644
--- a/clang/docs/CMakeLists.txt
+++ b/clang/docs/CMakeLists.txt
@@ -103,6 +103,13 @@ function (gen_rst_file_from_td output_file td_option 
source docs_targets)
 endfunction()
 
 if (LLVM_ENABLE_SPHINX)
+  llvm_find_program(dot)
+  if (HAVE_DOT)
+set(DOT ${LLVM_PATH_DOT})
+  else()
+message(FATAL_ERROR "Cannot find DOT")
+  endif()
+
   include(AddSphinxTarget)
   if (SPHINX_FOUND AND (${SPHINX_OUTPUT_HTML} OR ${SPHINX_OUTPUT_MAN}))
 # Copy rst files to build directory before generating the html
diff --git a/clang/docs/ClangRepl.rst b/clang/docs/ClangRepl.rst
index bd99bc82f17..47513dec18f04e7 100644
--- a/clang/docs/ClangRepl.rst
+++ b/clang/docs/ClangRepl.rst
@@ -213,6 +213,411 @@ concept helps support advanced use cases such as template 
instantiations on dema
 automatic language interoperability. It also helps static languages such as 
C/C++ become
 apt for data science.
 
+Execution Results Handling in Clang-Repl
+
+
+Execution Results Handling features discussed below help extend the Clang-Repl
+functionality by creating an interface between the execution results of a
+program and the compiled program.
+
+1. **Capture Execution Results**: This feature helps capture the execution 
results
+of a program and bring them back to the compiled program.
+
+2. **Dump Captured Execution Results**: This feature helps create a temporary 
dump
+for Value Printing/Automatic Printf, that is, to display the value and type of
+the captured data.
+
+
+1. Capture Execution Results
+
+
+In many cases, it is useful to bring back the program execution result to the
+compiled program. This result can be stored in an object of type **Value**.
+
+How Execution Results are captured (Value Synthesis):
+-
+
+The synthesizer chooses which expression to synthesize, and then it replaces
+the original expression with the synthesized expression. Depending on the
+expression type, it may choose to save an object (``LastValue``) of type 
'value'
+while allocating memory to it (``SetValueWithAlloc()``), or not (
+``SetValueNoAlloc()``).
+
+.. graphviz::
+:name: valuesynthesis
+:caption: Value Synthesis
+:alt: Shows how an object of type 'Value' is synthesized
+:align: center
+
+ digraph "valuesynthesis" {
+ rankdir="LR";
+ graph [fontname="Verdana", fontsize="12"];
+ node [fontname="Verdana", fontsize="12"];
+ edge [fontname="Sans", fontsize="9"];
+
+ start [label=" Create an Object \n 'Last Value' \n of type 'Value' ", 
shape="note", fontcolor=white, fillcolor="#ff", style=filled];
+ assign [label=" Assign the result \n to the 'LastValue' \n (based on 
respective \n Memory Allocation \n scenario) ", shape="box"]
+ print [label=" Pretty Print \n the Value Object ", shape="Msquare", 
fillcolor="yellow", style=filled];
+ start -> assign;
+ assign -> print;
+
+   subgraph SynthesizeExpression {
+ synth [label=" SynthesizeExpr() ", shape="note", fontcolor=white, 
fillcolor="#ff", style=filled];
+ mem [label=" New Memory \n Allocation? ", shape="diamond"];
+ withaloc [label=" SetValueWithAlloc() ", shape="box"];
+ noaloc [label=" SetValueNoAlloc() ", shape="box"];
+ right [label=" 1. RValue Structure \n (a temporary value)", 
shape="box"];
+ left2 [label=" 2. LValue Structure \n (a variable with \n an 
address)", shape="box"];
+ left3 [label=" 3. Built-In Type \n (int, float, etc.)", 
shape="box"];
+ output [label=" move to 'Assign' step ", shape="box"];
+
+ synth -> mem;
+ mem -> withaloc [label="Yes"];
+ mem -> noaloc [label="No"];
+ withaloc -> right;
+ noaloc -> left2;
+ noaloc -> left3;
+ right -> output;
+ left2 -> output;
+ left3 -> output;
+  }
+output -> assign
+  }
+
+Where is the captured result stored?
+
+
+``LastValue`` holds the last result of the value printing. It is a class member
+because it can be accessed even after subsequent inputs.
+
+**Note:** If no value printing happens, then it is in an invalid state.
+
+Improving Efficien

[PATCH] D158540: Improve error message for constexpr constructors of virtual base classes

2023-10-03 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/docs/ReleaseNotes.rst:211-212
   with terminals with dark background colors. This is also more consistent 
with GCC.
+- Clang now displays an improved diagnostic and a note when defaulted special 
+  member is a contexpr in a class with virtual base class
 

aaron.ballman wrote:
> 
It looks like these changes got missed.



Comment at: clang/test/CXX/dcl.dcl/dcl.spec/dcl.constexpr/p3.cpp:295
+};
\ No newline at end of file


Please add a newline back to the end of the file.


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

https://reviews.llvm.org/D158540

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


[clang] 0bb4b24 - [clang][AIX]Fix -flto-jobs for AIX. (#67853)

2023-10-03 Thread via cfe-commits

Author: Dhanrajbir-Hira
Date: 2023-10-03T09:18:21-04:00
New Revision: 0bb4b24ca35e1e67efc8ea2152085f981207210c

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

LOG: [clang][AIX]Fix -flto-jobs for AIX. (#67853)

Currently using the `-flto-jobs=N` option passes `-bplugin_opt:jobs=N`
to the AIX linker which is not a valid option. This PR seeks to change
this behaviour to instead pass `-bplugin_opt:-threads=N` to control the
level of concurrency during LTO builds.

Added: 


Modified: 
clang/lib/Driver/ToolChains/CommonArgs.cpp
clang/test/Driver/lto-jobs.c

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/CommonArgs.cpp 
b/clang/lib/Driver/ToolChains/CommonArgs.cpp
index 48170fa908fd62f..25fd940584624ee 100644
--- a/clang/lib/Driver/ToolChains/CommonArgs.cpp
+++ b/clang/lib/Driver/ToolChains/CommonArgs.cpp
@@ -631,6 +631,7 @@ void tools::addLTOOptions(const ToolChain &ToolChain, const 
ArgList &Args,
 
   const char *PluginOptPrefix = IsOSAIX ? "-bplugin_opt:" : "-plugin-opt=";
   const char *ExtraDash = IsOSAIX ? "-" : "";
+  const char *ParallelismOpt = IsOSAIX ? "-threads=" : "jobs=";
 
   // Note, this solution is far from perfect, better to encode it into IR
   // metadata, but this may not be worth it, since it looks like aranges is on
@@ -690,8 +691,8 @@ void tools::addLTOOptions(const ToolChain &ToolChain, const 
ArgList &Args,
 
   StringRef Parallelism = getLTOParallelism(Args, D);
   if (!Parallelism.empty())
-CmdArgs.push_back(
-Args.MakeArgString(Twine(PluginOptPrefix) + "jobs=" + Parallelism));
+CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) +
+ ParallelismOpt + Parallelism));
 
   // If an explicit debugger tuning argument appeared, pass it along.
   if (Arg *A =

diff  --git a/clang/test/Driver/lto-jobs.c b/clang/test/Driver/lto-jobs.c
index 73d7a94dd289cfa..43a478b0664d847 100644
--- a/clang/test/Driver/lto-jobs.c
+++ b/clang/test/Driver/lto-jobs.c
@@ -17,3 +17,8 @@
 // RUN: FileCheck -check-prefix=CHECK-LINK-THIN-JOBS2-ACTION < %t %s
 //
 // CHECK-LINK-THIN-JOBS2-ACTION: "-mllvm" "-threads={{[0-9]+}}"
+
+// RUN: %clang --target=powerpc-ibm-aix -### %s -flto=thin -flto-jobs=5 2> %t
+// RUN: FileCheck -check-prefix=CHECK-AIX-LINK-THIN-JOBS-ACTION < %t %s
+//
+// CHECK-AIX-LINK-THIN-JOBS-ACTION: "-bplugin_opt:-threads=5"



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


[clang] [clang][AIX]Fix -flto-jobs for AIX. (PR #67853)

2023-10-03 Thread Qiongsi Wu via cfe-commits

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


[clang] bc0c178 - [Clang][OpenMP][OMPIRBuilder] Move Clang's OpenMP Member/MemberOf flag helpers into the OMPIRBuilder (#67844)

2023-10-03 Thread via cfe-commits

Author: agozillon
Date: 2023-10-03T15:20:44+02:00
New Revision: bc0c1783fd5a4b0a2202ee9613cefd2c67d7

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

LOG: [Clang][OpenMP][OMPIRBuilder] Move Clang's OpenMP Member/MemberOf flag 
helpers into the OMPIRBuilder (#67844)

This patch seeks to move the following functions to the OMPIRBuilder:
 - getFlagMemberOffset
 - getMemberOfFlag
 - setCorrectMemberOfFlag

These small helper functions help set the end bits of the
OpenMPOffloadMappingFlags flag that correspond to the reserved segment
for OMP_MAP_MEMBER_OF.

They will be of use in the future for lowering MLIR types/values that
can contian members and can be lowered similarly to a structure or class
type within the OpenMPToLLVMIRTranslation step of the OpenMP dialects
lowering to LLVM-IR. In particular for Flang which currently uses this
flow. Types with descriptors like pointers/allocatables, and likely
derived types in certain cases can be lowered as if they were structures
with explicitly mapped members.

Added: 


Modified: 
clang/lib/CodeGen/CGOpenMPRuntime.cpp
llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGOpenMPRuntime.cpp 
b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
index 45ed7fe052dec26..aae1a0ea250eea2 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntime.cpp
+++ b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
@@ -7734,30 +7734,6 @@ class MappableExprsHandler {
OpenMPOffloadMappingFlags::OMP_MAP_FROM;
   }
 
-  static OpenMPOffloadMappingFlags getMemberOfFlag(unsigned Position) {
-// Rotate by getFlagMemberOffset() bits.
-return static_cast(((uint64_t)Position + 1)
-  << getFlagMemberOffset());
-  }
-
-  static void setCorrectMemberOfFlag(OpenMPOffloadMappingFlags &Flags,
- OpenMPOffloadMappingFlags MemberOfFlag) {
-// If the entry is PTR_AND_OBJ but has not been marked with the special
-// placeholder value 0x in the MEMBER_OF field, then it should not be
-// marked as MEMBER_OF.
-if (static_cast>(
-Flags & OpenMPOffloadMappingFlags::OMP_MAP_PTR_AND_OBJ) &&
-static_cast>(
-(Flags & OpenMPOffloadMappingFlags::OMP_MAP_MEMBER_OF) !=
-OpenMPOffloadMappingFlags::OMP_MAP_MEMBER_OF))
-  return;
-
-// Reset the placeholder value to prepare the flag for the assignment of 
the
-// proper MEMBER_OF value.
-Flags &= ~OpenMPOffloadMappingFlags::OMP_MAP_MEMBER_OF;
-Flags |= MemberOfFlag;
-  }
-
   void getPlainLayout(const CXXRecordDecl *RD,
   llvm::SmallVectorImpl &Layout,
   bool AsBase) const {
@@ -7825,6 +7801,7 @@ class MappableExprsHandler {
   /// the device pointers info array.
   void generateAllInfoForClauses(
   ArrayRef Clauses, MapCombinedInfoTy &CombinedInfo,
+  llvm::OpenMPIRBuilder &OMPBuilder,
   const llvm::DenseSet> &SkipVarSet =
   llvm::DenseSet>()) const {
 // We have to process the component lists that relate with the same
@@ -8159,7 +8136,7 @@ class MappableExprsHandler {
   if (PartialStruct.Base.isValid()) {
 CurInfo.NonContigInfo.Dims.push_back(0);
 emitCombinedEntry(CombinedInfo, CurInfo.Types, PartialStruct,
-  /*IsMapThis*/ !VD, VD);
+  /*IsMapThis*/ !VD, OMPBuilder, VD);
   }
 
   // We need to append the results of this capture to what we already
@@ -8226,6 +8203,7 @@ class MappableExprsHandler {
   void emitCombinedEntry(MapCombinedInfoTy &CombinedInfo,
  MapFlagsArrayTy &CurTypes,
  const StructRangeInfoTy &PartialStruct, bool 
IsMapThis,
+ llvm::OpenMPIRBuilder &OMPBuilder,
  const ValueDecl *VD = nullptr,
  bool NotTargetParams = true) const {
 if (CurTypes.size() == 1 &&
@@ -8313,9 +8291,9 @@ class MappableExprsHandler {
 // (except for PTR_AND_OBJ entries which do not have a placeholder value
 // 0x in the MEMBER_OF field).
 OpenMPOffloadMappingFlags MemberOfFlag =
-getMemberOfFlag(CombinedInfo.BasePointers.size() - 1);
+OMPBuilder.getMemberOfFlag(CombinedInfo.BasePointers.size() - 1);
 for (auto &M : CurTypes)
-  setCorrectMemberOfFlag(M, MemberOfFlag);
+  OMPBuilder.setCorrectMemberOfFlag(M, MemberOfFlag);
   }
 
   /// Generate all the base pointers, section pointers, sizes, map types, and
@@ -8324,23 +8302,26 @@ class MappableExprsHandler {
   /// pair of the relevant declaration and index where it occurs is appended to
   /// the device pointers info array.
   void generat

[clang] [Clang][OpenMP][OMPIRBuilder] Move Clang's OpenMP Member/MemberOf flag helpers into the OMPIRBuilder (PR #67844)

2023-10-03 Thread via cfe-commits

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


[clang] [Clang] Do not try to classify dependant call expression (PR #68078)

2023-10-03 Thread via cfe-commits

https://github.com/cor3ntin updated 
https://github.com/llvm/llvm-project/pull/68078

>From a14d189cfd513d4b2c8353fbab1a53927d2feaf5 Mon Sep 17 00:00:00 2001
From: Corentin Jabot 
Date: Tue, 3 Oct 2023 09:55:08 +0200
Subject: [PATCH 1/2] [Clang] Do not try to classify dependant call expression
 when the callee is an object.

When implementing deducing this, we changed
`DeduceTemplateArgumentsFromCallArgument` to take an argument
classification because we need to deduce the type of
argument for which we might not have an expression yet.

However classifying a dependent call expression whose
type is just some sort of record or elaborated type is not
supported.

We avoid that by adding a `DeduceTemplateArgumentsFromCallArgument`
that takes a `IsLvalue` boolean so that we don't have to call `Classify`.

The alternative might be to change `getCallReturnType` to support
callees with type is a record type.

Fixes #68024
---
 clang/lib/Sema/SemaTemplateDeduction.cpp  | 58 +--
 .../SemaTemplate/temp_arg_nontype_cxx1z.cpp   | 12 
 2 files changed, 51 insertions(+), 19 deletions(-)

diff --git a/clang/lib/Sema/SemaTemplateDeduction.cpp 
b/clang/lib/Sema/SemaTemplateDeduction.cpp
index 69b857d3510dc63..53975068751e128 100644
--- a/clang/lib/Sema/SemaTemplateDeduction.cpp
+++ b/clang/lib/Sema/SemaTemplateDeduction.cpp
@@ -3877,9 +3877,8 @@ ResolveOverloadForDeduction(Sema &S, 
TemplateParameterList *TemplateParams,
 /// overloaded function set that could not be resolved.
 static bool AdjustFunctionParmAndArgTypesForDeduction(
 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
-QualType &ParamType, QualType &ArgType,
-Expr::Classification ArgClassification, Expr *Arg, unsigned &TDF,
-TemplateSpecCandidateSet *FailedTSC = nullptr) {
+QualType &ParamType, QualType &ArgType, bool IsLValue, Expr *Arg,
+unsigned &TDF, TemplateSpecCandidateSet *FailedTSC = nullptr) {
   // C++0x [temp.deduct.call]p3:
   //   If P is a cv-qualified type, the top level cv-qualifiers of P's type
   //   are ignored for type deduction.
@@ -3914,7 +3913,7 @@ static bool AdjustFunctionParmAndArgTypesForDeduction(
 //   If P is a forwarding reference and the argument is an lvalue, the type
 //   "lvalue reference to A" is used in place of A for type deduction.
 if (isForwardingReference(QualType(ParamRefType, 0), FirstInnerIndex) &&
-ArgClassification.isLValue()) {
+IsLValue) {
   if (S.getLangOpts().OpenCL && !ArgType.hasAddressSpace())
 ArgType = S.Context.getAddrSpaceQualType(
 ArgType, S.Context.getDefaultOpenCLPointeeAddrSpace());
@@ -3973,6 +3972,15 @@ static bool
 hasDeducibleTemplateParameters(Sema &S, FunctionTemplateDecl *FunctionTemplate,
QualType T);
 
+static Sema::TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument(
+Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
+QualType ParamType, QualType ArgType, bool IsLValue, Expr *Arg,
+TemplateDeductionInfo &Info,
+SmallVectorImpl &Deduced,
+SmallVectorImpl &OriginalCallArgs,
+bool DecomposedParam, unsigned ArgIdx, unsigned TDF,
+TemplateSpecCandidateSet *FailedTSC = nullptr);
+
 static Sema::TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument(
 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
 QualType ParamType, QualType ArgType,
@@ -4022,9 +4030,8 @@ static Sema::TemplateDeductionResult 
DeduceFromInitializerList(
   if (ElTy->isDependentType()) {
 for (Expr *E : ILE->inits()) {
   if (auto Result = DeduceTemplateArgumentsFromCallArgument(
-  S, TemplateParams, 0, ElTy, E->getType(),
-  E->Classify(S.getASTContext()), E, Info, Deduced,
-  OriginalCallArgs, true, ArgIdx, TDF))
+  S, TemplateParams, 0, ElTy, E->getType(), E->isLValue(), E, Info,
+  Deduced, OriginalCallArgs, true, ArgIdx, TDF))
 return Result;
 }
   }
@@ -4055,8 +4062,7 @@ static Sema::TemplateDeductionResult 
DeduceFromInitializerList(
 ///single parameter / argument pair.
 static Sema::TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument(
 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
-QualType ParamType, QualType ArgType,
-Expr::Classification ArgClassification, Expr *Arg,
+QualType ParamType, QualType ArgType, bool IsLValue, Expr *Arg,
 TemplateDeductionInfo &Info,
 SmallVectorImpl &Deduced,
 SmallVectorImpl &OriginalCallArgs,
@@ -4068,8 +4074,8 @@ static Sema::TemplateDeductionResult 
DeduceTemplateArgumentsFromCallArgument(
   //   If P is a reference type [...]
   //   If P is a cv-qualified type [...]
   if (AdjustFunctionParmAndArgTypesForDeduction(
-  S, TemplateParams, FirstInnerIndex, ParamType, ArgType,
-  ArgClassification, Arg, TDF, FailedTSC))
+  S, TemplateParams, First

[PATCH] D148381: [Clang] Implement the 'counted_by' attribute

2023-10-03 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/lib/Sema/SemaDeclAttr.cpp:8420-8428
+if (Result.getResultKind() == LookupResult::Found) {
+  SourceRange SR = CBA->getCountedByFieldLoc();
+  Diag(SR.getBegin(),
+   diag::err_flexible_array_counted_by_attr_field_not_found_in_struct)
+  << CBA->getCountedByField() << SR;
+
+  SR = Result.getAsSingle()->getSourceRange();

void wrote:
> aaron.ballman wrote:
> > The logic here still seems incorrect. I was expecting the code to look more 
> > like this:
> > ```
> > bool Sema::CheckCountedByAttr(Scope *S, const FieldDecl *FD) {
> >   const RecordDecl *RD = FD->getParent();
> >   const auto *CBA = FD->getAttr();
> >   const IdentifierInfo *FieldName = CBA->getCountedByField();
> >   DeclarationNameInfo NameInfo(FieldName,
> >CBA->getCountedByFieldLoc().getBegin());
> >   LookupResult Result(*this, NameInfo, Sema::LookupMemberName);
> > 
> >   LookupName(Result, S);
> >   if (Result.empty()) {
> > CXXScopeSpec SS;
> > DeclFilterCCC Filter(const_cast > *>(FieldName));
> > if (DiagnoseEmptyLookup(S, SS, Result, Filter, nullptr, std::nullopt,
> > const_cast > *>(FD->getDeclContext(
> >   return true;
> >   }
> > 
> >   const FieldDecl *Field = Result.getAsSingle();
> >   LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel =
> >   Context.getLangOpts().getStrictFlexArraysLevel();
> >   ...
> > ```
> > I tested this locally on code like:
> > ```
> > struct not_a_fam {
> >   int foo;
> >   int fam[] __attribute__((counted_by(fob)));
> > };
> > ```
> > and get a diagnostic like: 
> > ```
> > C:\Users\aballman\OneDrive - Intel Corporation\Desktop\test.c:3:39: error: 
> > use of undeclared identifier 'fob'; did you
> >   mean 'foo'?
> > 3 |   int fam[] __attribute__((counted_by(fob)));
> >   |   ^~~
> >   |   foo
> > C:\Users\aballman\OneDrive - Intel Corporation\Desktop\test.c:2:7: note: 
> > 'foo' declared here
> > 2 |   int foo;
> >   |   ^
> > 1 error generated.
> > ```
> > Note, I had to add a constructor to `DeclFilterCCC` to expose the base 
> > class constructor, and modify `DiagnoseEmptyLookup()` like this:
> > ```
> > diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
> > index 2ed31a90c5dc..3c4ade391a5e 100644
> > --- a/clang/lib/Sema/SemaExpr.cpp
> > +++ b/clang/lib/Sema/SemaExpr.cpp
> > @@ -2458,7 +2458,8 @@ bool Sema::DiagnoseDependentMemberLookup(const 
> > LookupResult &R) {
> >  bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
> > CorrectionCandidateCallback &CCC,
> > TemplateArgumentListInfo 
> > *ExplicitTemplateArgs,
> > -   ArrayRef Args, TypoExpr **Out) {
> > +   ArrayRef Args, DeclContext 
> > *LookupCtx,
> > +   TypoExpr **Out) {
> >DeclarationName Name = R.getLookupName();
> > 
> >unsigned diagnostic = diag::err_undeclared_var_use;
> > @@ -2474,7 +2475,9 @@ bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec 
> > &SS, LookupResult &R,
> >// unqualified lookup.  This is useful when (for example) the
> >// original lookup would not have found something because it was a
> >// dependent name.
> > -  DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
> > +  DeclContext *DC =
> > +  LookupCtx ? LookupCtx : (SS.isEmpty() ? CurContext : nullptr);
> > +  DeclContext *OrigLookupCtx = DC;
> >while (DC) {
> >  if (isa(DC)) {
> >LookupQualifiedName(R, DC);
> > @@ -2517,12 +2520,12 @@ bool Sema::DiagnoseEmptyLookup(Scope *S, 
> > CXXScopeSpec &SS, LookupResult &R,
> >emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
> >  diagnostic, diagnostic_suggest);
> >  },
> > -nullptr, CTK_ErrorRecovery);
> > +nullptr, CTK_ErrorRecovery, OrigLookupCtx);
> >  if (*Out)
> >return true;
> > -  } else if (S &&
> > - (Corrected = CorrectTypo(R.getLookupNameInfo(), 
> > R.getLookupKind(),
> > -  S, &SS, CCC, CTK_ErrorRecovery))) {
> > +  } else if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(),
> > +   R.getLookupKind(), S, &SS, CCC,
> > +   CTK_ErrorRecovery, 
> > OrigLookupCtx))) {
> >  std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
> >  bool DroppedSpecifier =
> >  Corrected.WillReplaceSpecifier() && Name.getAsString() == 
> > CorrectedStr;
> > @@ -2812,7 +2815,7 @@ Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
> >  // a template name, but we happen to have always already looked up the 
> > name
> > 

[clang] [clang-format] Fix alignment in presence of template functions (PR #68029)

2023-10-03 Thread Björn Schäpers via cfe-commits

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


  1   2   3   4   5   >