[clang] [clang][Interp] Support AddOffset with 128bit offsets (PR #68679)

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

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

>From 5fff64e74c885472abcd2a320d6db9005cc7c4fd Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Tue, 10 Oct 2023 08:52:43 +0200
Subject: [PATCH] [clang][Interp] Support AddOffset with 128bit offsets

---
 clang/lib/AST/Interp/Integral.h   |  3 +++
 clang/lib/AST/Interp/IntegralAP.h |  3 +++
 clang/lib/AST/Interp/Interp.h |  4 ++--
 clang/lib/AST/Interp/Opcodes.td   | 13 +
 clang/test/AST/Interp/intap.cpp   |  9 +
 5 files changed, 26 insertions(+), 6 deletions(-)

diff --git a/clang/lib/AST/Interp/Integral.h b/clang/lib/AST/Interp/Integral.h
index 4dbe9c9bcb14b43..cc1cab8f39fb1e5 100644
--- a/clang/lib/AST/Interp/Integral.h
+++ b/clang/lib/AST/Interp/Integral.h
@@ -88,6 +88,9 @@ template  class Integral final {
   }
 
   Integral operator-() const { return Integral(-V); }
+  Integral operator-(const Integral &Other) const {
+return Integral(V - Other.V);
+  }
   Integral operator~() const { return Integral(~V); }
 
   template 
diff --git a/clang/lib/AST/Interp/IntegralAP.h 
b/clang/lib/AST/Interp/IntegralAP.h
index a8df431bef11784..f7e69da5689df4e 100644
--- a/clang/lib/AST/Interp/IntegralAP.h
+++ b/clang/lib/AST/Interp/IntegralAP.h
@@ -55,6 +55,9 @@ template  class IntegralAP final {
   IntegralAP() : V(APSInt::getMaxValue(1024, Signed)) {}
 
   IntegralAP operator-() const { return IntegralAP(-V); }
+  IntegralAP operator-(const IntegralAP &Other) const {
+return IntegralAP(V - Other.V);
+  }
   bool operator>(IntegralAP RHS) const { return V > RHS.V; }
   bool operator>=(IntegralAP RHS) const { return V >= RHS.V; }
   bool operator<(IntegralAP RHS) const { return V < RHS.V; }
diff --git a/clang/lib/AST/Interp/Interp.h b/clang/lib/AST/Interp/Interp.h
index 47dc1d08c9c4d8b..b730ed9fcc445a4 100644
--- a/clang/lib/AST/Interp/Interp.h
+++ b/clang/lib/AST/Interp/Interp.h
@@ -1421,7 +1421,7 @@ bool OffsetHelper(InterpState &S, CodePtr OpPC, const T 
&Offset,
   // Get a version of the index comparable to the type.
   T Index = T::from(Ptr.getIndex(), Offset.bitWidth());
   // Compute the largest index into the array.
-  unsigned MaxIndex = Ptr.getNumElems();
+  T MaxIndex = T::from(Ptr.getNumElems(), Offset.bitWidth());
 
   // Helper to report an invalid offset, computed as APSInt.
   auto InvalidOffset = [&]() {
@@ -1437,7 +1437,7 @@ bool OffsetHelper(InterpState &S, CodePtr OpPC, const T 
&Offset,
 return false;
   };
 
-  unsigned MaxOffset = MaxIndex - Ptr.getIndex();
+  T MaxOffset = T::from(MaxIndex - Index, Offset.bitWidth());
   if constexpr (Op == ArithOp::Add) {
 // If the new offset would be negative, bail out.
 if (Offset.isNegative() && (Offset.isMin() || -Offset > Index))
diff --git a/clang/lib/AST/Interp/Opcodes.td b/clang/lib/AST/Interp/Opcodes.td
index 50b6c0ac154de30..54f0a2bc43a845a 100644
--- a/clang/lib/AST/Interp/Opcodes.td
+++ b/clang/lib/AST/Interp/Opcodes.td
@@ -128,6 +128,11 @@ class AluOpcode : Opcode {
   let HasGroup = 1;
 }
 
+class OffsetOpcode : Opcode {
+  let Types = [IntegerTypeClass];
+  let HasGroup = 1;
+}
+
 class FloatOpcode : Opcode {
   let Types = [];
   let Args = [ArgRoundingMode];
@@ -338,8 +343,8 @@ def NarrowPtr : Opcode;
 // [Pointer] -> [Pointer]
 def ExpandPtr : Opcode;
 // [Pointer, Offset] -> [Pointer]
-def ArrayElemPtr : AluOpcode;
-def ArrayElemPtrPop : AluOpcode;
+def ArrayElemPtr : OffsetOpcode;
+def ArrayElemPtrPop : OffsetOpcode;
 
 
//===--===//
 // Direct field accessors
@@ -465,9 +470,9 @@ def InitElemPop : Opcode {
 
//===--===//
 
 // [Pointer, Integral] -> [Pointer]
-def AddOffset : AluOpcode;
+def AddOffset : OffsetOpcode;
 // [Pointer, Integral] -> [Pointer]
-def SubOffset : AluOpcode;
+def SubOffset : OffsetOpcode;
 
 // [Pointer, Pointer] -> [Integral]
 def SubPtr : Opcode {
diff --git a/clang/test/AST/Interp/intap.cpp b/clang/test/AST/Interp/intap.cpp
index b3f02d2b769531d..e9e68438bb597aa 100644
--- a/clang/test/AST/Interp/intap.cpp
+++ b/clang/test/AST/Interp/intap.cpp
@@ -76,6 +76,15 @@ namespace i128 {
// expected-note {{is outside the 
range of representable values of type}}
 }
 
+namespace AddSubOffset {
+  constexpr __int128 A = 1;
+  constexpr int arr[] = {1,2,3};
+  constexpr const int *P = arr + A;
+  static_assert(*P == 2, "");
+  constexpr const int *P2 = P - A;
+  static_assert(*P2 == 1,"");
+}
+
 #else
 /// No int128 support, so no expected directives.
 

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


[clang] [Clang] Check features of tune CPU against target CPU (PR #68861)

2023-10-12 Thread Qiu Chaofan via cfe-commits

https://github.com/ecnelises created 
https://github.com/llvm/llvm-project/pull/68861

Tune CPU relies on model of instruction sets. Compiler should warn if not all 
instruction sets of current target CPU are supported by tune CPU. Although 
there is limitation that Clang cannot analyze actual required features of a 
function.

This is enabled to PowerPC only, because feature lists of targets are complex.

>From 04d3c01ca7bb645191d8355dacb6e22daa6d3287 Mon Sep 17 00:00:00 2001
From: Qiu Chaofan 
Date: Thu, 12 Oct 2023 15:47:17 +0800
Subject: [PATCH] [Clang] Check features of tune CPU against target CPU

Tune CPU relies on model of instruction sets. Compiler should warn if
not all instruction sets of current target CPU are supported by tune
CPU. Although there is limitation that Clang cannot analyze actual
required features of a function.

This is enabled to PowerPC only, because feature lists of targets are
complex.
---
 .../clang/Basic/DiagnosticFrontendKinds.td   |  3 +++
 clang/include/clang/Basic/TargetInfo.h   |  6 ++
 clang/lib/Basic/Targets.cpp  | 16 
 clang/lib/Basic/Targets/PPC.h|  8 
 clang/test/Frontend/tune-cpu-features.c  |  8 
 5 files changed, 41 insertions(+)
 create mode 100644 clang/test/Frontend/tune-cpu-features.c

diff --git a/clang/include/clang/Basic/DiagnosticFrontendKinds.td 
b/clang/include/clang/Basic/DiagnosticFrontendKinds.td
index 715e0c0dc8fa84e..4adc433ac11b9f9 100644
--- a/clang/include/clang/Basic/DiagnosticFrontendKinds.td
+++ b/clang/include/clang/Basic/DiagnosticFrontendKinds.td
@@ -278,6 +278,9 @@ def err_builtin_needs_feature : Error<"%0 needs target 
feature %1">;
 def err_function_needs_feature : Error<
   "always_inline function %1 requires target feature '%2', but would "
   "be inlined into function %0 that is compiled without support for '%2'">;
+def warn_tune_cpu_feature_unavailable : Warning<
+  "instructions of current target may not be supported by tune CPU '%0'">,
+  InGroup;
 
 def warn_avx_calling_convention
 : Warning<"AVX vector %select{return|argument}0 of type %1 without '%2' "
diff --git a/clang/include/clang/Basic/TargetInfo.h 
b/clang/include/clang/Basic/TargetInfo.h
index 9d56e97a3d4bb88..b941b2201b84e1c 100644
--- a/clang/include/clang/Basic/TargetInfo.h
+++ b/clang/include/clang/Basic/TargetInfo.h
@@ -976,6 +976,12 @@ class TargetInfo : public TransferrableTargetInfo,
   /// with this target.
   virtual BuiltinVaListKind getBuiltinVaListKind() const = 0;
 
+  /// Return whether a feature matters for tune CPU. If true, present in
+  /// current target but missing in tune CPU triggers a warning.
+  virtual bool isFeatureConsumedByTuneCPU(StringRef Feature) const {
+return false;
+  }
+
   /// Returns whether or not type \c __builtin_ms_va_list type is
   /// available on this target.
   bool hasBuiltinMSVaList() const { return HasBuiltinMSVaList; }
diff --git a/clang/lib/Basic/Targets.cpp b/clang/lib/Basic/Targets.cpp
index 8130f90a276749e..d73535f53af3bf6 100644
--- a/clang/lib/Basic/Targets.cpp
+++ b/clang/lib/Basic/Targets.cpp
@@ -833,6 +833,22 @@ TargetInfo::CreateTargetInfo(DiagnosticsEngine &Diags,
   if (!Target->handleTargetFeatures(Opts->Features, Diags))
 return nullptr;
 
+  // If TuneCPU is set, check if it contains all instruction sets needed by
+  // current feature map.
+  if (!Opts->TuneCPU.empty() && Opts->TuneCPU != Opts->CPU) {
+llvm::StringMap TuneFeatureMap;
+Target->initFeatureMap(TuneFeatureMap, Diags, Opts->TuneCPU, {});
+if (std::any_of(Opts->FeatureMap.begin(), Opts->FeatureMap.end(),
+[&](const llvm::StringMapEntry &F) {
+  return F.getValue() &&
+ Target->isFeatureConsumedByTuneCPU(F.getKey()) &&
+ (!TuneFeatureMap.contains(F.getKey()) ||
+  !TuneFeatureMap[F.getKey()]);
+})) {
+  Diags.Report(diag::warn_tune_cpu_feature_unavailable) << Opts->TuneCPU;
+}
+  }
+
   Target->setSupportedOpenCLOpts();
   Target->setCommandLineOpenCLOpts();
   Target->setMaxAtomicWidth();
diff --git a/clang/lib/Basic/Targets/PPC.h b/clang/lib/Basic/Targets/PPC.h
index 4d62673ba7fb8c5..3f95708f695b096 100644
--- a/clang/lib/Basic/Targets/PPC.h
+++ b/clang/lib/Basic/Targets/PPC.h
@@ -187,6 +187,14 @@ class LLVM_LIBRARY_VISIBILITY PPCTargetInfo : public 
TargetInfo {
  StringRef CPU,
  const std::vector &FeaturesVec) const override;
 
+  bool isFeatureConsumedByTuneCPU(StringRef Feature) const override {
+// FIXME: Ignore htm to avoid unnecessary warning on cpu=pwr8/tune=pwr10,
+// once clang can analyze function features with granularity, remove it.
+return Feature != "aix-small-local-exec-tls" && Feature != "rop-protect" &&
+   Feature != "pcrelative-memops" && Feature != "quadword-atomics" &&
+   Feature != "htm";

[clang] [Clang] Check features of tune CPU against target CPU (PR #68861)

2023-10-12 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Qiu Chaofan (ecnelises)


Changes

Tune CPU relies on model of instruction sets. Compiler should warn if not all 
instruction sets of current target CPU are supported by tune CPU. Although 
there is limitation that Clang cannot analyze actual required features of a 
function.

This is enabled to PowerPC only, because feature lists of targets are complex.

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


5 Files Affected:

- (modified) clang/include/clang/Basic/DiagnosticFrontendKinds.td (+3) 
- (modified) clang/include/clang/Basic/TargetInfo.h (+6) 
- (modified) clang/lib/Basic/Targets.cpp (+16) 
- (modified) clang/lib/Basic/Targets/PPC.h (+8) 
- (added) clang/test/Frontend/tune-cpu-features.c (+8) 


``diff
diff --git a/clang/include/clang/Basic/DiagnosticFrontendKinds.td 
b/clang/include/clang/Basic/DiagnosticFrontendKinds.td
index 715e0c0dc8fa84e..4adc433ac11b9f9 100644
--- a/clang/include/clang/Basic/DiagnosticFrontendKinds.td
+++ b/clang/include/clang/Basic/DiagnosticFrontendKinds.td
@@ -278,6 +278,9 @@ def err_builtin_needs_feature : Error<"%0 needs target 
feature %1">;
 def err_function_needs_feature : Error<
   "always_inline function %1 requires target feature '%2', but would "
   "be inlined into function %0 that is compiled without support for '%2'">;
+def warn_tune_cpu_feature_unavailable : Warning<
+  "instructions of current target may not be supported by tune CPU '%0'">,
+  InGroup;
 
 def warn_avx_calling_convention
 : Warning<"AVX vector %select{return|argument}0 of type %1 without '%2' "
diff --git a/clang/include/clang/Basic/TargetInfo.h 
b/clang/include/clang/Basic/TargetInfo.h
index 9d56e97a3d4bb88..b941b2201b84e1c 100644
--- a/clang/include/clang/Basic/TargetInfo.h
+++ b/clang/include/clang/Basic/TargetInfo.h
@@ -976,6 +976,12 @@ class TargetInfo : public TransferrableTargetInfo,
   /// with this target.
   virtual BuiltinVaListKind getBuiltinVaListKind() const = 0;
 
+  /// Return whether a feature matters for tune CPU. If true, present in
+  /// current target but missing in tune CPU triggers a warning.
+  virtual bool isFeatureConsumedByTuneCPU(StringRef Feature) const {
+return false;
+  }
+
   /// Returns whether or not type \c __builtin_ms_va_list type is
   /// available on this target.
   bool hasBuiltinMSVaList() const { return HasBuiltinMSVaList; }
diff --git a/clang/lib/Basic/Targets.cpp b/clang/lib/Basic/Targets.cpp
index 8130f90a276749e..d73535f53af3bf6 100644
--- a/clang/lib/Basic/Targets.cpp
+++ b/clang/lib/Basic/Targets.cpp
@@ -833,6 +833,22 @@ TargetInfo::CreateTargetInfo(DiagnosticsEngine &Diags,
   if (!Target->handleTargetFeatures(Opts->Features, Diags))
 return nullptr;
 
+  // If TuneCPU is set, check if it contains all instruction sets needed by
+  // current feature map.
+  if (!Opts->TuneCPU.empty() && Opts->TuneCPU != Opts->CPU) {
+llvm::StringMap TuneFeatureMap;
+Target->initFeatureMap(TuneFeatureMap, Diags, Opts->TuneCPU, {});
+if (std::any_of(Opts->FeatureMap.begin(), Opts->FeatureMap.end(),
+[&](const llvm::StringMapEntry &F) {
+  return F.getValue() &&
+ Target->isFeatureConsumedByTuneCPU(F.getKey()) &&
+ (!TuneFeatureMap.contains(F.getKey()) ||
+  !TuneFeatureMap[F.getKey()]);
+})) {
+  Diags.Report(diag::warn_tune_cpu_feature_unavailable) << Opts->TuneCPU;
+}
+  }
+
   Target->setSupportedOpenCLOpts();
   Target->setCommandLineOpenCLOpts();
   Target->setMaxAtomicWidth();
diff --git a/clang/lib/Basic/Targets/PPC.h b/clang/lib/Basic/Targets/PPC.h
index 4d62673ba7fb8c5..3f95708f695b096 100644
--- a/clang/lib/Basic/Targets/PPC.h
+++ b/clang/lib/Basic/Targets/PPC.h
@@ -187,6 +187,14 @@ class LLVM_LIBRARY_VISIBILITY PPCTargetInfo : public 
TargetInfo {
  StringRef CPU,
  const std::vector &FeaturesVec) const override;
 
+  bool isFeatureConsumedByTuneCPU(StringRef Feature) const override {
+// FIXME: Ignore htm to avoid unnecessary warning on cpu=pwr8/tune=pwr10,
+// once clang can analyze function features with granularity, remove it.
+return Feature != "aix-small-local-exec-tls" && Feature != "rop-protect" &&
+   Feature != "pcrelative-memops" && Feature != "quadword-atomics" &&
+   Feature != "htm";
+  }
+
   void addP10SpecificFeatures(llvm::StringMap &Features) const;
   void addFutureSpecificFeatures(llvm::StringMap &Features) const;
 
diff --git a/clang/test/Frontend/tune-cpu-features.c 
b/clang/test/Frontend/tune-cpu-features.c
new file mode 100644
index 000..df0fe7f94a09cf4
--- /dev/null
+++ b/clang/test/Frontend/tune-cpu-features.c
@@ -0,0 +1,8 @@
+// RUN: %clang_cc1 -triple powerpc64le-unknown-linux-gnu -target-cpu pwr10 
-tune-cpu pwr8 %s 2>&1 | FileCheck --check-prefix=P8 %s
+// RUN: %clang_cc1 -triple powerpc64le-un

[clang-tools-extra] Clean up strange uses of getAnalysisIfAvailable (PR #65729)

2023-10-12 Thread Björn Pettersson via cfe-commits

bjope wrote:

> > I guess I don't know how pull requests and reviewing works in github. I 
> > actually added 3 comments on this patch a several days (or weeks) ago. But 
> > turns out that they were "pending" because I had only "started review" and 
> > not found the place to "submit review".
> 
> For that reason I usually click "add single comment" instead of "start a 
> review".

Thanks. I'll try to remember that.

If they for example had named the buttons "Post comment directly" and "Save as 
draft", then it has been more obvious.
I also do not know how to find all my pending "draft reviews" (unless I'm 
already "assigned" or "requested as reviewer") as the https://github.com/pulls 
is just crap compared to my old dashboard in phabricator.

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


[clang] [TSAN] add support for riscv64 (PR #68735)

2023-10-12 Thread Alex Fan via cfe-commits

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


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


[clang] LoongArch fp16,fp128 basic support (PR #68851)

2023-10-12 Thread WÁNG Xuěruì via cfe-commits

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


[clang] LoongArch fp16,fp128 basic support (PR #68851)

2023-10-12 Thread WÁNG Xuěruì via cfe-commits


@@ -214,6 +214,13 @@ LoongArchTargetLowering::LoongArchTargetLowering(const 
TargetMachine &TM,
   setOperationAction(ISD::FRINT, MVT::f64, Legal);
   }
 
+  setOperationAction(ISD::FP16_TO_FP,MVT::f32,   Expand);
+  setOperationAction(ISD::FP_TO_FP16,MVT::f32,   Expand);

xen0n wrote:

Please shrink those whitespaces; I believe that's what triggered the style 
checker. (After the transition away from Phabricator/Arcanist workflow, you 
have to set up your own auto-formatting and/or pre-commit linting hooks.)

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


[clang] LoongArch fp16,fp128 basic support (PR #68851)

2023-10-12 Thread WÁNG Xuěruì via cfe-commits

https://github.com/xen0n commented:

Thanks for the contribution and welcome!

As for the commit message, please take a look at the existing commits for the 
general feel. (For example, people typically prefix the commit title with the 
involved topic(s) in brackets, and use a verb phrase for the remaining.)

Besides, the LLVM side of the change lacks a test case; you can look at the 
other targets for reference.

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


[clang-tools-extra] [InstCombine] Canonicalize `(X +/- Y) & Y` into `~X & Y` when Y is a power of 2 (PR #67915)

2023-10-12 Thread Nikita Popov via cfe-commits

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

LGTM

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


[clang] [InstCombine] Canonicalize `(X +/- Y) & Y` into `~X & Y` when Y is a power of 2 (PR #67915)

2023-10-12 Thread Nikita Popov via cfe-commits

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

LGTM

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


[clang-tools-extra] [InstCombine] Canonicalize `(X +/- Y) & Y` into `~X & Y` when Y is a power of 2 (PR #67915)

2023-10-12 Thread Yingwei Zheng via cfe-commits

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


[clang] Draft:[clang][ASTImporter] Fix crash when template class static member imported to other translation unit. (PR #68774)

2023-10-12 Thread via cfe-commits

https://github.com/mzyKi updated https://github.com/llvm/llvm-project/pull/68774

>From ad651d68e6ac161da4e521cc0bebd6d59a5f38cb Mon Sep 17 00:00:00 2001
From: miaozhiyuan 
Date: Wed, 11 Oct 2023 15:45:36 +0800
Subject: [PATCH] [clang][ASTImporter] Fix crash when template class static
 member imported to other translation unit. Fixes: #68769

---
 clang/docs/ReleaseNotes.rst   |  4 
 clang/lib/AST/ASTImporter.cpp | 11 +++
 .../Inputs/externalDefMap.txt |  1 +
 .../Inputs/template-class-static-member.cpp   |  3 +++
 .../Inputs/template-class-static-member.h |  7 +++
 .../ctu/template-class-static-member/main.cpp | 19 +++
 6 files changed, 45 insertions(+)
 create mode 100644 
clang/test/Analysis/ctu/template-class-static-member/Inputs/externalDefMap.txt
 create mode 100644 
clang/test/Analysis/ctu/template-class-static-member/Inputs/template-class-static-member.cpp
 create mode 100644 
clang/test/Analysis/ctu/template-class-static-member/Inputs/template-class-static-member.h
 create mode 100644 
clang/test/Analysis/ctu/template-class-static-member/main.cpp

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 2d918967e7f0b02..3be9e60c82a18d0 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -497,6 +497,10 @@ Bug Fixes to C++ Support
   rather than prefer the non-templated constructor as specified in
   [standard.group]p3.
 
+- Fix crash when template class static member imported to other translation 
unit.
+  Fixes:
+  (`#68769 `_)
+
 Bug Fixes to AST Handling
 ^
 - Fixed an import failure of recursive friend class template.
diff --git a/clang/lib/AST/ASTImporter.cpp b/clang/lib/AST/ASTImporter.cpp
index 72e70427161bb0e..2a8add84f55dc3b 100644
--- a/clang/lib/AST/ASTImporter.cpp
+++ b/clang/lib/AST/ASTImporter.cpp
@@ -4475,6 +4475,17 @@ ExpectedDecl ASTNodeImporter::VisitVarDecl(VarDecl *D) {
 auto ToVTOrErr = import(D->getDescribedVarTemplate());
 if (!ToVTOrErr)
   return ToVTOrErr.takeError();
+  } else if (MemberSpecializationInfo *MSI = D->getMemberSpecializationInfo()) 
{
+TemplateSpecializationKind SK = MSI->getTemplateSpecializationKind();
+VarDecl *FromInst = D->getInstantiatedFromStaticDataMember();
+if (Expected ToInstOrErr = import(FromInst))
+  ToVar->setInstantiationOfStaticDataMember(*ToInstOrErr, SK);
+else
+  return ToInstOrErr.takeError();
+if (ExpectedSLoc POIOrErr = import(MSI->getPointOfInstantiation()))
+  ToVar->getMemberSpecializationInfo()->setPointOfInstantiation(*POIOrErr);
+else
+  return POIOrErr.takeError();
   }
 
   if (Error Err = ImportInitializer(D, ToVar))
diff --git 
a/clang/test/Analysis/ctu/template-class-static-member/Inputs/externalDefMap.txt
 
b/clang/test/Analysis/ctu/template-class-static-member/Inputs/externalDefMap.txt
new file mode 100644
index 000..2cc394701d12e1d
--- /dev/null
+++ 
b/clang/test/Analysis/ctu/template-class-static-member/Inputs/externalDefMap.txt
@@ -0,0 +1 @@
+19:c:@S@Test>#I@length template-class-static-member.cpp.ast
diff --git 
a/clang/test/Analysis/ctu/template-class-static-member/Inputs/template-class-static-member.cpp
 
b/clang/test/Analysis/ctu/template-class-static-member/Inputs/template-class-static-member.cpp
new file mode 100644
index 000..489aa41aec70452
--- /dev/null
+++ 
b/clang/test/Analysis/ctu/template-class-static-member/Inputs/template-class-static-member.cpp
@@ -0,0 +1,3 @@
+#include "template-class-static-member.h"
+
+template<> const unsigned int Test::length = 0;
diff --git 
a/clang/test/Analysis/ctu/template-class-static-member/Inputs/template-class-static-member.h
 
b/clang/test/Analysis/ctu/template-class-static-member/Inputs/template-class-static-member.h
new file mode 100644
index 000..f31d05728594a9a
--- /dev/null
+++ 
b/clang/test/Analysis/ctu/template-class-static-member/Inputs/template-class-static-member.h
@@ -0,0 +1,7 @@
+template  class Test
+{
+public:
+   static const unsigned int length;
+};
+
+template<> const unsigned int Test::length;
diff --git a/clang/test/Analysis/ctu/template-class-static-member/main.cpp 
b/clang/test/Analysis/ctu/template-class-static-member/main.cpp
new file mode 100644
index 000..6138c43ffcd4e07
--- /dev/null
+++ b/clang/test/Analysis/ctu/template-class-static-member/main.cpp
@@ -0,0 +1,19 @@
+// RUN: rm -rf %t && mkdir %t
+// RUN: mkdir -p %t/ctudir
+// RUN: %clang_cc1 -std=c++14 -triple x86_64-pc-linux-gnu \
+// RUN: -emit-pch -o %t/ctudir/template-class-static-member.cpp.ast 
%p/Inputs/template-class-static-member.cpp
+// RUN: cp %p/Inputs/externalDefMap.txt %t/ctudir/externalDefMap.txt
+// RUN: %clang_analyze_cc1 -triple x86_64-pc-linux-gnu \
+// RUN: -analyzer-checker=core.DivideZero \
+// RUN: -analyzer-config experimental-enable-naive-ctu-analysis=true \
+// RUN:

[clang] Draft:[clang][ASTImporter] Fix crash when template class static member imported to other translation unit. (PR #68774)

2023-10-12 Thread via cfe-commits

https://github.com/mzyKi edited https://github.com/llvm/llvm-project/pull/68774
___
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 template class static member imported to other translation unit. (PR #68774)

2023-10-12 Thread via cfe-commits

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


[clang] ac0015f - [flang][driver] add command line arguments for alias tags pass

2023-10-12 Thread Tom Eccles via cfe-commits

Author: Tom Eccles
Date: 2023-10-12T09:37:58Z
New Revision: ac0015fe21110700fb5e7e9f89b377e80fc843dd

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

LOG: [flang][driver] add command line arguments for alias tags pass

The ultimate intention is to have this pass enabled by default whenever
we are optimizing for speed. But for now, just add the arguments so this
can be more easily tested.

PR: https://github.com/llvm/llvm-project/pull/68595

Added: 
flang/test/Driver/falias-analysis.f90

Modified: 
clang/include/clang/Driver/Options.td
clang/lib/Driver/ToolChains/Flang.cpp
flang/include/flang/Frontend/CodeGenOptions.def
flang/include/flang/Optimizer/CodeGen/CodeGen.h
flang/include/flang/Optimizer/CodeGen/TypeConverter.h
flang/include/flang/Tools/CLOptions.inc
flang/include/flang/Tools/CrossToolHelpers.h
flang/lib/Frontend/CompilerInvocation.cpp
flang/lib/Optimizer/CodeGen/CodeGen.cpp
flang/lib/Optimizer/CodeGen/TypeConverter.cpp
flang/test/Driver/driver-help-hidden.f90
flang/test/Driver/driver-help.f90
flang/test/Fir/tbaa-codegen.fir

Removed: 




diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index c272a7f1c398aa6..3f2058a5d4650ca 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -6264,6 +6264,9 @@ defm stack_arrays : BoolOptionWithoutMarshalling<"f", 
"stack-arrays",
 defm loop_versioning : BoolOptionWithoutMarshalling<"f", 
"version-loops-for-stride",
   PosFlag,
NegFlag>;
+defm alias_analysis : BoolOptionWithoutMarshalling<"f", "alias-analysis",
+  PosFlag,
+  NegFlag>;
 } // let Visibility = [FC1Option, FlangOption]
 
 def J : JoinedOrSeparate<["-"], "J">,

diff  --git a/clang/lib/Driver/ToolChains/Flang.cpp 
b/clang/lib/Driver/ToolChains/Flang.cpp
index c5bc572bef03458..999039f83ddfb92 100644
--- a/clang/lib/Driver/ToolChains/Flang.cpp
+++ b/clang/lib/Driver/ToolChains/Flang.cpp
@@ -145,7 +145,9 @@ void Flang::addCodegenOptions(const ArgList &Args,
   Args.addAllArgs(CmdArgs, {options::OPT_flang_experimental_hlfir,
 options::OPT_flang_experimental_polymorphism,
 options::OPT_fno_ppc_native_vec_elem_order,
-options::OPT_fppc_native_vec_elem_order});
+options::OPT_fppc_native_vec_elem_order,
+options::OPT_falias_analysis,
+options::OPT_fno_alias_analysis});
 }
 
 void Flang::addPicOptions(const ArgList &Args, ArgStringList &CmdArgs) const {

diff  --git a/flang/include/flang/Frontend/CodeGenOptions.def 
b/flang/include/flang/Frontend/CodeGenOptions.def
index c3a04108aa081c7..1e350869f1377e3 100644
--- a/flang/include/flang/Frontend/CodeGenOptions.def
+++ b/flang/include/flang/Frontend/CodeGenOptions.def
@@ -32,6 +32,7 @@ CODEGENOPT(PrepareForThinLTO , 1, 0) ///< Set when -flto=thin 
is enabled on the
  ///< compile step.
 CODEGENOPT(StackArrays, 1, 0) ///< -fstack-arrays (enable the stack-arrays 
pass)
 CODEGENOPT(LoopVersioning, 1, 0) ///< Enable loop versioning.
+CODEGENOPT(AliasAnalysis, 1, 0) ///< Enable alias analysis pass
 
 CODEGENOPT(Underscoring, 1, 1)
 ENUM_CODEGENOPT(RelocationModel, llvm::Reloc::Model, 3, llvm::Reloc::PIC_) 
///< Name of the relocation model to use.

diff  --git a/flang/include/flang/Optimizer/CodeGen/CodeGen.h 
b/flang/include/flang/Optimizer/CodeGen/CodeGen.h
index 64747b871de0943..7d8e548d89a18b5 100644
--- a/flang/include/flang/Optimizer/CodeGen/CodeGen.h
+++ b/flang/include/flang/Optimizer/CodeGen/CodeGen.h
@@ -54,6 +54,9 @@ struct FIRToLLVMPassOptions {
 
   // Generate TBAA information for FIR types and memory accessing operations.
   bool applyTBAA = false;
+
+  // Force the usage of a unified tbaa tree in TBAABuilder.
+  bool forceUnifiedTBAATree = false;
 };
 
 /// Convert FIR to the LLVM IR dialect with default options.

diff  --git a/flang/include/flang/Optimizer/CodeGen/TypeConverter.h 
b/flang/include/flang/Optimizer/CodeGen/TypeConverter.h
index 5b8b51b5a30bc8c..29d0a902f556269 100644
--- a/flang/include/flang/Optimizer/CodeGen/TypeConverter.h
+++ b/flang/include/flang/Optimizer/CodeGen/TypeConverter.h
@@ -45,7 +45,8 @@ namespace fir {
 /// This converts FIR types to LLVM types (for now)
 class LLVMTypeConverter : public mlir::LLVMTypeConverter {
 public:
-  LLVMTypeConverter(mlir::ModuleOp module, bool applyTBAA);
+  LLVMTypeConverter(mlir::ModuleOp module, bool applyTBAA,
+bool forceUnifiedTBAATree);
 
   // i32 is used here because LLVM wants i32 constants when indexing into 
struct
   // types. Indexing into other aggregate types is more flexible.

diff  --git a/

[clang] [flang] Add flags controlling whether to run the fir alias tags pass (PR #68595)

2023-10-12 Thread Tom Eccles via cfe-commits

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


[clang] [flang] Add flags controlling whether to run the fir alias tags pass (PR #68595)

2023-10-12 Thread Tom Eccles via cfe-commits

tblah wrote:

Merged manually with ac0015fe21110700fb5e7e9f89b377e80fc843dd

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


[clang] [clang][Interp] Handle unknown-size arrays better (PR #68868)

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

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

We unfortunately actually need to do some checks for array-to-pointer decays it 
seems.

>From 4947d93ac3487941c83728725c219bb23f884cce Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Thu, 12 Oct 2023 11:50:16 +0200
Subject: [PATCH] [clang][Interp] Handle unknown-size arrays better

We unfortunately actually need to do some checks for array-to-pointer
decays it seems.
---
 clang/lib/AST/Interp/ByteCodeExprGen.cpp | 14 +++-
 clang/lib/AST/Interp/EvalEmitter.cpp |  6 
 clang/lib/AST/Interp/Interp.cpp  |  2 ++
 clang/lib/AST/Interp/Interp.h| 20 +++
 clang/lib/AST/Interp/Opcodes.td  |  2 ++
 clang/test/AST/Interp/arrays.cpp | 45 
 6 files changed, 88 insertions(+), 1 deletion(-)

diff --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index 2b745d6a1509868..da4e4a58207cfce 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -162,7 +162,16 @@ bool ByteCodeExprGen::VisitCastExpr(const 
CastExpr *CE) {
 return this->emitCastPointerIntegral(T, CE);
   }
 
-  case CK_ArrayToPointerDecay:
+  case CK_ArrayToPointerDecay: {
+if (!this->visit(SubExpr))
+  return false;
+if (!this->emitArrayDecay(CE))
+  return false;
+if (DiscardResult)
+  return this->emitPopPtr(CE);
+return true;
+  }
+
   case CK_AtomicToNonAtomic:
   case CK_ConstructorConversion:
   case CK_FunctionToPointerDecay:
@@ -499,6 +508,9 @@ bool 
ByteCodeExprGen::VisitImplicitValueInitExpr(const ImplicitValueIni
   if (QT->isRecordType())
 return false;
 
+  if (QT->isIncompleteArrayType())
+return true;
+
   if (QT->isArrayType()) {
 const ArrayType *AT = QT->getAsArrayTypeUnsafe();
 assert(AT);
diff --git a/clang/lib/AST/Interp/EvalEmitter.cpp 
b/clang/lib/AST/Interp/EvalEmitter.cpp
index f46ef1067cf52a0..466327e2c7c7b86 100644
--- a/clang/lib/AST/Interp/EvalEmitter.cpp
+++ b/clang/lib/AST/Interp/EvalEmitter.cpp
@@ -177,6 +177,12 @@ bool EvalEmitter::emitRetValue(const SourceInfo &Info) {
   }
   return Ok;
 }
+
+if (Ty->isIncompleteArrayType()) {
+  R = APValue(APValue::UninitArray(), 0, 0);
+  return true;
+}
+
 if (const auto *AT = Ty->getAsArrayTypeUnsafe()) {
   const size_t NumElems = Ptr.getNumElems();
   QualType ElemTy = AT->getElementType();
diff --git a/clang/lib/AST/Interp/Interp.cpp b/clang/lib/AST/Interp/Interp.cpp
index a4d6844ebe61722..41edbfe0da3f381 100644
--- a/clang/lib/AST/Interp/Interp.cpp
+++ b/clang/lib/AST/Interp/Interp.cpp
@@ -454,6 +454,8 @@ static bool CheckFieldsInitialized(InterpState &S, CodePtr 
OpPC,
 
 if (FieldType->isRecordType()) {
   Result &= CheckFieldsInitialized(S, OpPC, FieldPtr, 
FieldPtr.getRecord());
+} else if (FieldType->isIncompleteArrayType()) {
+  // Nothing to do here.
 } else if (FieldType->isArrayType()) {
   const auto *CAT =
   cast(FieldType->getAsArrayTypeUnsafe());
diff --git a/clang/lib/AST/Interp/Interp.h b/clang/lib/AST/Interp/Interp.h
index 1ad3b8bfc7711d3..bf285e2701814ca 100644
--- a/clang/lib/AST/Interp/Interp.h
+++ b/clang/lib/AST/Interp/Interp.h
@@ -1797,17 +1797,37 @@ inline bool ArrayElemPtr(InterpState &S, CodePtr OpPC) {
   const T &Offset = S.Stk.pop();
   const Pointer &Ptr = S.Stk.peek();
 
+  if (!CheckArray(S, OpPC, Ptr))
+return false;
+
   if (!OffsetHelper(S, OpPC, Offset, Ptr))
 return false;
 
   return NarrowPtr(S, OpPC);
 }
 
+/// Just takes a pointer and checks if its' an incomplete
+/// array type.
+inline bool ArrayDecay(InterpState &S, CodePtr OpPC) {
+  const Pointer &Ptr = S.Stk.peek();
+
+  if (!Ptr.isUnknownSizeArray())
+return true;
+
+  const SourceInfo &E = S.Current->getSource(OpPC);
+  S.FFDiag(E, diag::note_constexpr_unsupported_unsized_array);
+
+  return false;
+}
+
 template ::T>
 inline bool ArrayElemPtrPop(InterpState &S, CodePtr OpPC) {
   const T &Offset = S.Stk.pop();
   const Pointer &Ptr = S.Stk.pop();
 
+  if (!CheckArray(S, OpPC, Ptr))
+return false;
+
   if (!OffsetHelper(S, OpPC, Offset, Ptr))
 return false;
 
diff --git a/clang/lib/AST/Interp/Opcodes.td b/clang/lib/AST/Interp/Opcodes.td
index 9d390fed152417f..29c83e7ba9efc64 100644
--- a/clang/lib/AST/Interp/Opcodes.td
+++ b/clang/lib/AST/Interp/Opcodes.td
@@ -674,3 +674,5 @@ def InvalidCast : Opcode {
 def InvalidDeclRef : Opcode {
   let Args = [ArgDeclRef];
 }
+
+def ArrayDecay : Opcode;
diff --git a/clang/test/AST/Interp/arrays.cpp b/clang/test/AST/Interp/arrays.cpp
index 281835f828bbd7c..919e3407d3afa05 100644
--- a/clang/test/AST/Interp/arrays.cpp
+++ b/clang/test/AST/Interp/arrays.cpp
@@ -390,3 +390,48 @@ namespace StringZeroFill {
   static_assert(b[4] == '\0', "");
   static_assert(b[5] == '\0', "");
 }
+
+namespace Incomplete {
+  struct Foo {
+char c;
+int a[]

[clang] [clang][Interp] Handle unknown-size arrays better (PR #68868)

2023-10-12 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Timm Baeder (tbaederr)


Changes

We unfortunately actually need to do some checks for array-to-pointer decays it 
seems.

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


6 Files Affected:

- (modified) clang/lib/AST/Interp/ByteCodeExprGen.cpp (+13-1) 
- (modified) clang/lib/AST/Interp/EvalEmitter.cpp (+6) 
- (modified) clang/lib/AST/Interp/Interp.cpp (+2) 
- (modified) clang/lib/AST/Interp/Interp.h (+20) 
- (modified) clang/lib/AST/Interp/Opcodes.td (+2) 
- (modified) clang/test/AST/Interp/arrays.cpp (+45) 


``diff
diff --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index 2b745d6a1509868..da4e4a58207cfce 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -162,7 +162,16 @@ bool ByteCodeExprGen::VisitCastExpr(const 
CastExpr *CE) {
 return this->emitCastPointerIntegral(T, CE);
   }
 
-  case CK_ArrayToPointerDecay:
+  case CK_ArrayToPointerDecay: {
+if (!this->visit(SubExpr))
+  return false;
+if (!this->emitArrayDecay(CE))
+  return false;
+if (DiscardResult)
+  return this->emitPopPtr(CE);
+return true;
+  }
+
   case CK_AtomicToNonAtomic:
   case CK_ConstructorConversion:
   case CK_FunctionToPointerDecay:
@@ -499,6 +508,9 @@ bool 
ByteCodeExprGen::VisitImplicitValueInitExpr(const ImplicitValueIni
   if (QT->isRecordType())
 return false;
 
+  if (QT->isIncompleteArrayType())
+return true;
+
   if (QT->isArrayType()) {
 const ArrayType *AT = QT->getAsArrayTypeUnsafe();
 assert(AT);
diff --git a/clang/lib/AST/Interp/EvalEmitter.cpp 
b/clang/lib/AST/Interp/EvalEmitter.cpp
index f46ef1067cf52a0..466327e2c7c7b86 100644
--- a/clang/lib/AST/Interp/EvalEmitter.cpp
+++ b/clang/lib/AST/Interp/EvalEmitter.cpp
@@ -177,6 +177,12 @@ bool EvalEmitter::emitRetValue(const SourceInfo &Info) {
   }
   return Ok;
 }
+
+if (Ty->isIncompleteArrayType()) {
+  R = APValue(APValue::UninitArray(), 0, 0);
+  return true;
+}
+
 if (const auto *AT = Ty->getAsArrayTypeUnsafe()) {
   const size_t NumElems = Ptr.getNumElems();
   QualType ElemTy = AT->getElementType();
diff --git a/clang/lib/AST/Interp/Interp.cpp b/clang/lib/AST/Interp/Interp.cpp
index a4d6844ebe61722..41edbfe0da3f381 100644
--- a/clang/lib/AST/Interp/Interp.cpp
+++ b/clang/lib/AST/Interp/Interp.cpp
@@ -454,6 +454,8 @@ static bool CheckFieldsInitialized(InterpState &S, CodePtr 
OpPC,
 
 if (FieldType->isRecordType()) {
   Result &= CheckFieldsInitialized(S, OpPC, FieldPtr, 
FieldPtr.getRecord());
+} else if (FieldType->isIncompleteArrayType()) {
+  // Nothing to do here.
 } else if (FieldType->isArrayType()) {
   const auto *CAT =
   cast(FieldType->getAsArrayTypeUnsafe());
diff --git a/clang/lib/AST/Interp/Interp.h b/clang/lib/AST/Interp/Interp.h
index 1ad3b8bfc7711d3..bf285e2701814ca 100644
--- a/clang/lib/AST/Interp/Interp.h
+++ b/clang/lib/AST/Interp/Interp.h
@@ -1797,17 +1797,37 @@ inline bool ArrayElemPtr(InterpState &S, CodePtr OpPC) {
   const T &Offset = S.Stk.pop();
   const Pointer &Ptr = S.Stk.peek();
 
+  if (!CheckArray(S, OpPC, Ptr))
+return false;
+
   if (!OffsetHelper(S, OpPC, Offset, Ptr))
 return false;
 
   return NarrowPtr(S, OpPC);
 }
 
+/// Just takes a pointer and checks if its' an incomplete
+/// array type.
+inline bool ArrayDecay(InterpState &S, CodePtr OpPC) {
+  const Pointer &Ptr = S.Stk.peek();
+
+  if (!Ptr.isUnknownSizeArray())
+return true;
+
+  const SourceInfo &E = S.Current->getSource(OpPC);
+  S.FFDiag(E, diag::note_constexpr_unsupported_unsized_array);
+
+  return false;
+}
+
 template ::T>
 inline bool ArrayElemPtrPop(InterpState &S, CodePtr OpPC) {
   const T &Offset = S.Stk.pop();
   const Pointer &Ptr = S.Stk.pop();
 
+  if (!CheckArray(S, OpPC, Ptr))
+return false;
+
   if (!OffsetHelper(S, OpPC, Offset, Ptr))
 return false;
 
diff --git a/clang/lib/AST/Interp/Opcodes.td b/clang/lib/AST/Interp/Opcodes.td
index 9d390fed152417f..29c83e7ba9efc64 100644
--- a/clang/lib/AST/Interp/Opcodes.td
+++ b/clang/lib/AST/Interp/Opcodes.td
@@ -674,3 +674,5 @@ def InvalidCast : Opcode {
 def InvalidDeclRef : Opcode {
   let Args = [ArgDeclRef];
 }
+
+def ArrayDecay : Opcode;
diff --git a/clang/test/AST/Interp/arrays.cpp b/clang/test/AST/Interp/arrays.cpp
index 281835f828bbd7c..919e3407d3afa05 100644
--- a/clang/test/AST/Interp/arrays.cpp
+++ b/clang/test/AST/Interp/arrays.cpp
@@ -390,3 +390,48 @@ namespace StringZeroFill {
   static_assert(b[4] == '\0', "");
   static_assert(b[5] == '\0', "");
 }
+
+namespace Incomplete {
+  struct Foo {
+char c;
+int a[];
+  };
+
+  constexpr Foo F{};
+  constexpr const int *A = F.a; // ref-error {{must be initialized by a 
constant expression}} \
+// ref-note {{array-to-pointer decay of array 
member without known bound}} \
+ 

[clang] [AMDGPU] Change the representation of double literals in operands (PR #68740)

2023-10-12 Thread Stanislav Mekhanoshin via cfe-commits

https://github.com/rampitec updated 
https://github.com/llvm/llvm-project/pull/68740

>From cc9e065a9218eb36750a2c2a4a4d08fae3f329fa Mon Sep 17 00:00:00 2001
From: Stanislav Mekhanoshin 
Date: Wed, 4 Oct 2023 13:36:25 -0700
Subject: [PATCH 1/3] [AMDGPU] Change the representation of double literals in
 operands

A 64-bit literal can be used as a 32-bit zero or sign extended
operand. In case of double zeroes are added to the low 32 bits.
Currently asm parser stores only high 32 bits of a double into
an operand. To support codegen as requested by the
https://github.com/llvm/llvm-project/issues/67781 we need to
change the representation to store a full 64-bit value so that
codegen can simply add immediates to an instruction.

There is some code to support compatibility with existing tests
and asm kernels. We allow to use short hex strings to represent
only a high 32 bit of a double value as a valid literal.
---
 .../AMDGPU/AsmParser/AMDGPUAsmParser.cpp  | 21 --
 .../Disassembler/AMDGPUDisassembler.cpp   | 28 ++-
 .../AMDGPU/Disassembler/AMDGPUDisassembler.h  |  9 --
 .../AMDGPU/MCTargetDesc/AMDGPUInstPrinter.cpp | 12 +---
 .../AMDGPU/MCTargetDesc/AMDGPUInstPrinter.h   |  2 +-
 .../MCTargetDesc/AMDGPUMCCodeEmitter.cpp  |  3 ++
 llvm/lib/Target/AMDGPU/SIRegisterInfo.td  |  4 ++-
 .../Target/AMDGPU/Utils/AMDGPUBaseInfo.cpp|  7 +
 llvm/lib/Target/AMDGPU/Utils/AMDGPUBaseInfo.h |  3 ++
 9 files changed, 70 insertions(+), 19 deletions(-)

diff --git a/llvm/lib/Target/AMDGPU/AsmParser/AMDGPUAsmParser.cpp 
b/llvm/lib/Target/AMDGPU/AsmParser/AMDGPUAsmParser.cpp
index 35656bcaea1af7f..0553d3f20b21c56 100644
--- a/llvm/lib/Target/AMDGPU/AsmParser/AMDGPUAsmParser.cpp
+++ b/llvm/lib/Target/AMDGPU/AsmParser/AMDGPUAsmParser.cpp
@@ -2140,9 +2140,10 @@ void AMDGPUOperand::addLiteralImmOperand(MCInst &Inst, 
int64_t Val, bool ApplyMo
   const_cast(AsmParser)->Warning(Inst.getLoc(),
   "Can't encode literal as exact 64-bit floating-point operand. "
   "Low 32-bits will be set to zero");
+  Val &= 0xu;
 }
 
-Inst.addOperand(MCOperand::createImm(Literal.lshr(32).getZExtValue()));
+Inst.addOperand(MCOperand::createImm(Val));
 setImmKindLiteral();
 return;
   }
@@ -2241,7 +2242,10 @@ void AMDGPUOperand::addLiteralImmOperand(MCInst &Inst, 
int64_t Val, bool ApplyMo
   return;
 }
 
-Inst.addOperand(MCOperand::createImm(Lo_32(Val)));
+if (isInt<32>(Val) || isUInt<32>(Val))
+  Val = AMDGPU::isSISrcFPOperand(InstDesc, OpNum) ? Val << 32 : Lo_32(Val);
+
+Inst.addOperand(MCOperand::createImm(Val));
 setImmKindLiteral();
 return;
 
@@ -4297,7 +4301,18 @@ bool AMDGPUAsmParser::validateVOPLiteral(const MCInst 
&Inst,
   continue;
 
 if (MO.isImm() && !isInlineConstant(Inst, OpIdx)) {
-  uint32_t Value = static_cast(MO.getImm());
+  uint64_t Value = static_cast(MO.getImm());
+  bool IsFP = AMDGPU::isSISrcFPOperand(Desc, OpIdx);
+  bool IsValid32Op = AMDGPU::isValid32BitLiteral(Value, IsFP);
+
+  if (!IsValid32Op && !isInt<32>(Value) && !isUInt<32>(Value)) {
+Error(getLitLoc(Operands), "invalid operand for instruction");
+return false;
+  }
+
+  if (IsFP && IsValid32Op)
+Value = Hi_32(Value);
+
   if (NumLiterals == 0 || LiteralValue != Value) {
 LiteralValue = Value;
 ++NumLiterals;
diff --git a/llvm/lib/Target/AMDGPU/Disassembler/AMDGPUDisassembler.cpp 
b/llvm/lib/Target/AMDGPU/Disassembler/AMDGPUDisassembler.cpp
index 439762bc6caf786..8c49c9a9c87772e 100644
--- a/llvm/lib/Target/AMDGPU/Disassembler/AMDGPUDisassembler.cpp
+++ b/llvm/lib/Target/AMDGPU/Disassembler/AMDGPUDisassembler.cpp
@@ -378,6 +378,15 @@ static DecodeStatus decodeOperand_AVLdSt_Any(MCInst &Inst, 
unsigned Imm,
   return addOperand(Inst, DAsm->decodeSrcOp(Opw, Imm | 256));
 }
 
+static DecodeStatus
+decodeOperand_VSrc_f64(MCInst &Inst, unsigned Imm, uint64_t Addr,
+   const MCDisassembler *Decoder) {
+  assert(Imm < (1 << 9) && "9-bit encoding");
+  auto DAsm = static_cast(Decoder);
+  return addOperand(Inst, DAsm->decodeSrcOp(AMDGPUDisassembler::OPW64, Imm,
+false, 64, true));
+}
+
 static DecodeStatus
 DecodeAVLdSt_32RegisterClass(MCInst &Inst, unsigned Imm, uint64_t Addr,
  const MCDisassembler *Decoder) {
@@ -1218,7 +1227,7 @@ 
AMDGPUDisassembler::decodeMandatoryLiteralConstant(unsigned Val) const {
   return MCOperand::createImm(Literal);
 }
 
-MCOperand AMDGPUDisassembler::decodeLiteralConstant() const {
+MCOperand AMDGPUDisassembler::decodeLiteralConstant(bool ExtendFP64) const {
   // For now all literal constants are supposed to be unsigned integer
   // ToDo: deal with signed/unsigned 64-bit integer constants
   // ToDo: deal with float/double constants
@@ -1228,9 +1237,11 @@ MCOperand AMDGPUDisassembler::decodeLite

[clang] [AMDGPU] Change the representation of double literals in operands (PR #68740)

2023-10-12 Thread Stanislav Mekhanoshin via cfe-commits


@@ -2241,7 +2242,10 @@ void AMDGPUOperand::addLiteralImmOperand(MCInst &Inst, 
int64_t Val, bool ApplyMo
   return;
 }
 
-Inst.addOperand(MCOperand::createImm(Lo_32(Val)));
+if (isInt<32>(Val) || isUInt<32>(Val))
+  Val = AMDGPU::isSISrcFPOperand(InstDesc, OpNum) ? Val << 32 : Lo_32(Val);

rampitec wrote:

> I still find the Int/UInt check confusing here. How about:

Done.

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


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

2023-10-12 Thread via cfe-commits

https://github.com/xbjfk updated https://github.com/llvm/llvm-project/pull/68690

>From 92899d94e91a6812de8fa5ec7c15c37a81280108 Mon Sep 17 00:00:00 2001
From: Reagan Bohan 
Date: Tue, 10 Oct 2023 11:32:47 +
Subject: [PATCH 1/2] [clang] Add /Zc:__STDC__ flag to clang-cl

This commit adds the /Zc:__STDC__ argument from MSVC, which defines __STDC__.
This means, alongside stronger feature parity with MSVC,
that things that rely on __STDC__, such as autoconf, can work.
---
 clang/include/clang/Basic/LangOptions.def |  2 +-
 clang/include/clang/Driver/Options.td |  7 +++
 clang/lib/Driver/ToolChains/Clang.cpp | 10 +-
 clang/lib/Frontend/InitPreprocessor.cpp   |  3 ++-
 clang/test/Driver/cl-zc.cpp   |  4 
 5 files changed, 23 insertions(+), 3 deletions(-)

diff --git a/clang/include/clang/Basic/LangOptions.def 
b/clang/include/clang/Basic/LangOptions.def
index c0ea4ecb9806a5b..97101d0166a135a 100644
--- a/clang/include/clang/Basic/LangOptions.def
+++ b/clang/include/clang/Basic/LangOptions.def
@@ -282,7 +282,7 @@ 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(MSVCEnableStdcMacro , 1, 0, "define __STDC__ with -fms-compatability")
 LANGOPT(SizedDeallocation , 1, 0, "sized deallocation")
 LANGOPT(AlignedAllocation , 1, 0, "aligned allocation")
 LANGOPT(AlignedAllocationUnavailable, 1, 0, "aligned allocation functions are 
unavailable")
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index c272a7f1c398aa6..fae1dcc2b5117f7 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -2821,6 +2821,10 @@ def fms_compatibility : Flag<["-"], 
"fms-compatibility">, Group,
   Visibility<[ClangOption, CC1Option, CLOption]>,
   HelpText<"Enable full Microsoft Visual C++ compatibility">,
   MarshallingInfoFlag>;
+def fms_define_stdc : Flag<["-"], "fms-define-stdc">, Group,
+  Visibility<[ClangOption, CC1Option]>,
+  HelpText<"Define __STDC__ in MSVC Compatibility mode">,
+  MarshallingInfoFlag>;
 def fms_extensions : Flag<["-"], "fms-extensions">, Group,
   Visibility<[ClangOption, CC1Option, CLOption]>,
   HelpText<"Accept some non-standard constructs supported by the Microsoft 
compiler">,
@@ -7933,6 +7937,9 @@ def _SLASH_vd : CLJoined<"vd">, HelpText<"Control 
vtordisp placement">,
   Alias;
 def _SLASH_X : CLFlag<"X">,
   HelpText<"Do not add %INCLUDE% to include search path">, Alias;
+def _SLASH_Zc___STDC__ : CLFlag<"Zc:__STDC__">,
+  HelpText<"Define __STDC__">,
+  Alias;
 def _SLASH_Zc_sizedDealloc : CLFlag<"Zc:sizedDealloc">,
   HelpText<"Enable C++14 sized global deallocation functions">,
   Alias;
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index bfd6c5c2864abf7..2834786ba17decf 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -6744,8 +6744,12 @@ void Clang::ConstructJob(Compilation &C, const JobAction 
&JA,
   options::OPT_fms_compatibility, options::OPT_fno_ms_compatibility,
   (IsWindowsMSVC && Args.hasFlag(options::OPT_fms_extensions,
  options::OPT_fno_ms_extensions, true)));
-  if (IsMSVCCompat)
+  if (IsMSVCCompat) {
 CmdArgs.push_back("-fms-compatibility");
+bool IsMSVCDefineStdc = Args.hasArg(options::OPT_fms_define_stdc);
+if (IsMSVCDefineStdc)
+  CmdArgs.push_back("-fms-define-stdc");
+  }
 
   if (Triple.isWindowsMSVCEnvironment() && !D.IsCLMode() &&
   Args.hasArg(options::OPT_fms_runtime_lib_EQ))
@@ -7922,6 +7926,10 @@ void Clang::AddClangCLArgs(const ArgList &Args, 
types::ID InputType,
CmdArgs.push_back("-fno-wchar");
  }
 
+ if (Args.hasArg(options::OPT_fms_define_stdc)) {
+   CmdArgs.push_back("-fms-define-stdc");
+ }
+
  if (Args.hasArg(options::OPT__SLASH_kernel)) {
llvm::Triple::ArchType Arch = getToolChain().getArch();
std::vector Values =
diff --git a/clang/lib/Frontend/InitPreprocessor.cpp 
b/clang/lib/Frontend/InitPreprocessor.cpp
index 846e5fce6de7b2c..e7ce08a8766d80c 100644
--- a/clang/lib/Frontend/InitPreprocessor.cpp
+++ b/clang/lib/Frontend/InitPreprocessor.cpp
@@ -423,7 +423,8 @@ static void InitializeStandardPredefinedMacros(const 
TargetInfo &TI,
   //  [C++] Whether __STDC__ is predefined and if so, what its value is,
   //  are implementation-defined.
   // (Removed in C++20.)
-  if (!LangOpts.MSVCCompat && !LangOpts.TraditionalCPP)
+  if ((!LangOpts.MSVCCompat || LangOpts.MSVCEnableStdcMacro) &&
+  !LangOpts.TraditionalCPP)

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

2023-10-12 Thread via cfe-commits

https://github.com/xbjfk updated https://github.com/llvm/llvm-project/pull/68690

>From 92899d94e91a6812de8fa5ec7c15c37a81280108 Mon Sep 17 00:00:00 2001
From: Reagan Bohan 
Date: Tue, 10 Oct 2023 11:32:47 +
Subject: [PATCH 1/3] [clang] Add /Zc:__STDC__ flag to clang-cl

This commit adds the /Zc:__STDC__ argument from MSVC, which defines __STDC__.
This means, alongside stronger feature parity with MSVC,
that things that rely on __STDC__, such as autoconf, can work.
---
 clang/include/clang/Basic/LangOptions.def |  2 +-
 clang/include/clang/Driver/Options.td |  7 +++
 clang/lib/Driver/ToolChains/Clang.cpp | 10 +-
 clang/lib/Frontend/InitPreprocessor.cpp   |  3 ++-
 clang/test/Driver/cl-zc.cpp   |  4 
 5 files changed, 23 insertions(+), 3 deletions(-)

diff --git a/clang/include/clang/Basic/LangOptions.def 
b/clang/include/clang/Basic/LangOptions.def
index c0ea4ecb9806a5b..97101d0166a135a 100644
--- a/clang/include/clang/Basic/LangOptions.def
+++ b/clang/include/clang/Basic/LangOptions.def
@@ -282,7 +282,7 @@ 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(MSVCEnableStdcMacro , 1, 0, "define __STDC__ with -fms-compatability")
 LANGOPT(SizedDeallocation , 1, 0, "sized deallocation")
 LANGOPT(AlignedAllocation , 1, 0, "aligned allocation")
 LANGOPT(AlignedAllocationUnavailable, 1, 0, "aligned allocation functions are 
unavailable")
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index c272a7f1c398aa6..fae1dcc2b5117f7 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -2821,6 +2821,10 @@ def fms_compatibility : Flag<["-"], 
"fms-compatibility">, Group,
   Visibility<[ClangOption, CC1Option, CLOption]>,
   HelpText<"Enable full Microsoft Visual C++ compatibility">,
   MarshallingInfoFlag>;
+def fms_define_stdc : Flag<["-"], "fms-define-stdc">, Group,
+  Visibility<[ClangOption, CC1Option]>,
+  HelpText<"Define __STDC__ in MSVC Compatibility mode">,
+  MarshallingInfoFlag>;
 def fms_extensions : Flag<["-"], "fms-extensions">, Group,
   Visibility<[ClangOption, CC1Option, CLOption]>,
   HelpText<"Accept some non-standard constructs supported by the Microsoft 
compiler">,
@@ -7933,6 +7937,9 @@ def _SLASH_vd : CLJoined<"vd">, HelpText<"Control 
vtordisp placement">,
   Alias;
 def _SLASH_X : CLFlag<"X">,
   HelpText<"Do not add %INCLUDE% to include search path">, Alias;
+def _SLASH_Zc___STDC__ : CLFlag<"Zc:__STDC__">,
+  HelpText<"Define __STDC__">,
+  Alias;
 def _SLASH_Zc_sizedDealloc : CLFlag<"Zc:sizedDealloc">,
   HelpText<"Enable C++14 sized global deallocation functions">,
   Alias;
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index bfd6c5c2864abf7..2834786ba17decf 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -6744,8 +6744,12 @@ void Clang::ConstructJob(Compilation &C, const JobAction 
&JA,
   options::OPT_fms_compatibility, options::OPT_fno_ms_compatibility,
   (IsWindowsMSVC && Args.hasFlag(options::OPT_fms_extensions,
  options::OPT_fno_ms_extensions, true)));
-  if (IsMSVCCompat)
+  if (IsMSVCCompat) {
 CmdArgs.push_back("-fms-compatibility");
+bool IsMSVCDefineStdc = Args.hasArg(options::OPT_fms_define_stdc);
+if (IsMSVCDefineStdc)
+  CmdArgs.push_back("-fms-define-stdc");
+  }
 
   if (Triple.isWindowsMSVCEnvironment() && !D.IsCLMode() &&
   Args.hasArg(options::OPT_fms_runtime_lib_EQ))
@@ -7922,6 +7926,10 @@ void Clang::AddClangCLArgs(const ArgList &Args, 
types::ID InputType,
CmdArgs.push_back("-fno-wchar");
  }
 
+ if (Args.hasArg(options::OPT_fms_define_stdc)) {
+   CmdArgs.push_back("-fms-define-stdc");
+ }
+
  if (Args.hasArg(options::OPT__SLASH_kernel)) {
llvm::Triple::ArchType Arch = getToolChain().getArch();
std::vector Values =
diff --git a/clang/lib/Frontend/InitPreprocessor.cpp 
b/clang/lib/Frontend/InitPreprocessor.cpp
index 846e5fce6de7b2c..e7ce08a8766d80c 100644
--- a/clang/lib/Frontend/InitPreprocessor.cpp
+++ b/clang/lib/Frontend/InitPreprocessor.cpp
@@ -423,7 +423,8 @@ static void InitializeStandardPredefinedMacros(const 
TargetInfo &TI,
   //  [C++] Whether __STDC__ is predefined and if so, what its value is,
   //  are implementation-defined.
   // (Removed in C++20.)
-  if (!LangOpts.MSVCCompat && !LangOpts.TraditionalCPP)
+  if ((!LangOpts.MSVCCompat || LangOpts.MSVCEnableStdcMacro) &&
+  !LangOpts.TraditionalCPP)

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

2023-10-12 Thread via cfe-commits

https://github.com/xbjfk updated https://github.com/llvm/llvm-project/pull/68690

>From 92899d94e91a6812de8fa5ec7c15c37a81280108 Mon Sep 17 00:00:00 2001
From: Reagan Bohan 
Date: Tue, 10 Oct 2023 11:32:47 +
Subject: [PATCH 1/4] [clang] Add /Zc:__STDC__ flag to clang-cl

This commit adds the /Zc:__STDC__ argument from MSVC, which defines __STDC__.
This means, alongside stronger feature parity with MSVC,
that things that rely on __STDC__, such as autoconf, can work.
---
 clang/include/clang/Basic/LangOptions.def |  2 +-
 clang/include/clang/Driver/Options.td |  7 +++
 clang/lib/Driver/ToolChains/Clang.cpp | 10 +-
 clang/lib/Frontend/InitPreprocessor.cpp   |  3 ++-
 clang/test/Driver/cl-zc.cpp   |  4 
 5 files changed, 23 insertions(+), 3 deletions(-)

diff --git a/clang/include/clang/Basic/LangOptions.def 
b/clang/include/clang/Basic/LangOptions.def
index c0ea4ecb9806a5b..97101d0166a135a 100644
--- a/clang/include/clang/Basic/LangOptions.def
+++ b/clang/include/clang/Basic/LangOptions.def
@@ -282,7 +282,7 @@ 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(MSVCEnableStdcMacro , 1, 0, "define __STDC__ with -fms-compatability")
 LANGOPT(SizedDeallocation , 1, 0, "sized deallocation")
 LANGOPT(AlignedAllocation , 1, 0, "aligned allocation")
 LANGOPT(AlignedAllocationUnavailable, 1, 0, "aligned allocation functions are 
unavailable")
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index c272a7f1c398aa6..fae1dcc2b5117f7 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -2821,6 +2821,10 @@ def fms_compatibility : Flag<["-"], 
"fms-compatibility">, Group,
   Visibility<[ClangOption, CC1Option, CLOption]>,
   HelpText<"Enable full Microsoft Visual C++ compatibility">,
   MarshallingInfoFlag>;
+def fms_define_stdc : Flag<["-"], "fms-define-stdc">, Group,
+  Visibility<[ClangOption, CC1Option]>,
+  HelpText<"Define __STDC__ in MSVC Compatibility mode">,
+  MarshallingInfoFlag>;
 def fms_extensions : Flag<["-"], "fms-extensions">, Group,
   Visibility<[ClangOption, CC1Option, CLOption]>,
   HelpText<"Accept some non-standard constructs supported by the Microsoft 
compiler">,
@@ -7933,6 +7937,9 @@ def _SLASH_vd : CLJoined<"vd">, HelpText<"Control 
vtordisp placement">,
   Alias;
 def _SLASH_X : CLFlag<"X">,
   HelpText<"Do not add %INCLUDE% to include search path">, Alias;
+def _SLASH_Zc___STDC__ : CLFlag<"Zc:__STDC__">,
+  HelpText<"Define __STDC__">,
+  Alias;
 def _SLASH_Zc_sizedDealloc : CLFlag<"Zc:sizedDealloc">,
   HelpText<"Enable C++14 sized global deallocation functions">,
   Alias;
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index bfd6c5c2864abf7..2834786ba17decf 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -6744,8 +6744,12 @@ void Clang::ConstructJob(Compilation &C, const JobAction 
&JA,
   options::OPT_fms_compatibility, options::OPT_fno_ms_compatibility,
   (IsWindowsMSVC && Args.hasFlag(options::OPT_fms_extensions,
  options::OPT_fno_ms_extensions, true)));
-  if (IsMSVCCompat)
+  if (IsMSVCCompat) {
 CmdArgs.push_back("-fms-compatibility");
+bool IsMSVCDefineStdc = Args.hasArg(options::OPT_fms_define_stdc);
+if (IsMSVCDefineStdc)
+  CmdArgs.push_back("-fms-define-stdc");
+  }
 
   if (Triple.isWindowsMSVCEnvironment() && !D.IsCLMode() &&
   Args.hasArg(options::OPT_fms_runtime_lib_EQ))
@@ -7922,6 +7926,10 @@ void Clang::AddClangCLArgs(const ArgList &Args, 
types::ID InputType,
CmdArgs.push_back("-fno-wchar");
  }
 
+ if (Args.hasArg(options::OPT_fms_define_stdc)) {
+   CmdArgs.push_back("-fms-define-stdc");
+ }
+
  if (Args.hasArg(options::OPT__SLASH_kernel)) {
llvm::Triple::ArchType Arch = getToolChain().getArch();
std::vector Values =
diff --git a/clang/lib/Frontend/InitPreprocessor.cpp 
b/clang/lib/Frontend/InitPreprocessor.cpp
index 846e5fce6de7b2c..e7ce08a8766d80c 100644
--- a/clang/lib/Frontend/InitPreprocessor.cpp
+++ b/clang/lib/Frontend/InitPreprocessor.cpp
@@ -423,7 +423,8 @@ static void InitializeStandardPredefinedMacros(const 
TargetInfo &TI,
   //  [C++] Whether __STDC__ is predefined and if so, what its value is,
   //  are implementation-defined.
   // (Removed in C++20.)
-  if (!LangOpts.MSVCCompat && !LangOpts.TraditionalCPP)
+  if ((!LangOpts.MSVCCompat || LangOpts.MSVCEnableStdcMacro) &&
+  !LangOpts.TraditionalCPP)

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

2023-10-12 Thread via cfe-commits


@@ -123,6 +123,10 @@
 // CHECK-CHAR8_T_: "-fno-char8_t"
 
 
+// RUN: %clang_cl /dev/null /E -Xclang -dM 2> /dev/null | FileCheck 
-match-full-lines %s --check-prefix=STDCOFF
+// RUN: %clang_cl /dev/null /E -Xclang -dM /Zc:__STDC__ 2> /dev/null | 
FileCheck -match-full-lines %s --check-prefix=STDCON

xbjfk wrote:

Good catch, in this case I guess it's best to create a `cl-zc.c` file?

I think it shouldn't be allowed in clang in C++ mode - after all if someone 
really wants it they can use `-Xclang -fms-define-stdc` or even `-D__STDC__` 
manually. My guess would be the primary use case of `-fms-compatibility` with 
clang (rather than clang-cl) is code whose build system is compiler agnostic 
but the code itself depends on MSVC behavior - in which case they would not be 
expecting `__STDC__` to be defined.

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


[clang] 22b6b8d - [clang][Interp][NFC] Remove Pointer.h include from Function.h

2023-10-12 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2023-10-12T12:51:38+02:00
New Revision: 22b6b8d7b53105bb7fbcbb94c7dd77ce028a8c23

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

LOG: [clang][Interp][NFC] Remove Pointer.h include from Function.h

Added: 


Modified: 
clang/lib/AST/Interp/Function.h
clang/lib/AST/Interp/InterpStack.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/Function.h b/clang/lib/AST/Interp/Function.h
index 0bae314e97701d9..b93477c56346a9d 100644
--- a/clang/lib/AST/Interp/Function.h
+++ b/clang/lib/AST/Interp/Function.h
@@ -15,8 +15,8 @@
 #ifndef LLVM_CLANG_AST_INTERP_FUNCTION_H
 #define LLVM_CLANG_AST_INTERP_FUNCTION_H
 
-#include "Pointer.h"
 #include "Source.h"
+#include "Descriptor.h"
 #include "clang/AST/ASTLambda.h"
 #include "clang/AST/Decl.h"
 #include "llvm/Support/raw_ostream.h"
@@ -25,6 +25,7 @@ namespace clang {
 namespace interp {
 class Program;
 class ByteCodeEmitter;
+class Pointer;
 enum PrimType : uint32_t;
 
 /// Describes a scope block.

diff  --git a/clang/lib/AST/Interp/InterpStack.cpp 
b/clang/lib/AST/Interp/InterpStack.cpp
index da4b36f8c1bf351..18a34079c3b16ae 100644
--- a/clang/lib/AST/Interp/InterpStack.cpp
+++ b/clang/lib/AST/Interp/InterpStack.cpp
@@ -10,6 +10,7 @@
 #include "Boolean.h"
 #include "Floating.h"
 #include "Integral.h"
+#include "Pointer.h"
 #include 
 #include 
 



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


[clang] 2f43ace - [clang][Interp] Fix expected values for Pointer API

2023-10-12 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2023-10-12T13:08:42+02:00
New Revision: 2f43ace0f48f393e12a15af557aac6a8f84bfd2b

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

LOG: [clang][Interp] Fix expected values for Pointer API

Add a unit test for this.

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

Added: 
clang/unittests/AST/Interp/CMakeLists.txt
clang/unittests/AST/Interp/Descriptor.cpp

Modified: 
clang/lib/AST/Interp/Context.h
clang/lib/AST/Interp/Pointer.h
clang/unittests/AST/CMakeLists.txt

Removed: 




diff  --git a/clang/lib/AST/Interp/Context.h b/clang/lib/AST/Interp/Context.h
index 6df61e93ad83abc..7649caef2242816 100644
--- a/clang/lib/AST/Interp/Context.h
+++ b/clang/lib/AST/Interp/Context.h
@@ -86,6 +86,9 @@ class Context final {
 return false;
   }
 
+  /// Returns the program. This is only needed for unittests.
+  Program &getProgram() const { return *P.get(); }
+
 private:
   /// Runs a function.
   bool Run(State &Parent, const Function *Func, APValue &Result);

diff  --git a/clang/lib/AST/Interp/Pointer.h b/clang/lib/AST/Interp/Pointer.h
index 8c97a965320e106..d5279e757f04764 100644
--- a/clang/lib/AST/Interp/Pointer.h
+++ b/clang/lib/AST/Interp/Pointer.h
@@ -78,6 +78,15 @@ class Pointer {
   void operator=(const Pointer &P);
   void operator=(Pointer &&P);
 
+  /// Equality operators are just for tests.
+  bool operator==(const Pointer &P) const {
+return Pointee == P.Pointee && Base == P.Base && Offset == P.Offset;
+  }
+
+  bool operator!=(const Pointer &P) const {
+return Pointee != P.Pointee || Base != P.Base || Offset != P.Offset;
+  }
+
   /// Converts the pointer to an APValue.
   APValue toAPValue() const;
 
@@ -276,7 +285,8 @@ class Pointer {
   const Record *getRecord() const { return getFieldDesc()->ElemRecord; }
   /// Returns the element record type, if this is a non-primive array.
   const Record *getElemRecord() const {
-return getFieldDesc()->ElemDesc->ElemRecord;
+const Descriptor *ElemDesc = getFieldDesc()->ElemDesc;
+return ElemDesc ? ElemDesc->ElemRecord : nullptr;
   }
   /// Returns the field information.
   const FieldDecl *getField() const { return getFieldDesc()->asFieldDecl(); }
@@ -326,6 +336,11 @@ class Pointer {
   int64_t getIndex() const {
 if (isElementPastEnd())
   return 1;
+
+// narrow()ed element in a composite array.
+if (Base > 0 && Base == Offset)
+  return 0;
+
 if (auto ElemSize = elemSize())
   return getOffset() / ElemSize;
 return 0;

diff  --git a/clang/unittests/AST/CMakeLists.txt 
b/clang/unittests/AST/CMakeLists.txt
index 12484be9206e23c..584cfb1bd2f11d0 100644
--- a/clang/unittests/AST/CMakeLists.txt
+++ b/clang/unittests/AST/CMakeLists.txt
@@ -5,6 +5,8 @@ set(LLVM_LINK_COMPONENTS
   )
 
 
+add_subdirectory(Interp)
+
 add_clang_unittest(ASTTests
   ASTContextParentMapTest.cpp
   ASTExprTest.cpp

diff  --git a/clang/unittests/AST/Interp/CMakeLists.txt 
b/clang/unittests/AST/Interp/CMakeLists.txt
new file mode 100644
index 000..afa571576a60e59
--- /dev/null
+++ b/clang/unittests/AST/Interp/CMakeLists.txt
@@ -0,0 +1,14 @@
+add_clang_unittest(InterpTests
+  Descriptor.cpp
+  )
+
+clang_target_link_libraries(InterpTests
+  PRIVATE
+  clangAST
+  clangBasic
+  )
+
+  target_link_libraries(InterpTests
+  PRIVATE
+  clangTesting
+)

diff  --git a/clang/unittests/AST/Interp/Descriptor.cpp 
b/clang/unittests/AST/Interp/Descriptor.cpp
new file mode 100644
index 000..fb1690a97061890
--- /dev/null
+++ b/clang/unittests/AST/Interp/Descriptor.cpp
@@ -0,0 +1,385 @@
+#include "../../../lib/AST/Interp/Descriptor.h"
+#include "../../../lib/AST/Interp/Context.h"
+#include "../../../lib/AST/Interp/Program.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Decl.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/Tooling/Tooling.h"
+#include "gtest/gtest.h"
+
+using namespace clang;
+using namespace clang::interp;
+using namespace clang::ast_matchers;
+
+/// Inspect generated Descriptors as well as the pointers we create.
+///
+TEST(Descriptor, Primitives) {
+  constexpr char Code[] =
+  "struct A { bool a; bool b; };\n"
+  "struct S {\n"
+  "  float f;\n"
+  "  char s[4];\n"
+  "  A a[3];\n"
+  "  short l[3][3];\n"
+  "};\n"
+  "constexpr S d = {0.0, \"foo\", {{true, false}, {false, true}, {false, 
false}},\n"
+  "  {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}};\n";
+
+  auto AST = tooling::buildASTFromCodeWithArgs(
+  Code, {"-fexperimental-new-constant-interpreter"});
+
+  const VarDecl *D = selectFirst(
+  "d", match(varDecl().bind("d"), AST->getASTContext()));
+  ASSERT_NE(D, nullptr);
+
+  const auto &Ctx = AST->getASTContext().getInterpCon

[PATCH] D158069: [clang][Interp] Fix getIndex() for composite array elements

2023-10-12 Thread Timm Bäder 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 rG2f43ace0f48f: [clang][Interp] Fix expected values for 
Pointer API (authored by tbaeder).

Changed prior to commit:
  https://reviews.llvm.org/D158069?vs=557656&id=557689#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D158069

Files:
  clang/lib/AST/Interp/Context.h
  clang/lib/AST/Interp/Pointer.h
  clang/unittests/AST/CMakeLists.txt
  clang/unittests/AST/Interp/CMakeLists.txt
  clang/unittests/AST/Interp/Descriptor.cpp

Index: clang/unittests/AST/Interp/Descriptor.cpp
===
--- /dev/null
+++ clang/unittests/AST/Interp/Descriptor.cpp
@@ -0,0 +1,385 @@
+#include "../../../lib/AST/Interp/Descriptor.h"
+#include "../../../lib/AST/Interp/Context.h"
+#include "../../../lib/AST/Interp/Program.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Decl.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/Tooling/Tooling.h"
+#include "gtest/gtest.h"
+
+using namespace clang;
+using namespace clang::interp;
+using namespace clang::ast_matchers;
+
+/// Inspect generated Descriptors as well as the pointers we create.
+///
+TEST(Descriptor, Primitives) {
+  constexpr char Code[] =
+  "struct A { bool a; bool b; };\n"
+  "struct S {\n"
+  "  float f;\n"
+  "  char s[4];\n"
+  "  A a[3];\n"
+  "  short l[3][3];\n"
+  "};\n"
+  "constexpr S d = {0.0, \"foo\", {{true, false}, {false, true}, {false, false}},\n"
+  "  {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}};\n";
+
+  auto AST = tooling::buildASTFromCodeWithArgs(
+  Code, {"-fexperimental-new-constant-interpreter"});
+
+  const VarDecl *D = selectFirst(
+  "d", match(varDecl().bind("d"), AST->getASTContext()));
+  ASSERT_NE(D, nullptr);
+
+  const auto &Ctx = AST->getASTContext().getInterpContext();
+  Program &Prog = Ctx.getProgram();
+  // Global is registered.
+  ASSERT_TRUE(Prog.getGlobal(D));
+
+  // Get a Pointer to the global.
+  const Pointer &GlobalPtr = Prog.getPtrGlobal(*Prog.getGlobal(D));
+
+  // Test Descriptor of the struct S.
+  const Descriptor *GlobalDesc = GlobalPtr.getFieldDesc();
+  ASSERT_TRUE(GlobalDesc == GlobalPtr.getDeclDesc());
+
+  ASSERT_TRUE(GlobalDesc->asDecl() == D);
+  ASSERT_FALSE(GlobalDesc->asExpr());
+  ASSERT_TRUE(GlobalDesc->asValueDecl() == D);
+  ASSERT_FALSE(GlobalDesc->asFieldDecl());
+  ASSERT_FALSE(GlobalDesc->asRecordDecl());
+
+  // Still true because this is a global variable.
+  ASSERT_TRUE(GlobalDesc->getMetadataSize() == 0);
+  ASSERT_FALSE(GlobalDesc->isPrimitiveArray());
+  ASSERT_FALSE(GlobalDesc->isCompositeArray());
+  ASSERT_FALSE(GlobalDesc->isZeroSizeArray());
+  ASSERT_FALSE(GlobalDesc->isUnknownSizeArray());
+  ASSERT_FALSE(GlobalDesc->isPrimitive());
+  ASSERT_FALSE(GlobalDesc->isArray());
+  ASSERT_TRUE(GlobalDesc->isRecord());
+
+  // Test the Record for the struct S.
+  const Record *SRecord = GlobalDesc->ElemRecord;
+  ASSERT_TRUE(SRecord);
+  ASSERT_TRUE(SRecord->getNumFields() == 4);
+  ASSERT_TRUE(SRecord->getNumBases() == 0);
+  ASSERT_FALSE(SRecord->getDestructor());
+
+  // First field.
+  const Record::Field *F1 = SRecord->getField(0u);
+  ASSERT_TRUE(F1);
+  ASSERT_FALSE(F1->isBitField());
+  ASSERT_TRUE(F1->Desc->isPrimitive());
+
+  // Second field.
+  const Record::Field *F2 = SRecord->getField(1u);
+  ASSERT_TRUE(F2);
+  ASSERT_FALSE(F2->isBitField());
+  ASSERT_TRUE(F2->Desc->isArray());
+  ASSERT_FALSE(F2->Desc->isCompositeArray());
+  ASSERT_TRUE(F2->Desc->isPrimitiveArray());
+  ASSERT_FALSE(F2->Desc->isPrimitive());
+  ASSERT_FALSE(F2->Desc->ElemDesc);
+  ASSERT_EQ(F2->Desc->getNumElems(), 4u);
+  ASSERT_TRUE(F2->Desc->getElemSize() > 0);
+
+  // Third field.
+  const Record::Field *F3 = SRecord->getField(2u);
+  ASSERT_TRUE(F3);
+  ASSERT_FALSE(F3->isBitField());
+  ASSERT_TRUE(F3->Desc->isArray());
+  ASSERT_TRUE(F3->Desc->isCompositeArray());
+  ASSERT_FALSE(F3->Desc->isPrimitiveArray());
+  ASSERT_FALSE(F3->Desc->isPrimitive());
+  ASSERT_TRUE(F3->Desc->ElemDesc);
+  ASSERT_EQ(F3->Desc->getNumElems(), 3u);
+  ASSERT_TRUE(F3->Desc->getElemSize() > 0);
+
+  // Fourth field.
+  // Multidimensional arrays are treated as composite arrays, even
+  // if the value type is primitive.
+  const Record::Field *F4 = SRecord->getField(3u);
+  ASSERT_TRUE(F4);
+  ASSERT_FALSE(F4->isBitField());
+  ASSERT_TRUE(F4->Desc->isArray());
+  ASSERT_TRUE(F4->Desc->isCompositeArray());
+  ASSERT_FALSE(F4->Desc->isPrimitiveArray());
+  ASSERT_FALSE(F4->Desc->isPrimitive());
+  ASSERT_TRUE(F4->Desc->ElemDesc);
+  ASSERT_EQ(F4->Desc->getNumElems(), 3u);
+  ASSERT_TRUE(F4->Desc->getElemSize() > 0);
+  ASSERT_TRUE(F4->Desc->ElemDesc->isPrimitiveArray());
+
+  // Check pointer stuff.
+  // Global variables have no inline des

[clang] e54b0be - [clang][dataflow] Various formatting tweaks to HTMLLogger. (#68392)

2023-10-12 Thread via cfe-commits

Author: martinboehme
Date: 2023-10-12T13:12:21+02:00
New Revision: e54b0bef53bcab9d040f1e965e10f3558fafba44

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

LOG: [clang][dataflow] Various formatting tweaks to HTMLLogger. (#68392)

*  Ensure timeline entries don't have linebreaks by setting
   `min-width: max-content`.

* Give the timeline header some padding on the right so it doesn't run
into the
   "Function" header.

* Put some padding around the iteration choosers so they don't run into
each
   other.

* Eliminate the "Iteration" text from the iteration choosers, which took
up a
lot of space. It should be clear what these are without the "Iteration"
text. (This makes the above problem of iteration choosers running into
each
   other less likely, but also add the padding nonetheless.)

Before:


![html_logger_before](https://github.com/llvm/llvm-project/assets/29098113/b938360f-c943-4552-829f-7b4857260959)

After:


![html_logger_after](https://github.com/llvm/llvm-project/assets/29098113/fecf4eab-7992-4e7d-a6e1-451887b699ab)

Added: 


Modified: 
clang/lib/Analysis/FlowSensitive/HTMLLogger.css
clang/lib/Analysis/FlowSensitive/HTMLLogger.html

Removed: 




diff  --git a/clang/lib/Analysis/FlowSensitive/HTMLLogger.css 
b/clang/lib/Analysis/FlowSensitive/HTMLLogger.css
index 4de1d1ccc2b08ee..5da8db8fa87bf2f 100644
--- a/clang/lib/Analysis/FlowSensitive/HTMLLogger.css
+++ b/clang/lib/Analysis/FlowSensitive/HTMLLogger.css
@@ -19,6 +19,7 @@ section header {
   color: white;
   font-weight: bold;
   font-size: large;
+  padding-right: 0.5em;
 }
 section h2 {
   font-size: medium;
@@ -27,7 +28,7 @@ section h2 {
   border-top: 1px solid #aaa;
 }
 #timeline {
-  min-width: 0;
+  min-width: max-content;
 }
 #timeline .entry.hover {
   background-color: #aaa;
@@ -62,6 +63,10 @@ section h2 {
 #iterations .chooser {
   flex-grow: 1;
   text-align: center;
+  padding-left: 0.2em;
+}
+#iterations .chooser :last-child {
+  padding-right: 0.2em;
 }
 #iterations .chooser:not(.iter-select).hover {
   background-color: #ddd;

diff  --git a/clang/lib/Analysis/FlowSensitive/HTMLLogger.html 
b/clang/lib/Analysis/FlowSensitive/HTMLLogger.html
index ec9d74c71d35d98..b9f76c5074c7539 100644
--- a/clang/lib/Analysis/FlowSensitive/HTMLLogger.html
+++ b/clang/lib/Analysis/FlowSensitive/HTMLLogger.html
@@ -62,7 +62,7 @@
   
 
   Post-visit
-  Iteration {{iter.iter}}
+  {{iter.iter}}
→|
 
   



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


[clang] [clang][dataflow] Various formatting tweaks to HTMLLogger. (PR #68392)

2023-10-12 Thread via cfe-commits

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


[clang] [ARM] fix "+fp.dp" in multilib selection (PR #67412)

2023-10-12 Thread via cfe-commits


@@ -366,26 +366,50 @@ StringRef ARM::getArchExtFeature(StringRef ArchExt) {
 }
 
 static ARM::FPUKind findDoublePrecisionFPU(ARM::FPUKind InputFPUKind) {
+  if (InputFPUKind == ARM::FK_INVALID || InputFPUKind == ARM::FK_NONE)
+return ARM::FK_INVALID;
+
+  const ARM::FPUName &InputFPU = ARM::FPUNames[InputFPUKind];
+
+  if (ARM::isDoublePrecision(InputFPU.Restriction))
+return InputFPUKind;
+
+  // Otherwise, look for an FPU entry with all the same fields, except
+  // that it supports double precision.
+  for (const ARM::FPUName &CandidateFPU : ARM::FPUNames) {
+if (CandidateFPU.FPUVer == InputFPU.FPUVer &&
+CandidateFPU.NeonSupport == InputFPU.NeonSupport &&
+ARM::has32Regs(CandidateFPU.Restriction) ==
+ARM::has32Regs(InputFPU.Restriction) &&
+ARM::isDoublePrecision(CandidateFPU.Restriction)) {
+  return CandidateFPU.ID;
+}
+  }
+
+  // nothing found
+  return ARM::FK_INVALID;
+}
+
+static ARM::FPUKind findSinglePrecisionFPU(ARM::FPUKind InputFPUKind) {
+  if (InputFPUKind == ARM::FK_INVALID || InputFPUKind == ARM::FK_NONE)
+return ARM::FK_INVALID;
+
   const ARM::FPUName &InputFPU = ARM::FPUNames[InputFPUKind];
 
   // If the input FPU already supports double-precision, then there
   // isn't any different FPU we can return here.

john-brawn-arm wrote:

This comment should be above in findDoublePrecisionFPU, the comment here should 
be the opposite (i.e. should say the input FPU already doesn't have 
double-precision).

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


[clang] 28e3552 - [clang][Tests] Add clangTooling dep to Interp unittest

2023-10-12 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2023-10-12T13:17:06+02:00
New Revision: 28e3552e3ebf12ece3dfc69d707e7c60e21cdc36

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

LOG: [clang][Tests] Add clangTooling dep to Interp unittest

This broke builders, e.g.:

https://lab.llvm.org/buildbot/#/builders/139/builds/51404

Let's see if this works better.

Added: 


Modified: 
clang/unittests/AST/Interp/CMakeLists.txt

Removed: 




diff  --git a/clang/unittests/AST/Interp/CMakeLists.txt 
b/clang/unittests/AST/Interp/CMakeLists.txt
index afa571576a60e59..e8d41091af40cda 100644
--- a/clang/unittests/AST/Interp/CMakeLists.txt
+++ b/clang/unittests/AST/Interp/CMakeLists.txt
@@ -6,6 +6,7 @@ clang_target_link_libraries(InterpTests
   PRIVATE
   clangAST
   clangBasic
+  clangTooling
   )
 
   target_link_libraries(InterpTests



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


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

2023-10-12 Thread via cfe-commits

https://github.com/xbjfk updated https://github.com/llvm/llvm-project/pull/68690

>From 92899d94e91a6812de8fa5ec7c15c37a81280108 Mon Sep 17 00:00:00 2001
From: Reagan Bohan 
Date: Tue, 10 Oct 2023 11:32:47 +
Subject: [PATCH 1/5] [clang] Add /Zc:__STDC__ flag to clang-cl

This commit adds the /Zc:__STDC__ argument from MSVC, which defines __STDC__.
This means, alongside stronger feature parity with MSVC,
that things that rely on __STDC__, such as autoconf, can work.
---
 clang/include/clang/Basic/LangOptions.def |  2 +-
 clang/include/clang/Driver/Options.td |  7 +++
 clang/lib/Driver/ToolChains/Clang.cpp | 10 +-
 clang/lib/Frontend/InitPreprocessor.cpp   |  3 ++-
 clang/test/Driver/cl-zc.cpp   |  4 
 5 files changed, 23 insertions(+), 3 deletions(-)

diff --git a/clang/include/clang/Basic/LangOptions.def 
b/clang/include/clang/Basic/LangOptions.def
index c0ea4ecb9806a5b..97101d0166a135a 100644
--- a/clang/include/clang/Basic/LangOptions.def
+++ b/clang/include/clang/Basic/LangOptions.def
@@ -282,7 +282,7 @@ 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(MSVCEnableStdcMacro , 1, 0, "define __STDC__ with -fms-compatability")
 LANGOPT(SizedDeallocation , 1, 0, "sized deallocation")
 LANGOPT(AlignedAllocation , 1, 0, "aligned allocation")
 LANGOPT(AlignedAllocationUnavailable, 1, 0, "aligned allocation functions are 
unavailable")
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index c272a7f1c398aa6..fae1dcc2b5117f7 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -2821,6 +2821,10 @@ def fms_compatibility : Flag<["-"], 
"fms-compatibility">, Group,
   Visibility<[ClangOption, CC1Option, CLOption]>,
   HelpText<"Enable full Microsoft Visual C++ compatibility">,
   MarshallingInfoFlag>;
+def fms_define_stdc : Flag<["-"], "fms-define-stdc">, Group,
+  Visibility<[ClangOption, CC1Option]>,
+  HelpText<"Define __STDC__ in MSVC Compatibility mode">,
+  MarshallingInfoFlag>;
 def fms_extensions : Flag<["-"], "fms-extensions">, Group,
   Visibility<[ClangOption, CC1Option, CLOption]>,
   HelpText<"Accept some non-standard constructs supported by the Microsoft 
compiler">,
@@ -7933,6 +7937,9 @@ def _SLASH_vd : CLJoined<"vd">, HelpText<"Control 
vtordisp placement">,
   Alias;
 def _SLASH_X : CLFlag<"X">,
   HelpText<"Do not add %INCLUDE% to include search path">, Alias;
+def _SLASH_Zc___STDC__ : CLFlag<"Zc:__STDC__">,
+  HelpText<"Define __STDC__">,
+  Alias;
 def _SLASH_Zc_sizedDealloc : CLFlag<"Zc:sizedDealloc">,
   HelpText<"Enable C++14 sized global deallocation functions">,
   Alias;
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index bfd6c5c2864abf7..2834786ba17decf 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -6744,8 +6744,12 @@ void Clang::ConstructJob(Compilation &C, const JobAction 
&JA,
   options::OPT_fms_compatibility, options::OPT_fno_ms_compatibility,
   (IsWindowsMSVC && Args.hasFlag(options::OPT_fms_extensions,
  options::OPT_fno_ms_extensions, true)));
-  if (IsMSVCCompat)
+  if (IsMSVCCompat) {
 CmdArgs.push_back("-fms-compatibility");
+bool IsMSVCDefineStdc = Args.hasArg(options::OPT_fms_define_stdc);
+if (IsMSVCDefineStdc)
+  CmdArgs.push_back("-fms-define-stdc");
+  }
 
   if (Triple.isWindowsMSVCEnvironment() && !D.IsCLMode() &&
   Args.hasArg(options::OPT_fms_runtime_lib_EQ))
@@ -7922,6 +7926,10 @@ void Clang::AddClangCLArgs(const ArgList &Args, 
types::ID InputType,
CmdArgs.push_back("-fno-wchar");
  }
 
+ if (Args.hasArg(options::OPT_fms_define_stdc)) {
+   CmdArgs.push_back("-fms-define-stdc");
+ }
+
  if (Args.hasArg(options::OPT__SLASH_kernel)) {
llvm::Triple::ArchType Arch = getToolChain().getArch();
std::vector Values =
diff --git a/clang/lib/Frontend/InitPreprocessor.cpp 
b/clang/lib/Frontend/InitPreprocessor.cpp
index 846e5fce6de7b2c..e7ce08a8766d80c 100644
--- a/clang/lib/Frontend/InitPreprocessor.cpp
+++ b/clang/lib/Frontend/InitPreprocessor.cpp
@@ -423,7 +423,8 @@ static void InitializeStandardPredefinedMacros(const 
TargetInfo &TI,
   //  [C++] Whether __STDC__ is predefined and if so, what its value is,
   //  are implementation-defined.
   // (Removed in C++20.)
-  if (!LangOpts.MSVCCompat && !LangOpts.TraditionalCPP)
+  if ((!LangOpts.MSVCCompat || LangOpts.MSVCEnableStdcMacro) &&
+  !LangOpts.TraditionalCPP)

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

2023-10-12 Thread via cfe-commits

xbjfk wrote:

Okay, I made sure it says `argument unused during compilation: '/Zc:__STDC__'` 
and never defines __STDC__ in C++ mode, but I have couple of questions:
 - Where should I put the test to make sure `-fno-ms-define-stdc` is not 
accepted?
 -  !IsCXX feels kind of wrong - is this a justified case for creating `isC` in 
`clang/lib/Driver/Types.cpp`?
- now that I think about it, what should the behavior be with Objective-C? 
I imagine the number of people compiling Objective-C with `-fms-compatibility` 
is very small
 
Thank you 

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


[clang] [mlir][OpenMP] Added `omp.structured_region` operation (PR #68825)

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


@@ -1468,6 +1468,18 @@ LogicalResult CancellationPointOp::verify() {
   return success();
 }
 
+//===--===//
+// RegionOp
+//===--===//
+
+LogicalResult StructuredRegionOp::verify() {
+  Operation *parentOp = (*this)->getParentOp();
+  assert(parentOp && "'omp.region' op must have a parent");
+  if (!isa(parentOp->getDialect()))
+return emitOpError() << "must be used under an OpenMP Dialect operation";
+  return success();
+}

kiranchandramohan wrote:

This is OK for now, But in future when privatisation is modelled in the dialect 
for things like the worksharing loop where the bounds can also be privatised, 
this can be a wrapper around the region.
```
omp.structured_region private(%upper=%x) {
%upper:
  omp.wsloop for  (%i) : i32 = (%c1) to (%upper) inclusive step (%c1) {
  }
}
```

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


[clang] [mlir][OpenMP] Added `omp.structured_region` operation (PR #68825)

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


@@ -1987,4 +1987,40 @@ def ClauseRequiresAttr :
   EnumAttr {
 }
 
+
+def StructuredRegionOp : OpenMP_Op<"structured_region"> {
+  let summary = "Encapsulates a region in an OpenMP construct.";
+  let description = [{
+Encapsulates a region surrounded by an OpenMP Construct. The intended use
+of this operation is that within an OpenMP operation's region, there would
+be a single `omp.structured_region` operation and a terminator operation as
+shown below.
+
+```
+// Example with `omp.sections`
+omp.sections {
+  %x = omp.structured_region {
+%t = call @foo : () -> (i32)
+omp.yield(%t : i32)
+  }
+  omp.terminator
+}
+```
+
+This operation is especially more useful in operations that use `omp.yield`
+as a terminator. For example, in the proposed canonical loop operation,
+this operation would help fix the arguments of the yield operation and it
+is not affected by branches in the region assosciated with the canonical
+loop. In cases where the yielded value has to be a compile time constant,
+this provides a mechanism to avoid complex static analysis for the constant
+value.

kiranchandramohan wrote:

You can skip the section for now. Maybe just say that this is a useful 
operation to model OpenMP structured regions, where there can be branches 
inside the OpenMP region, but no branches outside. If we proceed with using 
this for Canonical Loop then we can update here.

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


[clang-tools-extra] [mlir][OpenMP] Added `omp.structured_region` operation (PR #68825)

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


@@ -1987,4 +1987,40 @@ def ClauseRequiresAttr :
   EnumAttr {
 }
 
+
+def StructuredRegionOp : OpenMP_Op<"structured_region"> {
+  let summary = "Encapsulates a region in an OpenMP construct.";
+  let description = [{
+Encapsulates a region surrounded by an OpenMP Construct. The intended use
+of this operation is that within an OpenMP operation's region, there would
+be a single `omp.structured_region` operation and a terminator operation as
+shown below.
+
+```
+// Example with `omp.sections`
+omp.sections {
+  %x = omp.structured_region {
+%t = call @foo : () -> (i32)
+omp.yield(%t : i32)
+  }
+  omp.terminator
+}
+```
+
+This operation is especially more useful in operations that use `omp.yield`
+as a terminator. For example, in the proposed canonical loop operation,
+this operation would help fix the arguments of the yield operation and it
+is not affected by branches in the region assosciated with the canonical
+loop. In cases where the yielded value has to be a compile time constant,
+this provides a mechanism to avoid complex static analysis for the constant
+value.

kiranchandramohan wrote:

You can skip the section for now. Maybe just say that this is a useful 
operation to model OpenMP structured regions, where there can be branches 
inside the OpenMP region, but no branches outside. If we proceed with using 
this for Canonical Loop then we can update here.

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


[clang-tools-extra] [mlir][OpenMP] Added `omp.structured_region` operation (PR #68825)

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


@@ -1468,6 +1468,18 @@ LogicalResult CancellationPointOp::verify() {
   return success();
 }
 
+//===--===//
+// RegionOp
+//===--===//
+
+LogicalResult StructuredRegionOp::verify() {
+  Operation *parentOp = (*this)->getParentOp();
+  assert(parentOp && "'omp.region' op must have a parent");
+  if (!isa(parentOp->getDialect()))
+return emitOpError() << "must be used under an OpenMP Dialect operation";
+  return success();
+}

kiranchandramohan wrote:

This is OK for now, But in future when privatisation is modelled in the dialect 
for things like the worksharing loop where the bounds can also be privatised, 
this can be a wrapper around the region.
```
omp.structured_region private(%upper=%x) {
%upper:
  omp.wsloop for  (%i) : i32 = (%c1) to (%upper) inclusive step (%c1) {
  }
}
```

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


[clang] [analyzer] Fix note for member reference (PR #68691)

2023-10-12 Thread via cfe-commits


@@ -41,3 +41,34 @@ int testRefToNullPtr2() {
   return *p2; //expected-warning {{Dereference of null pointer}}
   // expected-note@-1{{Dereference of null pointer}}
 }
+
+void testMemberNullPointerDeref() {
+  struct Wrapper {char c; int *ptr; };  
+  Wrapper w = {'a', nullptr};   // expected-note {{'w.ptr' initialized 
to a null pointer value}}
+  *w.ptr = 1;   //expected-warning {{Dereference of 
null pointer}}
+// expected-note@-1{{Dereference of 
null pointer}}
+}
+
+void testMemberNullReferenceDeref() {
+  struct Wrapper {char c; int &ref; };
+  Wrapper w = {.c = 'a', .ref = *(int *)0 }; // expected-note {{'w.ref' 
initialized to a null pointer value}}
+ // expected-warning@-1 {{binding 
dereferenced null pointer to reference has undefined behavior}}
+  w.ref = 1; //expected-warning {{Dereference 
of null pointer}}
+ // expected-note@-1{{Dereference 
of null pointer}}
+}
+
+void testReferenceToPointerWithNullptr() {
+  int *i = nullptr;   // expected-note {{'i' initialized to a 
null pointer value}}
+  struct Wrapper {char c; int *&a;};
+  Wrapper w {'c', i}; // expected-note{{'w.a' initialized 
here}}
+  *(w.a) = 25;// expected-warning {{Dereference of 
null pointer}}
+  // expected-note@-1 {{Dereference of 
null pointer}}
+}
+
+void aaa() {

DonatNagyE wrote:

```suggestion
void testNullReferenceToPointer() {
```

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


[clang] [analyzer] Fix note for member reference (PR #68691)

2023-10-12 Thread via cfe-commits

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

LGTM; my only suggestions are comment / naming clarifications.

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


[clang] [analyzer] Fix note for member reference (PR #68691)

2023-10-12 Thread via cfe-commits


@@ -132,6 +132,18 @@ const Expr *bugreporter::getDerefExpr(const Stmt *S) {
 }
 // Pattern match for a few useful cases: a[0], p->f, *p etc.
 else if (const auto *ME = dyn_cast(E)) {
+  // This handles the case when the dereferencing of a member reference
+  // happens. This is needed, because the ast for dereferencing of a

DonatNagyE wrote:

```suggestion
  // happens. This is needed, because the AST for dereferencing a
```

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


[clang] [analyzer] Fix note for member reference (PR #68691)

2023-10-12 Thread via cfe-commits

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


[clang] [clang]Transform uninstantiated ExceptionSpec in TemplateInstantiator (PR #68878)

2023-10-12 Thread Congcong Cai via cfe-commits

https://github.com/HerrCai0907 created 
https://github.com/llvm/llvm-project/pull/68878

Fixes #68543, #42496

>From b93096929aa98e17dfdb0240a9285d315fc95bfc Mon Sep 17 00:00:00 2001
From: Congcong Cai 
Date: Thu, 12 Oct 2023 19:31:08 +0800
Subject: [PATCH] [clang]Transform uninstantiated ExceptionSpec in
 TemplateInstantiator

Fixes #68543, #42496
---
 clang/docs/ReleaseNotes.rst   |  2 ++
 clang/lib/Sema/SemaTemplateDeduction.cpp  |  9 -
 clang/lib/Sema/SemaTemplateInstantiate.cpp| 19 +--
 .../dependent-noexcept-uninstantiated.cpp | 11 +++
 4 files changed, 38 insertions(+), 3 deletions(-)
 create mode 100644 clang/test/SemaCXX/dependent-noexcept-uninstantiated.cpp

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 2d918967e7f0b02..d3612db7957391d 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -377,6 +377,8 @@ Bug Fixes in This Version
   cannot be used with ``Release`` mode builds. (`#68237 
`_).
 - Fix crash in evaluating ``constexpr`` value for invalid template function.
   Fixes (`#68542 `_)
+- Clang will correctly evaluate ``noexcept`` expression with template in 
template
+  method of template record.
 
 - Fixed an issue when a shift count larger than ``__INT64_MAX__``, in a right
   shift operation, could result in missing warnings about
diff --git a/clang/lib/Sema/SemaTemplateDeduction.cpp 
b/clang/lib/Sema/SemaTemplateDeduction.cpp
index 62fbd903a04044b..2883e650b1ebd94 100644
--- a/clang/lib/Sema/SemaTemplateDeduction.cpp
+++ b/clang/lib/Sema/SemaTemplateDeduction.cpp
@@ -3367,7 +3367,14 @@ Sema::TemplateDeductionResult 
Sema::SubstituteExplicitTemplateArguments(
 SmallVector ExceptionStorage;
 if (getLangOpts().CPlusPlus17 &&
 SubstExceptionSpec(Function->getLocation(), EPI.ExceptionSpec,
-   ExceptionStorage, MLTAL))
+   ExceptionStorage,
+   getTemplateInstantiationArgs(
+   FunctionTemplate, /*Final=*/true,
+   /*Innermost=*/SugaredExplicitArgumentList,
+   /*RelativeToPrimary=*/false,
+   /*Pattern=*/nullptr,
+   /*ForConstraintInstantiation=*/false,
+   /*SkipForSpecialization=*/true)))
   return TDK_SubstitutionFailure;
 
 *FunctionType = BuildFunctionType(ResultType, ParamTypes,
diff --git a/clang/lib/Sema/SemaTemplateInstantiate.cpp 
b/clang/lib/Sema/SemaTemplateInstantiate.cpp
index 23de64080a070ca..f28768931cfabf4 100644
--- a/clang/lib/Sema/SemaTemplateInstantiate.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiate.cpp
@@ -1325,6 +1325,11 @@ namespace {
 /// declaration.
 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation 
Loc);
 
+bool TransformExceptionSpec(SourceLocation Loc,
+FunctionProtoType::ExceptionSpecInfo &ESI,
+SmallVectorImpl &Exceptions,
+bool &Changed);
+
 /// Rebuild the exception declaration and register the declaration
 /// as an instantiated local.
 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
@@ -1607,6 +1612,18 @@ Decl 
*TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
   return Inst;
 }
 
+bool TemplateInstantiator::TransformExceptionSpec(
+SourceLocation Loc, FunctionProtoType::ExceptionSpecInfo &ESI,
+SmallVectorImpl &Exceptions, bool &Changed) {
+  if (ESI.Type == EST_Uninstantiated) {
+ESI.NoexceptExpr = cast(ESI.SourceTemplate->getType())
+   ->getNoexceptExpr();
+ESI.Type = EST_DependentNoexcept;
+Changed = true;
+  }
+  return inherited::TransformExceptionSpec(Loc, ESI, Exceptions, Changed);
+}
+
 NamedDecl *
 TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
  SourceLocation Loc) {
@@ -2672,8 +2689,6 @@ bool Sema::SubstExceptionSpec(SourceLocation Loc,
   FunctionProtoType::ExceptionSpecInfo &ESI,
   SmallVectorImpl &ExceptionStorage,
   const MultiLevelTemplateArgumentList &Args) {
-  assert(ESI.Type != EST_Uninstantiated);
-
   bool Changed = false;
   TemplateInstantiator Instantiator(*this, Args, Loc, DeclarationName());
   return Instantiator.TransformExceptionSpec(Loc, ESI, ExceptionStorage,
diff --git a/clang/test/SemaCXX/dependent-noexcept-uninstantiated.cpp 
b/clang/test/SemaCXX/dependent-noexcept-uninstantiated.cpp
new file mode 100644
index 000..ddb269890227539
--- /dev/null
+++ b/clang/test/SemaCXX/dependent-noexcept-uninstantiated.cpp
@@ -0,0 +1,11 @@
+// RUN: %clang_cc1 -fsyntax-only -std=c++

[clang] [analyzer] Fix note for member reference (PR #68691)

2023-10-12 Thread via cfe-commits


@@ -157,26 +169,43 @@ const Expr *bugreporter::getDerefExpr(const Stmt *S) {
   return E;
 }
 
+static const VarDecl *getVarDeclForExpression(const Expr *E) {
+  if (const auto *DR = dyn_cast(E))
+return dyn_cast(DR->getDecl());
+  return nullptr;
+}
+
 static const MemRegion *
 getLocationRegionIfReference(const Expr *E, const ExplodedNode *N,
  bool LookingForReference = true) {
-  if (const auto *DR = dyn_cast(E)) {
-if (const auto *VD = dyn_cast(DR->getDecl())) {
-  if (LookingForReference && !VD->getType()->isReferenceType())
-return nullptr;
-  return N->getState()
-  ->getLValue(VD, N->getLocationContext())
-  .getAsRegion();
+  if (const auto *ME = dyn_cast(E)) {
+// This handles other kinds of null references,
+// for example, references from FieldRegions:

DonatNagyE wrote:

```suggestion
// This handles null references from FieldRegions, for example:
```
After moving this comment here, the "other" was left dangling.

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


[clang] [analyzer] Fix note for member reference (PR #68691)

2023-10-12 Thread via cfe-commits


@@ -132,6 +132,18 @@ const Expr *bugreporter::getDerefExpr(const Stmt *S) {
 }
 // Pattern match for a few useful cases: a[0], p->f, *p etc.
 else if (const auto *ME = dyn_cast(E)) {
+  // This handles the case when the dereferencing of a member reference
+  // happens. This is needed, because the ast for dereferencing of a
+  // member reference looks like the following:
+  // |-MemberExpr
+  //  `-DeclRefExpr
+  // This branch without the special case just takes out the DeclRefExpr
+  // of the struct, class or union.
+  // This is wrong, because this DeclRefExpr will be passed
+  // to the bug reporting and the notes will refer to wrong variable
+  // (the struct instead of the member).

DonatNagyE wrote:

```suggestion
  // Without this special case the notes would refer to the whole object
  // (struct, class or union variable) instead of just the relevant member.

```

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


[clang] [clang]Transform uninstantiated ExceptionSpec in TemplateInstantiator (PR #68878)

2023-10-12 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Congcong Cai (HerrCai0907)


Changes

Fixes #68543, #42496

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


4 Files Affected:

- (modified) clang/docs/ReleaseNotes.rst (+2) 
- (modified) clang/lib/Sema/SemaTemplateDeduction.cpp (+8-1) 
- (modified) clang/lib/Sema/SemaTemplateInstantiate.cpp (+17-2) 
- (added) clang/test/SemaCXX/dependent-noexcept-uninstantiated.cpp (+11) 


``diff
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 2d918967e7f0b02..d3612db7957391d 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -377,6 +377,8 @@ Bug Fixes in This Version
   cannot be used with ``Release`` mode builds. (`#68237 
`_).
 - Fix crash in evaluating ``constexpr`` value for invalid template function.
   Fixes (`#68542 `_)
+- Clang will correctly evaluate ``noexcept`` expression with template in 
template
+  method of template record.
 
 - Fixed an issue when a shift count larger than ``__INT64_MAX__``, in a right
   shift operation, could result in missing warnings about
diff --git a/clang/lib/Sema/SemaTemplateDeduction.cpp 
b/clang/lib/Sema/SemaTemplateDeduction.cpp
index 62fbd903a04044b..2883e650b1ebd94 100644
--- a/clang/lib/Sema/SemaTemplateDeduction.cpp
+++ b/clang/lib/Sema/SemaTemplateDeduction.cpp
@@ -3367,7 +3367,14 @@ Sema::TemplateDeductionResult 
Sema::SubstituteExplicitTemplateArguments(
 SmallVector ExceptionStorage;
 if (getLangOpts().CPlusPlus17 &&
 SubstExceptionSpec(Function->getLocation(), EPI.ExceptionSpec,
-   ExceptionStorage, MLTAL))
+   ExceptionStorage,
+   getTemplateInstantiationArgs(
+   FunctionTemplate, /*Final=*/true,
+   /*Innermost=*/SugaredExplicitArgumentList,
+   /*RelativeToPrimary=*/false,
+   /*Pattern=*/nullptr,
+   /*ForConstraintInstantiation=*/false,
+   /*SkipForSpecialization=*/true)))
   return TDK_SubstitutionFailure;
 
 *FunctionType = BuildFunctionType(ResultType, ParamTypes,
diff --git a/clang/lib/Sema/SemaTemplateInstantiate.cpp 
b/clang/lib/Sema/SemaTemplateInstantiate.cpp
index 23de64080a070ca..f28768931cfabf4 100644
--- a/clang/lib/Sema/SemaTemplateInstantiate.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiate.cpp
@@ -1325,6 +1325,11 @@ namespace {
 /// declaration.
 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation 
Loc);
 
+bool TransformExceptionSpec(SourceLocation Loc,
+FunctionProtoType::ExceptionSpecInfo &ESI,
+SmallVectorImpl &Exceptions,
+bool &Changed);
+
 /// Rebuild the exception declaration and register the declaration
 /// as an instantiated local.
 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
@@ -1607,6 +1612,18 @@ Decl 
*TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
   return Inst;
 }
 
+bool TemplateInstantiator::TransformExceptionSpec(
+SourceLocation Loc, FunctionProtoType::ExceptionSpecInfo &ESI,
+SmallVectorImpl &Exceptions, bool &Changed) {
+  if (ESI.Type == EST_Uninstantiated) {
+ESI.NoexceptExpr = cast(ESI.SourceTemplate->getType())
+   ->getNoexceptExpr();
+ESI.Type = EST_DependentNoexcept;
+Changed = true;
+  }
+  return inherited::TransformExceptionSpec(Loc, ESI, Exceptions, Changed);
+}
+
 NamedDecl *
 TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
  SourceLocation Loc) {
@@ -2672,8 +2689,6 @@ bool Sema::SubstExceptionSpec(SourceLocation Loc,
   FunctionProtoType::ExceptionSpecInfo &ESI,
   SmallVectorImpl &ExceptionStorage,
   const MultiLevelTemplateArgumentList &Args) {
-  assert(ESI.Type != EST_Uninstantiated);
-
   bool Changed = false;
   TemplateInstantiator Instantiator(*this, Args, Loc, DeclarationName());
   return Instantiator.TransformExceptionSpec(Loc, ESI, ExceptionStorage,
diff --git a/clang/test/SemaCXX/dependent-noexcept-uninstantiated.cpp 
b/clang/test/SemaCXX/dependent-noexcept-uninstantiated.cpp
new file mode 100644
index 000..ddb269890227539
--- /dev/null
+++ b/clang/test/SemaCXX/dependent-noexcept-uninstantiated.cpp
@@ -0,0 +1,11 @@
+// RUN: %clang_cc1 -fsyntax-only -std=c++17 %s
+// expected-no-diagnostics
+
+using A = int;
+using B = char;
+
+template  struct C {
+  template  void f0() noexcept(sizeof(T) == sizeof(A) && sizeof(V) == 
sizeof(B)) {}
+};
+
+void (C::*tmp1)() noexcept = &C::f0;

``




https://github.com/llvm/llvm-

[clang] [analyzer] Fix note for member reference (PR #68691)

2023-10-12 Thread Gábor Spaits via cfe-commits

https://github.com/spaits updated 
https://github.com/llvm/llvm-project/pull/68691

From bb9cb77cab7b073d45c0b998c926a0b60a75a35e Mon Sep 17 00:00:00 2001
From: Gabor Spaits 
Date: Tue, 10 Oct 2023 13:40:05 +0200
Subject: [PATCH 1/3] [analyzer] Fix note for member reference

---
 .../Core/BugReporterVisitors.cpp  | 57 ++-
 1 file changed, 43 insertions(+), 14 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp 
b/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
index 42d03f67510cf88..914011f367d8f2e 100644
--- a/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
+++ b/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
@@ -132,6 +132,18 @@ const Expr *bugreporter::getDerefExpr(const Stmt *S) {
 }
 // Pattern match for a few useful cases: a[0], p->f, *p etc.
 else if (const auto *ME = dyn_cast(E)) {
+  // This handles the case when the dereferencing of a member reference
+  // happens. This is needed, because the ast for dereferencing of a
+  // member reference looks like the following:
+  // |-MemberExpr
+  //  `-DeclRefExpr
+  // This branch without the special case just takes out the DeclRefExpr
+  // of the struct, class or union.
+  // This is wrong, because this DeclRefExpr will be passed
+  // to the bug reporting and the notes will refer to wrong variable
+  // (the struct instead of the member).
+  if (ME->getMemberDecl()->getType()->isReferenceType())
+break;
   E = ME->getBase();
 } else if (const auto *IvarRef = dyn_cast(E)) {
   E = IvarRef->getBase();
@@ -157,26 +169,43 @@ const Expr *bugreporter::getDerefExpr(const Stmt *S) {
   return E;
 }
 
+static const VarDecl *getVarDeclForExpression(const Expr *E) {
+  if (const auto *DR = dyn_cast(E))
+return dyn_cast(DR->getDecl());
+  return nullptr;
+}
+
 static const MemRegion *
 getLocationRegionIfReference(const Expr *E, const ExplodedNode *N,
  bool LookingForReference = true) {
-  if (const auto *DR = dyn_cast(E)) {
-if (const auto *VD = dyn_cast(DR->getDecl())) {
-  if (LookingForReference && !VD->getType()->isReferenceType())
-return nullptr;
-  return N->getState()
-  ->getLValue(VD, N->getLocationContext())
-  .getAsRegion();
+  if (const auto *ME = dyn_cast(E)) {
+// This handles other kinds of null references,
+// for example, references from FieldRegions:
+//   struct Wrapper { int &ref; };
+//   Wrapper w = { *(int *)0 };
+//   w.ref = 1;
+const Expr *Base = ME->getBase();
+const VarDecl *VD = getVarDeclForExpression(Base);
+if (!VD)
+  return nullptr;
+
+const auto *FD = dyn_cast(ME->getMemberDecl());
+if (!FD)
+  return nullptr;
+
+if (FD->getType()->isReferenceType()) {
+  SVal StructSVal = N->getState()->getLValue(VD, N->getLocationContext());
+  return N->getState()->getLValue(FD, StructSVal).getAsRegion();
 }
+return nullptr;
   }
 
-  // FIXME: This does not handle other kinds of null references,
-  // for example, references from FieldRegions:
-  //   struct Wrapper { int &ref; };
-  //   Wrapper w = { *(int *)0 };
-  //   w.ref = 1;
-
-  return nullptr;
+  const VarDecl *VD = getVarDeclForExpression(E);
+  if (!VD)
+return nullptr;
+  if (LookingForReference && !VD->getType()->isReferenceType())
+return nullptr;
+  return N->getState()->getLValue(VD, N->getLocationContext()).getAsRegion();
 }
 
 /// Comparing internal representations of symbolic values (via

From 5bf3ba5f3b66d972e3c26c8f782ae077700e459a Mon Sep 17 00:00:00 2001
From: Gabor Spaits 
Date: Tue, 10 Oct 2023 15:26:28 +0200
Subject: [PATCH 2/3] Add test cases for null reference reports

---
 .../deref-track-symbolic-region.cpp   | 31 +++
 1 file changed, 31 insertions(+)

diff --git a/clang/test/Analysis/diagnostics/deref-track-symbolic-region.cpp 
b/clang/test/Analysis/diagnostics/deref-track-symbolic-region.cpp
index e258a60aa966a53..2442851da989b16 100644
--- a/clang/test/Analysis/diagnostics/deref-track-symbolic-region.cpp
+++ b/clang/test/Analysis/diagnostics/deref-track-symbolic-region.cpp
@@ -41,3 +41,34 @@ int testRefToNullPtr2() {
   return *p2; //expected-warning {{Dereference of null pointer}}
   // expected-note@-1{{Dereference of null pointer}}
 }
+
+void testMemberNullPointerDeref() {
+  struct Wrapper {char c; int *ptr; };  
+  Wrapper w = {'a', nullptr};   // expected-note {{'w.ptr' initialized 
to a null pointer value}}
+  *w.ptr = 1;   //expected-warning {{Dereference of 
null pointer}}
+// expected-note@-1{{Dereference of 
null pointer}}
+}
+
+void testMemberNullReferenceDeref() {
+  struct Wrapper {char c; int &ref; };
+  Wrapper w = {.c = 'a', .ref = *(int *)0 }; // expected-note {{'w.ref' 
initialized to a null pointer value}}
+   

[clang] [analyzer] Fix note for member reference (PR #68691)

2023-10-12 Thread Gábor Spaits via cfe-commits

https://github.com/spaits updated 
https://github.com/llvm/llvm-project/pull/68691

From bb9cb77cab7b073d45c0b998c926a0b60a75a35e Mon Sep 17 00:00:00 2001
From: Gabor Spaits 
Date: Tue, 10 Oct 2023 13:40:05 +0200
Subject: [PATCH 1/4] [analyzer] Fix note for member reference

---
 .../Core/BugReporterVisitors.cpp  | 57 ++-
 1 file changed, 43 insertions(+), 14 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp 
b/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
index 42d03f67510cf88..914011f367d8f2e 100644
--- a/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
+++ b/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
@@ -132,6 +132,18 @@ const Expr *bugreporter::getDerefExpr(const Stmt *S) {
 }
 // Pattern match for a few useful cases: a[0], p->f, *p etc.
 else if (const auto *ME = dyn_cast(E)) {
+  // This handles the case when the dereferencing of a member reference
+  // happens. This is needed, because the ast for dereferencing of a
+  // member reference looks like the following:
+  // |-MemberExpr
+  //  `-DeclRefExpr
+  // This branch without the special case just takes out the DeclRefExpr
+  // of the struct, class or union.
+  // This is wrong, because this DeclRefExpr will be passed
+  // to the bug reporting and the notes will refer to wrong variable
+  // (the struct instead of the member).
+  if (ME->getMemberDecl()->getType()->isReferenceType())
+break;
   E = ME->getBase();
 } else if (const auto *IvarRef = dyn_cast(E)) {
   E = IvarRef->getBase();
@@ -157,26 +169,43 @@ const Expr *bugreporter::getDerefExpr(const Stmt *S) {
   return E;
 }
 
+static const VarDecl *getVarDeclForExpression(const Expr *E) {
+  if (const auto *DR = dyn_cast(E))
+return dyn_cast(DR->getDecl());
+  return nullptr;
+}
+
 static const MemRegion *
 getLocationRegionIfReference(const Expr *E, const ExplodedNode *N,
  bool LookingForReference = true) {
-  if (const auto *DR = dyn_cast(E)) {
-if (const auto *VD = dyn_cast(DR->getDecl())) {
-  if (LookingForReference && !VD->getType()->isReferenceType())
-return nullptr;
-  return N->getState()
-  ->getLValue(VD, N->getLocationContext())
-  .getAsRegion();
+  if (const auto *ME = dyn_cast(E)) {
+// This handles other kinds of null references,
+// for example, references from FieldRegions:
+//   struct Wrapper { int &ref; };
+//   Wrapper w = { *(int *)0 };
+//   w.ref = 1;
+const Expr *Base = ME->getBase();
+const VarDecl *VD = getVarDeclForExpression(Base);
+if (!VD)
+  return nullptr;
+
+const auto *FD = dyn_cast(ME->getMemberDecl());
+if (!FD)
+  return nullptr;
+
+if (FD->getType()->isReferenceType()) {
+  SVal StructSVal = N->getState()->getLValue(VD, N->getLocationContext());
+  return N->getState()->getLValue(FD, StructSVal).getAsRegion();
 }
+return nullptr;
   }
 
-  // FIXME: This does not handle other kinds of null references,
-  // for example, references from FieldRegions:
-  //   struct Wrapper { int &ref; };
-  //   Wrapper w = { *(int *)0 };
-  //   w.ref = 1;
-
-  return nullptr;
+  const VarDecl *VD = getVarDeclForExpression(E);
+  if (!VD)
+return nullptr;
+  if (LookingForReference && !VD->getType()->isReferenceType())
+return nullptr;
+  return N->getState()->getLValue(VD, N->getLocationContext()).getAsRegion();
 }
 
 /// Comparing internal representations of symbolic values (via

From 5bf3ba5f3b66d972e3c26c8f782ae077700e459a Mon Sep 17 00:00:00 2001
From: Gabor Spaits 
Date: Tue, 10 Oct 2023 15:26:28 +0200
Subject: [PATCH 2/4] Add test cases for null reference reports

---
 .../deref-track-symbolic-region.cpp   | 31 +++
 1 file changed, 31 insertions(+)

diff --git a/clang/test/Analysis/diagnostics/deref-track-symbolic-region.cpp 
b/clang/test/Analysis/diagnostics/deref-track-symbolic-region.cpp
index e258a60aa966a53..2442851da989b16 100644
--- a/clang/test/Analysis/diagnostics/deref-track-symbolic-region.cpp
+++ b/clang/test/Analysis/diagnostics/deref-track-symbolic-region.cpp
@@ -41,3 +41,34 @@ int testRefToNullPtr2() {
   return *p2; //expected-warning {{Dereference of null pointer}}
   // expected-note@-1{{Dereference of null pointer}}
 }
+
+void testMemberNullPointerDeref() {
+  struct Wrapper {char c; int *ptr; };  
+  Wrapper w = {'a', nullptr};   // expected-note {{'w.ptr' initialized 
to a null pointer value}}
+  *w.ptr = 1;   //expected-warning {{Dereference of 
null pointer}}
+// expected-note@-1{{Dereference of 
null pointer}}
+}
+
+void testMemberNullReferenceDeref() {
+  struct Wrapper {char c; int &ref; };
+  Wrapper w = {.c = 'a', .ref = *(int *)0 }; // expected-note {{'w.ref' 
initialized to a null pointer value}}
+   

[clang] [analyzer] Fix note for member reference (PR #68691)

2023-10-12 Thread Gábor Spaits via cfe-commits

https://github.com/spaits updated 
https://github.com/llvm/llvm-project/pull/68691

From bb9cb77cab7b073d45c0b998c926a0b60a75a35e Mon Sep 17 00:00:00 2001
From: Gabor Spaits 
Date: Tue, 10 Oct 2023 13:40:05 +0200
Subject: [PATCH 1/5] [analyzer] Fix note for member reference

---
 .../Core/BugReporterVisitors.cpp  | 57 ++-
 1 file changed, 43 insertions(+), 14 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp 
b/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
index 42d03f67510cf88..914011f367d8f2e 100644
--- a/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
+++ b/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
@@ -132,6 +132,18 @@ const Expr *bugreporter::getDerefExpr(const Stmt *S) {
 }
 // Pattern match for a few useful cases: a[0], p->f, *p etc.
 else if (const auto *ME = dyn_cast(E)) {
+  // This handles the case when the dereferencing of a member reference
+  // happens. This is needed, because the ast for dereferencing of a
+  // member reference looks like the following:
+  // |-MemberExpr
+  //  `-DeclRefExpr
+  // This branch without the special case just takes out the DeclRefExpr
+  // of the struct, class or union.
+  // This is wrong, because this DeclRefExpr will be passed
+  // to the bug reporting and the notes will refer to wrong variable
+  // (the struct instead of the member).
+  if (ME->getMemberDecl()->getType()->isReferenceType())
+break;
   E = ME->getBase();
 } else if (const auto *IvarRef = dyn_cast(E)) {
   E = IvarRef->getBase();
@@ -157,26 +169,43 @@ const Expr *bugreporter::getDerefExpr(const Stmt *S) {
   return E;
 }
 
+static const VarDecl *getVarDeclForExpression(const Expr *E) {
+  if (const auto *DR = dyn_cast(E))
+return dyn_cast(DR->getDecl());
+  return nullptr;
+}
+
 static const MemRegion *
 getLocationRegionIfReference(const Expr *E, const ExplodedNode *N,
  bool LookingForReference = true) {
-  if (const auto *DR = dyn_cast(E)) {
-if (const auto *VD = dyn_cast(DR->getDecl())) {
-  if (LookingForReference && !VD->getType()->isReferenceType())
-return nullptr;
-  return N->getState()
-  ->getLValue(VD, N->getLocationContext())
-  .getAsRegion();
+  if (const auto *ME = dyn_cast(E)) {
+// This handles other kinds of null references,
+// for example, references from FieldRegions:
+//   struct Wrapper { int &ref; };
+//   Wrapper w = { *(int *)0 };
+//   w.ref = 1;
+const Expr *Base = ME->getBase();
+const VarDecl *VD = getVarDeclForExpression(Base);
+if (!VD)
+  return nullptr;
+
+const auto *FD = dyn_cast(ME->getMemberDecl());
+if (!FD)
+  return nullptr;
+
+if (FD->getType()->isReferenceType()) {
+  SVal StructSVal = N->getState()->getLValue(VD, N->getLocationContext());
+  return N->getState()->getLValue(FD, StructSVal).getAsRegion();
 }
+return nullptr;
   }
 
-  // FIXME: This does not handle other kinds of null references,
-  // for example, references from FieldRegions:
-  //   struct Wrapper { int &ref; };
-  //   Wrapper w = { *(int *)0 };
-  //   w.ref = 1;
-
-  return nullptr;
+  const VarDecl *VD = getVarDeclForExpression(E);
+  if (!VD)
+return nullptr;
+  if (LookingForReference && !VD->getType()->isReferenceType())
+return nullptr;
+  return N->getState()->getLValue(VD, N->getLocationContext()).getAsRegion();
 }
 
 /// Comparing internal representations of symbolic values (via

From 5bf3ba5f3b66d972e3c26c8f782ae077700e459a Mon Sep 17 00:00:00 2001
From: Gabor Spaits 
Date: Tue, 10 Oct 2023 15:26:28 +0200
Subject: [PATCH 2/5] Add test cases for null reference reports

---
 .../deref-track-symbolic-region.cpp   | 31 +++
 1 file changed, 31 insertions(+)

diff --git a/clang/test/Analysis/diagnostics/deref-track-symbolic-region.cpp 
b/clang/test/Analysis/diagnostics/deref-track-symbolic-region.cpp
index e258a60aa966a53..2442851da989b16 100644
--- a/clang/test/Analysis/diagnostics/deref-track-symbolic-region.cpp
+++ b/clang/test/Analysis/diagnostics/deref-track-symbolic-region.cpp
@@ -41,3 +41,34 @@ int testRefToNullPtr2() {
   return *p2; //expected-warning {{Dereference of null pointer}}
   // expected-note@-1{{Dereference of null pointer}}
 }
+
+void testMemberNullPointerDeref() {
+  struct Wrapper {char c; int *ptr; };  
+  Wrapper w = {'a', nullptr};   // expected-note {{'w.ptr' initialized 
to a null pointer value}}
+  *w.ptr = 1;   //expected-warning {{Dereference of 
null pointer}}
+// expected-note@-1{{Dereference of 
null pointer}}
+}
+
+void testMemberNullReferenceDeref() {
+  struct Wrapper {char c; int &ref; };
+  Wrapper w = {.c = 'a', .ref = *(int *)0 }; // expected-note {{'w.ref' 
initialized to a null pointer value}}
+   

[clang] [analyzer] Fix note for member reference (PR #68691)

2023-10-12 Thread Gábor Spaits via cfe-commits

https://github.com/spaits updated 
https://github.com/llvm/llvm-project/pull/68691

From bb9cb77cab7b073d45c0b998c926a0b60a75a35e Mon Sep 17 00:00:00 2001
From: Gabor Spaits 
Date: Tue, 10 Oct 2023 13:40:05 +0200
Subject: [PATCH 1/6] [analyzer] Fix note for member reference

---
 .../Core/BugReporterVisitors.cpp  | 57 ++-
 1 file changed, 43 insertions(+), 14 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp 
b/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
index 42d03f67510cf88..914011f367d8f2e 100644
--- a/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
+++ b/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
@@ -132,6 +132,18 @@ const Expr *bugreporter::getDerefExpr(const Stmt *S) {
 }
 // Pattern match for a few useful cases: a[0], p->f, *p etc.
 else if (const auto *ME = dyn_cast(E)) {
+  // This handles the case when the dereferencing of a member reference
+  // happens. This is needed, because the ast for dereferencing of a
+  // member reference looks like the following:
+  // |-MemberExpr
+  //  `-DeclRefExpr
+  // This branch without the special case just takes out the DeclRefExpr
+  // of the struct, class or union.
+  // This is wrong, because this DeclRefExpr will be passed
+  // to the bug reporting and the notes will refer to wrong variable
+  // (the struct instead of the member).
+  if (ME->getMemberDecl()->getType()->isReferenceType())
+break;
   E = ME->getBase();
 } else if (const auto *IvarRef = dyn_cast(E)) {
   E = IvarRef->getBase();
@@ -157,26 +169,43 @@ const Expr *bugreporter::getDerefExpr(const Stmt *S) {
   return E;
 }
 
+static const VarDecl *getVarDeclForExpression(const Expr *E) {
+  if (const auto *DR = dyn_cast(E))
+return dyn_cast(DR->getDecl());
+  return nullptr;
+}
+
 static const MemRegion *
 getLocationRegionIfReference(const Expr *E, const ExplodedNode *N,
  bool LookingForReference = true) {
-  if (const auto *DR = dyn_cast(E)) {
-if (const auto *VD = dyn_cast(DR->getDecl())) {
-  if (LookingForReference && !VD->getType()->isReferenceType())
-return nullptr;
-  return N->getState()
-  ->getLValue(VD, N->getLocationContext())
-  .getAsRegion();
+  if (const auto *ME = dyn_cast(E)) {
+// This handles other kinds of null references,
+// for example, references from FieldRegions:
+//   struct Wrapper { int &ref; };
+//   Wrapper w = { *(int *)0 };
+//   w.ref = 1;
+const Expr *Base = ME->getBase();
+const VarDecl *VD = getVarDeclForExpression(Base);
+if (!VD)
+  return nullptr;
+
+const auto *FD = dyn_cast(ME->getMemberDecl());
+if (!FD)
+  return nullptr;
+
+if (FD->getType()->isReferenceType()) {
+  SVal StructSVal = N->getState()->getLValue(VD, N->getLocationContext());
+  return N->getState()->getLValue(FD, StructSVal).getAsRegion();
 }
+return nullptr;
   }
 
-  // FIXME: This does not handle other kinds of null references,
-  // for example, references from FieldRegions:
-  //   struct Wrapper { int &ref; };
-  //   Wrapper w = { *(int *)0 };
-  //   w.ref = 1;
-
-  return nullptr;
+  const VarDecl *VD = getVarDeclForExpression(E);
+  if (!VD)
+return nullptr;
+  if (LookingForReference && !VD->getType()->isReferenceType())
+return nullptr;
+  return N->getState()->getLValue(VD, N->getLocationContext()).getAsRegion();
 }
 
 /// Comparing internal representations of symbolic values (via

From 5bf3ba5f3b66d972e3c26c8f782ae077700e459a Mon Sep 17 00:00:00 2001
From: Gabor Spaits 
Date: Tue, 10 Oct 2023 15:26:28 +0200
Subject: [PATCH 2/6] Add test cases for null reference reports

---
 .../deref-track-symbolic-region.cpp   | 31 +++
 1 file changed, 31 insertions(+)

diff --git a/clang/test/Analysis/diagnostics/deref-track-symbolic-region.cpp 
b/clang/test/Analysis/diagnostics/deref-track-symbolic-region.cpp
index e258a60aa966a53..2442851da989b16 100644
--- a/clang/test/Analysis/diagnostics/deref-track-symbolic-region.cpp
+++ b/clang/test/Analysis/diagnostics/deref-track-symbolic-region.cpp
@@ -41,3 +41,34 @@ int testRefToNullPtr2() {
   return *p2; //expected-warning {{Dereference of null pointer}}
   // expected-note@-1{{Dereference of null pointer}}
 }
+
+void testMemberNullPointerDeref() {
+  struct Wrapper {char c; int *ptr; };  
+  Wrapper w = {'a', nullptr};   // expected-note {{'w.ptr' initialized 
to a null pointer value}}
+  *w.ptr = 1;   //expected-warning {{Dereference of 
null pointer}}
+// expected-note@-1{{Dereference of 
null pointer}}
+}
+
+void testMemberNullReferenceDeref() {
+  struct Wrapper {char c; int &ref; };
+  Wrapper w = {.c = 'a', .ref = *(int *)0 }; // expected-note {{'w.ref' 
initialized to a null pointer value}}
+   

[clang] [ASAN] Adjust asan instrumented GlobalVariable size to not include redzone (PR #66666)

2023-10-12 Thread Mitch Phillips via cfe-commits

hctim wrote:

My gut feeling is that it's a really bad idea to have a global variable whose 
symtab size differs from the underlying GV size. So I tested against lld, gold, 
and ld, and they all seem to end up with `int`-typed GVs having a filesize of 
32 bytes and an ELF `st_size` of 4 bytes, and the runtime seems okay, but I 
think this breaks ELF rules:

https://docs.oracle.com/cd/E19683-01/816-1386/chapter6-79797/index.html#:~:text=Symbol%20Values%22.-,st_size,-Many%20symbols%20have

> st_size: Many symbols have associated sizes. For example, a data object's 
> size is the number of bytes contained in the object. This member holds 0 if 
> the symbol has no size or an unknown size.

I suspect this could break relinkers and various other things.

It doesn't seem clear to me *why* amdgpu has problems with copying the extra 
redzone padding. We may also actually use the redzone for metadata and would 
expect that it would be consistent.

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


[clang] e44c9fd - [Clang] Regenerate test checks (NFC)

2023-10-12 Thread Nikita Popov via cfe-commits

Author: Nikita Popov
Date: 2023-10-12T14:24:26+02:00
New Revision: e44c9fd197a2209b6b7b266fb0a381ee8fcec12b

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

LOG: [Clang] Regenerate test checks (NFC)

Avoid extra diffs on future change.

Added: 


Modified: 
clang/test/CodeGen/PowerPC/builtins-ppc-pair-mma.c
clang/test/CodeGen/attr-arm-sve-vector-bits-bitcast.c
clang/test/CodeGen/attr-riscv-rvv-vector-bits-bitcast.c

Removed: 




diff  --git a/clang/test/CodeGen/PowerPC/builtins-ppc-pair-mma.c 
b/clang/test/CodeGen/PowerPC/builtins-ppc-pair-mma.c
index 95e28da9b0bf0e6..3922513e22469a9 100644
--- a/clang/test/CodeGen/PowerPC/builtins-ppc-pair-mma.c
+++ b/clang/test/CodeGen/PowerPC/builtins-ppc-pair-mma.c
@@ -4,7 +4,7 @@
 // RUN: %clang_cc1 -O3 -triple powerpc64-unknown-unknown -target-cpu pwr10 \
 // RUN: -emit-llvm %s -o - | FileCheck %s
 
-// CHECK-LABEL: define {{[^@]+}}@test1(
+// CHECK-LABEL: @test1(
 // CHECK-NEXT:  entry:
 // CHECK-NEXT:[[TMP0:%.*]] = tail call <512 x i1> 
@llvm.ppc.mma.assemble.acc(<16 x i8> [[VC:%.*]], <16 x i8> [[VC]], <16 x i8> 
[[VC]], <16 x i8> [[VC]])
 // CHECK-NEXT:store <512 x i1> [[TMP0]], ptr [[RESP:%.*]], align 64, !tbaa 
[[TBAA2:![0-9]+]]
@@ -18,7 +18,7 @@ void test1(unsigned char *vqp, unsigned char *vpp, vector 
unsigned char vc, unsi
   *((__vector_quad *)resp) = res;
 }
 
-// CHECK-LABEL: define {{[^@]+}}@test2(
+// CHECK-LABEL: @test2(
 // CHECK-NEXT:  entry:
 // CHECK-NEXT:[[TMP0:%.*]] = load <512 x i1>, ptr [[VQP:%.*]], align 64
 // CHECK-NEXT:[[TMP1:%.*]] = tail call { <16 x i8>, <16 x i8>, <16 x i8>, 
<16 x i8> } @llvm.ppc.mma.disassemble.acc(<512 x i1> [[TMP0]])
@@ -39,7 +39,7 @@ void test2(unsigned char *vqp, unsigned char *vpp, vector 
unsigned char vc, unsi
   __builtin_mma_disassemble_acc(resp, (__vector_quad*)vqp);
 }
 
-// CHECK-LABEL: define {{[^@]+}}@test3(
+// CHECK-LABEL: @test3(
 // CHECK-NEXT:  entry:
 // CHECK-NEXT:[[TMP0:%.*]] = tail call <256 x i1> 
@llvm.ppc.vsx.assemble.pair(<16 x i8> [[VC:%.*]], <16 x i8> [[VC]])
 // CHECK-NEXT:store <256 x i1> [[TMP0]], ptr [[RESP:%.*]], align 32, !tbaa 
[[TBAA6:![0-9]+]]
@@ -53,7 +53,7 @@ void test3(unsigned char *vqp, unsigned char *vpp, vector 
unsigned char vc, unsi
   *((__vector_pair *)resp) = res;
 }
 
-// CHECK-LABEL: define {{[^@]+}}@test4(
+// CHECK-LABEL: @test4(
 // CHECK-NEXT:  entry:
 // CHECK-NEXT:[[TMP0:%.*]] = load <256 x i1>, ptr [[VPP:%.*]], align 32
 // CHECK-NEXT:[[TMP1:%.*]] = tail call { <16 x i8>, <16 x i8> } 
@llvm.ppc.vsx.disassemble.pair(<256 x i1> [[TMP0]])
@@ -68,7 +68,7 @@ void test4(unsigned char *vqp, unsigned char *vpp, vector 
unsigned char vc, unsi
   __builtin_vsx_disassemble_pair(resp, (__vector_pair*)vpp);
 }
 
-// CHECK-LABEL: define {{[^@]+}}@test5(
+// CHECK-LABEL: @test5(
 // CHECK-NEXT:  entry:
 // CHECK-NEXT:[[TMP0:%.*]] = load <512 x i1>, ptr [[VQP:%.*]], align 64, 
!tbaa [[TBAA2]]
 // CHECK-NEXT:[[TMP1:%.*]] = tail call <512 x i1> 
@llvm.ppc.mma.xxmtacc(<512 x i1> [[TMP0]])
@@ -82,7 +82,7 @@ void test5(unsigned char *vqp, unsigned char *vpp, vector 
unsigned char vc, unsi
   *((__vector_quad *)resp) = vq;
 }
 
-// CHECK-LABEL: define {{[^@]+}}@test6(
+// CHECK-LABEL: @test6(
 // CHECK-NEXT:  entry:
 // CHECK-NEXT:[[TMP0:%.*]] = load <512 x i1>, ptr [[VQP:%.*]], align 64, 
!tbaa [[TBAA2]]
 // CHECK-NEXT:[[TMP1:%.*]] = tail call <512 x i1> 
@llvm.ppc.mma.xxmfacc(<512 x i1> [[TMP0]])
@@ -96,7 +96,7 @@ void test6(unsigned char *vqp, unsigned char *vpp, vector 
unsigned char vc, unsi
   *((__vector_quad *)resp) = vq;
 }
 
-// CHECK-LABEL: define {{[^@]+}}@test7(
+// CHECK-LABEL: @test7(
 // CHECK-NEXT:  entry:
 // CHECK-NEXT:[[TMP0:%.*]] = tail call <512 x i1> @llvm.ppc.mma.xxsetaccz()
 // CHECK-NEXT:store <512 x i1> [[TMP0]], ptr [[RESP:%.*]], align 64, !tbaa 
[[TBAA2]]
@@ -109,7 +109,7 @@ void test7(unsigned char *vqp, unsigned char *vpp, vector 
unsigned char vc, unsi
   *((__vector_quad *)resp) = vq;
 }
 
-// CHECK-LABEL: define {{[^@]+}}@test8(
+// CHECK-LABEL: @test8(
 // CHECK-NEXT:  entry:
 // CHECK-NEXT:[[TMP0:%.*]] = tail call <512 x i1> 
@llvm.ppc.mma.xvi4ger8(<16 x i8> [[VC:%.*]], <16 x i8> [[VC]])
 // CHECK-NEXT:store <512 x i1> [[TMP0]], ptr [[RESP:%.*]], align 64, !tbaa 
[[TBAA2]]
@@ -122,7 +122,7 @@ void test8(unsigned char *vqp, unsigned char *vpp, vector 
unsigned char vc, unsi
   *((__vector_quad *)resp) = vq;
 }
 
-// CHECK-LABEL: define {{[^@]+}}@test9(
+// CHECK-LABEL: @test9(
 // CHECK-NEXT:  entry:
 // CHECK-NEXT:[[TMP0:%.*]] = tail call <512 x i1> 
@llvm.ppc.mma.xvi8ger4(<16 x i8> [[VC:%.*]], <16 x i8> [[VC]])
 // CHECK-NEXT:store <512 x i1> [[TMP0]], ptr [[RESP:%.*]], align 64, !tbaa 
[[TBAA2]]
@@ -135,7 +135,7 @@ void test9(unsigned c

[clang] [flang] add tbaa tags to global and direct values (PR #68727)

2023-10-12 Thread Tom Eccles via cfe-commits

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


[clang] [ARM] fix "+fp.dp" in multilib selection (PR #67412)

2023-10-12 Thread via cfe-commits


@@ -420,20 +444,35 @@ bool ARM::appendArchExtFeatures(StringRef CPU, 
ARM::ArchKind AK,
 CPU = "generic";
 
   if (ArchExt == "fp" || ArchExt == "fp.dp") {
+const ARM::FPUKind DefaultFPU = getDefaultFPU(CPU, AK);
 ARM::FPUKind FPUKind;
 if (ArchExt == "fp.dp") {
+  const bool IsDP = ArgFPUKind != ARM::FK_INVALID &&
+ArgFPUKind != ARM::FK_NONE &&
+isDoublePrecision(getFPURestriction(ArgFPUKind));

john-brawn-arm wrote:

This function is called in order to set ArgFPUKind, so checking it here (and 
below) looks strange. I would expect it to always be FK_INVALID, is there any 
situation in which it's not?

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


[PATCH] D158069: [clang][Interp] Fix getIndex() for composite array elements

2023-10-12 Thread Nico Weber via Phabricator via cfe-commits
thakis added inline comments.



Comment at: clang/unittests/AST/Interp/CMakeLists.txt:2
+add_clang_unittest(InterpTests
+  Descriptor.cpp
+  )

Why is this in a separate executable instead of in ASTTests? So it can have 
fewer deps?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D158069

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


[clang] [InstCombine] Canonicalize constant GEPs to i8 source element type (PR #68882)

2023-10-12 Thread Nikita Popov via cfe-commits


@@ -560,14 +560,15 @@ define i32 @test28() nounwind  {
 ; CHECK-NEXT:  entry:
 ; CHECK-NEXT:[[ORIENTATIONS:%.*]] = alloca [1 x [1 x %struct.x]], align 8
 ; CHECK-NEXT:[[T3:%.*]] = call i32 @puts(ptr noundef nonnull 
dereferenceable(1) @.str) #[[ATTR0]]
+; CHECK-NEXT:[[T45:%.*]] = getelementptr inbounds i8, ptr 
[[ORIENTATIONS]], i64 1
 ; CHECK-NEXT:br label [[BB10:%.*]]
 ; CHECK:   bb10:
 ; CHECK-NEXT:[[INDVAR:%.*]] = phi i32 [ 0, [[ENTRY:%.*]] ], [ 
[[INDVAR_NEXT:%.*]], [[BB10]] ]
 ; CHECK-NEXT:[[T12_REC:%.*]] = xor i32 [[INDVAR]], -1
 ; CHECK-NEXT:[[TMP0:%.*]] = sext i32 [[T12_REC]] to i64
-; CHECK-NEXT:[[T12:%.*]] = getelementptr inbounds [1 x [1 x %struct.x]], 
ptr [[ORIENTATIONS]], i64 1, i64 0, i64 [[TMP0]]
+; CHECK-NEXT:[[T12:%.*]] = getelementptr inbounds [[STRUCT_X:%.*]], ptr 
[[T45]], i64 [[TMP0]]
 ; CHECK-NEXT:[[T16:%.*]] = call i32 (ptr, ...) @printf(ptr noundef nonnull 
dereferenceable(1) @.str1, ptr nonnull [[T12]]) #[[ATTR0]]
-; CHECK-NEXT:[[T84:%.*]] = icmp eq i32 [[INDVAR]], 0
+; CHECK-NEXT:[[T84:%.*]] = icmp eq ptr [[T12]], [[ORIENTATIONS]]

nikic wrote:

Index compare fold regression.

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


[clang] [InstCombine] Canonicalize constant GEPs to i8 source element type (PR #68882)

2023-10-12 Thread Nikita Popov via cfe-commits


@@ -3,8 +3,9 @@
 
 define ptr @f1(ptr %arg, i64 %arg1) {
 ; CHECK-LABEL: @f1(
-; CHECK-NEXT:[[TMP1:%.*]] = getelementptr [6 x i32], ptr [[ARG:%.*]], i64 
3, i64 [[ARG1:%.*]]
-; CHECK-NEXT:ret ptr [[TMP1]]
+; CHECK-NEXT:[[TMP1:%.*]] = getelementptr i8, ptr [[ARG:%.*]], i64 72
+; CHECK-NEXT:[[TMP2:%.*]] = getelementptr [6 x i32], ptr [[TMP1]], i64 0, 
i64 [[ARG1:%.*]]

nikic wrote:

Possible regression. We kind of want to move in his direction, though it 
happens by accident here.

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


[clang] [InstCombine] Canonicalize constant GEPs to i8 source element type (PR #68882)

2023-10-12 Thread Nikita Popov via cfe-commits

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


[clang] [InstCombine] Canonicalize constant GEPs to i8 source element type (PR #68882)

2023-10-12 Thread Nikita Popov via cfe-commits

https://github.com/nikic commented:

I looked through the test diffs, and it seems like the only substantial 
regressions are all related to the indexed compare fold, which should be made 
type-independent.

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


[clang] [InstCombine] Canonicalize constant GEPs to i8 source element type (PR #68882)

2023-10-12 Thread Nikita Popov via cfe-commits


@@ -597,14 +598,13 @@ define ptr @gep_of_phi_of_gep_different_type(i1 %c, ptr 
%p) {
 ; CHECK-LABEL: @gep_of_phi_of_gep_different_type(
 ; CHECK-NEXT:br i1 [[C:%.*]], label [[IF:%.*]], label [[ELSE:%.*]]
 ; CHECK:   if:
-; CHECK-NEXT:[[GEP1:%.*]] = getelementptr i32, ptr [[P:%.*]], i64 1
 ; CHECK-NEXT:br label [[JOIN:%.*]]
 ; CHECK:   else:
-; CHECK-NEXT:[[GEP2:%.*]] = getelementptr i64, ptr [[P]], i64 2
 ; CHECK-NEXT:br label [[JOIN]]
 ; CHECK:   join:
-; CHECK-NEXT:[[PHI:%.*]] = phi ptr [ [[GEP1]], [[IF]] ], [ [[GEP2]], 
[[ELSE]] ]
-; CHECK-NEXT:[[GEP:%.*]] = getelementptr i32, ptr [[PHI]], i64 1
+; CHECK-NEXT:[[TMP1:%.*]] = phi i64 [ 4, [[IF]] ], [ 16, [[ELSE]] ]
+; CHECK-NEXT:[[TMP2:%.*]] = getelementptr i8, ptr [[P:%.*]], i64 [[TMP1]]
+; CHECK-NEXT:[[GEP:%.*]] = getelementptr i8, ptr [[TMP2]], i64 4

nikic wrote:

Improvement.

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


[clang] [InstCombine] Canonicalize constant GEPs to i8 source element type (PR #68882)

2023-10-12 Thread Nikita Popov via cfe-commits


@@ -637,9 +637,8 @@ define ptr @select_of_gep(i1 %c, ptr %p) {
 
 define ptr @select_of_gep_different_type(i1 %c, ptr %p) {
 ; CHECK-LABEL: @select_of_gep_different_type(
-; CHECK-NEXT:[[GEP1:%.*]] = getelementptr i32, ptr [[P:%.*]], i64 1
-; CHECK-NEXT:[[GEP2:%.*]] = getelementptr i64, ptr [[P]], i64 2
-; CHECK-NEXT:[[S:%.*]] = select i1 [[C:%.*]], ptr [[GEP1]], ptr [[GEP2]]
+; CHECK-NEXT:[[S_V:%.*]] = select i1 [[C:%.*]], i64 4, i64 16
+; CHECK-NEXT:[[S:%.*]] = getelementptr i8, ptr [[P:%.*]], i64 [[S_V]]

nikic wrote:

Improvement.

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


[clang] [InstCombine] Canonicalize constant GEPs to i8 source element type (PR #68882)

2023-10-12 Thread Nikita Popov via cfe-commits


@@ -6,15 +6,16 @@ target datalayout = 
"e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:32:32-f3
 define ptr@test1(ptr %A, i32 %Offset) {
 ; CHECK-LABEL: @test1(
 ; CHECK-NEXT:  entry:
+; CHECK-NEXT:[[TMP:%.*]] = getelementptr inbounds i32, ptr [[A:%.*]], i32 
[[OFFSET:%.*]]
 ; CHECK-NEXT:br label [[BB:%.*]]
 ; CHECK:   bb:
-; CHECK-NEXT:[[RHS_IDX:%.*]] = phi i32 [ [[RHS_ADD:%.*]], [[BB]] ], [ 
[[OFFSET:%.*]], [[ENTRY:%.*]] ]
-; CHECK-NEXT:[[RHS_ADD]] = add nsw i32 [[RHS_IDX]], 1
-; CHECK-NEXT:[[COND:%.*]] = icmp sgt i32 [[RHS_IDX]], 100
+; CHECK-NEXT:[[RHS:%.*]] = phi ptr [ [[RHS_NEXT:%.*]], [[BB]] ], [ 
[[TMP]], [[ENTRY:%.*]] ]
+; CHECK-NEXT:[[LHS:%.*]] = getelementptr inbounds i8, ptr [[A]], i32 400
+; CHECK-NEXT:[[RHS_NEXT]] = getelementptr inbounds i8, ptr [[RHS]], i32 4
+; CHECK-NEXT:[[COND:%.*]] = icmp ult ptr [[LHS]], [[RHS]]
 ; CHECK-NEXT:br i1 [[COND]], label [[BB2:%.*]], label [[BB]]
 ; CHECK:   bb2:
-; CHECK-NEXT:[[RHS_PTR:%.*]] = getelementptr inbounds i32, ptr [[A:%.*]], 
i32 [[RHS_IDX]]
-; CHECK-NEXT:ret ptr [[RHS_PTR]]
+; CHECK-NEXT:ret ptr [[RHS]]

nikic wrote:

Index compare fold regression.

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


[PATCH] D158069: [clang][Interp] Fix getIndex() for composite array elements

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



Comment at: clang/unittests/AST/Interp/CMakeLists.txt:2
+add_clang_unittest(InterpTests
+  Descriptor.cpp
+  )

thakis wrote:
> Why is this in a separate executable instead of in ASTTests? So it can have 
> fewer deps?
Mostly because running ASTTests takes very long


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D158069

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


[clang] [time-trace] Add a new time trace scope variable named "ParseDeclarationOrFunctionDefinition". (PR #65268)

2023-10-12 Thread via cfe-commits

https://github.com/MaggieYingYi updated 
https://github.com/llvm/llvm-project/pull/65268

>From cc5cf9500cbdbb2fdd332c7de26c0516e49594bf Mon Sep 17 00:00:00 2001
From: Ying Yi 
Date: Fri, 1 Sep 2023 15:30:44 +0100
Subject: [PATCH 1/2] Add a new time trace scope variable named
 "ParseDeclarationOrFunctionDefinition".

When profiling code using `-ftime-trace` with the default 
`time-trace-granularity` value (500 microseconds), in some code there is a 
large empty timeline in the flame chart profiling view (using Chrome Tracing 
view).  If you pass `-ftime-trace-granularity=0` in order to show all time 
traces, the empty timeline consists of a large number of small time scopes 
named `EvaluateAsConstExpr`.  This change adds an enclosing time trace scope 
for the function `Parser::ParseDeclarationOrFunctionDefinition` to record the 
time spent parsing  the function's declaration or definition.
---
 clang/lib/Parse/Parser.cpp|  6 ++-
 ...e-ParseDeclarationOrFunctionDefinition.cpp | 10 +
 clang/unittests/Support/TimeProfilerTest.cpp  | 42 +++
 3 files changed, 39 insertions(+), 19 deletions(-)
 create mode 100644 
clang/test/Driver/check-time-trace-ParseDeclarationOrFunctionDefinition.cpp

diff --git a/clang/lib/Parse/Parser.cpp b/clang/lib/Parse/Parser.cpp
index 0f930248e77174b..ef0d98d60746f9c 100644
--- a/clang/lib/Parse/Parser.cpp
+++ b/clang/lib/Parse/Parser.cpp
@@ -13,8 +13,8 @@
 #include "clang/Parse/Parser.h"
 #include "clang/AST/ASTConsumer.h"
 #include "clang/AST/ASTContext.h"
-#include "clang/AST/DeclTemplate.h"
 #include "clang/AST/ASTLambda.h"
+#include "clang/AST/DeclTemplate.h"
 #include "clang/Basic/FileManager.h"
 #include "clang/Parse/ParseDiagnostic.h"
 #include "clang/Parse/RAIIObjectsForParser.h"
@@ -22,6 +22,7 @@
 #include "clang/Sema/ParsedTemplate.h"
 #include "clang/Sema/Scope.h"
 #include "llvm/Support/Path.h"
+#include "llvm/Support/TimeProfiler.h"
 using namespace clang;
 
 
@@ -1229,6 +1230,9 @@ Parser::DeclGroupPtrTy 
Parser::ParseDeclOrFunctionDefInternal(
 Parser::DeclGroupPtrTy Parser::ParseDeclarationOrFunctionDefinition(
 ParsedAttributes &Attrs, ParsedAttributes &DeclSpecAttrs,
 ParsingDeclSpec *DS, AccessSpecifier AS) {
+  // Add an enclosing time trace scope for a bunch of small scopes with
+  // "EvaluateAsConstExpr".
+  llvm::TimeTraceScope TimeScope("ParseDeclarationOrFunctionDefinition");
   if (DS) {
 return ParseDeclOrFunctionDefInternal(Attrs, DeclSpecAttrs, *DS, AS);
   } else {
diff --git 
a/clang/test/Driver/check-time-trace-ParseDeclarationOrFunctionDefinition.cpp 
b/clang/test/Driver/check-time-trace-ParseDeclarationOrFunctionDefinition.cpp
new file mode 100644
index 000..be1cc51cc6669f3
--- /dev/null
+++ 
b/clang/test/Driver/check-time-trace-ParseDeclarationOrFunctionDefinition.cpp
@@ -0,0 +1,10 @@
+// RUN: %clangxx -S -ftime-trace -ftime-trace-granularity=0 -o 
%T/check-time-trace-ParseDeclarationOrFunctionDefinition %s
+// RUN: cat %T/check-time-trace-ParseDeclarationOrFunctionDefinition.json \
+// RUN:   | %python -c 'import json, sys; 
json.dump(json.loads(sys.stdin.read()), sys.stdout, sort_keys=True, indent=2)' \
+// RUN:   | FileCheck %s
+
+// CHECK: "name": "ParseDeclarationOrFunctionDefinition"
+
+template 
+void foo(T) {}
+void bar() { foo(0); }
diff --git a/clang/unittests/Support/TimeProfilerTest.cpp 
b/clang/unittests/Support/TimeProfilerTest.cpp
index a7ca2bf91e474ef..62b37ab5c5e6424 100644
--- a/clang/unittests/Support/TimeProfilerTest.cpp
+++ b/clang/unittests/Support/TimeProfilerTest.cpp
@@ -177,22 +177,27 @@ constexpr int slow_init_list[] = {1, 1, 2, 3, 5, 8, 13, 
21}; // 25th line
   std::string TraceGraph = buildTraceGraph(Json);
   ASSERT_TRUE(TraceGraph == R"(
 Frontend
-| EvaluateAsRValue ()
-| EvaluateForOverflow ()
-| EvaluateForOverflow ()
-| EvaluateAsRValue ()
-| EvaluateForOverflow ()
-| isPotentialConstantExpr (slow_namespace::slow_func)
-| EvaluateAsBooleanCondition ()
-| | EvaluateAsRValue ()
-| EvaluateAsBooleanCondition ()
-| | EvaluateAsRValue ()
-| EvaluateAsInitializer (slow_value)
-| EvaluateAsConstantExpr ()
-| EvaluateAsConstantExpr ()
-| EvaluateAsConstantExpr ()
-| EvaluateAsRValue ()
-| EvaluateAsInitializer (slow_init_list)
+| ParseDeclarationOrFunctionDefinition
+| ParseDeclarationOrFunctionDefinition
+| | EvaluateAsRValue ()
+| | EvaluateForOverflow ()
+| | EvaluateForOverflow ()
+| | EvaluateAsRValue ()
+| | EvaluateForOverflow ()
+| | isPotentialConstantExpr (slow_namespace::slow_func)
+| | EvaluateAsBooleanCondition ()
+| | | EvaluateAsRValue ()
+| | EvaluateAsBooleanCondition ()
+| | | EvaluateAsRValue ()
+| ParseDeclarationOrFunctionDefinition
+| | EvaluateAsInitializer (slow_value)
+| | EvaluateAsConstantExpr ()
+| | EvaluateAsConstantExpr ()
+| | EvaluateAsConstantExpr ()
+| ParseDeclarationOrFunctionDefinition
+| | EvaluateAsRValue ()
+| ParseDeclarationOrFunctionDefinition
+| | EvaluateAsInitializer (slow_init_list)
 | PerformPendingInstantiati

[clang] [time-trace] Add a new time trace scope variable named "ParseDeclarationOrFunctionDefinition". (PR #65268)

2023-10-12 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-driver

Author: None (MaggieYingYi)


Changes

When profiling code using `-ftime-trace` with the default 
`time-trace-granularity` value (500 microseconds), in some code there is a 
large empty timeline in the flame chart profiling view (using Chrome Tracing 
view).  If you pass `-ftime-trace-granularity=0` in order to show all time 
traces, the empty timeline consists of a large number of small time scopes 
named `EvaluateAsConstExpr`.  This change adds an enclosing time trace scope 
for the function `Parser::ParseDeclarationOrFunctionDefinition` to record the 
time spent parsing  the function's declaration or definition.

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


3 Files Affected:

- (modified) clang/lib/Parse/Parser.cpp (+9-1) 
- (added) 
clang/test/Driver/check-time-trace-ParseDeclarationOrFunctionDefinition.cpp 
(+14) 
- (modified) clang/unittests/Support/TimeProfilerTest.cpp (+26-18) 


``diff
diff --git a/clang/lib/Parse/Parser.cpp b/clang/lib/Parse/Parser.cpp
index 0f930248e77174b..533a9af173178b0 100644
--- a/clang/lib/Parse/Parser.cpp
+++ b/clang/lib/Parse/Parser.cpp
@@ -13,8 +13,8 @@
 #include "clang/Parse/Parser.h"
 #include "clang/AST/ASTConsumer.h"
 #include "clang/AST/ASTContext.h"
-#include "clang/AST/DeclTemplate.h"
 #include "clang/AST/ASTLambda.h"
+#include "clang/AST/DeclTemplate.h"
 #include "clang/Basic/FileManager.h"
 #include "clang/Parse/ParseDiagnostic.h"
 #include "clang/Parse/RAIIObjectsForParser.h"
@@ -22,6 +22,7 @@
 #include "clang/Sema/ParsedTemplate.h"
 #include "clang/Sema/Scope.h"
 #include "llvm/Support/Path.h"
+#include "llvm/Support/TimeProfiler.h"
 using namespace clang;
 
 
@@ -1229,6 +1230,9 @@ Parser::DeclGroupPtrTy 
Parser::ParseDeclOrFunctionDefInternal(
 Parser::DeclGroupPtrTy Parser::ParseDeclarationOrFunctionDefinition(
 ParsedAttributes &Attrs, ParsedAttributes &DeclSpecAttrs,
 ParsingDeclSpec *DS, AccessSpecifier AS) {
+  // Add an enclosing time trace scope for a bunch of small scopes with
+  // "EvaluateAsConstExpr".
+  llvm::TimeTraceScope TimeScope("ParseDeclarationOrFunctionDefinition");
   if (DS) {
 return ParseDeclOrFunctionDefInternal(Attrs, DeclSpecAttrs, *DS, AS);
   } else {
@@ -1259,6 +1263,10 @@ Parser::DeclGroupPtrTy 
Parser::ParseDeclarationOrFunctionDefinition(
 Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D,
   const ParsedTemplateInfo &TemplateInfo,
   LateParsedAttrList *LateParsedAttrs) {
+  llvm::TimeTraceScope TimeScope(
+  "ParseFunctionDefinition",
+  Actions.GetNameForDeclarator(D).getName().getAsString());
+
   // Poison SEH identifiers so they are flagged as illegal in function bodies.
   PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
   const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
diff --git 
a/clang/test/Driver/check-time-trace-ParseDeclarationOrFunctionDefinition.cpp 
b/clang/test/Driver/check-time-trace-ParseDeclarationOrFunctionDefinition.cpp
new file mode 100644
index 000..96bb37d57823e8b
--- /dev/null
+++ 
b/clang/test/Driver/check-time-trace-ParseDeclarationOrFunctionDefinition.cpp
@@ -0,0 +1,14 @@
+// RUN: %clangxx -S -ftime-trace -ftime-trace-granularity=0 -o 
%T/check-time-trace-ParseDeclarationOrFunctionDefinition %s
+// RUN: cat %T/check-time-trace-ParseDeclarationOrFunctionDefinition.json \
+// RUN:   | %python -c 'import json, sys; 
json.dump(json.loads(sys.stdin.read()), sys.stdout, sort_keys=True, indent=2)' \
+// RUN:   | FileCheck %s
+
+// CHECK-DAG: "name": "ParseDeclarationOrFunctionDefinition"
+// CHECK-DAG: "name": "ParseFunctionDefinition"
+// CHECK-DAG: "detail": "foo"
+// CHECK-DAG: "name": "ParseFunctionDefinition"
+// CHECK-DAG: "detail": "bar"
+
+template 
+void foo(T) {}
+void bar() { foo(0); }
diff --git a/clang/unittests/Support/TimeProfilerTest.cpp 
b/clang/unittests/Support/TimeProfilerTest.cpp
index a7ca2bf91e474ef..f69a54692b0072a 100644
--- a/clang/unittests/Support/TimeProfilerTest.cpp
+++ b/clang/unittests/Support/TimeProfilerTest.cpp
@@ -177,22 +177,29 @@ constexpr int slow_init_list[] = {1, 1, 2, 3, 5, 8, 13, 
21}; // 25th line
   std::string TraceGraph = buildTraceGraph(Json);
   ASSERT_TRUE(TraceGraph == R"(
 Frontend
-| EvaluateAsRValue ()
-| EvaluateForOverflow ()
-| EvaluateForOverflow ()
-| EvaluateAsRValue ()
-| EvaluateForOverflow ()
-| isPotentialConstantExpr (slow_namespace::slow_func)
-| EvaluateAsBooleanCondition ()
-| | EvaluateAsRValue ()
-| EvaluateAsBooleanCondition ()
-| | EvaluateAsRValue ()
-| EvaluateAsInitializer (slow_value)
-| EvaluateAsConstantExpr ()
-| EvaluateAsConstantExpr ()
-| EvaluateAsConstantExpr ()
-| EvaluateAsRValue ()
-| EvaluateAsInitializer (slow_init_list)
+| ParseDeclarationOrFunctionDefinition
+| ParseDeclarationOrFunctionDefinition
+| | ParseFunctionDefinition (slow_func)
+| | | EvaluateAsRValue ()
+| | | Eva

[clang] [clang][Interp] Add explicit dummy descriptors (PR #68888)

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

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

Instead of (ab)using incomplete array types for this, add a 'Dummy' bit to 
Descriptor. We need to be able to differentiate between the two when adding an 
offset.

>From 03184302329bfd3e02cd97ccfa26613379d8767f Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Thu, 12 Oct 2023 15:27:38 +0200
Subject: [PATCH] [clang][Interp] Add explicit dummy descriptors

Instead of (ab)using incomplete array types for this, add a 'Dummy' bit
to Descriptor. We need to be able to differentiate between the two when
adding an offset.
---
 clang/lib/AST/Interp/Descriptor.cpp|  7 +++
 clang/lib/AST/Interp/Descriptor.h  |  6 ++
 clang/lib/AST/Interp/Interp.cpp|  6 ++
 clang/lib/AST/Interp/Interp.h  | 20 ++--
 clang/lib/AST/Interp/InterpBuiltin.cpp |  3 +++
 clang/lib/AST/Interp/Pointer.h |  2 ++
 clang/lib/AST/Interp/Program.cpp   | 20 +++-
 clang/test/AST/Interp/c.c  | 10 ++
 8 files changed, 59 insertions(+), 15 deletions(-)

diff --git a/clang/lib/AST/Interp/Descriptor.cpp 
b/clang/lib/AST/Interp/Descriptor.cpp
index 4ecb7466998e705..56e03a32abe5c34 100644
--- a/clang/lib/AST/Interp/Descriptor.cpp
+++ b/clang/lib/AST/Interp/Descriptor.cpp
@@ -284,6 +284,13 @@ Descriptor::Descriptor(const DeclTy &D, Record *R, 
MetadataSize MD,
   assert(Source && "Missing source");
 }
 
+Descriptor::Descriptor(const DeclTy &D, MetadataSize MD)
+: Source(D), ElemSize(1), Size(ElemSize), MDSize(MD.value_or(0)),
+  AllocSize(Size + MDSize), ElemRecord(nullptr), IsConst(true),
+  IsMutable(false), IsTemporary(false), IsDummy(true) {
+  assert(Source && "Missing source");
+}
+
 QualType Descriptor::getType() const {
   if (auto *E = asExpr())
 return E->getType();
diff --git a/clang/lib/AST/Interp/Descriptor.h 
b/clang/lib/AST/Interp/Descriptor.h
index 55a754c3505cce7..8de637a31a0 100644
--- a/clang/lib/AST/Interp/Descriptor.h
+++ b/clang/lib/AST/Interp/Descriptor.h
@@ -109,6 +109,8 @@ struct Descriptor final {
   const bool IsTemporary = false;
   /// Flag indicating if the block is an array.
   const bool IsArray = false;
+  /// Flag indicating if this is a dummy descriptor.
+  const bool IsDummy = false;
 
   /// Storage management methods.
   const BlockCtorFn CtorFn = nullptr;
@@ -137,6 +139,8 @@ struct Descriptor final {
   Descriptor(const DeclTy &D, Record *R, MetadataSize MD, bool IsConst,
  bool IsTemporary, bool IsMutable);
 
+  Descriptor(const DeclTy &D, MetadataSize MD);
+
   QualType getType() const;
   QualType getElemQualType() const;
   SourceLocation getLocation() const;
@@ -190,6 +194,8 @@ struct Descriptor final {
   bool isArray() const { return IsArray; }
   /// Checks if the descriptor is of a record.
   bool isRecord() const { return !IsArray && ElemRecord; }
+  /// Checks if this is a dummy descriptor.
+  bool isDummy() const { return IsDummy; }
 };
 
 /// Bitfield tracking the initialisation status of elements of primitive 
arrays.
diff --git a/clang/lib/AST/Interp/Interp.cpp b/clang/lib/AST/Interp/Interp.cpp
index a4d6844ebe61722..1d14241106a63eb 100644
--- a/clang/lib/AST/Interp/Interp.cpp
+++ b/clang/lib/AST/Interp/Interp.cpp
@@ -186,6 +186,10 @@ bool CheckLive(InterpState &S, CodePtr OpPC, const Pointer 
&Ptr,
   return true;
 }
 
+bool CheckDummy(InterpState &S, CodePtr OpPC, const Pointer &Ptr) {
+  return !Ptr.isDummy();
+}
+
 bool CheckNull(InterpState &S, CodePtr OpPC, const Pointer &Ptr,
CheckSubobjectKind CSK) {
   if (!Ptr.isZero())
@@ -268,6 +272,8 @@ bool CheckInitialized(InterpState &S, CodePtr OpPC, const 
Pointer &Ptr,
 }
 
 bool CheckLoad(InterpState &S, CodePtr OpPC, const Pointer &Ptr) {
+  if (!CheckDummy(S, OpPC, Ptr))
+return false;
   if (!CheckLive(S, OpPC, Ptr, AK_Read))
 return false;
   if (!CheckExtern(S, OpPC, Ptr))
diff --git a/clang/lib/AST/Interp/Interp.h b/clang/lib/AST/Interp/Interp.h
index 1ad3b8bfc7711d3..4d2cd9dc2ae8c1d 100644
--- a/clang/lib/AST/Interp/Interp.h
+++ b/clang/lib/AST/Interp/Interp.h
@@ -55,6 +55,10 @@ bool CheckArray(InterpState &S, CodePtr OpPC, const Pointer 
&Ptr);
 /// Checks if a pointer is live and accessible.
 bool CheckLive(InterpState &S, CodePtr OpPC, const Pointer &Ptr,
AccessKinds AK);
+
+/// Checks if a pointer is a dummy pointer.
+bool CheckDummy(InterpState &S, CodePtr OpPC, const Pointer &Ptr);
+
 /// Checks if a pointer is null.
 bool CheckNull(InterpState &S, CodePtr OpPC, const Pointer &Ptr,
CheckSubobjectKind CSK);
@@ -1423,8 +1427,9 @@ bool OffsetHelper(InterpState &S, CodePtr OpPC, const T 
&Offset,
   // Compute the largest index into the array.
   unsigned MaxIndex = Ptr.getNumElems();
 
+  bool Invalid = false;
   // Helper to report an invalid offset, computed as APSInt.
-  auto InvalidOffset = [&]() {
+  auto DiagInvalidOffset = [&]() -> void {
 cons

[clang] [clang][Interp] Add explicit dummy descriptors (PR #68888)

2023-10-12 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Timm Baeder (tbaederr)


Changes

Instead of (ab)using incomplete array types for this, add a 'Dummy' bit to 
Descriptor. We need to be able to differentiate between the two when adding an 
offset.

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


8 Files Affected:

- (modified) clang/lib/AST/Interp/Descriptor.cpp (+7) 
- (modified) clang/lib/AST/Interp/Descriptor.h (+6) 
- (modified) clang/lib/AST/Interp/Interp.cpp (+6) 
- (modified) clang/lib/AST/Interp/Interp.h (+14-6) 
- (modified) clang/lib/AST/Interp/InterpBuiltin.cpp (+3) 
- (modified) clang/lib/AST/Interp/Pointer.h (+2) 
- (modified) clang/lib/AST/Interp/Program.cpp (+11-9) 
- (modified) clang/test/AST/Interp/c.c (+10) 


``diff
diff --git a/clang/lib/AST/Interp/Descriptor.cpp 
b/clang/lib/AST/Interp/Descriptor.cpp
index 4ecb7466998e705..56e03a32abe5c34 100644
--- a/clang/lib/AST/Interp/Descriptor.cpp
+++ b/clang/lib/AST/Interp/Descriptor.cpp
@@ -284,6 +284,13 @@ Descriptor::Descriptor(const DeclTy &D, Record *R, 
MetadataSize MD,
   assert(Source && "Missing source");
 }
 
+Descriptor::Descriptor(const DeclTy &D, MetadataSize MD)
+: Source(D), ElemSize(1), Size(ElemSize), MDSize(MD.value_or(0)),
+  AllocSize(Size + MDSize), ElemRecord(nullptr), IsConst(true),
+  IsMutable(false), IsTemporary(false), IsDummy(true) {
+  assert(Source && "Missing source");
+}
+
 QualType Descriptor::getType() const {
   if (auto *E = asExpr())
 return E->getType();
diff --git a/clang/lib/AST/Interp/Descriptor.h 
b/clang/lib/AST/Interp/Descriptor.h
index 55a754c3505cce7..8de637a31a0 100644
--- a/clang/lib/AST/Interp/Descriptor.h
+++ b/clang/lib/AST/Interp/Descriptor.h
@@ -109,6 +109,8 @@ struct Descriptor final {
   const bool IsTemporary = false;
   /// Flag indicating if the block is an array.
   const bool IsArray = false;
+  /// Flag indicating if this is a dummy descriptor.
+  const bool IsDummy = false;
 
   /// Storage management methods.
   const BlockCtorFn CtorFn = nullptr;
@@ -137,6 +139,8 @@ struct Descriptor final {
   Descriptor(const DeclTy &D, Record *R, MetadataSize MD, bool IsConst,
  bool IsTemporary, bool IsMutable);
 
+  Descriptor(const DeclTy &D, MetadataSize MD);
+
   QualType getType() const;
   QualType getElemQualType() const;
   SourceLocation getLocation() const;
@@ -190,6 +194,8 @@ struct Descriptor final {
   bool isArray() const { return IsArray; }
   /// Checks if the descriptor is of a record.
   bool isRecord() const { return !IsArray && ElemRecord; }
+  /// Checks if this is a dummy descriptor.
+  bool isDummy() const { return IsDummy; }
 };
 
 /// Bitfield tracking the initialisation status of elements of primitive 
arrays.
diff --git a/clang/lib/AST/Interp/Interp.cpp b/clang/lib/AST/Interp/Interp.cpp
index a4d6844ebe61722..1d14241106a63eb 100644
--- a/clang/lib/AST/Interp/Interp.cpp
+++ b/clang/lib/AST/Interp/Interp.cpp
@@ -186,6 +186,10 @@ bool CheckLive(InterpState &S, CodePtr OpPC, const Pointer 
&Ptr,
   return true;
 }
 
+bool CheckDummy(InterpState &S, CodePtr OpPC, const Pointer &Ptr) {
+  return !Ptr.isDummy();
+}
+
 bool CheckNull(InterpState &S, CodePtr OpPC, const Pointer &Ptr,
CheckSubobjectKind CSK) {
   if (!Ptr.isZero())
@@ -268,6 +272,8 @@ bool CheckInitialized(InterpState &S, CodePtr OpPC, const 
Pointer &Ptr,
 }
 
 bool CheckLoad(InterpState &S, CodePtr OpPC, const Pointer &Ptr) {
+  if (!CheckDummy(S, OpPC, Ptr))
+return false;
   if (!CheckLive(S, OpPC, Ptr, AK_Read))
 return false;
   if (!CheckExtern(S, OpPC, Ptr))
diff --git a/clang/lib/AST/Interp/Interp.h b/clang/lib/AST/Interp/Interp.h
index 1ad3b8bfc7711d3..4d2cd9dc2ae8c1d 100644
--- a/clang/lib/AST/Interp/Interp.h
+++ b/clang/lib/AST/Interp/Interp.h
@@ -55,6 +55,10 @@ bool CheckArray(InterpState &S, CodePtr OpPC, const Pointer 
&Ptr);
 /// Checks if a pointer is live and accessible.
 bool CheckLive(InterpState &S, CodePtr OpPC, const Pointer &Ptr,
AccessKinds AK);
+
+/// Checks if a pointer is a dummy pointer.
+bool CheckDummy(InterpState &S, CodePtr OpPC, const Pointer &Ptr);
+
 /// Checks if a pointer is null.
 bool CheckNull(InterpState &S, CodePtr OpPC, const Pointer &Ptr,
CheckSubobjectKind CSK);
@@ -1423,8 +1427,9 @@ bool OffsetHelper(InterpState &S, CodePtr OpPC, const T 
&Offset,
   // Compute the largest index into the array.
   unsigned MaxIndex = Ptr.getNumElems();
 
+  bool Invalid = false;
   // Helper to report an invalid offset, computed as APSInt.
-  auto InvalidOffset = [&]() {
+  auto DiagInvalidOffset = [&]() -> void {
 const unsigned Bits = Offset.bitWidth();
 APSInt APOffset(Offset.toAPSInt().extend(Bits + 2), false);
 APSInt APIndex(Index.toAPSInt().extend(Bits + 2), false);
@@ -1434,28 +1439,31 @@ bool OffsetHelper(InterpState &S, CodePtr OpPC, const T 
&Offset,
 << NewIndex
 << /*array*/ static_cast(!Ptr.inArray())
 << static

[clang] [clang][Interp] Only evaluate the source array initialization of an `ArrayInitLoopExpr` once (PR #68039)

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

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


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


[clang] [clang][Interp] Only evaluate the source array initialization of an `ArrayInitLoopExpr` once (PR #68039)

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

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


[clang] [clang][Interp] Only evaluate the source array initialization of an `ArrayInitLoopExpr` once (PR #68039)

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


@@ -478,6 +480,43 @@ template  class SourceLocScope final {
   bool Enabled = false;
 };
 
+template  class StoredOpaqueValueScope final {
+public:
+  StoredOpaqueValueScope(ByteCodeExprGen *Ctx) : Ctx(Ctx) {}
+
+  bool VisitAndStoreOpaqueValue(const OpaqueValueExpr *Ove) {
+assert(Ove && "OpaqueValueExpr is a nullptr!");
+assert(!Ctx->OpaqueExprs.contains(Ove) &&
+   "OpaqueValueExpr already stored!");
+
+std::optional CommonTy = Ctx->classify(Ove);
+std::optional LocalIndex = Ctx->allocateLocalPrimitive(
+Ove, *CommonTy, Ove->getType().isConstQualified());
+if (!LocalIndex)
+  return false;
+
+if (!Ctx->visit(Ove))
+  return false;
+
+if (!Ctx->emitSetLocal(*CommonTy, *LocalIndex, Ove))
+  return false;
+
+Ctx->OpaqueExprs.insert({Ove, *LocalIndex});
+StoredValues.emplace_back(Ove);
+
+return true;

tbaederr wrote:

I think all the visiting logic should go into `ByteCodeExprGen.cpp`.

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


[clang] [clang][Interp] Only evaluate the source array initialization of an `ArrayInitLoopExpr` once (PR #68039)

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


@@ -478,6 +480,43 @@ template  class SourceLocScope final {
   bool Enabled = false;
 };
 
+template  class StoredOpaqueValueScope final {
+public:
+  StoredOpaqueValueScope(ByteCodeExprGen *Ctx) : Ctx(Ctx) {}
+
+  bool VisitAndStoreOpaqueValue(const OpaqueValueExpr *Ove) {
+assert(Ove && "OpaqueValueExpr is a nullptr!");
+assert(!Ctx->OpaqueExprs.contains(Ove) &&
+   "OpaqueValueExpr already stored!");
+
+std::optional CommonTy = Ctx->classify(Ove);
+std::optional LocalIndex = Ctx->allocateLocalPrimitive(
+Ove, *CommonTy, Ove->getType().isConstQualified());
+if (!LocalIndex)
+  return false;
+
+if (!Ctx->visit(Ove))
+  return false;
+
+if (!Ctx->emitSetLocal(*CommonTy, *LocalIndex, Ove))
+  return false;
+
+Ctx->OpaqueExprs.insert({Ove, *LocalIndex});
+StoredValues.emplace_back(Ove);
+
+return true;
+  }
+
+  ~StoredOpaqueValueScope() {
+for (const auto *SV : StoredValues)
+  Ctx->OpaqueExprs.erase(SV);
+  }
+
+private:
+  ByteCodeExprGen *Ctx;
+  std::vector StoredValues;

tbaederr wrote:

Why is this vector necessary?

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


[clang] [clang][Interp] Only evaluate the source array initialization of an `ArrayInitLoopExpr` once (PR #68039)

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


@@ -366,8 +363,7 @@ namespace ArrayInitLoop {
   auto [a, b, c] = f(n).arr;
   return a + b + c;
   }
-  static_assert(g() == 6); // expected-error {{failed}} \
-   // expected-note {{15 == 6}}
+  static_assert(g() == 6);

tbaederr wrote:

```suggestion
  static_assert(g() == 6, "");
```

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


[clang] [clang][Interp] Only evaluate the source array initialization of an `ArrayInitLoopExpr` once (PR #68039)

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


@@ -827,6 +829,9 @@ bool ByteCodeExprGen::VisitArrayInitLoopExpr(
 
 template 
 bool ByteCodeExprGen::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
+  if (OpaqueExprs.contains(E))
+return this->emitGetLocal(*classify(E), OpaqueExprs[E], E);

tbaederr wrote:

Can `E` be of  composite type? If so, we need to handle that. If not,  you can 
just use `classifyPrim` instead.

This code also potentially does two lookups. you should do `auto It = 
OpaqueExprs.find(E); It != OpaqueExprs.end()) {`

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


[clang] [time-trace] Add a new time trace scope variable named "ParseDeclarationOrFunctionDefinition". (PR #65268)

2023-10-12 Thread via cfe-commits


@@ -1224,6 +1225,9 @@ Parser::DeclGroupPtrTy 
Parser::ParseDeclOrFunctionDefInternal(
 Parser::DeclGroupPtrTy Parser::ParseDeclarationOrFunctionDefinition(
 ParsedAttributes &Attrs, ParsedAttributes &DeclSpecAttrs,
 ParsingDeclSpec *DS, AccessSpecifier AS) {
+  // Add an enclosing time trace scope for a bunch of small scopes with
+  // "EvaluateAsConstExpr".
+  llvm::TimeTraceScope TimeScope("ParseDeclarationOrFunctionDefinition");

MaggieYingYi wrote:

Hi @AaronBallman ,

Many thanks for your suggestions.

> Should we supply a second argument to the ctor here so that we can include 
> the function name as part of the time trace output?

Good point. I cannot add `function name` as a second argument in the 
`Parser::ParseDeclarationOrFunctionDefinition()` since the function 
definition/declaration is not parsed yet. However, as you suggested, I have 
added a new time trace variable to `Parser::ParseFunctionDefinition()` and 
included the function name as a part of the time trace output in the commit 
https://github.com/llvm/llvm-project/pull/65268/commits/deecf8c2.

> Also, I wonder if we want more or less granularity here. This will fire for 
> function declarations and function definitions, so we could add it to 
> `Parser::ParseFunctionDefinition()` instead to only time function definition 
> parsing, or we could split it up so that we time parsing function signatures 
> separately from parsing the function body so we can more easily see how much 
> time is spent in which activity.

As mentioned above, I have added a new time trace variable of 
`ParseFunctionDefinition`. However, I cannot remove the time trace variable of 
"ParseDeclarationOrFunctionDefinition" since `ParseFunctionDefinition` doesn't 
enclose small time scopes (named EvaluateAsConstExpr) in the function 
declarations. The initial issue is shown in the function declarations (not 
function definitions).

I will use a simple test to show the issue.

1. Source file test.cpp:
```
$ cat test.cpp
consteval double slow_func() {
double d = 0.0;
for (int i = 0; i < 100; ++i) {
d += i;
}
return d;
}

void slow_test() {
constexpr auto slow_value = slow_func();
}

int slow_arr[12 + 34 * 56 + static_cast(slow_func())];
```

2. Compile test.cpp using the clang which is built using the repo of 
yingyi/main/time-trace:
```
$ clang.exe -ftime-trace -ftime-trace-granularity=0  -std=c++20 test.cpp -c -o 
test.o
```

3. View the generated time-trace file of test.json using `chrome://tracing/`.

For `slow_arr`, it uses the `slow_func()` declaration. `EvaluateAsConstantExpr` 
is under the time scope of `ParseDeclarationOrFunctionDefinition` but not under 
the time scope of `ParseFunctionDefinition`.

Therefore, I think we need both time scope variables of 
`ParseDeclarationOrFunctionDefinition` and 
`ParseFunctionDefinition`.

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


[clang] [clang][Interp] Fix crash during `InterpStack` printing (PR #68246)

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

tbaederr wrote:

> Although the previous
> implementation didn't have unittests either, so I'm not sure if we actually 
> care that much or not.

We don't, I think I've used this function once. But I don't want to delete it 
either because it could come in handy in the future.


LGTM

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


[clang] [clang][Interp] Fix crash during `InterpStack` printing (PR #68246)

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

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


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


[clang] [CodeGen][OpenMP] Set the default schedule for loops to static,1 if TSan is enabled (PR #68891)

2023-10-12 Thread via cfe-commits

https://github.com/felilxtomski created 
https://github.com/llvm/llvm-project/pull/68891

To ease the race detection in OpenMP for loops where no schedule is specified 
as in the new archer test from DRB.

>From 6f6cba41a85598f28e70fbfdebcd3e5aef4e9df4 Mon Sep 17 00:00:00 2001
From: "felix.tomski" 
Date: Thu, 12 Oct 2023 15:03:48 +0200
Subject: [PATCH 1/2] [openmp] Set the default schedule for loops to static,1
 if TSan is enabled

To ease the race detection in for loops where no schedule is specified.
---
 clang/lib/CodeGen/CGOpenMPRuntime.cpp | 7 ---
 1 file changed, 4 insertions(+), 3 deletions(-)

diff --git a/clang/lib/CodeGen/CGOpenMPRuntime.cpp 
b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
index aae1a0ea250eea2..c17d352fdbeb19e 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntime.cpp
+++ b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
@@ -2446,9 +2446,10 @@ unsigned 
CGOpenMPRuntime::getDefaultFlagsForBarriers(OpenMPDirectiveKind Kind) {
 void CGOpenMPRuntime::getDefaultScheduleAndChunk(
 CodeGenFunction &CGF, const OMPLoopDirective &S,
 OpenMPScheduleClauseKind &ScheduleKind, const Expr *&ChunkExpr) const {
-  // Check if the loop directive is actually a doacross loop directive. In this
-  // case choose static, 1 schedule.
-  if (llvm::any_of(
+  // Check if the loop directive is actually a doacross loop directive or
+  // ThreadSanitizer is enabled. In these cases choose static, 1 schedule.
+  if (CGF.SanOpts.has(SanitizerKind::Thread) ||
+  llvm::any_of(
   S.getClausesOfKind(),
   [](const OMPOrderedClause *C) { return C->getNumForLoops(); })) {
 ScheduleKind = OMPC_SCHEDULE_static;

>From 8b25e95008c4d794c4423d026c39382a0c7cfbf8 Mon Sep 17 00:00:00 2001
From: "felix.tomski" 
Date: Wed, 11 Oct 2023 16:17:39 +0200
Subject: [PATCH 2/2] [archer] Add DRB test originally requiring 36 threads
 with default schedule

---
 .../races/DRB006-indirectaccess2-orig-yes.c   | 161 ++
 1 file changed, 161 insertions(+)
 create mode 100644 
openmp/tools/archer/tests/races/DRB006-indirectaccess2-orig-yes.c

diff --git a/openmp/tools/archer/tests/races/DRB006-indirectaccess2-orig-yes.c 
b/openmp/tools/archer/tests/races/DRB006-indirectaccess2-orig-yes.c
new file mode 100644
index 000..c9d1bf0ae0ed9bc
--- /dev/null
+++ b/openmp/tools/archer/tests/races/DRB006-indirectaccess2-orig-yes.c
@@ -0,0 +1,161 @@
+/*
+ * DRB006-indirectaccess2-orig-yes.c -- Archer testcase
+ */
+//===--===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+//
+// See tools/archer/LICENSE.txt for details.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+/*
+Copyright (c) 2017, Lawrence Livermore National Security, LLC.
+Produced at the Lawrence Livermore National Laboratory
+Written by Chunhua Liao, Pei-Hung Lin, Joshua Asplund,
+Markus Schordan, and Ian Karlin
+(email: li...@llnl.gov, li...@llnl.gov, asplu...@llnl.gov,
+schord...@llnl.gov, karl...@llnl.gov)
+LLNL-CODE-732144
+All rights reserved.
+
+This file is part of DataRaceBench. For details, see
+https://github.com/LLNL/dataracebench. Please also see the LICENSE file
+for our additional BSD notice.
+
+Redistribution and use in source and binary forms, with
+or without modification, are permitted provided that the following
+conditions are met:
+
+* Redistributions of source code must retain the above copyright
+  notice, this list of conditions and the disclaimer below.
+
+* Redistributions in binary form must reproduce the above copyright
+  notice, this list of conditions and the disclaimer (as noted below)
+  in the documentation and/or other materials provided with the
+  distribution.
+
+* Neither the name of the LLNS/LLNL nor the names of its contributors
+  may be used to endorse or promote products derived from this
+  software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
+CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
+INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL LAWRENCE LIVERMORE NATIONAL
+SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE
+LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
+OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
+IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+THE POSSIBILITY OF SUCH DAMAGE.
+*/
+/*
+Two pointers have a distance of 12 (p1 - p2 = 12).
+They are used as base addresses for indirect array accesses using an index set 
(another arr

[clang] [CodeGen][OpenMP] Set the default schedule for loops to static,1 if TSan is enabled (PR #68891)

2023-10-12 Thread via cfe-commits

github-actions[bot] wrote:




:warning: C/C++ code formatter, clang-format found issues in your code. 
:warning:



You can test this locally with the following command:


``bash
git-clang-format --diff 30240e428f0ec7d4a6d1b84f9f807ce12b46cfd1 
8b25e95008c4d794c4423d026c39382a0c7cfbf8 -- 
openmp/tools/archer/tests/races/DRB006-indirectaccess2-orig-yes.c 
clang/lib/CodeGen/CGOpenMPRuntime.cpp
``





View the diff from clang-format here.


``diff
diff --git a/openmp/tools/archer/tests/races/DRB006-indirectaccess2-orig-yes.c 
b/openmp/tools/archer/tests/races/DRB006-indirectaccess2-orig-yes.c
index c9d1bf0ae..bfa451484 100644
--- a/openmp/tools/archer/tests/races/DRB006-indirectaccess2-orig-yes.c
+++ b/openmp/tools/archer/tests/races/DRB006-indirectaccess2-orig-yes.c
@@ -57,19 +57,21 @@ THE POSSIBILITY OF SUCH DAMAGE.
 */
 /*
 Two pointers have a distance of 12 (p1 - p2 = 12).
-They are used as base addresses for indirect array accesses using an index set 
(another array).
+They are used as base addresses for indirect array accesses using an index set
+(another array).
 
 The index set has two indices with a distance of 12 :
 indexSet[5]- indexSet[0] = 533 - 521 =  12
-So there is loop carried dependence (e.g. between loops with index values of 0 
and 5).
+So there is loop carried dependence (e.g. between loops with index values of 0
+and 5).
 
 We use the default loop scheduling (static even) in OpenMP.
 It is possible that two dependent iterations will be scheduled
 within a same chunk to a same thread. So there is no runtime data races.
 
 When N is 180, two iterations with N=0 and N= 5 have loop carried dependencies.
-For static even scheduling, we must have at least 36 threads (180/36=5 
iterations)
-so iteration 0 and 5 will be scheduled to two different threads.
+For static even scheduling, we must have at least 36 threads (180/36=5
+iterations) so iteration 0 and 5 will be scheduled to two different threads.
 Data race pair: xa1[idx]@128:5:W vs. xa2[idx]@129:5:W
 */
 
@@ -78,74 +80,63 @@ Data race pair: xa1[idx]@128:5:W vs. xa2[idx]@129:5:W
 // REQUIRES: tsan
 #include 
 #include 
-#include 
 #include 
+#include 
 
 #define NUM_THREADS 2
 
 #define N 180
-int indexSet[N] = {
-521, 523, 525, 527, 529, 533, // 521+12=533
-547, 549, 551, 553, 555, 557,
-573, 575, 577, 579, 581, 583,
-599, 601, 603, 605, 607, 609,
-625, 627, 629, 631, 633, 635,
-
-651, 653, 655, 657, 659, 661,
-859, 861, 863, 865, 867, 869,
-885, 887, 889, 891, 893, 895,
-911, 913, 915, 917, 919, 921, 
-937, 939, 941, 943, 945, 947,
-
-963, 965, 967, 969, 971, 973,
-989, 991, 993, 995, 997, 999, 
-1197, 1199, 1201, 1203, 1205, 1207,
-1223, 1225, 1227, 1229, 1231, 1233,
-1249, 1251, 1253, 1255, 1257, 1259,
-
-1275, 1277, 1279, 1281, 1283, 1285,
-1301, 1303, 1305, 1307, 1309, 1311,
-1327, 1329, 1331, 1333, 1335, 1337,
-1535, 1537, 1539, 1541, 1543, 1545,
-1561, 1563, 1565, 1567, 1569, 1571,
-
-1587, 1589, 1591, 1593, 1595, 1597,
-1613, 1615, 1617, 1619, 1621, 1623,
-1639, 1641, 1643, 1645, 1647, 1649,
-1665, 1667, 1669, 1671, 1673, 1675,
-1873, 1875, 1877, 1879, 1881, 1883,
-
-1899, 1901, 1903, 1905, 1907, 1909,
-1925, 1927, 1929, 1931, 1933, 1935,
-1951, 1953, 1955, 1957, 1959, 1961,
-1977, 1979, 1981, 1983, 1985, 1987,
-2003, 2005, 2007, 2009, 2011, 2013};
-
-int main (int argc, char* argv[])
-{
-  double * base = (double*) malloc(sizeof(double)* (2013+12+1));
+int indexSet[N] = {521,  523,  525,  527,  529,  533, // 521+12=533
+   547,  549,  551,  553,  555,  557,  573,  575,  577,  579,
+   581,  583,  599,  601,  603,  605,  607,  609,  625,  627,
+   629,  631,  633,  635,
+
+   651,  653,  655,  657,  659,  661,  859,  861,  863,  865,
+   867,  869,  885,  887,  889,  891,  893,  895,  911,  913,
+   915,  917,  919,  921,  937,  939,  941,  943,  945,  947,
+
+   963,  965,  967,  969,  971,  973,  989,  991,  993,  995,
+   997,  999,  1197, 1199, 1201, 1203, 1205, 1207, 1223, 1225,
+   1227, 1229, 1231, 1233, 1249, 1251, 1253, 1255, 1257, 1259,
+
+   1275, 1277, 1279, 1281, 1283, 1285, 1301, 1303, 1305, 1307,
+   1309, 1311, 1327, 1329, 1331, 1333, 1335, 1337, 1535, 1537,
+   1539, 1541, 1543, 1545, 1561, 1563, 1565, 1567, 1569, 1571,
+
+   1587, 1589, 1591, 1593, 1595, 1597, 1613, 1615, 1617, 1619,
+   1621, 1623, 1639, 1641, 1643, 1645, 1647, 1649, 1665, 1667,
+   1669, 1671, 1673, 1675, 1873, 1875, 1877, 1879, 1881, 1883,
+
+   1899, 1901, 1903, 1905, 1907, 1909, 1925, 1927, 1929, 1931,
+   1933, 1935, 1951, 1953, 1955, 1957, 1959, 1961, 1977, 1979,
+   1981, 1983, 1985, 1987, 2003, 2005, 2007, 2009, 2011, 2013};
+
+int main(int argc, char *argv[]) {
+  double *base = (double *)malloc(sizeof(double) * (2013 + 12 + 1)

[clang] [CUDA][HIP] Fix host/device context in concept (PR #67721)

2023-10-12 Thread Yaxun Liu via cfe-commits

yxsamliu wrote:

ping

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


[clang] [CodeGen][OpenMP] Set the default schedule for loops to static,1 if TSan is enabled (PR #68891)

2023-10-12 Thread Shilei Tian via cfe-commits


@@ -0,0 +1,161 @@
+/*
+ * DRB006-indirectaccess2-orig-yes.c -- Archer testcase
+ */
+//===--===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+//
+// See tools/archer/LICENSE.txt for details.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+/*
+Copyright (c) 2017, Lawrence Livermore National Security, LLC.

shiltian wrote:

@jdoerfert what is our policy regarding test case copyright?

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


[clang] [ASAN] Adjust asan instrumented GlobalVariable size to not include redzone (PR #66666)

2023-10-12 Thread via cfe-commits

b-sumner wrote:

@hctim *any* implementation will have a problem when copying the redzone 
padding.  That is simply because the redzone is poisoned (hence the name).  Any 
access to a poisoned location will be reported and the application terminated.  
That is how ASAN works.

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


[clang] [clang]Transform uninstantiated ExceptionSpec in TemplateInstantiator (PR #68878)

2023-10-12 Thread Erich Keane via cfe-commits

https://github.com/erichkeane commented:

I'll have to think on this... First blush is that it is fine, but I want a 
chance to get other opinions as well

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


[clang] [clang]Transform uninstantiated ExceptionSpec in TemplateInstantiator (PR #68878)

2023-10-12 Thread Erich Keane via cfe-commits


@@ -377,6 +377,8 @@ Bug Fixes in This Version
   cannot be used with ``Release`` mode builds. (`#68237 
`_).
 - Fix crash in evaluating ``constexpr`` value for invalid template function.
   Fixes (`#68542 `_)
+- Clang will correctly evaluate ``noexcept`` expression with template in 
template
+  method of template record.

erichkeane wrote:

Please do a 'fixes' link to both of the bugs you're fixing.

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


[clang] [clang]Transform uninstantiated ExceptionSpec in TemplateInstantiator (PR #68878)

2023-10-12 Thread Erich Keane via cfe-commits

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


[clang] [flang][driver] support -dumpversion and -dumpmachine (PR #68896)

2023-10-12 Thread Yuanfang Chen via cfe-commits

https://github.com/yuanfang-chen created 
https://github.com/llvm/llvm-project/pull/68896

Match GCC driver. GCC has -cc1/-fc1 support too, but this patch does not 
address that.

>From b248b63c74853cfd57809ffc32f437c517a926ef Mon Sep 17 00:00:00 2001
From: Yuanfang Chen 
Date: Thu, 12 Oct 2023 07:40:13 +
Subject: [PATCH] [flang][driver] support -dumpversion and -dumpmachine

Match GCC driver. GCC has -cc1/-fc1 support too, but this patch
does not address that.
---
 clang/include/clang/Driver/Driver.h  | 7 ++-
 clang/include/clang/Driver/Options.td| 8 ++--
 clang/lib/Driver/Driver.cpp  | 9 +
 flang/test/Driver/driver-help-hidden.f90 | 2 ++
 flang/test/Driver/driver-help.f90| 2 ++
 flang/test/Driver/dumpmachine.f90| 8 
 flang/test/Driver/immediate-options.f90  | 2 ++
 7 files changed, 31 insertions(+), 7 deletions(-)
 create mode 100644 flang/test/Driver/dumpmachine.f90
 create mode 100644 flang/test/Driver/immediate-options.f90

diff --git a/clang/include/clang/Driver/Driver.h 
b/clang/include/clang/Driver/Driver.h
index 3ee1bcf2a69c9bd..fdb8aaf3572ba31 100644
--- a/clang/include/clang/Driver/Driver.h
+++ b/clang/include/clang/Driver/Driver.h
@@ -12,6 +12,7 @@
 #include "clang/Basic/Diagnostic.h"
 #include "clang/Basic/HeaderInclude.h"
 #include "clang/Basic/LLVM.h"
+#include "clang/Basic/Version.h"
 #include "clang/Driver/Action.h"
 #include "clang/Driver/DriverDiagnostic.h"
 #include "clang/Driver/InputInfo.h"
@@ -188,6 +189,9 @@ class Driver {
   /// Driver title to use with help.
   std::string DriverTitle;
 
+  /// Driver version.
+  std::string DriverVersion;
+
   /// Information about the host which can be overridden by the user.
   std::string HostBits, HostMachine, HostSystem, HostRelease;
 
@@ -373,7 +377,8 @@ class Driver {
 
   Driver(StringRef ClangExecutable, StringRef TargetTriple,
  DiagnosticsEngine &Diags, std::string Title = "clang LLVM compiler",
- IntrusiveRefCntPtr VFS = nullptr);
+ IntrusiveRefCntPtr VFS = nullptr,
+ std::string Version = CLANG_VERSION_STRING);
 
   /// @name Accessors
   /// @{
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index c272a7f1c398aa6..cae7bd07fc3cc54 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -1375,9 +1375,13 @@ def dsym_dir : JoinedOrSeparate<["-"], "dsym-dir">,
 def dumpdir : Separate<["-"], "dumpdir">, Visibility<[ClangOption, CC1Option]>,
   MetaVarName<"">,
   HelpText<"Use  as a prefix to form auxiliary and dump file names">;
-def dumpmachine : Flag<["-"], "dumpmachine">;
+def dumpmachine : Flag<["-"], "dumpmachine">,
+  Visibility<[ClangOption, FlangOption]>,
+  HelpText<"Display the compiler's target processor">;
+def dumpversion : Flag<["-"], "dumpversion">,
+  Visibility<[ClangOption, FlangOption]>,
+  HelpText<"Display the version of the compiler">;
 def dumpspecs : Flag<["-"], "dumpspecs">, Flags<[Unsupported]>;
-def dumpversion : Flag<["-"], "dumpversion">;
 def dylib__file : Separate<["-"], "dylib_file">;
 def dylinker__install__name : JoinedOrSeparate<["-"], "dylinker_install_name">;
 def dylinker : Flag<["-"], "dylinker">;
diff --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index 77328e1f99e5021..c84acb2beb17a70 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -190,14 +190,15 @@ std::string Driver::GetResourcesPath(StringRef BinaryPath,
 
 Driver::Driver(StringRef ClangExecutable, StringRef TargetTriple,
DiagnosticsEngine &Diags, std::string Title,
-   IntrusiveRefCntPtr VFS)
+   IntrusiveRefCntPtr VFS,
+   std::string Version)
 : Diags(Diags), VFS(std::move(VFS)), Mode(GCCMode),
   SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone),
   Offload(OffloadHostDevice), CXX20HeaderType(HeaderMode_None),
   ModulesModeCXX20(false), LTOMode(LTOK_None),
   ClangExecutable(ClangExecutable), SysRoot(DEFAULT_SYSROOT),
-  DriverTitle(Title), CCCPrintBindings(false), CCPrintOptions(false),
-  CCLogDiagnostics(false), CCGenDiagnostics(false),
+  DriverTitle(Title), DriverVersion(Version), CCCPrintBindings(false),
+  CCPrintOptions(false), CCLogDiagnostics(false), CCGenDiagnostics(false),
   CCPrintProcessStats(false), CCPrintInternalStats(false),
   TargetTriple(TargetTriple), Saver(Alloc), PrependArg(nullptr),
   CheckInputsExist(true), ProbePrecompiled(true),
@@ -2081,7 +2082,7 @@ bool Driver::HandleImmediateArgs(const Compilation &C) {
   if (C.getArgs().hasArg(options::OPT_dumpversion)) {
 // Since -dumpversion is only implemented for pedantic GCC compatibility, 
we
 // return an answer which matches our definition of __VERSION__.
-llvm::outs() << CLANG_VERSION_STRING << "\n";
+llvm::outs() << DriverVersion << "\n";
 return false;
   }
 
diff --git a/flang/test/Driver/driver-help-hidden.f90 

[clang] [flang][driver] support -dumpversion and -dumpmachine (PR #68896)

2023-10-12 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-flang-driver

Author: Yuanfang Chen (yuanfang-chen)


Changes

Match GCC driver. GCC has -cc1/-fc1 support too, but this patch does not 
address that.

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


7 Files Affected:

- (modified) clang/include/clang/Driver/Driver.h (+6-1) 
- (modified) clang/include/clang/Driver/Options.td (+6-2) 
- (modified) clang/lib/Driver/Driver.cpp (+5-4) 
- (modified) flang/test/Driver/driver-help-hidden.f90 (+2) 
- (modified) flang/test/Driver/driver-help.f90 (+2) 
- (added) flang/test/Driver/dumpmachine.f90 (+8) 
- (added) flang/test/Driver/immediate-options.f90 (+2) 


``diff
diff --git a/clang/include/clang/Driver/Driver.h 
b/clang/include/clang/Driver/Driver.h
index 3ee1bcf2a69c9bd..fdb8aaf3572ba31 100644
--- a/clang/include/clang/Driver/Driver.h
+++ b/clang/include/clang/Driver/Driver.h
@@ -12,6 +12,7 @@
 #include "clang/Basic/Diagnostic.h"
 #include "clang/Basic/HeaderInclude.h"
 #include "clang/Basic/LLVM.h"
+#include "clang/Basic/Version.h"
 #include "clang/Driver/Action.h"
 #include "clang/Driver/DriverDiagnostic.h"
 #include "clang/Driver/InputInfo.h"
@@ -188,6 +189,9 @@ class Driver {
   /// Driver title to use with help.
   std::string DriverTitle;
 
+  /// Driver version.
+  std::string DriverVersion;
+
   /// Information about the host which can be overridden by the user.
   std::string HostBits, HostMachine, HostSystem, HostRelease;
 
@@ -373,7 +377,8 @@ class Driver {
 
   Driver(StringRef ClangExecutable, StringRef TargetTriple,
  DiagnosticsEngine &Diags, std::string Title = "clang LLVM compiler",
- IntrusiveRefCntPtr VFS = nullptr);
+ IntrusiveRefCntPtr VFS = nullptr,
+ std::string Version = CLANG_VERSION_STRING);
 
   /// @name Accessors
   /// @{
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index c272a7f1c398aa6..cae7bd07fc3cc54 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -1375,9 +1375,13 @@ def dsym_dir : JoinedOrSeparate<["-"], "dsym-dir">,
 def dumpdir : Separate<["-"], "dumpdir">, Visibility<[ClangOption, CC1Option]>,
   MetaVarName<"">,
   HelpText<"Use  as a prefix to form auxiliary and dump file names">;
-def dumpmachine : Flag<["-"], "dumpmachine">;
+def dumpmachine : Flag<["-"], "dumpmachine">,
+  Visibility<[ClangOption, FlangOption]>,
+  HelpText<"Display the compiler's target processor">;
+def dumpversion : Flag<["-"], "dumpversion">,
+  Visibility<[ClangOption, FlangOption]>,
+  HelpText<"Display the version of the compiler">;
 def dumpspecs : Flag<["-"], "dumpspecs">, Flags<[Unsupported]>;
-def dumpversion : Flag<["-"], "dumpversion">;
 def dylib__file : Separate<["-"], "dylib_file">;
 def dylinker__install__name : JoinedOrSeparate<["-"], "dylinker_install_name">;
 def dylinker : Flag<["-"], "dylinker">;
diff --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index 77328e1f99e5021..c84acb2beb17a70 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -190,14 +190,15 @@ std::string Driver::GetResourcesPath(StringRef BinaryPath,
 
 Driver::Driver(StringRef ClangExecutable, StringRef TargetTriple,
DiagnosticsEngine &Diags, std::string Title,
-   IntrusiveRefCntPtr VFS)
+   IntrusiveRefCntPtr VFS,
+   std::string Version)
 : Diags(Diags), VFS(std::move(VFS)), Mode(GCCMode),
   SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone),
   Offload(OffloadHostDevice), CXX20HeaderType(HeaderMode_None),
   ModulesModeCXX20(false), LTOMode(LTOK_None),
   ClangExecutable(ClangExecutable), SysRoot(DEFAULT_SYSROOT),
-  DriverTitle(Title), CCCPrintBindings(false), CCPrintOptions(false),
-  CCLogDiagnostics(false), CCGenDiagnostics(false),
+  DriverTitle(Title), DriverVersion(Version), CCCPrintBindings(false),
+  CCPrintOptions(false), CCLogDiagnostics(false), CCGenDiagnostics(false),
   CCPrintProcessStats(false), CCPrintInternalStats(false),
   TargetTriple(TargetTriple), Saver(Alloc), PrependArg(nullptr),
   CheckInputsExist(true), ProbePrecompiled(true),
@@ -2081,7 +2082,7 @@ bool Driver::HandleImmediateArgs(const Compilation &C) {
   if (C.getArgs().hasArg(options::OPT_dumpversion)) {
 // Since -dumpversion is only implemented for pedantic GCC compatibility, 
we
 // return an answer which matches our definition of __VERSION__.
-llvm::outs() << CLANG_VERSION_STRING << "\n";
+llvm::outs() << DriverVersion << "\n";
 return false;
   }
 
diff --git a/flang/test/Driver/driver-help-hidden.f90 
b/flang/test/Driver/driver-help-hidden.f90
index 807b0f938d27b5c..caea8880ba8fb8e 100644
--- a/flang/test/Driver/driver-help-hidden.f90
+++ b/flang/test/Driver/driver-help-hidden.f90
@@ -21,6 +21,8 @@
 ! CHECK-NEXT: -ccc-print-phases   Dump list of actions to perform
 ! CHECK-NEXT: -cppEnable predefi

[clang] [Sema] Add check for bitfield assignments to larger integral types (PR #68276)

2023-10-12 Thread via cfe-commits

vabridgers wrote:

Hi all, I believe all comments have been addressed to date. Please let me know 
if there's anything else required. Thank you! 

https://github.com/llvm/llvm-project/pull/68276
___
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-12 Thread Vassil Vassilev via cfe-commits

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

LGTM! Let's move forward.

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] b9b8fc4 - Add Documentation for Execution Results Handling in Clang-Repl (#65650)

2023-10-12 Thread via cfe-commits

Author: Krishna Narayanan
Date: 2023-10-12T07:31:56-07:00
New Revision: b9b8fc4878b6f7708f2ca2df6036a9c7bb5077b0

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

LOG: Add Documentation for Execution Results Handling in Clang-Repl (#65650)

[clang-repl] Add Documentation for Execution Results Handling.

This patch adds documentation for execution results handling in
Clang-REPL with
the below features:

- Automatic Printf feature
- Value Synthesis feature
- Pretty Printing feature


Continuing this work https://reviews.llvm.org/D156858 with this PR. I am
issuing this patch on behalf of Saqib.

Reviewers:
@vgvassilev 
@junaire

Added: 


Modified: 
clang/docs/CMakeLists.txt
clang/docs/ClangRepl.rst
clang/docs/conf.py

Removed: 




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..5399036c123fbbf 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;

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

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

https://github.com/vgvassilev closed 
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] D153131: [clang analysis][thread-safety] Handle return-by-reference...

2023-10-12 Thread Clement Courbet via Phabricator via cfe-commits
courbet added a comment.

In D153131#4653664 , @aaronpuchert 
wrote:

> In D153131#4653564 , @courbet wrote:
>
>> We have a large number of users of `-Werror -Wthread-safety-analysis` 
>> internally. When we make the new warnings part of that flag we cannot 
>> integrate because we're breaking all these users.
>
> The proposal was to include it in `-Wthread-safety-reference`, not 
> `-Wthread-safety-analysis`. See 
> https://clang.llvm.org/docs/DiagnosticsReference.html#wthread-safety for the 
> existing flags and their relations.

Sorry, I meant `-Wthread-safety-reference`.

>> If we don't integrate we can't run the new analysis to see what we would 
>> need to fix.
>
> Can you not add `-Wno-error=thread-safety-reference-return` together with the 
> integration? Or are there too many places adding it independently?

Yes, we have way too many instances. I'm going to discuss with people dealing 
with integrates to see whether disabling the new flag globally is a possibility.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153131

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


[clang] [time-trace] Add a new time trace scope variable named "ParseDeclarationOrFunctionDefinition". (PR #65268)

2023-10-12 Thread Aaron Ballman via cfe-commits


@@ -1224,6 +1225,9 @@ Parser::DeclGroupPtrTy 
Parser::ParseDeclOrFunctionDefInternal(
 Parser::DeclGroupPtrTy Parser::ParseDeclarationOrFunctionDefinition(
 ParsedAttributes &Attrs, ParsedAttributes &DeclSpecAttrs,
 ParsingDeclSpec *DS, AccessSpecifier AS) {
+  // Add an enclosing time trace scope for a bunch of small scopes with
+  // "EvaluateAsConstExpr".
+  llvm::TimeTraceScope TimeScope("ParseDeclarationOrFunctionDefinition");

AaronBallman wrote:

Ah, I see what's happening there, that makes sense to me to keep a time trace 
at this level, though I wonder if we should provide the source location of the 
current token being parsed, similar to how `EvaluateAsConstantExpr` does, so it 
helps orient the person reading the flame graph.

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


[clang] [Driver] Have -rdynamic be a no-op on Haiku (PR #67872)

2023-10-12 Thread Niels Sascha Reedijk via cfe-commits

nielx wrote:

Can confirm this is the case on Haiku and this is expected behaviour. 
Unfortunately, I do not have reviewing rights in GitHub.

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


[clang] [clang] Add information about lld presence in RISCVToolchain. (PR #68904)

2023-10-12 Thread Bushev Dmitry via cfe-commits

https://github.com/dybv-sc created 
https://github.com/llvm/llvm-project/pull/68904

When compiling for target riscv64/32-uknown-elf clang assumes that it do not 
use lld linker even if explicitly told ('-fuse-ld=lld').

>From 8512bbcee108751776591160797af32885377587 Mon Sep 17 00:00:00 2001
From: Dmitry Bushev 
Date: Mon, 9 Oct 2023 19:49:09 +0300
Subject: [PATCH] [clang] Add information about lld presence in RISCVToolchain.

---
 .../lib/Driver/ToolChains/RISCVToolchain.cpp  |  5 +++-
 clang/lib/Driver/ToolChains/RISCVToolchain.h  |  3 +++
 clang/test/Driver/riscv64-toolchain.c | 25 +++
 3 files changed, 32 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Driver/ToolChains/RISCVToolchain.cpp 
b/clang/lib/Driver/ToolChains/RISCVToolchain.cpp
index c98f43f6e05eb4b..b5685eaeed7b275 100644
--- a/clang/lib/Driver/ToolChains/RISCVToolchain.cpp
+++ b/clang/lib/Driver/ToolChains/RISCVToolchain.cpp
@@ -49,8 +49,11 @@ bool RISCVToolChain::hasGCCToolchain(const Driver &D,
 /// RISC-V Toolchain
 RISCVToolChain::RISCVToolChain(const Driver &D, const llvm::Triple &Triple,
const ArgList &Args)
-: Generic_ELF(D, Triple, Args) {
+: Generic_ELF(D, Triple, Args), UseLLD{Args.getLastArgValue(
+   options::OPT_fuse_ld_EQ)
+   .equals_insensitive("lld")} {
   GCCInstallation.init(Triple, Args);
+
   if (GCCInstallation.isValid()) {
 Multilibs = GCCInstallation.getMultilibs();
 SelectedMultilibs.assign({GCCInstallation.getMultilib()});
diff --git a/clang/lib/Driver/ToolChains/RISCVToolchain.h 
b/clang/lib/Driver/ToolChains/RISCVToolchain.h
index de6960726f1cd77..afe98968ecd8616 100644
--- a/clang/lib/Driver/ToolChains/RISCVToolchain.h
+++ b/clang/lib/Driver/ToolChains/RISCVToolchain.h
@@ -35,11 +35,14 @@ class LLVM_LIBRARY_VISIBILITY RISCVToolChain : public 
Generic_ELF {
   addLibStdCxxIncludePaths(const llvm::opt::ArgList &DriverArgs,
llvm::opt::ArgStringList &CC1Args) const override;
 
+  bool HasNativeLLVMSupport() const override { return UseLLD; }
+
 protected:
   Tool *buildLinker() const override;
 
 private:
   std::string computeSysRoot() const override;
+  bool UseLLD;
 };
 
 } // end namespace toolchains
diff --git a/clang/test/Driver/riscv64-toolchain.c 
b/clang/test/Driver/riscv64-toolchain.c
index f177bff33dd4d72..275cd8dde419218 100644
--- a/clang/test/Driver/riscv64-toolchain.c
+++ b/clang/test/Driver/riscv64-toolchain.c
@@ -121,6 +121,31 @@
 // C-RV64IMAC-BAREMETAL-MULTI-LP64: "--start-group" "-lc" "-lgloss" 
"--end-group" "-lgcc"
 // C-RV64IMAC-BAREMETAL-MULTI-LP64: 
"{{.*}}/Inputs/multilib_riscv_elf_sdk/lib/gcc/riscv64-unknown-elf/8.2.0/rv64imac/lp64/crtend.o"
 
+// Check that lto works in riscv-toolchain when explicitly specified lld as 
linker.
+// RUN: env "PATH=" %clang -### %s -fuse-ld=lld -flto \
+// RUN:   --target=riscv64-unknown-elf --rtlib=platform --sysroot= \
+// RUN:   -march=rv64imac -mabi=lp64\
+// RUN:   --gcc-toolchain=%S/Inputs/multilib_riscv_elf_sdk 2>&1 \
+// RUN:   | FileCheck -check-prefix=C-RV64IMAC-BAREMETAL-LTO-LP64 %s
+
+// C-RV64IMAC-BAREMETAL-LTO-LP64: "{{.*}}lld"
+// C-RV64IMAC-BAREMETAL-LTO-LP64: "-m" "elf64lriscv"
+// C-RV64IMAC-BAREMETAL-LTO-LP64: 
"{{.*}}/Inputs/multilib_riscv_elf_sdk/lib/gcc/riscv64-unknown-elf/8.2.0/../../..{{/|}}..{{/|}}riscv64-unknown-elf/lib/crt0.o"
+// C-RV64IMAC-BAREMETAL-LTO-LP64: 
"{{.*}}/Inputs/multilib_riscv_elf_sdk/lib/gcc/riscv64-unknown-elf/8.2.0/crtbegin.o"
+// C-RV64IMAC-BAREMETAL-LTO-LP64: 
"-L{{.*}}/Inputs/multilib_riscv_elf_sdk/lib/gcc/riscv64-unknown-elf/8.2.0"
+// C-RV64IMAC-BAREMETAL-LTO-LP64: 
"-L{{.*}}/Inputs/multilib_riscv_elf_sdk/lib/gcc/riscv64-unknown-elf/8.2.0/../../..{{/|}}..{{/|}}riscv64-unknown-elf/lib"
+// C-RV64IMAC-BAREMETAL-LTO-LP64: "--start-group" "-lc" "-lgloss" 
"--end-group" "-lgcc"
+// C-RV64IMAC-BAREMETAL-LTO-LP64: 
"{{.*}}/Inputs/multilib_riscv_elf_sdk/lib/gcc/riscv64-unknown-elf/8.2.0/crtend.o"
+
+// Check driver error when lto is used without specified lld linker.
+// RUN: env "PATH=" %clang -### %s -flto \
+// RUN:   --target=riscv64-unknown-elf --rtlib=platform --sysroot= \
+// RUN:   -march=rv64imac -mabi=lp64\
+// RUN:   --gcc-toolchain=%S/Inputs/multilib_riscv_elf_sdk 2>&1 \
+// RUN:   | FileCheck -check-prefix=C-RV64IMAC-BAREMETAL-LTO-FAIL-LP64 %s
+
+// C-RV64IMAC-BAREMETAL-LTO-FAIL-LP64: clang-16: error: 
'riscv64-unknown-unknown-elf': unable to pass LLVM bit-code files to linker
+
 // RUN: env "PATH=" %clang -### %s -fuse-ld=ld \
 // RUN:   --target=riscv64-unknown-elf --rtlib=platform --unwindlib=platform 
--sysroot= \
 // RUN:   -march=rv64imafdc -mabi=lp64d \

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


[clang] [clang] Add information about lld presence in RISCVToolchain. (PR #68904)

2023-10-12 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-driver

Author: Bushev Dmitry (dybv-sc)


Changes

When compiling for target riscv64/32-uknown-elf clang assumes that it do not 
use lld linker even if explicitly told ('-fuse-ld=lld').

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


3 Files Affected:

- (modified) clang/lib/Driver/ToolChains/RISCVToolchain.cpp (+4-1) 
- (modified) clang/lib/Driver/ToolChains/RISCVToolchain.h (+3) 
- (modified) clang/test/Driver/riscv64-toolchain.c (+25) 


``diff
diff --git a/clang/lib/Driver/ToolChains/RISCVToolchain.cpp 
b/clang/lib/Driver/ToolChains/RISCVToolchain.cpp
index c98f43f6e05eb4b..b5685eaeed7b275 100644
--- a/clang/lib/Driver/ToolChains/RISCVToolchain.cpp
+++ b/clang/lib/Driver/ToolChains/RISCVToolchain.cpp
@@ -49,8 +49,11 @@ bool RISCVToolChain::hasGCCToolchain(const Driver &D,
 /// RISC-V Toolchain
 RISCVToolChain::RISCVToolChain(const Driver &D, const llvm::Triple &Triple,
const ArgList &Args)
-: Generic_ELF(D, Triple, Args) {
+: Generic_ELF(D, Triple, Args), UseLLD{Args.getLastArgValue(
+   options::OPT_fuse_ld_EQ)
+   .equals_insensitive("lld")} {
   GCCInstallation.init(Triple, Args);
+
   if (GCCInstallation.isValid()) {
 Multilibs = GCCInstallation.getMultilibs();
 SelectedMultilibs.assign({GCCInstallation.getMultilib()});
diff --git a/clang/lib/Driver/ToolChains/RISCVToolchain.h 
b/clang/lib/Driver/ToolChains/RISCVToolchain.h
index de6960726f1cd77..afe98968ecd8616 100644
--- a/clang/lib/Driver/ToolChains/RISCVToolchain.h
+++ b/clang/lib/Driver/ToolChains/RISCVToolchain.h
@@ -35,11 +35,14 @@ class LLVM_LIBRARY_VISIBILITY RISCVToolChain : public 
Generic_ELF {
   addLibStdCxxIncludePaths(const llvm::opt::ArgList &DriverArgs,
llvm::opt::ArgStringList &CC1Args) const override;
 
+  bool HasNativeLLVMSupport() const override { return UseLLD; }
+
 protected:
   Tool *buildLinker() const override;
 
 private:
   std::string computeSysRoot() const override;
+  bool UseLLD;
 };
 
 } // end namespace toolchains
diff --git a/clang/test/Driver/riscv64-toolchain.c 
b/clang/test/Driver/riscv64-toolchain.c
index f177bff33dd4d72..275cd8dde419218 100644
--- a/clang/test/Driver/riscv64-toolchain.c
+++ b/clang/test/Driver/riscv64-toolchain.c
@@ -121,6 +121,31 @@
 // C-RV64IMAC-BAREMETAL-MULTI-LP64: "--start-group" "-lc" "-lgloss" 
"--end-group" "-lgcc"
 // C-RV64IMAC-BAREMETAL-MULTI-LP64: 
"{{.*}}/Inputs/multilib_riscv_elf_sdk/lib/gcc/riscv64-unknown-elf/8.2.0/rv64imac/lp64/crtend.o"
 
+// Check that lto works in riscv-toolchain when explicitly specified lld as 
linker.
+// RUN: env "PATH=" %clang -### %s -fuse-ld=lld -flto \
+// RUN:   --target=riscv64-unknown-elf --rtlib=platform --sysroot= \
+// RUN:   -march=rv64imac -mabi=lp64\
+// RUN:   --gcc-toolchain=%S/Inputs/multilib_riscv_elf_sdk 2>&1 \
+// RUN:   | FileCheck -check-prefix=C-RV64IMAC-BAREMETAL-LTO-LP64 %s
+
+// C-RV64IMAC-BAREMETAL-LTO-LP64: "{{.*}}lld"
+// C-RV64IMAC-BAREMETAL-LTO-LP64: "-m" "elf64lriscv"
+// C-RV64IMAC-BAREMETAL-LTO-LP64: 
"{{.*}}/Inputs/multilib_riscv_elf_sdk/lib/gcc/riscv64-unknown-elf/8.2.0/../../..{{/|}}..{{/|}}riscv64-unknown-elf/lib/crt0.o"
+// C-RV64IMAC-BAREMETAL-LTO-LP64: 
"{{.*}}/Inputs/multilib_riscv_elf_sdk/lib/gcc/riscv64-unknown-elf/8.2.0/crtbegin.o"
+// C-RV64IMAC-BAREMETAL-LTO-LP64: 
"-L{{.*}}/Inputs/multilib_riscv_elf_sdk/lib/gcc/riscv64-unknown-elf/8.2.0"
+// C-RV64IMAC-BAREMETAL-LTO-LP64: 
"-L{{.*}}/Inputs/multilib_riscv_elf_sdk/lib/gcc/riscv64-unknown-elf/8.2.0/../../..{{/|}}..{{/|}}riscv64-unknown-elf/lib"
+// C-RV64IMAC-BAREMETAL-LTO-LP64: "--start-group" "-lc" "-lgloss" 
"--end-group" "-lgcc"
+// C-RV64IMAC-BAREMETAL-LTO-LP64: 
"{{.*}}/Inputs/multilib_riscv_elf_sdk/lib/gcc/riscv64-unknown-elf/8.2.0/crtend.o"
+
+// Check driver error when lto is used without specified lld linker.
+// RUN: env "PATH=" %clang -### %s -flto \
+// RUN:   --target=riscv64-unknown-elf --rtlib=platform --sysroot= \
+// RUN:   -march=rv64imac -mabi=lp64\
+// RUN:   --gcc-toolchain=%S/Inputs/multilib_riscv_elf_sdk 2>&1 \
+// RUN:   | FileCheck -check-prefix=C-RV64IMAC-BAREMETAL-LTO-FAIL-LP64 %s
+
+// C-RV64IMAC-BAREMETAL-LTO-FAIL-LP64: clang-16: error: 
'riscv64-unknown-unknown-elf': unable to pass LLVM bit-code files to linker
+
 // RUN: env "PATH=" %clang -### %s -fuse-ld=ld \
 // RUN:   --target=riscv64-unknown-elf --rtlib=platform --unwindlib=platform 
--sysroot= \
 // RUN:   -march=rv64imafdc -mabi=lp64d \

``




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


[clang] [LLVM] Add new attribute `optdebug` to optimize for debugging (PR #66632)

2023-10-12 Thread Stephen Tozer via cfe-commits

https://github.com/SLTozer updated 
https://github.com/llvm/llvm-project/pull/66632

>From 18f494a4006b4c21b364a91107d4a07ceaf88213 Mon Sep 17 00:00:00 2001
From: Stephen Tozer 
Date: Mon, 18 Sep 2023 09:59:11 +0100
Subject: [PATCH 1/3] [LLVM] Add new attribute `optdebug` to optimize for
 debugging

This patch adds a new fn attribute, `optdebug`, that specifies that
optimizations should make decisions that prioritize debug info quality,
potentially at the cost of runtime performance.

This patch does not add any functional changes triggered by this attribute,
only the attribute itself.
---
 clang/lib/CodeGen/CodeGenModule.cpp | 1 +
 llvm/docs/BitCodeFormat.rst | 1 +
 llvm/docs/LangRef.rst   | 4 
 llvm/include/llvm/Bitcode/LLVMBitCodes.h| 1 +
 llvm/include/llvm/IR/Attributes.td  | 3 +++
 llvm/lib/Bitcode/Reader/BitcodeReader.cpp   | 2 ++
 llvm/lib/Bitcode/Writer/BitcodeWriter.cpp   | 2 ++
 llvm/lib/Transforms/Utils/CodeExtractor.cpp | 1 +
 llvm/test/Bitcode/attributes.ll | 7 +++
 llvm/utils/emacs/llvm-mode.el   | 2 +-
 llvm/utils/kate/llvm.xml| 1 +
 llvm/utils/vim/syntax/llvm.vim  | 1 +
 12 files changed, 25 insertions(+), 1 deletion(-)

diff --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index 8b0c9340775cbe9..96d053a6aa8f9e5 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -2325,6 +2325,7 @@ void 
CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
   B.addAttribute(llvm::Attribute::Naked);
 
 // OptimizeNone wins over OptimizeForSize and MinSize.
+F->removeFnAttr(llvm::Attribute::OptimizeForDebugging);
 F->removeFnAttr(llvm::Attribute::OptimizeForSize);
 F->removeFnAttr(llvm::Attribute::MinSize);
   } else if (D->hasAttr()) {
diff --git a/llvm/docs/BitCodeFormat.rst b/llvm/docs/BitCodeFormat.rst
index 70be73abef19d6d..ce0e29fb6b928a7 100644
--- a/llvm/docs/BitCodeFormat.rst
+++ b/llvm/docs/BitCodeFormat.rst
@@ -1085,6 +1085,7 @@ The integer codes are mapped to well-known attributes as 
follows.
 * code 77: ``elementtype``
 * code 78: ``disable_sanitizer_instrumentation``
 * code 79: ``nosanitize_bounds``
+* code 88: ``optdebug``
 
 .. note::
   The ``allocsize`` attribute has a special encoding for its arguments. Its two
diff --git a/llvm/docs/LangRef.rst b/llvm/docs/LangRef.rst
index f542e70bcfee810..fa274fdb66a5047 100644
--- a/llvm/docs/LangRef.rst
+++ b/llvm/docs/LangRef.rst
@@ -2024,6 +2024,10 @@ example:
Note: Comparing address of a global variable to ``null`` may still
evaluate to false because of a limitation in querying this attribute inside
constant expressions.
+``optdebug``
+This attribute suggests that optimization passes and code generator passes
+should make choices that try to preserve debug info without significantly
+degrading runtime performance.
 ``optforfuzzing``
 This attribute indicates that this function should be optimized
 for maximum fuzzing signal.
diff --git a/llvm/include/llvm/Bitcode/LLVMBitCodes.h 
b/llvm/include/llvm/Bitcode/LLVMBitCodes.h
index 52e76356a892e45..5d7be5ca936ad37 100644
--- a/llvm/include/llvm/Bitcode/LLVMBitCodes.h
+++ b/llvm/include/llvm/Bitcode/LLVMBitCodes.h
@@ -713,6 +713,7 @@ enum AttributeKindCodes {
   ATTR_KIND_SKIP_PROFILE = 85,
   ATTR_KIND_MEMORY = 86,
   ATTR_KIND_NOFPCLASS = 87,
+  ATTR_KIND_OPTIMIZE_FOR_DEBUGGING = 88,
 };
 
 enum ComdatSelectionKindCodes {
diff --git a/llvm/include/llvm/IR/Attributes.td 
b/llvm/include/llvm/IR/Attributes.td
index aba1d718f7f72f9..fda79f5f24495fb 100644
--- a/llvm/include/llvm/IR/Attributes.td
+++ b/llvm/include/llvm/IR/Attributes.td
@@ -200,6 +200,9 @@ def NoSanitizeCoverage : EnumAttr<"nosanitize_coverage", 
[FnAttr]>;
 /// Null pointer in address space zero is valid.
 def NullPointerIsValid : EnumAttr<"null_pointer_is_valid", [FnAttr]>;
 
+/// Select optimizations that give decent debug info.
+def OptimizeForDebugging : EnumAttr<"optdebug", [FnAttr]>;
+
 /// Select optimizations for best fuzzing signal.
 def OptForFuzzing : EnumAttr<"optforfuzzing", [FnAttr]>;
 
diff --git a/llvm/lib/Bitcode/Reader/BitcodeReader.cpp 
b/llvm/lib/Bitcode/Reader/BitcodeReader.cpp
index 1d1ec988a93d847..16eafa6e18f5d59 100644
--- a/llvm/lib/Bitcode/Reader/BitcodeReader.cpp
+++ b/llvm/lib/Bitcode/Reader/BitcodeReader.cpp
@@ -1980,6 +1980,8 @@ static Attribute::AttrKind getAttrFromCode(uint64_t Code) 
{
 return Attribute::NoSanitizeCoverage;
   case bitc::ATTR_KIND_NULL_POINTER_IS_VALID:
 return Attribute::NullPointerIsValid;
+  case bitc::ATTR_KIND_OPTIMIZE_FOR_DEBUGGING:
+return Attribute::OptimizeForDebugging;
   case bitc::ATTR_KIND_OPT_FOR_FUZZING:
 return Attribute::OptForFuzzing;
   case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
diff --git a/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp 
b/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp
index f53fbd73667762

[clang] [clang] Add information about lld presence in RISCVToolchain. (PR #68904)

2023-10-12 Thread via cfe-commits

github-actions[bot] wrote:




:warning: C/C++ code formatter, clang-format found issues in your code. 
:warning:



You can test this locally with the following command:


``bash
git-clang-format --diff a574ef61766d49db4350b6f06a108f36bccb25bb 
8512bbcee108751776591160797af32885377587 -- 
clang/lib/Driver/ToolChains/RISCVToolchain.cpp 
clang/lib/Driver/ToolChains/RISCVToolchain.h 
clang/test/Driver/riscv64-toolchain.c
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/Driver/ToolChains/RISCVToolchain.cpp 
b/clang/lib/Driver/ToolChains/RISCVToolchain.cpp
index b5685eaee..037741c2a 100644
--- a/clang/lib/Driver/ToolChains/RISCVToolchain.cpp
+++ b/clang/lib/Driver/ToolChains/RISCVToolchain.cpp
@@ -49,9 +49,9 @@ bool RISCVToolChain::hasGCCToolchain(const Driver &D,
 /// RISC-V Toolchain
 RISCVToolChain::RISCVToolChain(const Driver &D, const llvm::Triple &Triple,
const ArgList &Args)
-: Generic_ELF(D, Triple, Args), UseLLD{Args.getLastArgValue(
-   options::OPT_fuse_ld_EQ)
-   .equals_insensitive("lld")} {
+: Generic_ELF(D, Triple, Args),
+  UseLLD{Args.getLastArgValue(options::OPT_fuse_ld_EQ)
+ .equals_insensitive("lld")} {
   GCCInstallation.init(Triple, Args);
 
   if (GCCInstallation.isValid()) {

``




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


[clang] [Sema] Add check for bitfield assignments to larger integral types (PR #68276)

2023-10-12 Thread Aaron Ballman via cfe-commits

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

Just some minor things to cleanup, but this otherwise LGTM, thank you!

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


[clang] [Sema] Add check for bitfield assignments to larger integral types (PR #68276)

2023-10-12 Thread Aaron Ballman via cfe-commits

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


[clang] [Sema] Add check for bitfield assignments to larger integral types (PR #68276)

2023-10-12 Thread Aaron Ballman via cfe-commits


@@ -0,0 +1,37 @@
+// RUN: %clang_cc1 -Wconversion -fsyntax-only -verify %s
+// RUN: %clang_cc1 -Wbitfield-conversion -fsyntax-only -verify %s
+
+typedef struct _xx {
+ int bf:9; // expected-note{{declared here}}
+ // expected-note@-1{{declared here}}
+ // expected-note@-2{{declared here}}
+ // expected-note@-3{{declared here}}

AaronBallman wrote:

```suggestion
 int bf:9; // expected-note 4{{declared here}}
```
NFC, but is shorter

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


  1   2   3   >