[PATCH] D126364: Fix interaction of pragma FENV_ACCESS with other pragmas

2022-06-17 Thread Serge Pavlov via Phabricator via cfe-commits
sepavloff updated this revision to Diff 437807.
sepavloff added a comment.

Remade the patch according to the review notes


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126364

Files:
  clang/include/clang/Basic/FPOptions.def
  clang/include/clang/Basic/LangOptions.def
  clang/include/clang/Basic/LangOptions.h
  clang/include/clang/Driver/Options.td
  clang/include/clang/Sema/Sema.h
  clang/lib/AST/ExprConstant.cpp
  clang/lib/CodeGen/CGCall.cpp
  clang/lib/CodeGen/CodeGenFunction.cpp
  clang/lib/Frontend/CompilerInstance.cpp
  clang/lib/Parse/ParsePragma.cpp
  clang/lib/Sema/SemaAttr.cpp
  clang/test/AST/ast-dump-fpfeatures.cpp
  clang/test/CodeGen/pragma-fenv_access.c

Index: clang/test/CodeGen/pragma-fenv_access.c
===
--- clang/test/CodeGen/pragma-fenv_access.c
+++ clang/test/CodeGen/pragma-fenv_access.c
@@ -1,5 +1,15 @@
-// RUN: %clang_cc1 -fexperimental-strict-floating-point -ffp-exception-behavior=strict -triple %itanium_abi_triple -emit-llvm %s -o - | FileCheck %s
-// RUN: %clang_cc1 -fexperimental-strict-floating-point -ffp-exception-behavior=strict -triple %itanium_abi_triple -emit-llvm %s -o - -fms-extensions -DMS | FileCheck %s
+// RUN: %clang_cc1 -fexperimental-strict-floating-point -ffp-exception-behavior=strict -triple %itanium_abi_triple -emit-llvm %s -o - | FileCheck --check-prefixes=CHECK,STRICT %s
+// RUN: %clang_cc1 -fexperimental-strict-floating-point -ffp-exception-behavior=strict -triple %itanium_abi_triple -emit-llvm %s -o - -fms-extensions -DMS | FileCheck --check-prefixes=CHECK,STRICT %s
+// RUN: %clang_cc1 -fexperimental-strict-floating-point -triple %itanium_abi_triple -emit-llvm %s -o - | FileCheck --check-prefixes=CHECK,DEFAULT %s
+
+
+float func_00(float x, float y) {
+  return x + y;
+}
+// CHECK-LABEL: @func_00
+// STRICT: call float @llvm.experimental.constrained.fadd.f32(float {{.*}}, float {{.*}}, metadata !"round.tonearest", metadata !"fpexcept.strict")
+// DEFAULT: fadd float
+
 
 #ifdef MS
 #pragma fenv_access (on)
@@ -20,7 +30,7 @@
   return x + y;
 }
 // CHECK-LABEL: @func_02
-// CHECK: call float @llvm.experimental.constrained.fadd.f32(float {{.*}}, float {{.*}}, metadata !"round.dynamic", metadata !"fpexcept.ignore")
+// CHECK: call float @llvm.experimental.constrained.fadd.f32(float {{.*}}, float {{.*}}, metadata !"round.tonearest", metadata !"fpexcept.ignore")
 
 
 float func_03(float x, float y) {
@@ -41,7 +51,16 @@
   return x + y;
 }
 // CHECK-LABEL: @func_04
-// CHECK: call float @llvm.experimental.constrained.fadd.f32(float {{.*}}, float {{.*}}, metadata !"round.dynamic", metadata !"fpexcept.ignore")
+// STRICT: call float @llvm.experimental.constrained.fadd.f32(float {{.*}}, float {{.*}}, metadata !"round.tonearest", metadata !"fpexcept.ignore")
+// DEFAULT: fadd float
+
+
+float func_04a(float x, float y) {
+  #pragma float_control(except, on)
+  return x + y;
+}
+// CHECK-LABEL: @func_04a
+// CHECK: call float @llvm.experimental.constrained.fadd.f32(float {{.*}}, float {{.*}}, metadata !"round.tonearest", metadata !"fpexcept.strict")
 
 
 float func_05(float x, float y) {
@@ -57,18 +76,151 @@
   return x + y;
 }
 // CHECK-LABEL: @func_06
-// CHECK: call float @llvm.experimental.constrained.fadd.f32(float {{.*}}, float {{.*}}, metadata !"round.dynamic", metadata !"fpexcept.ignore")
+// STRICT: call float @llvm.experimental.constrained.fadd.f32(float {{.*}}, float {{.*}}, metadata !"round.tonearest", metadata !"fpexcept.ignore")
+// DEFAULT: fadd float
 
 
 float func_07(float x, float y) {
   x -= y;
   if (x) {
 #pragma STDC FENV_ACCESS ON
-y *= 2;
+y *= 2.0F;
   }
-  return y + 4;
+  return y + 4.0F;
 }
 // CHECK-LABEL: @func_07
-// CHECK: call float @llvm.experimental.constrained.fsub.f32(float {{.*}}, float {{.*}}, metadata !"round.dynamic", metadata !"fpexcept.strict")
-// CHECK: call float @llvm.experimental.constrained.fmul.f32(float {{.*}}, float {{.*}}, metadata !"round.dynamic", metadata !"fpexcept.strict")
+// STRICT: call float @llvm.experimental.constrained.fsub.f32(float {{.*}}, float {{.*}}, metadata !"round.tonearest", metadata !"fpexcept.strict")
+// STRICT: call float @llvm.experimental.constrained.fmul.f32(float {{.*}}, float {{.*}}, metadata !"round.dynamic", metadata !"fpexcept.strict")
+// STRICT: call float @llvm.experimental.constrained.fadd.f32(float {{.*}}, float {{.*}}, metadata !"round.tonearest", metadata !"fpexcept.strict")
+// DEFAULT: call float @llvm.experimental.constrained.fsub.f32(float {{.*}}, float {{.*}}, metadata !"round.tonearest", metadata !"fpexcept.ignore")
+// DEFAULT: call float @llvm.experimental.constrained.fmul.f32(float {{.*}}, float {{.*}}, metadata !"round.dynamic", metadata !"fpexcept.strict")
+// DEFAULT: call float @llvm.experimental.constrained.fadd.f32(float {{.*}}, float {{.*}}, metadata !"round.tonearest", metadata !"fpexcept.ignore")
+

[PATCH] D126364: Fix interaction of pragma FENV_ACCESS with other pragmas

2022-06-17 Thread Serge Pavlov via Phabricator via cfe-commits
sepavloff added inline comments.



Comment at: clang/include/clang/Basic/LangOptions.h:622
 setFPContractMode(LangOptions::FPM_Off);
 setRoundingMode(static_cast(LangOptions::FPR_ToNearest));
 setFPExceptionMode(LangOptions::FPE_Ignore);

efriedma wrote:
> sepavloff wrote:
> > efriedma wrote:
> > > sepavloff wrote:
> > > > efriedma wrote:
> > > > > sepavloff wrote:
> > > > > > efriedma wrote:
> > > > > > > sepavloff wrote:
> > > > > > > > efriedma wrote:
> > > > > > > > > I'm suggesting this should be 
> > > > > > > > > `setRoundingMode(llvm::RoundingMode::Dynamic)`.
> > > > > > > > > 
> > > > > > > > > If FENV_ACCESS is off, getEffectiveRoundingMode() converts 
> > > > > > > > > that to "nearest".  If FENV_ACCESS is turned on, the mode is 
> > > > > > > > > treated as dynamic.  This is exactly what we want.
> > > > > > > > It would change semantics. In particular, it would make 
> > > > > > > > impossible to use FP arithmetic in constexpr functions. An 
> > > > > > > > expression like `1.0 / 3.0` cannot be evaluated with dynamic 
> > > > > > > > rounding mode.
> > > > > > > Can we just change the relevant code in ExprConstant to call 
> > > > > > > getEffectiveRoundingMode()?
> > > > > > What is the advantage of using FE_DYNAMIC in the case when it is 
> > > > > > known that rounding mode is FE_TONEAREST?
> > > > > > 
> > > > > > Probably `FENV_ROUND FE_DYNAMIC` should result in `dynamic` 
> > > > > > rounding even if `FENV_ACCESS ON` is absent. Rounding mode cannot 
> > > > > > be changed in this case but it can be used to inform the compiler 
> > > > > > that such function can be called in environment, where rounding 
> > > > > > mode is non-default. It would prevent some constant evaluations and 
> > > > > > other transformations that assume rounding mode is known. Anyway 
> > > > > > the standard only allow to assume FE_TONEAREST but does not require 
> > > > > > this.
> > > > > > 
> > > > > > In such case `getEffectiveRoundingMode` is not needed.
> > > > > I really want to keep the state we store, and the state updates, as 
> > > > > simple as possible; if that means making getEffectiveRoundingMode() 
> > > > > or whatever more complicated, that's fine.  It's a matter of making 
> > > > > sure we understand all the relevant transitions.
> > > > > 
> > > > > As far as I can tell, according to the standard, the initial state 
> > > > > for FENV_ROUND is supposed to be FE_DYNAMIC, as if "#pragma STDC 
> > > > > FENV_ROUND FE_DYNAMIC" were written at the beginning of every file.  
> > > > > If we think we need a new state, something like FE_DYNAMIC_INITIAL, 
> > > > > to represent the initial state, we can, I guess, but I don't think 
> > > > > the standard text requires it.
> > > > > As far as I can tell, according to the standard, the initial state 
> > > > > for FENV_ROUND is supposed to be FE_DYNAMIC, as if "#pragma STDC 
> > > > > FENV_ROUND FE_DYNAMIC" were written at the beginning of every file. 
> > > > 
> > > > Could you please give any reference to this statement? I thought the 
> > > > initial state should be FE_TONEAREST, as it follows from F.8.3p1.
> > > " If no FENV_ROUND pragma is in effect, or the specified constant 
> > > rounding mode is FE_DYNAMIC, rounding is according to the mode specified 
> > > by the dynamic floating-point environment".  And all the other rules for 
> > > FENV_ROUND only apply to "an FENV_ROUND pragma establishing a mode other 
> > > than FE_DYNAMIC".  So no FENV_ROUND is equivalent to "FENV_ROUND 
> > > FENV_DYNAMIC".
> > > 
> > > The text also says, "If the FE_DYNAMIC mode is specified and FENV_ACCESS 
> > > is 'off', the translator may assume that the default rounding mode is in 
> > > effect".  But that's the same result you'd get if you didn't specify 
> > > FENV_ROUND at all: it's just combining the general rule that you're not 
> > > allowed to mess with the dynamic rounding mode outside the scope of 
> > > FENV_ACCESS, with the rule that the initial rounding mode is "nearest".
> > Thank you for the references. Indeed, default behavior specified by the 
> > standard is to use dynamic rounding. It however do not agree with the 
> > default compiler behavior - to use FE_TONEAREST. That's why we cannot make 
> > `setRoundingMode(llvm::RoundingMode::Dynamic)`. 
> > 
> > With options '-frounding-math' compiler conforms to the latest standard 
> > draft. In this case however FENV_ACCESS is not necessary. Using FE_DYNAMIC 
> > with subsequent deduction of actual rounding mode looks a fragile solution 
> > compared with setting actual mode in CurFPFeatures.
> My goal is to make the state transitions as simple as possible.  It's very 
> easy to mess up state machines.  This means as few variables as possible, in 
> as few states as possible, are involved in parsing the relevant pragmas.
> 
> > It however do not agree with the default compiler behavior - to use 
> > FE_TONEAREST.
> 
> My goal is to make the implementations

[clang-tools-extra] 5ea341d - [clang] Fix trivially copyable for copy constructor and copy assignment operator

2022-06-17 Thread Roy Jacobson via cfe-commits

Author: Javier Alvarez
Date: 2022-06-17T10:35:01+03:00
New Revision: 5ea341d7c4f9cc4933adc04ff74d59e26ad2f306

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

LOG: [clang] Fix trivially copyable for copy constructor and copy assignment 
operator

>From [class.copy.ctor]:

```
A non-template constructor for class X is a copy constructor if its first
parameter is of type X&, const X&, volatile X& or const volatile X&, and
either there are no other parameters or else all other parameters have
default arguments (9.3.4.7).

A copy/move constructor for class X is trivial if it is not user-provided and 
if:
- class X has no virtual functions (11.7.3) and no virtual base classes 
(11.7.2), and
- the constructor selected to copy/move each direct base class subobject is 
trivial, and
- or each non-static data member of X that is of class type (or array thereof),
  the constructor selected to copy/move that member is trivial;

otherwise the copy/move constructor is non-trivial.
```

So `T(T&) = default`; should be trivial assuming that the previous
provisions are met.

This works in GCC, but not in Clang at the moment:
https://godbolt.org/z/fTGe71b6P

Reviewed By: royjacobson

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

Added: 


Modified: 
clang-tools-extra/test/clang-tidy/checkers/modernize-loop-convert-const.cpp
clang/docs/ReleaseNotes.rst
clang/include/clang/Basic/LangOptions.h
clang/lib/Sema/SemaDeclCXX.cpp
clang/test/CXX/drs/dr21xx.cpp
clang/test/CXX/special/class.copy/p12-0x.cpp
clang/test/CXX/special/class.copy/p25-0x.cpp
clang/www/cxx_dr_status.html

Removed: 




diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/modernize-loop-convert-const.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/modernize-loop-convert-const.cpp
index fd3bddedd5675..beec7fae961a9 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/modernize-loop-convert-const.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/modernize-loop-convert-const.cpp
@@ -10,12 +10,12 @@ struct Str {
 };
 
 // This class is non-trivially copyable because the copy-constructor and copy
-// assignment take non-const references.
+// assignment take non-const references and are user-provided.
 struct ModifiesRightSide {
   ModifiesRightSide() = default;
-  ModifiesRightSide(ModifiesRightSide &) = default;
+  ModifiesRightSide(ModifiesRightSide &);
   bool operator<(ModifiesRightSide &) const;
-  ModifiesRightSide &operator=(ModifiesRightSide &) = default;
+  ModifiesRightSide &operator=(ModifiesRightSide &);
 };
 
 template 

diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index ecf574b3b0f8d..e9ea54d591dad 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -391,7 +391,6 @@ AIX Support
   ``-mignore-xcoff-visibility`` option can be manually specified on the
   command-line to recover the previous behavior if desired.
 
-
 C Language Changes in Clang
 ---
 
@@ -478,6 +477,11 @@ ABI Changes in Clang
   (e.g. ``int : 0``) no longer prevents the structure from being considered a
   homogeneous floating-point or vector aggregate. The new behavior agrees with
   the AAPCS specification, and matches the similar bug fix in GCC 12.1.
+- All copy constructors can now be trivial if they are not user-provided,
+  regardless of the type qualifiers of the argument of the defaulted 
constructor,
+  fixing dr2171.
+  You can switch back to the old ABI behavior with the flag:
+  ``-fclang-abi-compat=14.0``.
 
 OpenMP Support in Clang
 ---

diff  --git a/clang/include/clang/Basic/LangOptions.h 
b/clang/include/clang/Basic/LangOptions.h
index cf121de6699c8..f1b6cb60ae855 100644
--- a/clang/include/clang/Basic/LangOptions.h
+++ b/clang/include/clang/Basic/LangOptions.h
@@ -215,8 +215,12 @@ class LangOptions : public LangOptionsBase {
 Ver12,
 
 /// Attempt to be ABI-compatible with code generated by Clang 14.0.x.
-/// This causes clang to mangle dependent nested names incorrectly.
-/// This causes clang to pack non-POD members of packed structs.
+/// This causes clang to:
+///   - mangle dependent nested names incorrectly.
+///   - pack non-POD members of packed structs.
+///   - make trivial only those defaulted copy constructors with a
+/// parameter-type-list equivalent to the parameter-type-list of an
+/// implicit declaration.
 Ver14,
 
 /// Conform to the underlying platform's C and C++ ABIs as closely

diff  --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index 6c8704cd0b789..ebeb98b2f701c 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -9772,11 +9772,22 @@ bool Sema::SpecialMemberI

[PATCH] D127593: [clang] Fix trivially copyable for copy constructor and copy assignment operator

2022-06-17 Thread Roy Jacobson 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 rG5ea341d7c4f9: [clang] Fix trivially copyable for copy 
constructor and copy assignment operator (authored by Javier-varez, committed 
by royjacobson).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D127593

Files:
  clang-tools-extra/test/clang-tidy/checkers/modernize-loop-convert-const.cpp
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/LangOptions.h
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/test/CXX/drs/dr21xx.cpp
  clang/test/CXX/special/class.copy/p12-0x.cpp
  clang/test/CXX/special/class.copy/p25-0x.cpp
  clang/www/cxx_dr_status.html

Index: clang/www/cxx_dr_status.html
===
--- clang/www/cxx_dr_status.html
+++ clang/www/cxx_dr_status.html
@@ -12840,7 +12840,7 @@
 https://wg21.link/cwg2171";>2171
 CD4
 Triviality of copy constructor with less-qualified parameter
-Unknown
+Clang 15
   
   
 https://wg21.link/cwg2172";>2172
Index: clang/test/CXX/special/class.copy/p25-0x.cpp
===
--- clang/test/CXX/special/class.copy/p25-0x.cpp
+++ clang/test/CXX/special/class.copy/p25-0x.cpp
@@ -1,4 +1,5 @@
 // RUN: %clang_cc1 -std=c++11 -verify %s
+// RUN: %clang_cc1 -std=c++11 -verify %s -fclang-abi-compat=14 -DCLANG_ABI_COMPAT=14
 
 // expected-no-diagnostics
 
@@ -31,7 +32,30 @@
 struct NonConstCopy {
   NonConstCopy &operator=(NonConstCopy &) = default;
 };
+#if defined(CLANG_ABI_COMPAT) && CLANG_ABI_COMPAT <= 14
+// Up until (and including) Clang 14, non-const copy assignment operators were not trivial because
+// of dr2171
 using _ = not_trivially_assignable;
+#else
+// In the latest Clang version, all defaulted assignment operators are trivial, even if non-const,
+// because dr2171 is fixed
+static_assert(__has_trivial_assign(NonConstCopy), "");
+static_assert(__is_trivially_assignable(NonConstCopy &, NonConstCopy &), "");
+static_assert(!__is_trivially_assignable(NonConstCopy &, const NonConstCopy &), "");
+static_assert(!__is_trivially_assignable(NonConstCopy &, NonConstCopy), "");
+static_assert(!__is_trivially_assignable(NonConstCopy &, NonConstCopy &&), "");
+static_assert(__is_trivially_assignable(NonConstCopy &&, NonConstCopy &), "");
+static_assert(!__is_trivially_assignable(NonConstCopy &&, const NonConstCopy &), "");
+static_assert(!__is_trivially_assignable(NonConstCopy &&, NonConstCopy), "");
+static_assert(!__is_trivially_assignable(NonConstCopy &&, NonConstCopy &&), "");
+
+struct DefaultedSpecialMembers {
+  DefaultedSpecialMembers &operator=(const DefaultedSpecialMembers &) = default;
+  DefaultedSpecialMembers &operator=(DefaultedSpecialMembers &) = default;
+  DefaultedSpecialMembers &operator=(DefaultedSpecialMembers &&) = default;
+};
+using _ = trivially_assignable;
+#endif
 
 // class X has no virtual functions
 struct VFn {
Index: clang/test/CXX/special/class.copy/p12-0x.cpp
===
--- clang/test/CXX/special/class.copy/p12-0x.cpp
+++ clang/test/CXX/special/class.copy/p12-0x.cpp
@@ -1,4 +1,5 @@
 // RUN: %clang_cc1 -std=c++11 -verify %s -Wno-defaulted-function-deleted
+// RUN: %clang_cc1 -std=c++11 -verify %s -Wno-defaulted-function-deleted -fclang-abi-compat=14 -DCLANG_ABI_COMPAT=14
 
 // expected-no-diagnostics
 
@@ -28,7 +29,25 @@
 struct NonConstCopy {
   NonConstCopy(NonConstCopy &) = default;
 };
+#if defined(CLANG_ABI_COMPAT) && CLANG_ABI_COMPAT <= 14
+// Up until (and including) Clang 14, non-const copy constructors were not trivial because of dr2171
 using _ = not_trivially_copyable;
+#else
+// In the latest Clang version, all defaulted constructors are trivial, even if non-const, because
+// dr2171 is fixed.
+static_assert(__has_trivial_copy(NonConstCopy), "");
+static_assert(__is_trivially_constructible(NonConstCopy, NonConstCopy &), "");
+static_assert(!__is_trivially_constructible(NonConstCopy, NonConstCopy), "");
+static_assert(!__is_trivially_constructible(NonConstCopy, const NonConstCopy &), "");
+static_assert(!__is_trivially_constructible(NonConstCopy, NonConstCopy &&), "");
+
+struct DefaultedSpecialMembers {
+  DefaultedSpecialMembers(const DefaultedSpecialMembers &) = default;
+  DefaultedSpecialMembers(DefaultedSpecialMembers &) = default;
+  DefaultedSpecialMembers(DefaultedSpecialMembers &&) = default;
+};
+using _ = trivially_copyable;
+#endif
 
 // class X has no virtual functions
 struct VFn {
Index: clang/test/CXX/drs/dr21xx.cpp
===
--- clang/test/CXX/drs/dr21xx.cpp
+++ clang/test/CXX/drs/dr21xx.cpp
@@ -140,6 +140,33 @@
 #endif
 }
 
+namespace dr2171 { // dr2171: 15
+#if __cplusplus >= 201103L
+
+struct NonConstCopy {
+  NonConstCopy(NonConstCopy &) = def

[PATCH] D122931: [CMake][compiler-rt] Support for using in-tree libc++

2022-06-17 Thread Petr Hosek via Phabricator via cfe-commits
phosek added inline comments.
Herald added a subscriber: Enna1.



Comment at: compiler-rt/CMakeLists.txt:513-515
+# Don't use libcxx if LLVM_ENABLE_PROJECTS does not enable it.
+set(COMPILER_RT_LIBCXX_PATH ${LLVM_EXTERNAL_LIBCXX_SOURCE_DIR})
+set(COMPILER_RT_LIBCXXABI_PATH ${LLVM_EXTERNAL_LIBCXXABI_SOURCE_DIR})

ldionne wrote:
> I'm not sure I follow here -- we don't support using 
> `LLVM_ENABLE_PROJECTS=libcxx` anymore.
I cleaned this in D126905.



Comment at: compiler-rt/CMakeLists.txt:517-534
+foreach(path IN ITEMS ${LLVM_MAIN_SRC_DIR}/projects/libcxx
+  ${LLVM_MAIN_SRC_DIR}/runtimes/libcxx
+  ${LLVM_MAIN_SRC_DIR}/../libcxx
+  ${LLVM_EXTERNAL_LIBCXX_SOURCE_DIR})
+  if(IS_DIRECTORY ${path})
+set(COMPILER_RT_LIBCXX_PATH ${path})
+break()

ldionne wrote:
> Is there any reason why this can't be hardcoded to 
> `${LLVM_MAIN_SRC_DIR}/.../libcxx`? Why do we need to handle the other layouts?
> 
> Edit: Oh, I see, this was only moved around. I assume you prefer making these 
> other changes in separate patches.
I have created D126905 to clean up these flags.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122931

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


[PATCH] D126291: [flang][Driver] Update link job on windows

2022-06-17 Thread Diana Picus via Phabricator via cfe-commits
rovka added a comment.

I'm going to go ahead and commit this on Monday if nobody raises any objections 
until then. Thanks again to everyone for all the help & feedback!




Comment at: clang/lib/Driver/ToolChains/CommonArgs.cpp:773
+  // TODO: Make this work unconditionally once Flang is mature enough.
+  if (!Args.hasArg(options::OPT_flang_experimental_exec))
+return;

mstorsjo wrote:
> Don't you need to have the same check in `addFortranRuntimeLibs` above too? 
> As both of these functions are called without checking the condition in the 
> caller.
I'd rather not, since that would require adding the `ArgList` as an input to 
`addFortranRuntimeLibs`. I don't think it's worth changing the interface just 
for the sake of something temporary. The whole point of checking the flag 
inside `addFortranRuntimeLibraryPath` is to make it really easy to remove the 
check later, without having to update all the callsites.

See also [[ 
https://reviews.llvm.org/D126291#inline-1227536:~:text=this%20flag%20is%20here%20only%20temporarily
 | the previous discussion ]] (I don't know how to get a link to a comment in 
Phab, so I just linked some text inside it).


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

https://reviews.llvm.org/D126291

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


[PATCH] D126194: [Concepts] Implement overload resolution for destructors (P0848)

2022-06-17 Thread Roy Jacobson via Phabricator via cfe-commits
royjacobson added inline comments.



Comment at: clang/docs/ReleaseNotes.rst:434
 
+- As per "Conditionally Trivial Special Member Functions" (P0848), it is
+  now possible to overload destructors using concepts. Note that the rest

erichkeane wrote:
> Do we have enough to update cxx_status.html?
I think it's still partial enough that I don't want to communicate 'maybe it 
will work'.
I plan to finish the rest in time for Clang 15 so I prefer to just update it 
then :) But I don't feel very strongly about it either way.




Comment at: clang/include/clang/AST/DeclCXX.h:1430
+  /// out of which one will be selected at the end.
+  /// This is called separately from addedMember because it has to be deferred
+  /// to the completion of the class.

erichkeane wrote:
> @aaron.ballman  is messing around with addedMember recently... I wonder if 
> there are OTHER decisions that need to be updated/moved here?
Do you know what papers/DRs he's working on? It seemed like most constexpr 
stuff is done per-function and not per-class.

I don't think there's something else that needs to change but it's definitely 
possible I missed something.. I went through addedMember and tried to remove 
everything destructor related basically.




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126194

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


[PATCH] D126291: [flang][Driver] Update link job on windows

2022-06-17 Thread Martin Storsjö via Phabricator via cfe-commits
mstorsjo added inline comments.



Comment at: clang/lib/Driver/ToolChains/CommonArgs.cpp:773
+  // TODO: Make this work unconditionally once Flang is mature enough.
+  if (!Args.hasArg(options::OPT_flang_experimental_exec))
+return;

rovka wrote:
> mstorsjo wrote:
> > Don't you need to have the same check in `addFortranRuntimeLibs` above too? 
> > As both of these functions are called without checking the condition in the 
> > caller.
> I'd rather not, since that would require adding the `ArgList` as an input to 
> `addFortranRuntimeLibs`. I don't think it's worth changing the interface just 
> for the sake of something temporary. The whole point of checking the flag 
> inside `addFortranRuntimeLibraryPath` is to make it really easy to remove the 
> check later, without having to update all the callsites.
> 
> See also [[ 
> https://reviews.llvm.org/D126291#inline-1227536:~:text=this%20flag%20is%20here%20only%20temporarily
>  | the previous discussion ]] (I don't know how to get a link to a comment in 
> Phab, so I just linked some text inside it).
Ok, fair enough then!


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

https://reviews.llvm.org/D126291

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


[PATCH] D127579: [clang][WIP] add option to keep types of ptr args for non-kernel functions in metadata

2022-06-17 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia added a comment.

In D127579#3590632 , @aeubanks wrote:

> If I'm understanding correctly, previously the LLVM pointee type was used to 
> represent a frontend OpenCL type. An alternative to marking everything with 
> `elementtype` or adding metadata, can something be done in the frontend to 
> mangle the function name with OpenCL pointee types, then the backend 
> translates that to the proper SPIRV types?

We were trying to get away from relying on mangled names in the backend as it 
is harder to target for non-clang and non-OpenCL based languages.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D127579

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


[PATCH] D127579: [clang][WIP] add option to keep types of ptr args for non-kernel functions in metadata

2022-06-17 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia added a comment.

In D127579#3585537 , @nikic wrote:

> In D127579#3585516 , @beanz wrote:
>
>> 
>
> Clang is only permitted to encode pointer type information if that pointer 
> type has some kind of direct semantic meaning -- say, if the pointer element 
> type affects the call ABI in some way. If it does not have direct semantic 
> meaning, then deriving the pointer type based on usage (as DXIL does) and 
> using that for emission would be right approach.

@nikic what is the way for clang to encode the pointer type? Is it just 
generated regularly as before or using something like `elementtype` hint?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D127579

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


[clang] 2d9c891 - [OpenCL] Fix atomic_fetch_add/sub half overloads

2022-06-17 Thread Sven van Haastregt via cfe-commits

Author: Sven van Haastregt
Date: 2022-06-17T09:53:45+01:00
New Revision: 2d9c891cd949a4e6f15c35bd565b3d3588819e85

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

LOG: [OpenCL] Fix atomic_fetch_add/sub half overloads

Some of the atomic_fetch_add and atomic_fetch_sub overloads intended
for atomic_half types accidentally had an atomic_float parameter.

Added: 


Modified: 
clang/lib/Sema/OpenCLBuiltins.td

Removed: 




diff  --git a/clang/lib/Sema/OpenCLBuiltins.td 
b/clang/lib/Sema/OpenCLBuiltins.td
index 75cea2ffc19c..dc158454556a 100644
--- a/clang/lib/Sema/OpenCLBuiltins.td
+++ b/clang/lib/Sema/OpenCLBuiltins.td
@@ -1185,7 +1185,7 @@ let MinVersion = CL20 in {
   defvar extension_fp64 = 
!cast("FuncExtFloatAtomicsFp64" # addrspace # "Add");
 
   defm : BuiltinAtomicExplicit<"atomic_fetch_" # ModOp,
-  [Half, PointerType, addrspace>, Half], 
extension_fp16>;
+  [Half, PointerType, addrspace>, Half], 
extension_fp16>;
   defm : BuiltinAtomicExplicit<"atomic_fetch_" # ModOp,
   [Float, PointerType, addrspace>, Float], 
extension_fp32>;
   defm : BuiltinAtomicExplicit<"atomic_fetch_" # ModOp,



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


[PATCH] D127860: [msan] Allow KMSAN to use -fsanitize-memory-param-retval

2022-06-17 Thread Alexander Potapenko 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 rG7ab44b5c2155: [msan] Allow KMSAN to use 
-fsanitize-memory-param-retval (authored by glider).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D127860

Files:
  clang/lib/Driver/SanitizerArgs.cpp
  clang/test/CodeGen/kmsan-param-retval.c
  clang/test/Driver/fsanitize-memory-param-retval.c


Index: clang/test/Driver/fsanitize-memory-param-retval.c
===
--- clang/test/Driver/fsanitize-memory-param-retval.c
+++ clang/test/Driver/fsanitize-memory-param-retval.c
@@ -3,6 +3,8 @@
 // RUN: %clang -target aarch64-linux-gnu %s -fsanitize=memory 
-fsanitize-memory-param-retval -c -### 2>&1 | FileCheck %s
 // RUN: %clang -target riscv32-linux-gnu %s -fsanitize=memory 
-fsanitize-memory-param-retval -c -### 2>&1 | FileCheck %s
 // RUN: %clang -target riscv64-linux-gnu %s -fsanitize=memory 
-fsanitize-memory-param-retval -c -### 2>&1 | FileCheck %s
+// RUN: %clang -target x86_64-linux-gnu %s -fsanitize=kernel-memory 
-fsanitize-memory-param-retval -c -### 2>&1 | FileCheck %s
+
 // CHECK: "-fsanitize-memory-param-retval"
 
 // RUN: %clang -target aarch64-linux-gnu -fsyntax-only %s -fsanitize=memory 
-fsanitize-memory-param-retval -c -### 2>&1 | FileCheck --check-prefix=11 %s
Index: clang/test/CodeGen/kmsan-param-retval.c
===
--- /dev/null
+++ clang/test/CodeGen/kmsan-param-retval.c
@@ -0,0 +1,36 @@
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -S -emit-llvm -O2 
-fsanitize=kernel-memory -no-enable-noundef-analysis -o - %s | \
+// RUN: FileCheck %s --check-prefix=CLEAN
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -S -emit-llvm -O2 
-fsanitize=kernel-memory -o - %s | \
+// RUN: FileCheck %s --check-prefixes=NOUNDEF,NOUNDEF_ONLY
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -S -emit-llvm -O2 
-fsanitize=kernel-memory -mllvm -msan-eager-checks -o - %s | \
+// RUN: FileCheck %s --check-prefixes=NOUNDEF,EAGER
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -S -emit-llvm -O2 
-fsanitize=kernel-memory -no-enable-noundef-analysis 
-fsanitize-memory-param-retval -o - %s | \
+// RUN: FileCheck %s --check-prefixes=CLEAN
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -S -emit-llvm -O2 
-fsanitize=kernel-memory -fsanitize-memory-param-retval -o - %s | \
+// RUN: FileCheck %s --check-prefixes=NOUNDEF,EAGER
+
+void foo();
+
+void bar(int x) {
+  if (x)
+foo();
+}
+
+
+// CLEAN:   define dso_local void @bar(i32 %x)
+// NOUNDEF: define dso_local void @bar(i32 noundef %x)
+//
+// %param_shadow assignment gets optimized away with -O2, because it is at the 
beginning of the
+// struct returned by __msan_get_context_state(). Use %param_origin as a sign 
that the shadow of
+// the first argument is being used.
+//
+// Without noundef analysis, KMSAN emits metadata checks for the function 
parameter.
+// CLEAN:load i32, ptr %param_origin
+//
+// With noundef analysis enabled, but without eager checks, KMSAN still emits 
metadata checks,
+// although the parameter is known to be defined.
+// NOUNDEF_ONLY: load i32, ptr %param_origin
+//
+// With noundef analysis and eager checks enabled, KMSAN won't emit metadata 
checks for function
+// parameters.
+// EAGER-NOT:load i32, ptr %param_origin
Index: clang/lib/Driver/SanitizerArgs.cpp
===
--- clang/lib/Driver/SanitizerArgs.cpp
+++ clang/lib/Driver/SanitizerArgs.cpp
@@ -648,6 +648,11 @@
 options::OPT_fno_sanitize_memory_param_retval, MsanParamRetval);
 NeedPIE |= !(TC.getTriple().isOSLinux() &&
  TC.getTriple().getArch() == llvm::Triple::x86_64);
+  } else if (AllAddedKinds & SanitizerKind::KernelMemory) {
+MsanUseAfterDtor = false;
+MsanParamRetval = Args.hasFlag(
+options::OPT_fsanitize_memory_param_retval,
+options::OPT_fno_sanitize_memory_param_retval, MsanParamRetval);
   } else {
 MsanUseAfterDtor = false;
 MsanParamRetval = false;


Index: clang/test/Driver/fsanitize-memory-param-retval.c
===
--- clang/test/Driver/fsanitize-memory-param-retval.c
+++ clang/test/Driver/fsanitize-memory-param-retval.c
@@ -3,6 +3,8 @@
 // RUN: %clang -target aarch64-linux-gnu %s -fsanitize=memory -fsanitize-memory-param-retval -c -### 2>&1 | FileCheck %s
 // RUN: %clang -target riscv32-linux-gnu %s -fsanitize=memory -fsanitize-memory-param-retval -c -### 2>&1 | FileCheck %s
 // RUN: %clang -target riscv64-linux-gnu %s -fsanitize=memory -fsanitize-memory-param-retval -c -### 2>&1 | FileCheck %s
+// RUN: %clang -target x86_64-linux-gnu %s -fsanitize=kernel-memory -fsanitize-memory-param-retval -c -### 2>&1 | FileCheck %s
+
 // CHECK: "-fsanitize-memo

[clang] 7ab44b5 - [msan] Allow KMSAN to use -fsanitize-memory-param-retval

2022-06-17 Thread Alexander Potapenko via cfe-commits

Author: Alexander Potapenko
Date: 2022-06-17T10:54:20+02:00
New Revision: 7ab44b5c2155245d115ba8642fcaabe65b54e44b

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

LOG: [msan] Allow KMSAN to use -fsanitize-memory-param-retval

Let -fsanitize-memory-param-retval be used together with
-fsanitize=kernel-memory, so that it can be applied when building the
Linux kernel.

Also add clang/test/CodeGen/kmsan-param-retval.c to ensure that
-fsanitize-memory-param-retval eliminates shadow accesses for parameters
marked as undef.

Reviewed By: eugenis, vitalybuka

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

Added: 
clang/test/CodeGen/kmsan-param-retval.c

Modified: 
clang/lib/Driver/SanitizerArgs.cpp
clang/test/Driver/fsanitize-memory-param-retval.c

Removed: 




diff  --git a/clang/lib/Driver/SanitizerArgs.cpp 
b/clang/lib/Driver/SanitizerArgs.cpp
index edb1bfbe9bdf..55d44691050b 100644
--- a/clang/lib/Driver/SanitizerArgs.cpp
+++ b/clang/lib/Driver/SanitizerArgs.cpp
@@ -648,6 +648,11 @@ SanitizerArgs::SanitizerArgs(const ToolChain &TC,
 options::OPT_fno_sanitize_memory_param_retval, MsanParamRetval);
 NeedPIE |= !(TC.getTriple().isOSLinux() &&
  TC.getTriple().getArch() == llvm::Triple::x86_64);
+  } else if (AllAddedKinds & SanitizerKind::KernelMemory) {
+MsanUseAfterDtor = false;
+MsanParamRetval = Args.hasFlag(
+options::OPT_fsanitize_memory_param_retval,
+options::OPT_fno_sanitize_memory_param_retval, MsanParamRetval);
   } else {
 MsanUseAfterDtor = false;
 MsanParamRetval = false;

diff  --git a/clang/test/CodeGen/kmsan-param-retval.c 
b/clang/test/CodeGen/kmsan-param-retval.c
new file mode 100644
index ..3d952c01c7f7
--- /dev/null
+++ b/clang/test/CodeGen/kmsan-param-retval.c
@@ -0,0 +1,36 @@
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -S -emit-llvm -O2 
-fsanitize=kernel-memory -no-enable-noundef-analysis -o - %s | \
+// RUN: FileCheck %s --check-prefix=CLEAN
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -S -emit-llvm -O2 
-fsanitize=kernel-memory -o - %s | \
+// RUN: FileCheck %s --check-prefixes=NOUNDEF,NOUNDEF_ONLY
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -S -emit-llvm -O2 
-fsanitize=kernel-memory -mllvm -msan-eager-checks -o - %s | \
+// RUN: FileCheck %s --check-prefixes=NOUNDEF,EAGER
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -S -emit-llvm -O2 
-fsanitize=kernel-memory -no-enable-noundef-analysis 
-fsanitize-memory-param-retval -o - %s | \
+// RUN: FileCheck %s --check-prefixes=CLEAN
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -S -emit-llvm -O2 
-fsanitize=kernel-memory -fsanitize-memory-param-retval -o - %s | \
+// RUN: FileCheck %s --check-prefixes=NOUNDEF,EAGER
+
+void foo();
+
+void bar(int x) {
+  if (x)
+foo();
+}
+
+
+// CLEAN:   define dso_local void @bar(i32 %x)
+// NOUNDEF: define dso_local void @bar(i32 noundef %x)
+//
+// %param_shadow assignment gets optimized away with -O2, because it is at the 
beginning of the
+// struct returned by __msan_get_context_state(). Use %param_origin as a sign 
that the shadow of
+// the first argument is being used.
+//
+// Without noundef analysis, KMSAN emits metadata checks for the function 
parameter.
+// CLEAN:load i32, ptr %param_origin
+//
+// With noundef analysis enabled, but without eager checks, KMSAN still emits 
metadata checks,
+// although the parameter is known to be defined.
+// NOUNDEF_ONLY: load i32, ptr %param_origin
+//
+// With noundef analysis and eager checks enabled, KMSAN won't emit metadata 
checks for function
+// parameters.
+// EAGER-NOT:load i32, ptr %param_origin

diff  --git a/clang/test/Driver/fsanitize-memory-param-retval.c 
b/clang/test/Driver/fsanitize-memory-param-retval.c
index 98ca16e02777..d82d20812186 100644
--- a/clang/test/Driver/fsanitize-memory-param-retval.c
+++ b/clang/test/Driver/fsanitize-memory-param-retval.c
@@ -3,6 +3,8 @@
 // RUN: %clang -target aarch64-linux-gnu %s -fsanitize=memory 
-fsanitize-memory-param-retval -c -### 2>&1 | FileCheck %s
 // RUN: %clang -target riscv32-linux-gnu %s -fsanitize=memory 
-fsanitize-memory-param-retval -c -### 2>&1 | FileCheck %s
 // RUN: %clang -target riscv64-linux-gnu %s -fsanitize=memory 
-fsanitize-memory-param-retval -c -### 2>&1 | FileCheck %s
+// RUN: %clang -target x86_64-linux-gnu %s -fsanitize=kernel-memory 
-fsanitize-memory-param-retval -c -### 2>&1 | FileCheck %s
+
 // CHECK: "-fsanitize-memory-param-retval"
 
 // RUN: %clang -target aarch64-linux-gnu -fsyntax-only %s -fsanitize=memory 
-fsanitize-memory-param-retval -c -### 2>&1 | FileCheck --check-prefix=11 %s



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

[PATCH] D128036: [CMake] Option to select C++ library for runtimes that use it

2022-06-17 Thread Petr Hosek via Phabricator via cfe-commits
phosek created this revision.
phosek added reviewers: ldionne, smeenai, mstorsjo.
Herald added subscribers: Enna1, abrachet, mgorny.
Herald added a project: All.
phosek requested review of this revision.
Herald added projects: clang, Sanitizers.
Herald added subscribers: Sanitizers, cfe-commits.

We currently have an option to select C++ ABI and C++ library for tests
but there are runtimes that use C++ library, specifically ORC and XRay,
which aren't covered by existing options. This change introduces a new
option to control the use of C++ libray for these runtimes.

 

Ideally, this option should become the default way to select C++ library
for all of compiler-rt replacing the existing options (the C++ ABI
option could remain as a hidden internal option).


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D128036

Files:
  clang/cmake/caches/Fuchsia-stage2.cmake
  compiler-rt/CMakeLists.txt
  compiler-rt/lib/orc/CMakeLists.txt
  compiler-rt/lib/xray/CMakeLists.txt

Index: compiler-rt/lib/xray/CMakeLists.txt
===
--- compiler-rt/lib/xray/CMakeLists.txt
+++ compiler-rt/lib/xray/CMakeLists.txt
@@ -138,7 +138,9 @@
 include_directories(..)
 include_directories(../../include)
 
-set(XRAY_CFLAGS ${COMPILER_RT_COMMON_CFLAGS})
+set(XRAY_CFLAGS
+  ${COMPILER_RT_COMMON_CFLAGS}
+  ${COMPILER_RT_CXX_CFLAGS})
 set(XRAY_COMMON_DEFINITIONS XRAY_HAS_EXCEPTIONS=1)
 
 # Too many existing bugs, needs cleanup.
@@ -147,6 +149,9 @@
 # We don't need RTTI in XRay, so turn that off.
 append_rtti_flag(OFF XRAY_CFLAGS)
 
+set(XRAY_LINK_FLAGS ${COMPILER_RT_COMMON_LINK_FLAGS})
+set(XRAY_LINK_LIBS ${COMPILER_RT_CXX_LINK_LIBS})
+
 append_list_if(
   COMPILER_RT_HAS_XRAY_COMPILER_FLAG XRAY_SUPPORTED=1 XRAY_COMMON_DEFINITIONS)
 append_list_if(
@@ -164,7 +169,6 @@
 endif()
 
 if (APPLE)
-  set(XRAY_LINK_LIBS ${SANITIZER_COMMON_LINK_LIBS})
   add_asm_sources(XRAY_ASM_SOURCES xray_trampoline_x86_64.S)
 
   add_weak_symbols("sanitizer_common" WEAK_SYMBOL_LINK_FLAGS)
@@ -213,7 +217,7 @@
 RTSanitizerCommonLibc
 CFLAGS ${XRAY_CFLAGS}
 DEFS ${XRAY_COMMON_DEFINITIONS}
-LINK_FLAGS ${SANITIZER_COMMON_LINK_FLAGS} ${WEAK_SYMBOL_LINK_FLAGS}
+LINK_FLAGS ${XRAY_LINK_FLAGS} ${WEAK_SYMBOL_LINK_FLAGS}
 LINK_LIBS ${XRAY_LINK_LIBS}
 PARENT_TARGET xray)
   add_compiler_rt_runtime(clang_rt.xray-fdr
@@ -223,7 +227,7 @@
 OBJECT_LIBS RTXrayFDR
 CFLAGS ${XRAY_CFLAGS}
 DEFS ${XRAY_COMMON_DEFINITIONS}
-LINK_FLAGS ${SANITIZER_COMMON_LINK_FLAGS} ${WEAK_SYMBOL_LINK_FLAGS}
+LINK_FLAGS ${XRAY_LINK_FLAGS} ${WEAK_SYMBOL_LINK_FLAGS}
 LINK_LIBS ${XRAY_LINK_LIBS}
 PARENT_TARGET xray)
   add_compiler_rt_runtime(clang_rt.xray-basic
@@ -233,7 +237,7 @@
 OBJECT_LIBS RTXrayBASIC
 CFLAGS ${XRAY_CFLAGS}
 DEFS ${XRAY_COMMON_DEFINITIONS}
-LINK_FLAGS ${SANITIZER_COMMON_LINK_FLAGS} ${WEAK_SYMBOL_LINK_FLAGS}
+LINK_FLAGS ${XRAY_LINK_FLAGS} ${WEAK_SYMBOL_LINK_FLAGS}
 LINK_LIBS ${XRAY_LINK_LIBS}
 PARENT_TARGET xray)
   add_compiler_rt_runtime(clang_rt.xray-profiling
@@ -243,7 +247,7 @@
 OBJECT_LIBS RTXrayPROFILING
 CFLAGS ${XRAY_CFLAGS}
 DEFS ${XRAY_COMMON_DEFINITIONS}
-LINK_FLAGS ${SANITIZER_COMMON_LINK_FLAGS} ${WEAK_SYMBOL_LINK_FLAGS}
+LINK_FLAGS ${XRAY_LINK_FLAGS} ${WEAK_SYMBOL_LINK_FLAGS}
 LINK_LIBS ${XRAY_LINK_LIBS}
 PARENT_TARGET xray)
 else() # not Apple
@@ -285,6 +289,8 @@
  STATIC
  ARCHS ${arch}
  CFLAGS ${XRAY_CFLAGS}
+ LINK_FLAGS ${XRAY_LINK_FLAGS}
+ LINK_LIBS ${XRAY_LINK_LIBS}
  DEFS ${XRAY_COMMON_DEFINITIONS}
  OBJECT_LIBS ${XRAY_COMMON_RUNTIME_OBJECT_LIBS} RTXray
  PARENT_TARGET xray)
@@ -293,6 +299,8 @@
   STATIC
   ARCHS ${arch}
   CFLAGS ${XRAY_CFLAGS}
+  LINK_FLAGS ${XRAY_LINK_FLAGS}
+  LINK_LIBS ${XRAY_LINK_LIBS}
   DEFS ${XRAY_COMMON_DEFINITIONS}
   OBJECT_LIBS RTXrayFDR
   PARENT_TARGET xray)
@@ -301,6 +309,8 @@
   STATIC
   ARCHS ${arch}
   CFLAGS ${XRAY_CFLAGS}
+  LINK_FLAGS ${XRAY_LINK_FLAGS}
+  LINK_LIBS ${XRAY_LINK_LIBS}
   DEFS ${XRAY_COMMON_DEFINITIONS}
   OBJECT_LIBS RTXrayBASIC
   PARENT_TARGET xray)
@@ -309,6 +319,8 @@
  STATIC
  ARCHS ${arch}
  CFLAGS ${XRAY_CFLAGS}
+ LINK_FLAGS ${XRAY_LINK_FLAGS}
+ LINK_LIBS ${XRAY_LINK_LIBS}
  DEFS ${XRAY_COMMON_DEFINITIONS}
  OBJECT_LIBS RTXrayPROFILING
  PARENT_TARGET xray)
Index: compiler-rt/lib/orc/CMakeLists.txt
===
--- compiler-rt/lib/orc/CMakeLists.txt
+++ compiler-rt/lib/orc/CMakeLists.txt
@@ -49,7 +49,11 @@
 include_directories(..)
 include_directories(../../include)
 
-set(ORC_CFLAGS ${COMPILER_RT_COMMON_CFLAGS})
+set(ORC_CFLAGS
+  ${COMPILER_RT_COMMON_CFLAGS}
+  ${COMPILER_RT_CXX_CFLAGS})
+set(ORC_LINK_FLAGS ${COMPILER_RT_COMMON_LINK_FLAGS})
+set(ORC_LINK_LIBS ${COMPILER_RT_CXX_LINK_LIBS})
 
 # Allow the ORC runtime to ref

[PATCH] D128036: [CMake] Option to select C++ library for runtimes that use it

2022-06-17 Thread Petr Hosek via Phabricator via cfe-commits
phosek added a comment.

I'm aware of the duplication of logic for handling of `COMPILER_RT_CXX_LIBRARY` 
and `SANITIZER_TEST_CXX_LIBNAME`. Right now my goal is to make the use of 
in-tree libc++ in compiler-rt explicit, and then cleaning up the handling logic 
in follow up changes.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128036

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


[PATCH] D128036: [CMake] Option to select C++ library for runtimes that use it

2022-06-17 Thread Martin Storsjö via Phabricator via cfe-commits
mstorsjo added inline comments.



Comment at: compiler-rt/CMakeLists.txt:534
+if (COMPILER_RT_CXX_LIBRARY STREQUAL "libcxx")
+  # We are using the in-tree libc++ so avoid including the default one.
+  append_list_if(COMPILER_RT_HAS_NOSTDINCXX_FLAG -nostdinc++ 
COMPILER_RT_COMMON_CFLAGS)

Does this mean that if you set `COMPILER_RT_CXX_LIBRARY=libcxx`, it's assumed 
that you're actually _building_ that same libcxx in the same cmake invocation?

I'm currently building compiler-rt in a standalone cmake invocation, separate 
from all the others, with `-DSANITIZER_CXX_ABI=libc++`. Building them all at 
once might be something I could consider at some point, but I wouldn't want to 
force that situation right now, if it could be avoided?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128036

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


[PATCH] D128036: [CMake] Option to select C++ library for runtimes that use it

2022-06-17 Thread Petr Hosek via Phabricator via cfe-commits
phosek added inline comments.



Comment at: compiler-rt/CMakeLists.txt:534
+if (COMPILER_RT_CXX_LIBRARY STREQUAL "libcxx")
+  # We are using the in-tree libc++ so avoid including the default one.
+  append_list_if(COMPILER_RT_HAS_NOSTDINCXX_FLAG -nostdinc++ 
COMPILER_RT_COMMON_CFLAGS)

mstorsjo wrote:
> Does this mean that if you set `COMPILER_RT_CXX_LIBRARY=libcxx`, it's assumed 
> that you're actually _building_ that same libcxx in the same cmake invocation?
> 
> I'm currently building compiler-rt in a standalone cmake invocation, separate 
> from all the others, with `-DSANITIZER_CXX_ABI=libc++`. Building them all at 
> once might be something I could consider at some point, but I wouldn't want 
> to force that situation right now, if it could be avoided?
Yes, correct. This is modeled after 
https://github.com/llvm/llvm-project/blob/610139d2d9ce6746b3c617fb3e2f7886272d26ff/libcxx/CMakeLists.txt#L230
 and 
https://github.com/llvm/llvm-project/blob/610139d2d9ce6746b3c617fb3e2f7886272d26ff/libcxx/cmake/Modules/HandleLibCXXABI.cmake#L109.

In your case you'd likely want to use `-DCOMPILER_RT_CXX_LIBRARY=system-libcxx`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128036

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


[PATCH] D128036: [CMake] Option to select C++ library for runtimes that use it

2022-06-17 Thread Martin Storsjö via Phabricator via cfe-commits
mstorsjo accepted this revision.
mstorsjo added a comment.
This revision is now accepted and ready to land.

LGTM




Comment at: compiler-rt/CMakeLists.txt:534
+if (COMPILER_RT_CXX_LIBRARY STREQUAL "libcxx")
+  # We are using the in-tree libc++ so avoid including the default one.
+  append_list_if(COMPILER_RT_HAS_NOSTDINCXX_FLAG -nostdinc++ 
COMPILER_RT_COMMON_CFLAGS)

phosek wrote:
> mstorsjo wrote:
> > Does this mean that if you set `COMPILER_RT_CXX_LIBRARY=libcxx`, it's 
> > assumed that you're actually _building_ that same libcxx in the same cmake 
> > invocation?
> > 
> > I'm currently building compiler-rt in a standalone cmake invocation, 
> > separate from all the others, with `-DSANITIZER_CXX_ABI=libc++`. Building 
> > them all at once might be something I could consider at some point, but I 
> > wouldn't want to force that situation right now, if it could be avoided?
> Yes, correct. This is modeled after 
> https://github.com/llvm/llvm-project/blob/610139d2d9ce6746b3c617fb3e2f7886272d26ff/libcxx/CMakeLists.txt#L230
>  and 
> https://github.com/llvm/llvm-project/blob/610139d2d9ce6746b3c617fb3e2f7886272d26ff/libcxx/cmake/Modules/HandleLibCXXABI.cmake#L109.
> 
> In your case you'd likely want to use 
> `-DCOMPILER_RT_CXX_LIBRARY=system-libcxx`.
Oh right, there was such an option too. Right, that'd work fine yeah - sorry 
for overlooking it.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128036

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


[PATCH] D128008: [clang][deps] Sort submodules when calculating dependencies

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

Interesting edge-case. LGTM.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128008

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


[clang] 32805e6 - [clang] Dont print implicit forrange initializer

2022-06-17 Thread Kadir Cetinkaya via cfe-commits

Author: Kadir Cetinkaya
Date: 2022-06-17T11:29:44+02:00
New Revision: 32805e60c9de1f82887cd2af30d247dcabd2e1d3

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

LOG: [clang] Dont print implicit forrange initializer

Fixes https://github.com/clangd/clangd/issues/1158

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

Added: 


Modified: 
clang/lib/AST/DeclPrinter.cpp
clang/unittests/AST/DeclPrinterTest.cpp

Removed: 




diff  --git a/clang/lib/AST/DeclPrinter.cpp b/clang/lib/AST/DeclPrinter.cpp
index faafe307f03cf..c6a392c9c01b5 100644
--- a/clang/lib/AST/DeclPrinter.cpp
+++ b/clang/lib/AST/DeclPrinter.cpp
@@ -895,12 +895,15 @@ void DeclPrinter::VisitVarDecl(VarDecl *D) {
   Expr *Init = D->getInit();
   if (!Policy.SuppressInitializers && Init) {
 bool ImplicitInit = false;
-if (CXXConstructExpr *Construct =
-dyn_cast(Init->IgnoreImplicit())) {
+if (D->isCXXForRangeDecl()) {
+  // FIXME: We should print the range expression instead.
+  ImplicitInit = true;
+} else if (CXXConstructExpr *Construct =
+   dyn_cast(Init->IgnoreImplicit())) {
   if (D->getInitStyle() == VarDecl::CallInit &&
   !Construct->isListInitialization()) {
 ImplicitInit = Construct->getNumArgs() == 0 ||
-  Construct->getArg(0)->isDefaultArgument();
+   Construct->getArg(0)->isDefaultArgument();
   }
 }
 if (!ImplicitInit) {

diff  --git a/clang/unittests/AST/DeclPrinterTest.cpp 
b/clang/unittests/AST/DeclPrinterTest.cpp
index c2d7d78738f96..11dca6ed68167 100644
--- a/clang/unittests/AST/DeclPrinterTest.cpp
+++ b/clang/unittests/AST/DeclPrinterTest.cpp
@@ -1426,4 +1426,7 @@ TEST(DeclPrinter, VarDeclWithInitializer) {
   ASSERT_TRUE(PrintedDeclCXX17Matches(
   "int a = 0x15;", namedDecl(hasName("a")).bind("id"), "int a = 0x15",
   [](PrintingPolicy &Policy) { Policy.ConstantsAsWritten = true; }));
+  ASSERT_TRUE(
+  PrintedDeclCXX17Matches("void foo() {int arr[42]; for(int a : arr);}",
+  namedDecl(hasName("a")).bind("id"), "int a"));
 }



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


[PATCH] D127863: [clang] Dont print implicit forrange initializer

2022-06-17 Thread Kadir Cetinkaya 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 rG32805e60c9de: [clang] Dont print implicit forrange 
initializer (authored by kadircet).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D127863

Files:
  clang/lib/AST/DeclPrinter.cpp
  clang/unittests/AST/DeclPrinterTest.cpp


Index: clang/unittests/AST/DeclPrinterTest.cpp
===
--- clang/unittests/AST/DeclPrinterTest.cpp
+++ clang/unittests/AST/DeclPrinterTest.cpp
@@ -1426,4 +1426,7 @@
   ASSERT_TRUE(PrintedDeclCXX17Matches(
   "int a = 0x15;", namedDecl(hasName("a")).bind("id"), "int a = 0x15",
   [](PrintingPolicy &Policy) { Policy.ConstantsAsWritten = true; }));
+  ASSERT_TRUE(
+  PrintedDeclCXX17Matches("void foo() {int arr[42]; for(int a : arr);}",
+  namedDecl(hasName("a")).bind("id"), "int a"));
 }
Index: clang/lib/AST/DeclPrinter.cpp
===
--- clang/lib/AST/DeclPrinter.cpp
+++ clang/lib/AST/DeclPrinter.cpp
@@ -895,12 +895,15 @@
   Expr *Init = D->getInit();
   if (!Policy.SuppressInitializers && Init) {
 bool ImplicitInit = false;
-if (CXXConstructExpr *Construct =
-dyn_cast(Init->IgnoreImplicit())) {
+if (D->isCXXForRangeDecl()) {
+  // FIXME: We should print the range expression instead.
+  ImplicitInit = true;
+} else if (CXXConstructExpr *Construct =
+   dyn_cast(Init->IgnoreImplicit())) {
   if (D->getInitStyle() == VarDecl::CallInit &&
   !Construct->isListInitialization()) {
 ImplicitInit = Construct->getNumArgs() == 0 ||
-  Construct->getArg(0)->isDefaultArgument();
+   Construct->getArg(0)->isDefaultArgument();
   }
 }
 if (!ImplicitInit) {


Index: clang/unittests/AST/DeclPrinterTest.cpp
===
--- clang/unittests/AST/DeclPrinterTest.cpp
+++ clang/unittests/AST/DeclPrinterTest.cpp
@@ -1426,4 +1426,7 @@
   ASSERT_TRUE(PrintedDeclCXX17Matches(
   "int a = 0x15;", namedDecl(hasName("a")).bind("id"), "int a = 0x15",
   [](PrintingPolicy &Policy) { Policy.ConstantsAsWritten = true; }));
+  ASSERT_TRUE(
+  PrintedDeclCXX17Matches("void foo() {int arr[42]; for(int a : arr);}",
+  namedDecl(hasName("a")).bind("id"), "int a"));
 }
Index: clang/lib/AST/DeclPrinter.cpp
===
--- clang/lib/AST/DeclPrinter.cpp
+++ clang/lib/AST/DeclPrinter.cpp
@@ -895,12 +895,15 @@
   Expr *Init = D->getInit();
   if (!Policy.SuppressInitializers && Init) {
 bool ImplicitInit = false;
-if (CXXConstructExpr *Construct =
-dyn_cast(Init->IgnoreImplicit())) {
+if (D->isCXXForRangeDecl()) {
+  // FIXME: We should print the range expression instead.
+  ImplicitInit = true;
+} else if (CXXConstructExpr *Construct =
+   dyn_cast(Init->IgnoreImplicit())) {
   if (D->getInitStyle() == VarDecl::CallInit &&
   !Construct->isListInitialization()) {
 ImplicitInit = Construct->getNumArgs() == 0 ||
-  Construct->getArg(0)->isDefaultArgument();
+   Construct->getArg(0)->isDefaultArgument();
   }
 }
 if (!ImplicitInit) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D127270: [clang-format] Add space in placement new expression

2022-06-17 Thread omar ahmed via Phabricator via cfe-commits
omarahmed added inline comments.



Comment at: clang/docs/ClangFormatStyleOptions.rst:4261
 
+  **AfterPlacementOperator** (``AfterPlacementOperatorStyle``) 
:versionbadge:`clang-format 14`
+Defines in which cases to put a space between new/delete operators and 
opening parentheses.

MyDeveloperDay wrote:
> Are you making this by hand or by running tools/docs/dump_format_style.py?
I was doing it manually, as I didn't know there is a script that does that. I 
tried using the script but seems like it has a parsing error with this logic as 
it is the first time to use `enum` inside a `struct` in `format.h` file. So it 
seems that the parsing logic for this case needs to be added. I will try adding 
this parsing case to `dump_format_style.py` and add it to my next update for 
this patch.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D127270

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


[PATCH] D127961: [OpenCL] Reduce emitting candidate notes for builtins

2022-06-17 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia added inline comments.



Comment at: clang/lib/Sema/SemaOverload.cpp:11224
+  // so do not generate such notes.
+  if (S.getLangOpts().OpenCL && Fn->isImplicit() &&
+  Cand->FailureKind != ovl_fail_bad_conversion)

It would have been nice to print each of those overloads but my guess is that 
it's too much work?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D127961

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


[PATCH] D127961: [OpenCL] Reduce emitting candidate notes for builtins

2022-06-17 Thread Sven van Haastregt via Phabricator via cfe-commits
svenvh added inline comments.



Comment at: clang/lib/Sema/SemaOverload.cpp:11224
+  // so do not generate such notes.
+  if (S.getLangOpts().OpenCL && Fn->isImplicit() &&
+  Cand->FailureKind != ovl_fail_bad_conversion)

Anastasia wrote:
> It would have been nice to print each of those overloads but my guess is that 
> it's too much work?
It's not trivial to print those overloads because we don't have a real source 
declaration, but even if it was trivial I am not sure if there is much value in 
printing all overloads.  Typically there are a lot of overloads for OpenCL 
builtins, partly because of all the vector versions.  I don't think a user will 
get much value out of screens full of overloads that didn't match.

For example, for the following code
```
int i, j, k;
i = max(i, j, k);
```

without this patch clang produces 121 note diagnostics.  If we manage to fit 
the diagnostic and candidate on a single line (which I doubt we can, normally 
they take 3 lines each), a user will still have to scroll through a few screens 
(on a 50-line terminal) of note diagnostics before reaching the actual error 
diagnostic.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D127961

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


[PATCH] D128012: [HLSL] Add ExternalSemaSource & vector alias

2022-06-17 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia added a comment.

I wonder if accepting type alias with identifier `vector` while parsing would 
be simpler to implement? Then you could just add those type aliases into the 
internal header. I assume user code is not allowed to redefine those i.e. it 
would result in undefined behavior or something like for most of C++ standard 
library features...

It has a drawback of needing to check names for every type alias but it is an 
invalid program when used in other cases anyway so it should not be a concern 
for the parsing speed.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128012

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


[PATCH] D128043: [flang][driver] Add support for `-O{0|1|2|3}`

2022-06-17 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski created this revision.
awarzynski added reviewers: rovka, kiranchandramohan, schweitz, peixin.
Herald added subscribers: bzcheeseman, rriddle, mgorny.
Herald added a reviewer: sscalpone.
Herald added projects: Flang, All.
awarzynski requested review of this revision.
Herald added subscribers: cfe-commits, stephenneuendorffer, jdoerfert, MaskRay.
Herald added a project: clang.

This patch adds support for most common optimisation compiler flags:
`-O{0|1|2|3}`. This is implemented in both the compiler and fronted
drivers. At this point, these options are only used to configure the
LLVM optimisation pipelines (aka middle-end). LLVM backend or MLIR/FIR
optimisations are not supported yet.

Previously, the middle-end pass manager was only required when
generating LLVM bitcode (i.e. for `flang-new -c -emit-llvm ` or
`flang-new -fc1 -emit-llvm-bc `). With this change, it becomes
required for all frontend actions that are represented as
`CodeGenAction` and `CodeGenAction::executeAction` is refactored
accordingly (in the spirit of better code re-use).

Additionally, the `-fdebug-pass-manager` option is enabled to facilitate
testing. This flag can be used to configure the pass manager to print
the middle-end passes that are being run. Similar option exists in Clang
and the semantics in Flang are identical. This option translates to
extra configuration when setting up the pass manager. This is
implemented in `CodeGenAction::runOptimizationPipeline`.

This patch also adds some bolier plate code to manage code-gen options
("code-gen" refers to generating machine code in LLVM in this context).
This was extracted from Clang. In Clang, it simplifies defining code-gen
options and enables option marshalling. In Flang, option marshalling is
not yet supported (we might do at some point), but being able to
auto-generate some code with macros is beneficial. This will become
particularly apparent when we start adding more options (at least in
Clang, the list of code-gen options is rather long).


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D128043

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/Flang.cpp
  flang/include/flang/Frontend/CodeGenOptions.def
  flang/include/flang/Frontend/CodeGenOptions.h
  flang/include/flang/Frontend/CompilerInvocation.h
  flang/include/flang/Frontend/FrontendActions.h
  flang/lib/Frontend/CMakeLists.txt
  flang/lib/Frontend/CodeGenOptions.cpp
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/lib/Frontend/FrontendActions.cpp
  flang/test/Driver/default-optimization-pipelines.f90
  flang/test/Driver/driver-help.f90

Index: flang/test/Driver/driver-help.f90
===
--- flang/test/Driver/driver-help.f90
+++ flang/test/Driver/driver-help.f90
@@ -95,6 +95,7 @@
 ! HELP-FC1-NEXT: -fdebug-measure-parse-tree
 ! HELP-FC1-NEXT: Measure the parse tree
 ! HELP-FC1-NEXT: -fdebug-module-writer   Enable debug messages while writing module files
+! HELP-FC1-NEXT: -fdebug-pass-managerPrints debug information for the new pass manage
 ! HELP-FC1-NEXT: -fdebug-pre-fir-treeDump the pre-FIR tree
 ! HELP-FC1-NEXT: -fdebug-unparse-no-sema Unparse and stop (skips the semantic checks)
 ! HELP-FC1-NEXT: -fdebug-unparse-with-symbols
@@ -119,6 +120,7 @@
 ! HELP-FC1-NEXT: -fno-analyzed-objects-for-unparse
 ! HELP-FC1-NEXT:Do not use the analyzed objects when unparsing
 ! HELP-FC1-NEXT: -fno-automatic Implies the SAVE attribute for non-automatic local objects in subprograms unless RECURSIVE
+! HELP-FC1-NEXT: -fno-debug-pass-manager Disables debug printing for the new pass manager
 ! HELP-FC1-NEXT: -fno-reformat  Dump the cooked character stream in -E mode
 ! HELP-FC1-NEXT: -fopenacc  Enable OpenACC
 ! HELP-FC1-NEXT: -fopenmp   Parse OpenMP pragmas and generate parallel code.
Index: flang/test/Driver/default-optimization-pipelines.f90
===
--- /dev/null
+++ flang/test/Driver/default-optimization-pipelines.f90
@@ -0,0 +1,24 @@
+! Verify that`-O{n}` is indeed taken into account when definining the LLVM optimization/middle-end pass pass pipeline.
+
+!---
+! RUN LINES
+!---
+! RUN: %flang_fc1 -S -O0 %s -fdebug-pass-manager -o /dev/null 2>&1 | FileCheck %s --check-prefix=CHECK-O0
+! RUN: %flang_fc1 -S -O2 %s -fdebug-pass-manager -o /dev/null 2>&1 | FileCheck %s --check-prefix=CHECK-O2
+
+!---
+! EXPECTED OUTPUT
+!---
+! CHECK-O0-NOT: Running pass: SimplifyCFGPass on simple_loop_
+! CHECK-O0: Running analysis: TargetLibraryAnalysis on simple_loop_
+
+! CHECK-O2: Running pass: SimplifyCFGPass on simple_loop_
+
+!---
+! INPUT
+!---
+subroutine simple_loop
+  integer :: i
+  do i=1,5
+  end do
+end subroutine
Index: flang/lib/Frontend/FrontendActions.cpp
==

[PATCH] D128044: add new option "-ftime-trace-path"

2022-06-17 Thread dongjunduo via Phabricator via cfe-commits
dongjunduo created this revision.
Herald added a project: All.
dongjunduo requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay.
Herald added a project: clang.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D128044

Files:
  clang/include/clang/Driver/Options.td
  clang/include/clang/Frontend/FrontendOptions.h
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/tools/driver/cc1_main.cpp


Index: clang/tools/driver/cc1_main.cpp
===
--- clang/tools/driver/cc1_main.cpp
+++ clang/tools/driver/cc1_main.cpp
@@ -254,8 +254,10 @@
   llvm::TimerGroup::clearAll();
 
   if (llvm::timeTraceProfilerEnabled()) {
-SmallString<128> Path(Clang->getFrontendOpts().OutputFile);
-llvm::sys::path::replace_extension(Path, "json");
+SmallString<128> Path(Clang->getFrontendOpts().TimeTracePath);
+Path.append(llvm::sys::path::filename(
+Clang->getFrontendOpts().OutputFile));
+Path.append(".json");
 if (auto profilerOutput = Clang->createOutputFile(
 Path.str(), /*Binary=*/false, /*RemoveFileOnSignal=*/false,
 /*useTemporary=*/false)) {
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -6183,6 +6183,7 @@
   Args.AddLastArg(CmdArgs, options::OPT_ftime_report_EQ);
   Args.AddLastArg(CmdArgs, options::OPT_ftime_trace);
   Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_granularity_EQ);
+  Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_path);
   Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
   Args.AddLastArg(CmdArgs, options::OPT_malign_double);
   Args.AddLastArg(CmdArgs, options::OPT_fno_temp_file);
Index: clang/include/clang/Frontend/FrontendOptions.h
===
--- clang/include/clang/Frontend/FrontendOptions.h
+++ clang/include/clang/Frontend/FrontendOptions.h
@@ -499,6 +499,9 @@
   /// Minimum time granularity (in microseconds) traced by time profiler.
   unsigned TimeTraceGranularity;
 
+  /// Path which stores the output files of time profiler.
+  std::string TimeTracePath;
+
 public:
   FrontendOptions()
   : DisableFree(false), RelocatablePCH(false), ShowHelp(false),
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -2828,6 +2828,10 @@
   HelpText<"Minimum time granularity (in microseconds) traced by time 
profiler">,
   Flags<[CC1Option, CoreOption]>,
   MarshallingInfoInt, "500u">;
+def ftime_trace_path : Joined<["-"], "ftime-trace-path=">, Group,
+  HelpText<"Path which stores the output files of time profiler">,
+  Flags<[CC1Option, CoreOption]>,
+  MarshallingInfoString>;
 def fproc_stat_report : Joined<["-"], "fproc-stat-report">, Group,
   HelpText<"Print subprocess statistics">;
 def fproc_stat_report_EQ : Joined<["-"], "fproc-stat-report=">, Group,


Index: clang/tools/driver/cc1_main.cpp
===
--- clang/tools/driver/cc1_main.cpp
+++ clang/tools/driver/cc1_main.cpp
@@ -254,8 +254,10 @@
   llvm::TimerGroup::clearAll();
 
   if (llvm::timeTraceProfilerEnabled()) {
-SmallString<128> Path(Clang->getFrontendOpts().OutputFile);
-llvm::sys::path::replace_extension(Path, "json");
+SmallString<128> Path(Clang->getFrontendOpts().TimeTracePath);
+Path.append(llvm::sys::path::filename(
+Clang->getFrontendOpts().OutputFile));
+Path.append(".json");
 if (auto profilerOutput = Clang->createOutputFile(
 Path.str(), /*Binary=*/false, /*RemoveFileOnSignal=*/false,
 /*useTemporary=*/false)) {
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -6183,6 +6183,7 @@
   Args.AddLastArg(CmdArgs, options::OPT_ftime_report_EQ);
   Args.AddLastArg(CmdArgs, options::OPT_ftime_trace);
   Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_granularity_EQ);
+  Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_path);
   Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
   Args.AddLastArg(CmdArgs, options::OPT_malign_double);
   Args.AddLastArg(CmdArgs, options::OPT_fno_temp_file);
Index: clang/include/clang/Frontend/FrontendOptions.h
===
--- clang/include/clang/Frontend/FrontendOptions.h
+++ clang/include/clang/Frontend/FrontendOptions.h
@@ -499,6 +499,9 @@
   /// Minimum time granularity (in microseconds) traced by time profiler.
   unsigned TimeTraceGranularity;
 
+  /// Path which stores the output files of time profiler.
+  std::string TimeTracePath;
+
 public:
   FrontendOptions()
   : DisableFree(false

[PATCH] D126061: [clang] Reject non-declaration C++11 attributes on declarations

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

In D126061#3590896 , @dyung wrote:

> @mboehme, one of our internal tests started to fail to compile after this 
> change due to the compiler no longer accepting what I think should be a valid 
> attribute declaration. I have filed issue #56077 for the problem, can you 
> take a look?

Attributes are not allowed to occur in this position -- I'll discuss in more 
detail on #56077.

See also the response I'm making on a code comment, where a reviewer pointed 
out to me that the C++ standard does not allow `[[]]` attributes before `extern 
"C"`.




Comment at: clang/lib/Parse/Parser.cpp:1164
   DS.getParsedSpecifiers() == DeclSpec::PQ_StorageClassSpecifier) {
-Decl *TheDecl = ParseLinkage(DS, DeclaratorContext::File);
+Decl *TheDecl = ParseLinkage(DS, DeclaratorContext::File, Attrs);
 return Actions.ConvertDeclToDeclGroup(TheDecl);

mboehme wrote:
> aaron.ballman wrote:
> > rsmith wrote:
> > > We should `ProhibitAttrs` here rather than passing them on.
> > > ```
> > > [[]] extern "C" void f();
> > > ```
> > > ... is invalid. (Per the grammar in 
> > > https://eel.is/c++draft/dcl.dcl#dcl.pre-1 and 
> > > https://eel.is/c++draft/dcl.dcl#dcl.link-2 an attribute-specifier-seq 
> > > can't appear here.)
> > +1, looks like we're missing test coverage for that case (but those 
> > diagnostics by GCC or MSVC... hoo boy!): https://godbolt.org/z/cTfPbK837
> Fixed and added a test in test/Parser/cxx0x-attributes.cpp.
Update: @dyung is seeing errors on their codebase because of this -- see also 
the comment they added to this patch.

It's not unexpected that people would have this incorrect usage in their 
codebases because we used to allow it. At the same time, it's not hard to fix, 
and I would generally expect this kind of error to occur in first-party code 
(that is easily fixed) rather than third-party libraries, because the latter 
usually compile on GCC, and GCC disallows this usage.

Still, I wanted to discuss whether you think we need to reinstate support for 
this (incorrect) usage temporarily, with a deprecation warning rather than an 
error?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126061

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


[PATCH] D127910: [Clang][AArch64] Add SME C intrinsics for load and store

2022-06-17 Thread Sander de Smalen via Phabricator via cfe-commits
sdesmalen added inline comments.



Comment at: clang/lib/Basic/Targets/AArch64.cpp:342
+  if (HasSME)
+Builder.defineMacro("__ARM_FEATURE_SME", "1");
+

sagarkulkarni19 wrote:
> sdesmalen wrote:
> > When this macro is non-zero, it suggests that the compiler implements the 
> > full SME ACLE. That is currently not yet the case, so until then we should 
> > leave this macro undefined.
> Okay makes sense. But until all SME ACLE is implemented, do we need some sort 
> of guard in the meantime while the SME intrinsics that are implemented 
> incrementally? 
The tests need to have manual `-D__ARM_FEATURE_SME` in the RUN lines. Once the 
feature is implemented and we add the definition automatically when +sme is 
specified, we update the tests. See for example D81725 where we did this for 
SVE.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D127910

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


[PATCH] D128013: [clang][dataflow] Add support for comma binary operator

2022-06-17 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel accepted this revision.
ymandel added a comment.
This revision is now accepted and ready to land.

Thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128013

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


[clang] c80c576 - [Clang] Allow 'Complex float __attribute__((mode(HC)))'

2022-06-17 Thread Malhar Jajoo via cfe-commits

Author: Jolanta Jensen
Date: 2022-06-17T12:39:52+01:00
New Revision: c80c57674e4d9887dfa9159de9981941d9e6d18e

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

LOG: [Clang] Allow 'Complex float __attribute__((mode(HC)))'

Adding half float to types that can be represented by __attribute__((mode(xx))).
Original implementation authored by George Steed.

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

Added: 
clang/test/CodeGen/aarch64-attr-mode-complex.c
clang/test/CodeGen/aarch64-attr-mode-float.c

Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Basic/TargetInfo.h
clang/lib/AST/ASTContext.cpp
clang/lib/Basic/TargetInfo.cpp
clang/lib/Basic/Targets/X86.h
clang/test/Sema/attr-mode-vector-types.c
clang/test/Sema/attr-mode.c

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index e9ea54d591dad..947786a783452 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -367,6 +367,8 @@ Attribute Changes in Clang
 - Added the ``clang::annotate_type`` attribute, which can be used to add
   annotations to types (see documentation for details).
 
+- Added half float to types that can be represented by 
``__attribute__((mode(XX)))``.
+
 Windows Support
 ---
 

diff  --git a/clang/include/clang/Basic/TargetInfo.h 
b/clang/include/clang/Basic/TargetInfo.h
index 32a330a044c45..3ed47559ab4d0 100644
--- a/clang/include/clang/Basic/TargetInfo.h
+++ b/clang/include/clang/Basic/TargetInfo.h
@@ -53,11 +53,13 @@ namespace Builtin { struct Info; }
 
 enum class FloatModeKind {
   NoFloat = 255,
-  Float = 0,
+  Half = 0,
+  Float,
   Double,
   LongDouble,
   Float128,
-  Ibm128
+  Ibm128,
+  Last = Ibm128
 };
 
 /// Fields controlling how types are laid out in memory; these may need to
@@ -219,7 +221,7 @@ class TargetInfo : public virtual TransferrableTargetInfo,
   mutable VersionTuple PlatformMinVersion;
 
   unsigned HasAlignMac68kSupport : 1;
-  unsigned RealTypeUsesObjCFPRet : 3;
+  unsigned RealTypeUsesObjCFPRetMask : (int)FloatModeKind::Last + 1;
   unsigned ComplexLongDoubleUsesFP2Ret : 1;
 
   unsigned HasBuiltinMSVaList : 1;
@@ -888,7 +890,9 @@ class TargetInfo : public virtual TransferrableTargetInfo,
   /// Check whether the given real type should use the "fpret" flavor of
   /// Objective-C message passing on this target.
   bool useObjCFPRetForRealType(FloatModeKind T) const {
-return RealTypeUsesObjCFPRet & (1 << (int)T);
+assert(T <= FloatModeKind::Last &&
+   "T value is larger than RealTypeUsesObjCFPRetMask can handle");
+return RealTypeUsesObjCFPRetMask & (1 << (int)T);
   }
 
   /// Check whether _Complex long double should use the "fp2ret" flavor

diff  --git a/clang/lib/AST/ASTContext.cpp b/clang/lib/AST/ASTContext.cpp
index eab6c34bb8f1a..2b951c55f44a4 100644
--- a/clang/lib/AST/ASTContext.cpp
+++ b/clang/lib/AST/ASTContext.cpp
@@ -11758,6 +11758,8 @@ QualType ASTContext::getRealTypeForBitwidth(unsigned 
DestWidth,
   FloatModeKind Ty =
   getTargetInfo().getRealTypeByWidth(DestWidth, ExplicitType);
   switch (Ty) {
+  case FloatModeKind::Half:
+return HalfTy;
   case FloatModeKind::Float:
 return FloatTy;
   case FloatModeKind::Double:

diff  --git a/clang/lib/Basic/TargetInfo.cpp b/clang/lib/Basic/TargetInfo.cpp
index ba821f16c1f03..e22ed34e7da46 100644
--- a/clang/lib/Basic/TargetInfo.cpp
+++ b/clang/lib/Basic/TargetInfo.cpp
@@ -131,7 +131,7 @@ TargetInfo::TargetInfo(const llvm::Triple &T) : Triple(T) {
   ARMCDECoprocMask = 0;
 
   // Default to no types using fpret.
-  RealTypeUsesObjCFPRet = 0;
+  RealTypeUsesObjCFPRetMask = 0;
 
   // Default to not using fp2ret for __Complex long double
   ComplexLongDoubleUsesFP2Ret = false;
@@ -287,6 +287,8 @@ TargetInfo::IntType 
TargetInfo::getLeastIntTypeByWidth(unsigned BitWidth,
 
 FloatModeKind TargetInfo::getRealTypeByWidth(unsigned BitWidth,
  FloatModeKind ExplicitType) const 
{
+  if (getHalfWidth() == BitWidth)
+return FloatModeKind::Half;
   if (getFloatWidth() == BitWidth)
 return FloatModeKind::Float;
   if (getDoubleWidth() == BitWidth)

diff  --git a/clang/lib/Basic/Targets/X86.h b/clang/lib/Basic/Targets/X86.h
index 6b49b0f28bfc4..007d5c23ec4c7 100644
--- a/clang/lib/Basic/Targets/X86.h
+++ b/clang/lib/Basic/Targets/X86.h
@@ -418,7 +418,7 @@ class LLVM_LIBRARY_VISIBILITY X86_32TargetInfo : public 
X86TargetInfo {
 RegParmMax = 3;
 
 // Use fpret for all types.
-RealTypeUsesObjCFPRet =
+RealTypeUsesObjCFPRetMask =
 ((1 << (int)FloatModeKind::Float) | (1 << (int)FloatModeKind::Double) |
  (1 << (int)FloatModeKind::LongDouble));
 
@@ -699,7 +699,7 @@ class LLVM_LIBRARY_VISIBILITY X86_64TargetIn

[PATCH] D126479: [Clang] Allow 'Complex float __attribute__((mode(HC)))'

2022-06-17 Thread Malhar 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 rGc80c57674e4d: [Clang] Allow 'Complex float 
__attribute__((mode(HC)))' (authored by jolanta.jensen, committed by 
malharJ).

Changed prior to commit:
  https://reviews.llvm.org/D126479?vs=437202&id=437855#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126479

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/TargetInfo.h
  clang/lib/AST/ASTContext.cpp
  clang/lib/Basic/TargetInfo.cpp
  clang/lib/Basic/Targets/X86.h
  clang/test/CodeGen/aarch64-attr-mode-complex.c
  clang/test/CodeGen/aarch64-attr-mode-float.c
  clang/test/Sema/attr-mode-vector-types.c
  clang/test/Sema/attr-mode.c

Index: clang/test/Sema/attr-mode.c
===
--- clang/test/Sema/attr-mode.c
+++ clang/test/Sema/attr-mode.c
@@ -37,6 +37,11 @@
 __attribute__((mode(QI))) int invalid_func(void) { return 1; } // expected-error{{'mode' attribute only applies to variables, enums, typedefs, and non-static data members}}
 enum invalid_enum { A1 __attribute__((mode(QI))) }; // expected-error{{'mode' attribute only applies to}}
 
+typedef _Complex float c16a __attribute((mode(HC)));
+int c16a_test[sizeof(c16a) == 4 ? 1 : -1];
+typedef _Complex double c16b __attribute((mode(HC)));
+int c16b_test[sizeof(c16b) == 4 ? 1 : -1];
+
 typedef _Complex double c32 __attribute((mode(SC)));
 int c32_test[sizeof(c32) == 8 ? 1 : -1];
 typedef _Complex float c64 __attribute((mode(DC)));
Index: clang/test/Sema/attr-mode-vector-types.c
===
--- clang/test/Sema/attr-mode-vector-types.c
+++ clang/test/Sema/attr-mode-vector-types.c
@@ -22,8 +22,7 @@
 // expected-error@-1{{unsupported machine mode 'QC'}}
 // expected-error@-2{{type of machine mode does not match type of base type}}
 typedef _Complex float __attribute__((mode(HC))) __attribute__((vector_size(256))) vec_t9;
-// expected-error@-1{{unsupported machine mode 'HC'}}
-// expected-error@-2{{invalid vector element type '_Complex float'}}
+// expected-error@-1{{invalid vector element type '_Complex float'}}
 typedef int __attribute__((mode(SC))) __attribute__((vector_size(256))) vec_t10;
 // expected-error@-1{{type of machine mode does not match type of base type}}
 // expected-error@-2{{type of machine mode does not support base vector types}}
Index: clang/test/CodeGen/aarch64-attr-mode-float.c
===
--- /dev/null
+++ clang/test/CodeGen/aarch64-attr-mode-float.c
@@ -0,0 +1,29 @@
+// RUN: %clang_cc1 -triple arm64-none-linux-gnu -emit-llvm %s -o - | FileCheck %s
+
+typedef float f16a __attribute((mode(HF)));
+typedef double f16b __attribute((mode(HF)));
+typedef float f32a __attribute((mode(SF)));
+typedef double f32b __attribute((mode(SF)));
+typedef float f64a __attribute((mode(DF)));
+typedef double f64b __attribute((mode(DF)));
+f16b tmp;
+
+// CHECK: define{{.*}} ptr @f16_test(ptr noundef {{.*}})
+// CHECK:   store half {{.*}}, ptr @tmp, align 2
+// CHECK:   ret ptr @tmp
+f16b *f16_test(f16a *x) {
+  tmp = *x + *x;
+  return &tmp;
+}
+
+// CHECK: define{{.*}} float @f32_test(float noundef {{.*}})
+// CHECK:   ret float {{.*}}
+f32b f32_test(f32a x) {
+  return x + x;
+}
+
+// CHECK: define{{.*}} double @f64_test(double noundef {{.*}})
+// CHECK:   ret double {{.*}}
+f64b f64_test(f64a x) {
+  return x + x;
+}
Index: clang/test/CodeGen/aarch64-attr-mode-complex.c
===
--- /dev/null
+++ clang/test/CodeGen/aarch64-attr-mode-complex.c
@@ -0,0 +1,26 @@
+// RUN: %clang_cc1 -triple arm64-none-linux-gnu -emit-llvm %s -o - | FileCheck %s
+
+typedef _Complex float c16a __attribute((mode(HC)));
+typedef _Complex double c16b __attribute((mode(HC)));
+typedef _Complex float c32a __attribute((mode(SC)));
+typedef _Complex double c32b __attribute((mode(SC)));
+typedef _Complex float c64a __attribute((mode(DC)));
+typedef _Complex double c64b __attribute((mode(DC)));
+
+// CHECK: define{{.*}} { half, half } @c16_test([2 x half] noundef {{.*}}
+// CHECK:   ret { half, half } {{.*}}
+c16b c16_test(c16a x) {
+  return x + x;
+}
+
+// CHECK: define{{.*}} { float, float } @c32_test([2 x float] noundef {{.*}})
+// CHECK:   ret { float, float } {{.*}}
+c32b c32_test(c32a x) {
+  return x + x;
+}
+
+// CHECK: define{{.*}} { double, double } @c64_test([2 x double] noundef {{.*}})
+// CHECK:   ret { double, double } {{.*}}
+c64b c64_test(c64a x) {
+  return x + x;
+}
Index: clang/lib/Basic/Targets/X86.h
===
--- clang/lib/Basic/Targets/X86.h
+++ clang/lib/Basic/Targets/X86.h
@@ -418,7 +418,7 @@
 RegParmMax = 3;
 
 // Use fpret for all types.
-RealTypeUsesObjCFPRet =
+Rea

[PATCH] D126061: [clang] Reject non-declaration C++11 attributes on declarations

2022-06-17 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/lib/Parse/Parser.cpp:1164
   DS.getParsedSpecifiers() == DeclSpec::PQ_StorageClassSpecifier) {
-Decl *TheDecl = ParseLinkage(DS, DeclaratorContext::File);
+Decl *TheDecl = ParseLinkage(DS, DeclaratorContext::File, Attrs);
 return Actions.ConvertDeclToDeclGroup(TheDecl);

mboehme wrote:
> mboehme wrote:
> > aaron.ballman wrote:
> > > rsmith wrote:
> > > > We should `ProhibitAttrs` here rather than passing them on.
> > > > ```
> > > > [[]] extern "C" void f();
> > > > ```
> > > > ... is invalid. (Per the grammar in 
> > > > https://eel.is/c++draft/dcl.dcl#dcl.pre-1 and 
> > > > https://eel.is/c++draft/dcl.dcl#dcl.link-2 an attribute-specifier-seq 
> > > > can't appear here.)
> > > +1, looks like we're missing test coverage for that case (but those 
> > > diagnostics by GCC or MSVC... hoo boy!): https://godbolt.org/z/cTfPbK837
> > Fixed and added a test in test/Parser/cxx0x-attributes.cpp.
> Update: @dyung is seeing errors on their codebase because of this -- see also 
> the comment they added to this patch.
> 
> It's not unexpected that people would have this incorrect usage in their 
> codebases because we used to allow it. At the same time, it's not hard to 
> fix, and I would generally expect this kind of error to occur in first-party 
> code (that is easily fixed) rather than third-party libraries, because the 
> latter usually compile on GCC, and GCC disallows this usage.
> 
> Still, I wanted to discuss whether you think we need to reinstate support for 
> this (incorrect) usage temporarily, with a deprecation warning rather than an 
> error?
> Still, I wanted to discuss whether you think we need to reinstate support for 
> this (incorrect) usage temporarily, with a deprecation warning rather than an 
> error?

I think it depends heavily on what's been impacted. If it's application code, 
the error is fine because it's pretty trivial to fix. If it's system header or 
popular 3rd party library code, then a warning might make more sense.

It's worth noting that what we accepted didn't have any semantic impact anyway. 
We would accept the attribute, but not actually add it into the AST: 
https://godbolt.org/z/q7n1794Tx. So I'm not certain there's any harm aside from 
the annoyance of getting an error where you didn't previously get one before.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126061

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


[PATCH] D127863: [clang] Dont print implicit forrange initializer

2022-06-17 Thread Carlos Alberto Enciso via Phabricator via cfe-commits
CarlosAlbertoEnciso added a comment.

@kadircet It seems that your change broke couple of clang tests:

https://lab.llvm.org/buildbot/#/builders/109/builds/40797


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D127863

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


[PATCH] D128046: Add a new clang option "-ftime-trace-path"

2022-06-17 Thread dongjunduo via Phabricator via cfe-commits
dongjunduo created this revision.
Herald added a project: All.
dongjunduo requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Add a new clang option "-ftime-trace-path".

The time profiler traces the stages during the clang compile 
process. Each compiling stage of a single source file 
corresponds to a separately .json file which holds its 
time tracing data. However, the .json files are stored in the 
same path/directory as its corresponding stage's '-o' option.
For example, if we compile the "demo.cc" to "demo.o" with option
"-o /tmp/demo.o", the time trace data file path is "/tmp/demo.json".

A typical c++ project can contain multiple source files in different 
path, but all the json files' paths can be a mess.

The option "-ftime-trace-path" allows you to specify where the json 
files should be stored. This allows the users to place the time trace 
data files of interest in the desired location for further data analysis.

Usage:

  clang/clang++ -ftime-trace -ftime-trace-path=/path-you-want/ ...


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D128046

Files:
  clang/tools/driver/cc1_main.cpp


Index: clang/tools/driver/cc1_main.cpp
===
--- clang/tools/driver/cc1_main.cpp
+++ clang/tools/driver/cc1_main.cpp
@@ -255,8 +255,7 @@
 
   if (llvm::timeTraceProfilerEnabled()) {
 SmallString<128> Path(Clang->getFrontendOpts().TimeTracePath);
-Path.append(llvm::sys::path::filename(
-Clang->getFrontendOpts().OutputFile));
+
Path.append(llvm::sys::path::filename(Clang->getFrontendOpts().OutputFile));
 Path.append(".json");
 if (auto profilerOutput = Clang->createOutputFile(
 Path.str(), /*Binary=*/false, /*RemoveFileOnSignal=*/false,


Index: clang/tools/driver/cc1_main.cpp
===
--- clang/tools/driver/cc1_main.cpp
+++ clang/tools/driver/cc1_main.cpp
@@ -255,8 +255,7 @@
 
   if (llvm::timeTraceProfilerEnabled()) {
 SmallString<128> Path(Clang->getFrontendOpts().TimeTracePath);
-Path.append(llvm::sys::path::filename(
-Clang->getFrontendOpts().OutputFile));
+Path.append(llvm::sys::path::filename(Clang->getFrontendOpts().OutputFile));
 Path.append(".json");
 if (auto profilerOutput = Clang->createOutputFile(
 Path.str(), /*Binary=*/false, /*RemoveFileOnSignal=*/false,
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 7aac15d - Revert "[clang] Dont print implicit forrange initializer"

2022-06-17 Thread Nico Weber via cfe-commits

Author: Nico Weber
Date: 2022-06-17T08:59:17-04:00
New Revision: 7aac15d5df6cfa03b802e055b63227a95fa1734e

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

LOG: Revert "[clang] Dont print implicit forrange initializer"

This reverts commit 32805e60c9de1f82887cd2af30d247dcabd2e1d3.
Broke check-clang, see comments on https://reviews.llvm.org/D127863

Added: 


Modified: 
clang/lib/AST/DeclPrinter.cpp
clang/unittests/AST/DeclPrinterTest.cpp

Removed: 




diff  --git a/clang/lib/AST/DeclPrinter.cpp b/clang/lib/AST/DeclPrinter.cpp
index c6a392c9c01b5..faafe307f03cf 100644
--- a/clang/lib/AST/DeclPrinter.cpp
+++ b/clang/lib/AST/DeclPrinter.cpp
@@ -895,15 +895,12 @@ void DeclPrinter::VisitVarDecl(VarDecl *D) {
   Expr *Init = D->getInit();
   if (!Policy.SuppressInitializers && Init) {
 bool ImplicitInit = false;
-if (D->isCXXForRangeDecl()) {
-  // FIXME: We should print the range expression instead.
-  ImplicitInit = true;
-} else if (CXXConstructExpr *Construct =
-   dyn_cast(Init->IgnoreImplicit())) {
+if (CXXConstructExpr *Construct =
+dyn_cast(Init->IgnoreImplicit())) {
   if (D->getInitStyle() == VarDecl::CallInit &&
   !Construct->isListInitialization()) {
 ImplicitInit = Construct->getNumArgs() == 0 ||
-   Construct->getArg(0)->isDefaultArgument();
+  Construct->getArg(0)->isDefaultArgument();
   }
 }
 if (!ImplicitInit) {

diff  --git a/clang/unittests/AST/DeclPrinterTest.cpp 
b/clang/unittests/AST/DeclPrinterTest.cpp
index 11dca6ed68167..c2d7d78738f96 100644
--- a/clang/unittests/AST/DeclPrinterTest.cpp
+++ b/clang/unittests/AST/DeclPrinterTest.cpp
@@ -1426,7 +1426,4 @@ TEST(DeclPrinter, VarDeclWithInitializer) {
   ASSERT_TRUE(PrintedDeclCXX17Matches(
   "int a = 0x15;", namedDecl(hasName("a")).bind("id"), "int a = 0x15",
   [](PrintingPolicy &Policy) { Policy.ConstantsAsWritten = true; }));
-  ASSERT_TRUE(
-  PrintedDeclCXX17Matches("void foo() {int arr[42]; for(int a : arr);}",
-  namedDecl(hasName("a")).bind("id"), "int a"));
 }



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


[PATCH] D127863: [clang] Dont print implicit forrange initializer

2022-06-17 Thread Nico Weber via Phabricator via cfe-commits
thakis added a comment.

Before landing changes, please:

- Run tests
- Look at the result from the presubmit checks

After landing changes, please watch your favorite bot cycle green with it, and 
pay attention for buildbot email for a while.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D127863

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


[PATCH] D128048: Add a new clang option "-ftime-trace-path"

2022-06-17 Thread dongjunduo via Phabricator via cfe-commits
dongjunduo created this revision.
Herald added a project: All.
dongjunduo requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay.
Herald added a project: clang.

The time profiler traces the stages during the clang compile 
process. Each compiling stage of a single source file 
corresponds to a separately .json file which holds its 
time tracing data. However, the .json files are stored in the 
same path/directory as its corresponding stage's '-o' option.
For example, if we compile the "demo.cc" to "demo.o" with option
"-o /tmp/demo.o", the time trace data file path is "/tmp/demo.json".

A typical c++ project can contain multiple source files in different 
path, but all the json files' paths can be a mess.

The option "-ftime-trace-path" allows you to specify where the json 
files should be stored. This allows the users to place the time trace 
data files of interest in the desired location for further data analysis.

Usage:

  clang/clang++ -ftime-trace -ftime-trace-path=/path-you-want/ ...


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D128048

Files:
  clang/include/clang/Driver/Options.td
  clang/include/clang/Frontend/FrontendOptions.h
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/tools/driver/cc1_main.cpp


Index: clang/tools/driver/cc1_main.cpp
===
--- clang/tools/driver/cc1_main.cpp
+++ clang/tools/driver/cc1_main.cpp
@@ -254,8 +254,9 @@
   llvm::TimerGroup::clearAll();
 
   if (llvm::timeTraceProfilerEnabled()) {
-SmallString<128> Path(Clang->getFrontendOpts().OutputFile);
-llvm::sys::path::replace_extension(Path, "json");
+SmallString<128> Path(Clang->getFrontendOpts().TimeTracePath);
+
Path.append(llvm::sys::path::filename(Clang->getFrontendOpts().OutputFile));
+Path.append(".json");
 if (auto profilerOutput = Clang->createOutputFile(
 Path.str(), /*Binary=*/false, /*RemoveFileOnSignal=*/false,
 /*useTemporary=*/false)) {
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -6183,6 +6183,7 @@
   Args.AddLastArg(CmdArgs, options::OPT_ftime_report_EQ);
   Args.AddLastArg(CmdArgs, options::OPT_ftime_trace);
   Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_granularity_EQ);
+  Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_path);
   Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
   Args.AddLastArg(CmdArgs, options::OPT_malign_double);
   Args.AddLastArg(CmdArgs, options::OPT_fno_temp_file);
Index: clang/include/clang/Frontend/FrontendOptions.h
===
--- clang/include/clang/Frontend/FrontendOptions.h
+++ clang/include/clang/Frontend/FrontendOptions.h
@@ -499,6 +499,9 @@
   /// Minimum time granularity (in microseconds) traced by time profiler.
   unsigned TimeTraceGranularity;
 
+  /// Path which stores the output files of time profiler.
+  std::string TimeTracePath;
+
 public:
   FrontendOptions()
   : DisableFree(false), RelocatablePCH(false), ShowHelp(false),
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -2828,6 +2828,10 @@
   HelpText<"Minimum time granularity (in microseconds) traced by time 
profiler">,
   Flags<[CC1Option, CoreOption]>,
   MarshallingInfoInt, "500u">;
+def ftime_trace_path : Joined<["-"], "ftime-trace-path=">, Group,
+  HelpText<"Path which stores the output files of time profiler">,
+  Flags<[CC1Option, CoreOption]>,
+  MarshallingInfoString>;
 def fproc_stat_report : Joined<["-"], "fproc-stat-report">, Group,
   HelpText<"Print subprocess statistics">;
 def fproc_stat_report_EQ : Joined<["-"], "fproc-stat-report=">, Group,


Index: clang/tools/driver/cc1_main.cpp
===
--- clang/tools/driver/cc1_main.cpp
+++ clang/tools/driver/cc1_main.cpp
@@ -254,8 +254,9 @@
   llvm::TimerGroup::clearAll();
 
   if (llvm::timeTraceProfilerEnabled()) {
-SmallString<128> Path(Clang->getFrontendOpts().OutputFile);
-llvm::sys::path::replace_extension(Path, "json");
+SmallString<128> Path(Clang->getFrontendOpts().TimeTracePath);
+Path.append(llvm::sys::path::filename(Clang->getFrontendOpts().OutputFile));
+Path.append(".json");
 if (auto profilerOutput = Clang->createOutputFile(
 Path.str(), /*Binary=*/false, /*RemoveFileOnSignal=*/false,
 /*useTemporary=*/false)) {
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -6183,6 +6183,7 @@
   Args.AddLastArg(CmdArgs, options::OPT_ftime_report_EQ);
   Args.AddLastArg(CmdArgs

[PATCH] D126907: Deferred Concept Instantiation Implementation Take 2

2022-06-17 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added a comment.

In D126907#3591195 , @ChuanqiXu wrote:

> In D126907#3588708 , @erichkeane 
> wrote:
>
>> In D126907#3588417 , @ChuanqiXu 
>> wrote:
>>
>>> From what I can see, the crash reason would be the mismatch depth and the 
>>> setting of MultiLevelTemplateArgumentList. In 
>>> `::CheckConstraintSatisfaction`, the depth of `RawCompletionToken ` is 0, 
>>> while the depth of corresponding MultiLevelTemplateArgumentList is 2. So 
>>> the compiler would get the outermost template argument incorrectly (which 
>>> is a template pack in the example) in TransformTemplateTypeParmType.
>>>
>>> The first though was that we should set the depth of `RawCompletionToken ` 
>>> to 1 correctly. But I felt this might not be good later since in the normal 
>>> process of template instantiation (without concepts and constraints), the 
>>> depth of `RawCompletionToken ` is 0 indeed. What is different that time is 
>>> the depth of corresponding `MultiLevelTemplateArgumentList ` is 1. So it 
>>> looks like the process is constructed on the fly. It makes sense for the 
>>> perspective of compilation speed.
>>>
>>> So I feel like what we should do here is in 
>>> `Sema::CheckInstantiatedFunctionTemplateConstraints`, when we are computing 
>>> the desired MultiLevelTemplateArgumentList, we should compute a result with 
>>> depth of 1 in the particular case.
>>>
>>> ---
>>>
>>> Another idea is to not do instantiation when we're checking constraints. 
>>> But I need to think more about this.
>>
>> I don't know of the 'another idea'?  We have to do instantiation before 
>> checking, and if we do it too early, we aren't doing the deferred 
>> instantiation.  And the problem is that the RawCompletionToken uses a 
>> concept to refer to 'itself'.  However, this version of 'itself' isn't 
>> valid, since the 'depth' is wrong once it tries to instantiate relative to 
>> the 'top level'.  However, this IS happening during instantiation?
>>
>> My latest thought is that perhaps the "IsEvaluatingAConstraint" should NOT 
>> happen at the Sema level (but at the instantiator level), since it ends up 
>> catching things it shouldn't?  I tried it and have a handful of failures of 
>> trying to check uninstantiated constraints, but I've not dug completely into 
>> it.
>
> Yeah, we have to do instantiation before checking. My point is that it looks 
> like we're doing **another** instantiation when we check the concepts. And my 
> point is that if it we should avoid the second instantiation.

Hmm... yeah, I think we actually want to skip the FIRST instantiation?  I think 
the work I did above in Sema for `IsEvaluatingAConstraint` was too greedy, it 
ends up instantiating constraints on the 'while we are there' type things, 
rather than the things being currently checked.  I found that if I can make it 
a state of the instantiators themselves, it seems to work, at least for your 
example.  I've got it down to 1 'lit' test failure, but have been looking at 
the other problem first (below).

The Github-Issue crash IS a regression from this patch, and I've minimized it 
sufficiently.  I believe I have a hold on how to fix it, I just have to do so 
:)  If I make any further progress, I'll clean this up and put it up here, even 
if it DOES have the lit test failure.


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

https://reviews.llvm.org/D126907

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


Re: [PATCH] D127863: [clang] Dont print implicit forrange initializer

2022-06-17 Thread Kadir Çetinkaya via cfe-commits
thanks for the revert, you beat me to it.

On Fri, Jun 17, 2022 at 3:07 PM Nico Weber via Phabricator <
revi...@reviews.llvm.org> wrote:

> thakis added a comment.
>
> Before landing changes, please:
>
> - Run tests
> - Look at the result from the presubmit checks
>
> After landing changes, please watch your favorite bot cycle green with it,
> and pay attention for buildbot email for a while.
>
>
> Repository:
>   rG LLVM Github Monorepo
>
> CHANGES SINCE LAST ACTION
>   https://reviews.llvm.org/D127863/new/
>
> https://reviews.llvm.org/D127863
>
>
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D127873: [clang-format] Fix misplacemnt of `*` in declaration of pointer to struct

2022-06-17 Thread Jack Huang via Phabricator via cfe-commits
jackhong12 updated this revision to Diff 437868.
jackhong12 edited the summary of this revision.
jackhong12 added a comment.

- Add annotator test
- Add formatting test
- Handle reference cases by `PrevToken->MatchingParen`


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

https://reviews.llvm.org/D127873

Files:
  clang/lib/Format/TokenAnnotator.cpp
  clang/unittests/Format/FormatTest.cpp
  clang/unittests/Format/TokenAnnotatorTest.cpp


Index: clang/unittests/Format/TokenAnnotatorTest.cpp
===
--- clang/unittests/Format/TokenAnnotatorTest.cpp
+++ clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -85,6 +85,17 @@
   Tokens = annotate("case &x:");
   EXPECT_EQ(Tokens.size(), 5u) << Tokens;
   EXPECT_TOKEN(Tokens[1], tok::amp, TT_UnaryOperator);
+
+  Tokens = annotate("struct {\n"
+"  int element;\n"
+"} *ptr;");
+  EXPECT_EQ(Tokens.size(), 10u) << Tokens;
+  EXPECT_TOKEN(Tokens[6], tok::star, TT_PointerOrReference);
+  Tokens = annotate("struct {\n"
+"  int element;\n"
+"} &&ptr = {};");
+  EXPECT_EQ(Tokens.size(), 13u) << Tokens;
+  EXPECT_TOKEN(Tokens[6], tok::ampamp, TT_PointerOrReference);
 }
 
 TEST_F(TokenAnnotatorTest, UnderstandsUsesOfPlusAndMinus) {
Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -10431,6 +10431,13 @@
   "void F();",
   getGoogleStyleWithColumns(68));
 
+  verifyFormat("struct {\n"
+   "  int element;\n"
+   "} *ptr;");
+  verifyFormat("struct {\n"
+   "  int element;\n"
+   "} &&ptr = {};");
+
   verifyIndependentOfContext("MACRO(int *i);");
   verifyIndependentOfContext("MACRO(auto *a);");
   verifyIndependentOfContext("MACRO(const A *a);");
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -2306,10 +2306,14 @@
 
 if (PrevToken->Tok.isLiteral() ||
 PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::kw_true,
-   tok::kw_false, tok::r_brace)) {
+   tok::kw_false)) {
   return TT_BinaryOperator;
 }
 
+if (PrevToken->is(tok::r_brace) && Tok.isOneOf(tok::amp, tok::ampamp) &&
+PrevToken->MatchingParen && PrevToken->MatchingParen->is(TT_Unknown))
+  return TT_BinaryOperator;
+
 const FormatToken *NextNonParen = NextToken;
 while (NextNonParen && NextNonParen->is(tok::l_paren))
   NextNonParen = NextNonParen->getNextNonComment();


Index: clang/unittests/Format/TokenAnnotatorTest.cpp
===
--- clang/unittests/Format/TokenAnnotatorTest.cpp
+++ clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -85,6 +85,17 @@
   Tokens = annotate("case &x:");
   EXPECT_EQ(Tokens.size(), 5u) << Tokens;
   EXPECT_TOKEN(Tokens[1], tok::amp, TT_UnaryOperator);
+
+  Tokens = annotate("struct {\n"
+"  int element;\n"
+"} *ptr;");
+  EXPECT_EQ(Tokens.size(), 10u) << Tokens;
+  EXPECT_TOKEN(Tokens[6], tok::star, TT_PointerOrReference);
+  Tokens = annotate("struct {\n"
+"  int element;\n"
+"} &&ptr = {};");
+  EXPECT_EQ(Tokens.size(), 13u) << Tokens;
+  EXPECT_TOKEN(Tokens[6], tok::ampamp, TT_PointerOrReference);
 }
 
 TEST_F(TokenAnnotatorTest, UnderstandsUsesOfPlusAndMinus) {
Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -10431,6 +10431,13 @@
   "void F();",
   getGoogleStyleWithColumns(68));
 
+  verifyFormat("struct {\n"
+   "  int element;\n"
+   "} *ptr;");
+  verifyFormat("struct {\n"
+   "  int element;\n"
+   "} &&ptr = {};");
+
   verifyIndependentOfContext("MACRO(int *i);");
   verifyIndependentOfContext("MACRO(auto *a);");
   verifyIndependentOfContext("MACRO(const A *a);");
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -2306,10 +2306,14 @@
 
 if (PrevToken->Tok.isLiteral() ||
 PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::kw_true,
-   tok::kw_false, tok::r_brace)) {
+   tok::kw_false)) {
   return TT_BinaryOperator;
 }
 
+if (PrevToken->is(tok::r_brace) && Tok.isOneOf(tok::amp, tok::ampamp) &&
+PrevToken->MatchingParen && PrevToken->MatchingParen->is(TT_Unknown))
+  return TT_BinaryOperator;
+
 const FormatToken *NextNo

[PATCH] D126194: [Concepts] Implement overload resolution for destructors (P0848)

2022-06-17 Thread Erich Keane via Phabricator via cfe-commits
erichkeane accepted this revision.
erichkeane added inline comments.
This revision is now accepted and ready to land.



Comment at: clang/include/clang/AST/DeclCXX.h:1430
+  /// out of which one will be selected at the end.
+  /// This is called separately from addedMember because it has to be deferred
+  /// to the completion of the class.

royjacobson wrote:
> erichkeane wrote:
> > @aaron.ballman  is messing around with addedMember recently... I wonder if 
> > there are OTHER decisions that need to be updated/moved here?
> Do you know what papers/DRs he's working on? It seemed like most constexpr 
> stuff is done per-function and not per-class.
> 
> I don't think there's something else that needs to change but it's definitely 
> possible I missed something.. I went through addedMember and tried to remove 
> everything destructor related basically.
> 
> 
He's working on DR647, which does a lot of work with special member 
functions/constexpr/consteval constructors.

That said, I believe he said it isn't a problem, they are related, but not 
conflicting in a way that he had.




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126194

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


[PATCH] D128012: [HLSL] Add ExternalSemaSource & vector alias

2022-06-17 Thread Chris Bieneman via Phabricator via cfe-commits
beanz added a comment.

For just the type alias, adding it during parsing would probably work. Where 
things get more complicated is we have a whole mess of other data types that 
we’ll need to add too eventually. One of the advantages of using an external 
sema source is that we can create incomplete records during initialization, and 
complete them when the sema source gets the callback from lookup. That gives us 
cheap and efficient lazy-initialization of our buffer types which (in DXC) has 
a huge impact on compile time.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128012

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


[PATCH] D128048: Add a new clang option "-ftime-trace-path"

2022-06-17 Thread Whitney Tsang via Phabricator via cfe-commits
Whitney added a comment.

Can you please add some test cases?




Comment at: clang/tools/driver/cc1_main.cpp:257
   if (llvm::timeTraceProfilerEnabled()) {
-SmallString<128> Path(Clang->getFrontendOpts().OutputFile);
-llvm::sys::path::replace_extension(Path, "json");
+SmallString<128> Path(Clang->getFrontendOpts().TimeTracePath);
+
Path.append(llvm::sys::path::filename(Clang->getFrontendOpts().OutputFile));

What happens when TimeTracePath is not given? Ideally the originally behavior 
is not changed. 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128048

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


[PATCH] D126194: [Concepts] Implement overload resolution for destructors (P0848)

2022-06-17 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/include/clang/AST/DeclCXX.h:1430
+  /// out of which one will be selected at the end.
+  /// This is called separately from addedMember because it has to be deferred
+  /// to the completion of the class.

erichkeane wrote:
> royjacobson wrote:
> > erichkeane wrote:
> > > @aaron.ballman  is messing around with addedMember recently... I wonder 
> > > if there are OTHER decisions that need to be updated/moved here?
> > Do you know what papers/DRs he's working on? It seemed like most constexpr 
> > stuff is done per-function and not per-class.
> > 
> > I don't think there's something else that needs to change but it's 
> > definitely possible I missed something.. I went through addedMember and 
> > tried to remove everything destructor related basically.
> > 
> > 
> He's working on DR647, which does a lot of work with special member 
> functions/constexpr/consteval constructors.
> 
> That said, I believe he said it isn't a problem, they are related, but not 
> conflicting in a way that he had.
> 
> 
I don't see anything here that should conflict with what I'm working on (this 
is mostly about destructors and I've not started touching those yet). I'm 
working specifically on implementing this bit: 
http://eel.is/c++draft/dcl.constexpr#7


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126194

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


[PATCH] D127655: [AArch64] Define __FP_FAST_FMA[F]

2022-06-17 Thread Paul Walker via Phabricator via cfe-commits
paulwalker-arm added inline comments.



Comment at: clang/test/Preprocessor/aarch64-target-features.c:59-60
 // CHECK-NOT: __ARM_FEATURE_SVE_BITS 2048
+// CHECK: __FP_FAST_FMA 1
+// CHECK: __FP_FAST_FMAF 1
 

I don't think we need this change given `init-aarch64.c` provides enough 
coverage.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D127655

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


[PATCH] D127873: [clang-format] Fix misplacemnt of `*` in declaration of pointer to struct

2022-06-17 Thread Jack Huang via Phabricator via cfe-commits
jackhong12 updated this revision to Diff 437881.
jackhong12 added a comment.

Add Left/Middle/Right alignment test cases.


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

https://reviews.llvm.org/D127873

Files:
  clang/lib/Format/TokenAnnotator.cpp
  clang/unittests/Format/FormatTest.cpp
  clang/unittests/Format/TokenAnnotatorTest.cpp


Index: clang/unittests/Format/TokenAnnotatorTest.cpp
===
--- clang/unittests/Format/TokenAnnotatorTest.cpp
+++ clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -85,6 +85,17 @@
   Tokens = annotate("case &x:");
   EXPECT_EQ(Tokens.size(), 5u) << Tokens;
   EXPECT_TOKEN(Tokens[1], tok::amp, TT_UnaryOperator);
+
+  Tokens = annotate("struct {\n"
+"  int element;\n"
+"} *ptr;");
+  EXPECT_EQ(Tokens.size(), 10u) << Tokens;
+  EXPECT_TOKEN(Tokens[6], tok::star, TT_PointerOrReference);
+  Tokens = annotate("struct {\n"
+"  int element;\n"
+"} &&ptr = {};");
+  EXPECT_EQ(Tokens.size(), 13u) << Tokens;
+  EXPECT_TOKEN(Tokens[6], tok::ampamp, TT_PointerOrReference);
 }
 
 TEST_F(TokenAnnotatorTest, UnderstandsUsesOfPlusAndMinus) {
Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -10431,6 +10431,37 @@
   "void F();",
   getGoogleStyleWithColumns(68));
 
+  FormatStyle Style = getLLVMStyle();
+  Style.PointerAlignment = FormatStyle::PAS_Left;
+  verifyFormat("struct {\n"
+   "  int element;\n"
+   "}* ptr;",
+   Style);
+  verifyFormat("struct {\n"
+   "  int element;\n"
+   "}&& ptr = {};",
+   Style);
+
+  Style.PointerAlignment = FormatStyle::PAS_Middle;
+  verifyFormat("struct {\n"
+   "  int element;\n"
+   "} * ptr;",
+   Style);
+  verifyFormat("struct {\n"
+   "  int element;\n"
+   "} && ptr = {};",
+   Style);
+
+  Style.PointerAlignment = FormatStyle::PAS_Right;
+  verifyFormat("struct {\n"
+   "  int element;\n"
+   "} *ptr;",
+   Style);
+  verifyFormat("struct {\n"
+   "  int element;\n"
+   "} &&ptr = {};",
+   Style);
+
   verifyIndependentOfContext("MACRO(int *i);");
   verifyIndependentOfContext("MACRO(auto *a);");
   verifyIndependentOfContext("MACRO(const A *a);");
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -2306,10 +2306,14 @@
 
 if (PrevToken->Tok.isLiteral() ||
 PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::kw_true,
-   tok::kw_false, tok::r_brace)) {
+   tok::kw_false)) {
   return TT_BinaryOperator;
 }
 
+if (PrevToken->is(tok::r_brace) && Tok.isOneOf(tok::amp, tok::ampamp) &&
+PrevToken->MatchingParen && PrevToken->MatchingParen->is(TT_Unknown))
+  return TT_BinaryOperator;
+
 const FormatToken *NextNonParen = NextToken;
 while (NextNonParen && NextNonParen->is(tok::l_paren))
   NextNonParen = NextNonParen->getNextNonComment();


Index: clang/unittests/Format/TokenAnnotatorTest.cpp
===
--- clang/unittests/Format/TokenAnnotatorTest.cpp
+++ clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -85,6 +85,17 @@
   Tokens = annotate("case &x:");
   EXPECT_EQ(Tokens.size(), 5u) << Tokens;
   EXPECT_TOKEN(Tokens[1], tok::amp, TT_UnaryOperator);
+
+  Tokens = annotate("struct {\n"
+"  int element;\n"
+"} *ptr;");
+  EXPECT_EQ(Tokens.size(), 10u) << Tokens;
+  EXPECT_TOKEN(Tokens[6], tok::star, TT_PointerOrReference);
+  Tokens = annotate("struct {\n"
+"  int element;\n"
+"} &&ptr = {};");
+  EXPECT_EQ(Tokens.size(), 13u) << Tokens;
+  EXPECT_TOKEN(Tokens[6], tok::ampamp, TT_PointerOrReference);
 }
 
 TEST_F(TokenAnnotatorTest, UnderstandsUsesOfPlusAndMinus) {
Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -10431,6 +10431,37 @@
   "void F();",
   getGoogleStyleWithColumns(68));
 
+  FormatStyle Style = getLLVMStyle();
+  Style.PointerAlignment = FormatStyle::PAS_Left;
+  verifyFormat("struct {\n"
+   "  int element;\n"
+   "}* ptr;",
+   Style);
+  verifyFormat("struct {\n"
+   "  int element;\n"
+   "}&& ptr = {};",
+   Style);
+
+  Style.PointerAlignment = FormatStyle::PAS_Middle;
+  verifyFormat("struct {\n"
+ 

[PATCH] D128049: [mlir] move SCF headers to SCF/{IR,Transforms} respectively

2022-06-17 Thread Jacques Pienaar via Phabricator via cfe-commits
jpienaar accepted this revision.
jpienaar added a comment.
This revision is now accepted and ready to land.

More consistency is good and update for downstream users mechanical, so LGTM




Comment at: mlir/include/mlir/Dialect/SCF/Transforms/Transforms.h:13
 
-#ifndef MLIR_DIALECT_SCF_TRANSFORMS_H_
-#define MLIR_DIALECT_SCF_TRANSFORMS_H_
+#ifndef MLIR_DIALECT_SCF_TRANSFORMS_TRANSFORMS_H_
+#define MLIR_DIALECT_SCF_TRANSFORMS_TRANSFORMS_H_

Transforms transforms feels a bit strange, for many others I believe this would 
have been passes file (which is also not that accurate, patterns and passes 
would be more, but most others it is just passes and convenient shorthand). 
Keeping the move mostly mechanical is good though 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128049

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


[PATCH] D128049: [mlir] move SCF headers to SCF/{IR,Transforms} respectively

2022-06-17 Thread Alex Zinenko via Phabricator via cfe-commits
ftynse marked an inline comment as done.
ftynse added inline comments.



Comment at: mlir/include/mlir/Dialect/SCF/Transforms/Transforms.h:13
 
-#ifndef MLIR_DIALECT_SCF_TRANSFORMS_H_
-#define MLIR_DIALECT_SCF_TRANSFORMS_H_
+#ifndef MLIR_DIALECT_SCF_TRANSFORMS_TRANSFORMS_H_
+#define MLIR_DIALECT_SCF_TRANSFORMS_TRANSFORMS_H_

jpienaar wrote:
> Transforms transforms feels a bit strange, for many others I believe this 
> would have been passes file (which is also not that accurate, patterns and 
> passes would be more, but most others it is just passes and convenient 
> shorthand). Keeping the move mostly mechanical is good though 
There's already Transforms/Passes.h and Transforms/Patterns.h, these things are 
more like standalone transform functions. Maybe Transforms/Utils.h?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128049

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


[PATCH] D128056: [clang][dataflow] Singleton pointer values for null pointers.

2022-06-17 Thread weiyi via Phabricator via cfe-commits
wyt created this revision.
Herald added subscribers: martong, tschuett, xazax.hun.
Herald added a project: All.
wyt requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

When a `nullptr` is assigned to a pointer variable, it is wrapped in a 
`ImplicitCastExpr` with cast kind `CK_NullTo(Member)Pointer`. This patch 
assigns singleton pointer values representing null to these expressions.

For each pointee type, a singleton null `PointerValue` is created and stored in 
the `NullPointerVals` map of the `DataflowAnalysisContext` class. The pointee 
type is retrieved from the implicit cast expression, and used to initialise the 
`PointeeLoc` field of the `PointerValue`. The `PointeeLoc` created is not 
mapped to any `Value`, reflecting the absence of value indicated by null 
pointers.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D128056

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

Index: clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
@@ -2214,6 +2214,93 @@
   });
 }
 
+TEST_F(TransferTest, NullToPointerCast) {
+  std::string Code = R"(
+struct Baz {};
+void target() {
+  int *FooX = nullptr;
+  int *FooY = nullptr;
+  bool **Bar = nullptr;
+  Baz *Baz = nullptr;
+  // [[p]]
+}
+  )";
+  runDataflow(Code,
+  [](llvm::ArrayRef<
+ std::pair>>
+ Results,
+ ASTContext &ASTCtx) {
+ASSERT_THAT(Results, ElementsAre(Pair("p", _)));
+const Environment &Env = Results[0].second.Env;
+
+const ValueDecl *FooXDecl = findValueDecl(ASTCtx, "FooX");
+ASSERT_THAT(FooXDecl, NotNull());
+
+const ValueDecl *FooYDecl = findValueDecl(ASTCtx, "FooY");
+ASSERT_THAT(FooYDecl, NotNull());
+
+const ValueDecl *BarDecl = findValueDecl(ASTCtx, "Bar");
+ASSERT_THAT(BarDecl, NotNull());
+
+const ValueDecl *BazDecl = findValueDecl(ASTCtx, "Baz");
+ASSERT_THAT(BazDecl, NotNull());
+
+const auto *FooXVal =
+cast(Env.getValue(*FooXDecl, SkipPast::None));
+const auto *FooYVal =
+cast(Env.getValue(*FooYDecl, SkipPast::None));
+const auto *BarVal =
+cast(Env.getValue(*BarDecl, SkipPast::None));
+const auto *BazVal =
+cast(Env.getValue(*BazDecl, SkipPast::None));
+
+EXPECT_EQ(FooXVal, FooYVal);
+EXPECT_NE(FooXVal, BarVal);
+EXPECT_NE(FooXVal, BazVal);
+EXPECT_NE(BarVal, BazVal);
+
+const StorageLocation &FooPointeeLoc = FooXVal->getPointeeLoc();
+EXPECT_TRUE(isa(FooPointeeLoc));
+EXPECT_THAT(Env.getValue(FooPointeeLoc), IsNull());
+
+const StorageLocation &BarPointeeLoc = BarVal->getPointeeLoc();
+EXPECT_TRUE(isa(BarPointeeLoc));
+EXPECT_THAT(Env.getValue(BarPointeeLoc), IsNull());
+
+const StorageLocation &BazPointeeLoc = BazVal->getPointeeLoc();
+EXPECT_TRUE(isa(BazPointeeLoc));
+EXPECT_THAT(Env.getValue(BazPointeeLoc), IsNull());
+  });
+}
+
+TEST_F(TransferTest, NullToMemberPointerCast) {
+  std::string Code = R"(
+struct Foo {};
+void target(Foo *Foo) {
+  int Foo::*MemberPointer = nullptr;
+  // [[p]]
+}
+  )";
+  runDataflow(
+  Code, [](llvm::ArrayRef<
+   std::pair>>
+   Results,
+   ASTContext &ASTCtx) {
+ASSERT_THAT(Results, ElementsAre(Pair("p", _)));
+const Environment &Env = Results[0].second.Env;
+
+const ValueDecl *MemberPointerDecl =
+findValueDecl(ASTCtx, "MemberPointer");
+ASSERT_THAT(MemberPointerDecl, NotNull());
+
+const auto *MemberPointerVal = cast(
+Env.getValue(*MemberPointerDecl, SkipPast::None));
+
+const StorageLocation &MemberLoc = MemberPointerVal->getPointeeLoc();
+EXPECT_THAT(Env.getValue(MemberLoc), IsNull());
+  });
+}
+
 TEST_F(TransferTest, AddrOfValue) {
   std::string Code = R"(
 void target() {
Index: clang/lib/Analysis/FlowSensitive/Transfer.cpp
===
--- clang/lib/Analysis/FlowSensitive/Transfer.cpp
+++ clang/lib/Analysis/FlowSensitive/Transfer.cp

[PATCH] D127544: Add no_sanitize('hwaddress') (and 'memtag', but that's a no-op).

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

LGTM! The debian failures look like precommit CI is in a broken state again, 
but have nothing to do with your patch.




Comment at: clang/lib/Sema/SemaDeclAttr.cpp:8849
 break;
-  
   // HLSL attributes:

hctim wrote:
> aaron.ballman wrote:
> > hctim wrote:
> > > aaron.ballman wrote:
> > > > Spurious whitespace change?
> > > unfortunately there's no way in my editor to trim trailing whitespace 
> > > only on changed lines :(, so i end up fixing things like this drive-by.
> > > 
> > > let me know if you feel very strongly about this diff and I can kill it, 
> > > but I personally think the drive-by-fix isn't a huge problem and the 
> > > alternative of whitespace-fix-only commit seems a bit overkill
> > Personally, I don't feel very strongly because the chances of the 
> > whitespace being someone's entrypoint to git-blame is pretty minimal 
> > (especially given there's only one change here). However, we typically 
> > still ask for formatting changes to be separated out 
> > (https://llvm.org/docs/DeveloperPolicy.html#obtaining-commit-access #2) 
> > rather than lumped in with functional changes so reviewers will ask for 
> > these sort of changes to be backed out, so this may crop up repeatedly if 
> > your editor doesn't give you the options you need.
> Fixed in ee28837a1fbd574dbec14b9f09cb4effab6a492a.
Thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D127544

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


[PATCH] D128059: [Clang] Add a warning on invalid UTF-8 in comments.

2022-06-17 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin created this revision.
Herald added a subscriber: hiraditya.
Herald added a project: All.
cor3ntin requested review of this revision.
Herald added projects: clang, LLVM.
Herald added subscribers: llvm-commits, cfe-commits.

Introduce an off-by default `-Winvalid-utf8` warning
that detects invalid UTF-8 code units sequences in comments.

Invalid UTF-8 in other places is already diagnosed,
as that cannot appear in identifiers and other grammar constructs.

The warning is off by default as its likely to be somewhat disruptive
otherwise.

This warning allows clang to conform to the yet-to be approved WG21
"P2295R5 Support for UTF-8 as a portable source file encoding"
paper.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D128059

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/DiagnosticLexKinds.td
  clang/lib/Lex/Lexer.cpp
  clang/test/Lexer/comment-invalid-utf8.c
  llvm/include/llvm/Support/ConvertUTF.h
  llvm/lib/Support/ConvertUTF.cpp

Index: llvm/lib/Support/ConvertUTF.cpp
===
--- llvm/lib/Support/ConvertUTF.cpp
+++ llvm/lib/Support/ConvertUTF.cpp
@@ -417,6 +417,18 @@
 return isLegalUTF8(source, length);
 }
 
+/*
+ * Exported function to return the size of the first utf-8 code unit sequence,
+ * Or 0 if the sequence is not valid;
+ */
+unsigned getUTF8SequenceSize(const UTF8 *source, const UTF8 *sourceEnd) {
+  int length = trailingBytesForUTF8[*source] + 1;
+  if (length > sourceEnd - source) {
+return 0;
+  }
+  return isLegalUTF8(source, length) ? length : 0;
+}
+
 /* - */
 
 static unsigned
Index: llvm/include/llvm/Support/ConvertUTF.h
===
--- llvm/include/llvm/Support/ConvertUTF.h
+++ llvm/include/llvm/Support/ConvertUTF.h
@@ -181,6 +181,8 @@
 
 Boolean isLegalUTF8String(const UTF8 **source, const UTF8 *sourceEnd);
 
+unsigned getUTF8SequenceSize(const UTF8 *source, const UTF8 *sourceEnd);
+
 unsigned getNumBytesForUTF8(UTF8 firstByte);
 
 /*/
Index: clang/lib/Lex/Lexer.cpp
===
--- clang/lib/Lex/Lexer.cpp
+++ clang/lib/Lex/Lexer.cpp
@@ -2391,13 +2391,40 @@
   //
   // This loop terminates with CurPtr pointing at the newline (or end of buffer)
   // character that ends the line comment.
+
+  bool WarnOnInvalidUtf8 =
+  !isLexingRawMode() &&
+  !PP->getDiagnostics().isIgnored(diag::warn_invalid_utf8_in_comment,
+  getSourceLocation(CurPtr));
+  bool UnicodeDecodeFailed = false;
+
   char C;
   while (true) {
 C = *CurPtr;
 // Skip over characters in the fast loop.
-while (C != 0 &&// Potentially EOF.
-   C != '\n' && C != '\r')  // Newline or DOS-style newline.
+// Warn on invalid UTF-8 if the corresponding warning is enabled, emitting a
+// diagnostic only once per sequence that cannot be decoded.
+while ((!WarnOnInvalidUtf8 || isASCII(C)) && C != 0 && // Potentially EOF.
+   C != '\n' && C != '\r') { // Newline or DOS-style newline.
   C = *++CurPtr;
+  UnicodeDecodeFailed = false;
+}
+
+if (WarnOnInvalidUtf8 && !isASCII(C)) {
+  unsigned Length = llvm::getUTF8SequenceSize(
+  (const llvm::UTF8 *)CurPtr, (const llvm::UTF8 *)BufferEnd);
+  if (Length == 0) {
+if (!UnicodeDecodeFailed) {
+  Diag(CurPtr, diag::warn_invalid_utf8_in_comment);
+}
+UnicodeDecodeFailed = true;
+++CurPtr;
+  } else {
+UnicodeDecodeFailed = false;
+CurPtr += Length;
+  }
+  continue;
+}
 
 const char *NextLine = CurPtr;
 if (C != 0) {
@@ -2664,10 +2691,18 @@
   if (C == '/')
 C = *CurPtr++;
 
+  bool WarnOnInvalidUtf8 =
+  !isLexingRawMode() &&
+  !PP->getDiagnostics().isIgnored(diag::warn_invalid_utf8_in_comment,
+  getSourceLocation(CurPtr));
+  bool UnicodeDecodeFailed = false;
+
   while (true) {
 // Skip over all non-interesting characters until we find end of buffer or a
 // (probably ending) '/' character.
-if (CurPtr + 24 < BufferEnd &&
+// When diagnosing invalid UTF-8 sequences we always skip the fast
+// vectorized path.
+if (!WarnOnInvalidUtf8 && CurPtr + 24 < BufferEnd &&
 // If there is a code-completion point avoid the fast scan because it
 // doesn't check for '\0'.
 !(PP && PP->getCodeCompletionFileLoc() == FileLoc)) {
@@ -2714,9 +2749,28 @@
   C = *CurPtr++;
 }
 
-// Loop to scan the remainder.
-while (C != '/' && C != '\0')
-  C = *CurPtr++;
+// Loop to scan the remainder, warning on invalid UTF-8
+// if the corresponding warning is enabled, emitting a diagnostic only once
+// per sequence that can

[PATCH] D128060: [clang][dataflow] Extend flow condition in the body of a for loop

2022-06-17 Thread Stanislav Gatev via Phabricator via cfe-commits
sgatev created this revision.
sgatev added reviewers: ymandel, xazax.hun, gribozavr2.
Herald added subscribers: martong, tschuett, rnkovacs.
Herald added a project: All.
sgatev requested review of this revision.
Herald added a project: clang.

Extend flow condition in the body of a for loop.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D128060

Files:
  clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
  clang/unittests/Analysis/FlowSensitive/TransferTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
@@ -3557,4 +3557,87 @@
   });
 }
 
+TEST_F(TransferTest, BranchesExtendFlowCondition) {
+  std::string IfBranchCode = R"(
+void target(bool Foo) {
+  if (Foo) {
+(void)0;
+// [[if_branch_0]]
+  } else {
+(void)0;
+// [[if_branch_1]]
+  }
+}
+  )";
+  runDataflow(IfBranchCode,
+  [](llvm::ArrayRef<
+ std::pair>>
+ Results,
+ ASTContext &ASTCtx) {
+ASSERT_THAT(Results, ElementsAre(Pair("if_branch_1", _),
+ Pair("if_branch_0", _)));
+const Environment &Env0 = Results[1].second.Env;
+const Environment &Env1 = Results[0].second.Env;
+
+const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo");
+ASSERT_THAT(FooDecl, NotNull());
+
+BoolValue &FooVal0 =
+*cast(Env0.getValue(*FooDecl, SkipPast::None));
+EXPECT_TRUE(Env0.flowConditionImplies(FooVal0));
+
+BoolValue &FooVal1 =
+*cast(Env1.getValue(*FooDecl, SkipPast::None));
+EXPECT_TRUE(Env1.flowConditionImplies(Env1.makeNot(FooVal1)));
+  });
+
+  std::string WhileBranchCode = R"(
+void target(bool Foo) {
+  while (Foo) {
+(void)0;
+// [[while_branch]]
+  }
+}
+  )";
+  runDataflow(WhileBranchCode,
+  [](llvm::ArrayRef<
+ std::pair>>
+ Results,
+ ASTContext &ASTCtx) {
+ASSERT_THAT(Results, ElementsAre(Pair("while_branch", _)));
+const Environment &Env = Results[0].second.Env;
+
+const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo");
+ASSERT_THAT(FooDecl, NotNull());
+
+BoolValue &FooVal =
+*cast(Env.getValue(*FooDecl, SkipPast::None));
+EXPECT_TRUE(Env.flowConditionImplies(FooVal));
+  });
+
+  std::string ForBranchCode = R"(
+void target(bool Foo) {
+  for (; Foo;) {
+(void)0;
+// [[for_branch]]
+  }
+}
+  )";
+  runDataflow(ForBranchCode,
+  [](llvm::ArrayRef<
+ std::pair>>
+ Results,
+ ASTContext &ASTCtx) {
+ASSERT_THAT(Results, ElementsAre(Pair("for_branch", _)));
+const Environment &Env = Results[0].second.Env;
+
+const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo");
+ASSERT_THAT(FooDecl, NotNull());
+
+BoolValue &FooVal =
+*cast(Env.getValue(*FooDecl, SkipPast::None));
+EXPECT_TRUE(Env.flowConditionImplies(FooVal));
+  });
+}
+
 } // namespace
Index: clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
===
--- clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
+++ clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
@@ -89,6 +89,12 @@
 extendFlowCondition(*Cond);
   }
 
+  void VisitForStmt(const ForStmt *S) {
+auto *Cond = S->getCond();
+assert(Cond != nullptr);
+extendFlowCondition(*Cond);
+  }
+
   void VisitBinaryOperator(const BinaryOperator *S) {
 assert(S->getOpcode() == BO_LAnd || S->getOpcode() == BO_LOr);
 auto *LHS = S->getLHS();
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D128060: [clang][dataflow] Extend flow condition in the body of a for loop

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



Comment at: clang/unittests/Analysis/FlowSensitive/TransferTest.cpp:3577-3580
+ASSERT_THAT(Results, ElementsAre(Pair("if_branch_1", _),
+ Pair("if_branch_0", _)));
+const Environment &Env0 = Results[1].second.Env;
+const Environment &Env1 = Results[0].second.Env;




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128060

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


[PATCH] D128012: [HLSL] Add ExternalSemaSource & vector alias

2022-06-17 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia added a comment.

In D128012#3591828 , @beanz wrote:

> For just the type alias, adding it during parsing would probably work. Where 
> things get more complicated is we have a whole mess of other data types that 
> we’ll need to add too eventually. One of the advantages of using an external 
> sema source is that we can create incomplete records during initialization, 
> and complete them when the sema source gets the callback from lookup. That 
> gives us cheap and efficient lazy-initialization of our buffer types which 
> (in DXC) has a huge impact on compile time.

aha, are you having a lot of these types then? Ok that sounds similar problem 
to OpenCL builtin functions as we had to go away from a simple header include 
due to long parsing time.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128012

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


[clang] 1a02c96 - Revert "Revert "[clang] Dont print implicit forrange initializer""

2022-06-17 Thread Kadir Cetinkaya via cfe-commits

Author: Kadir Cetinkaya
Date: 2022-06-17T16:51:16+02:00
New Revision: 1a02c963e338100a3000734b91f5956da9b8c95e

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

LOG: Revert "Revert "[clang] Dont print implicit forrange initializer""

This reverts commit 7aac15d5df6cfa03b802e055b63227a95fa1734e.

Only updates the tests, as these statements are still part of the CFG
and its just the pretty printer policy that changes. Hopefully this
shouldn't affect any analysis.

Added: 


Modified: 
clang/lib/AST/DeclPrinter.cpp
clang/test/Analysis/auto-obj-dtors-cfg-output.cpp
clang/test/Analysis/scopes-cfg-output.cpp
clang/unittests/AST/DeclPrinterTest.cpp

Removed: 




diff  --git a/clang/lib/AST/DeclPrinter.cpp b/clang/lib/AST/DeclPrinter.cpp
index faafe307f03cf..c6a392c9c01b5 100644
--- a/clang/lib/AST/DeclPrinter.cpp
+++ b/clang/lib/AST/DeclPrinter.cpp
@@ -895,12 +895,15 @@ void DeclPrinter::VisitVarDecl(VarDecl *D) {
   Expr *Init = D->getInit();
   if (!Policy.SuppressInitializers && Init) {
 bool ImplicitInit = false;
-if (CXXConstructExpr *Construct =
-dyn_cast(Init->IgnoreImplicit())) {
+if (D->isCXXForRangeDecl()) {
+  // FIXME: We should print the range expression instead.
+  ImplicitInit = true;
+} else if (CXXConstructExpr *Construct =
+   dyn_cast(Init->IgnoreImplicit())) {
   if (D->getInitStyle() == VarDecl::CallInit &&
   !Construct->isListInitialization()) {
 ImplicitInit = Construct->getNumArgs() == 0 ||
-  Construct->getArg(0)->isDefaultArgument();
+   Construct->getArg(0)->isDefaultArgument();
   }
 }
 if (!ImplicitInit) {

diff  --git a/clang/test/Analysis/auto-obj-dtors-cfg-output.cpp 
b/clang/test/Analysis/auto-obj-dtors-cfg-output.cpp
index 82c86a95792a9..e5397f5678cb5 100644
--- a/clang/test/Analysis/auto-obj-dtors-cfg-output.cpp
+++ b/clang/test/Analysis/auto-obj-dtors-cfg-output.cpp
@@ -1098,7 +1098,7 @@ void test_for_implicit_scope() {
 // CHECK-NEXT:   2: [B3.1] (ImplicitCastExpr, LValueToRValue, int *)
 // CHECK-NEXT:   3: *[B3.2]
 // CHECK-NEXT:   4: [B3.3] (ImplicitCastExpr, LValueToRValue, int)
-// CHECK-NEXT:   5: int n = *__begin1;
+// CHECK-NEXT:   5: int n
 // WARNINGS-NEXT:   6:  (CXXConstructExpr, class A)
 // ANALYZER-NEXT:   6:  (CXXConstructExpr, [B3.7], class A)
 // CHECK-NEXT:   7: A c;

diff  --git a/clang/test/Analysis/scopes-cfg-output.cpp 
b/clang/test/Analysis/scopes-cfg-output.cpp
index c8212d51f6b24..ef2cac9538163 100644
--- a/clang/test/Analysis/scopes-cfg-output.cpp
+++ b/clang/test/Analysis/scopes-cfg-output.cpp
@@ -834,7 +834,7 @@ void test_for_compound_and_break() {
 // CHECK-NEXT:   2: __begin1
 // CHECK-NEXT:   3: [B4.2] (ImplicitCastExpr, LValueToRValue, class A *)
 // CHECK-NEXT:   4: *[B4.3]
-// CHECK-NEXT:   5: auto &i = *__begin1;
+// CHECK-NEXT:   5: auto &i
 // CHECK-NEXT:   6: operator=
 // CHECK-NEXT:   7: [B4.6] (ImplicitCastExpr, FunctionToPointerDecay, class A 
&(*)(const class A &)
 // CHECK-NEXT:   8: i

diff  --git a/clang/unittests/AST/DeclPrinterTest.cpp 
b/clang/unittests/AST/DeclPrinterTest.cpp
index c2d7d78738f96..11dca6ed68167 100644
--- a/clang/unittests/AST/DeclPrinterTest.cpp
+++ b/clang/unittests/AST/DeclPrinterTest.cpp
@@ -1426,4 +1426,7 @@ TEST(DeclPrinter, VarDeclWithInitializer) {
   ASSERT_TRUE(PrintedDeclCXX17Matches(
   "int a = 0x15;", namedDecl(hasName("a")).bind("id"), "int a = 0x15",
   [](PrintingPolicy &Policy) { Policy.ConstantsAsWritten = true; }));
+  ASSERT_TRUE(
+  PrintedDeclCXX17Matches("void foo() {int arr[42]; for(int a : arr);}",
+  namedDecl(hasName("a")).bind("id"), "int a"));
 }



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


[PATCH] D128012: [HLSL] Add ExternalSemaSource & vector alias

2022-06-17 Thread Chris Bieneman via Phabricator via cfe-commits
beanz added a comment.

In D128012#3592098 , @Anastasia wrote:

> aha, are you having a lot of these types then? Ok that sounds similar problem 
> to OpenCL builtin functions as we had to go away from a simple header include 
> due to long parsing time.

Very similar problem. We have a two-part problem where we both have enough of 
them that parsing a header would be too slow _and_ the HLSL language actually 
can't represent them. The later we're working to fix. My hope is that 
eventually we can write the HLSL libraries in HLSL and use a pre-compilation 
step (PCH or Module-style) to get past the performance issues.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128012

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


[PATCH] D127579: [clang][WIP] add option to keep types of ptr args for non-kernel functions in metadata

2022-06-17 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia added a comment.

Btw do we have any issue tracking this failure, I am having a feeling that the 
translation of special types might be related to 
https://github.com/llvm/llvm-project/issues/55121? I am not aware at which 
point libclc is expected to be linked for SPIR-V but if linking happens at 
SPIR-V binary level it is likely going to face the other problem I described 
here.

Either way we should track this problem and we probably need a solution ideally 
within a month or so, as we can't release clang-15 with broken SPIR-V 
support... potentially one solution is to enable pointer types just for SPIR-V 
but this is probably the least option we should consider.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D127579

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


[PATCH] D127351: clang: fix early substitution of alias templates

2022-06-17 Thread Matheus Izvekov via Phabricator via cfe-commits
mizvekov updated this revision to Diff 437905.
mizvekov added a comment.

rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D127351

Files:
  clang/include/clang/Sema/Template.h
  clang/lib/Sema/SemaTemplateInstantiate.cpp
  clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
  clang/test/AST/ast-dump-template-decls.cpp

Index: clang/test/AST/ast-dump-template-decls.cpp
===
--- clang/test/AST/ast-dump-template-decls.cpp
+++ clang/test/AST/ast-dump-template-decls.cpp
@@ -121,7 +121,7 @@
 // CHECK-NEXT: BuiltinType 0x{{[^ ]*}} 'void'
 // CHECK-NEXT: FunctionProtoType 0x{{[^ ]*}} 'void (int)' cdecl
 // CHECK-NEXT: SubstTemplateTypeParmType 0x{{[^ ]*}} 'void' sugar
-// CHECK-NEXT: TemplateTypeParmType 0x{{[^ ]*}} 'U' dependent depth 0 index 0
+// CHECK-NEXT: TemplateTypeParmType 0x{{[^ ]*}} 'U' dependent depth 1 index 0
 // CHECK-NEXT: TemplateTypeParm 0x{{[^ ]*}} 'U'
 // CHECK-NEXT: BuiltinType 0x{{[^ ]*}} 'void'
 // CHECK-NEXT: SubstTemplateTypeParmType 0x{{[^ ]*}} 'int' sugar
Index: clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
===
--- clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
+++ clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
@@ -1029,8 +1029,9 @@
   // will contain the instantiations of the template parameters.
   LocalInstantiationScope Scope(SemaRef);
 
-  TemplateParameterList *TempParams = D->getTemplateParameters();
-  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
+  auto EarlySubstitutionScope = TemplateArgs.getEarlySubstitutionRAII();
+  TemplateParameterList *InstParams =
+  SubstTemplateParams(D->getTemplateParameters());
   if (!InstParams)
 return nullptr;
 
@@ -2757,7 +2758,7 @@
 
   TemplateTypeParmDecl *Inst = TemplateTypeParmDecl::Create(
   SemaRef.Context, Owner, D->getBeginLoc(), D->getLocation(),
-  D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), D->getIndex(),
+  TemplateArgs.getNewDepth(D->getDepth()), D->getIndex(),
   D->getIdentifier(), D->wasDeclaredWithTypename(), D->isParameterPack(),
   D->hasTypeConstraint(), NumExpanded);
 
@@ -2910,14 +2911,14 @@
   if (IsExpandedParameterPack)
 Param = NonTypeTemplateParmDecl::Create(
 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
-D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
-D->getPosition(), D->getIdentifier(), T, DI, ExpandedParameterPackTypes,
+TemplateArgs.getNewDepth(D->getDepth()), D->getPosition(),
+D->getIdentifier(), T, DI, ExpandedParameterPackTypes,
 ExpandedParameterPackTypesAsWritten);
   else
 Param = NonTypeTemplateParmDecl::Create(
 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
-D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
-D->getPosition(), D->getIdentifier(), T, D->isParameterPack(), DI);
+TemplateArgs.getNewDepth(D->getDepth()), D->getPosition(),
+D->getIdentifier(), T, D->isParameterPack(), DI);
 
   if (AutoTypeLoc AutoLoc = DI->getTypeLoc().getContainedAutoTypeLoc())
 if (AutoLoc.isConstrained())
@@ -3051,13 +3052,13 @@
   if (IsExpandedParameterPack)
 Param = TemplateTemplateParmDecl::Create(
 SemaRef.Context, Owner, D->getLocation(),
-D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
-D->getPosition(), D->getIdentifier(), InstParams, ExpandedParams);
+TemplateArgs.getNewDepth(D->getDepth()), D->getPosition(),
+D->getIdentifier(), InstParams, ExpandedParams);
   else
 Param = TemplateTemplateParmDecl::Create(
 SemaRef.Context, Owner, D->getLocation(),
-D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
-D->getPosition(), D->isParameterPack(), D->getIdentifier(), InstParams);
+TemplateArgs.getNewDepth(D->getDepth()), D->getPosition(),
+D->isParameterPack(), D->getIdentifier(), InstParams);
   if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
 NestedNameSpecifierLoc QualifierLoc =
 D->getDefaultArgument().getTemplateQualifierLoc();
@@ -4021,6 +4022,7 @@
   if (Expr *E = L->getRequiresClause()) {
 EnterExpressionEvaluationContext ConstantEvaluated(
 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
+auto LateSubstitutionScope = TemplateArgs.getLateSubstitutionRAII();
 ExprResult Res = SemaRef.SubstExpr(E, TemplateArgs);
 if (Res.isInvalid() || !Res.isUsable()) {
   return nullptr;
Index: clang/lib/Sema/SemaTemplateInstantiate.cpp
===
--- clang/lib/Sema/SemaTemplateInstantiate.cpp
+++ clang/lib/Sema/SemaTemplateInstantiate.cpp
@@ -959,8 +959,12 @@
   this->Entity = Entity;
 }
 
-unsigned TransformTemplateDepth(unsigned Depth) {
-  return TemplateArgs

[PATCH] D127690: [NFC] clang/Parser: remove dead code

2022-06-17 Thread Matheus Izvekov via Phabricator via cfe-commits
mizvekov updated this revision to Diff 437906.
mizvekov added a comment.

rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D127690

Files:
  clang/lib/Parse/Parser.cpp


Index: clang/lib/Parse/Parser.cpp
===
--- clang/lib/Parse/Parser.cpp
+++ clang/lib/Parse/Parser.cpp
@@ -2056,36 +2056,6 @@
   return false;
 }
 
-// If this is a template-id, annotate with a template-id or type token.
-// FIXME: This appears to be dead code. We already have formed template-id
-// tokens when parsing the scope specifier; this can never form a new one.
-if (NextToken().is(tok::less)) {
-  TemplateTy Template;
-  UnqualifiedId TemplateName;
-  TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
-  bool MemberOfUnknownSpecialization;
-  if (TemplateNameKind TNK = Actions.isTemplateName(
-  getCurScope(), SS,
-  /*hasTemplateKeyword=*/false, TemplateName,
-  /*ObjectType=*/nullptr, /*EnteringContext*/false, Template,
-  MemberOfUnknownSpecialization)) {
-// Only annotate an undeclared template name as a template-id if the
-// following tokens have the form of a template argument list.
-if (TNK != TNK_Undeclared_template ||
-isTemplateArgumentList(1) != TPResult::False) {
-  // Consume the identifier.
-  ConsumeToken();
-  if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
-  TemplateName)) {
-// If an unrecoverable error occurred, we need to return true here,
-// because the token stream is in a damaged state.  We may not
-// return a valid identifier.
-return true;
-  }
-}
-  }
-}
-
 // The current token, which is either an identifier or a
 // template-id, is not part of the annotation. Fall through to
 // push that token back into the stream and complete the C++ scope


Index: clang/lib/Parse/Parser.cpp
===
--- clang/lib/Parse/Parser.cpp
+++ clang/lib/Parse/Parser.cpp
@@ -2056,36 +2056,6 @@
   return false;
 }
 
-// If this is a template-id, annotate with a template-id or type token.
-// FIXME: This appears to be dead code. We already have formed template-id
-// tokens when parsing the scope specifier; this can never form a new one.
-if (NextToken().is(tok::less)) {
-  TemplateTy Template;
-  UnqualifiedId TemplateName;
-  TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
-  bool MemberOfUnknownSpecialization;
-  if (TemplateNameKind TNK = Actions.isTemplateName(
-  getCurScope(), SS,
-  /*hasTemplateKeyword=*/false, TemplateName,
-  /*ObjectType=*/nullptr, /*EnteringContext*/false, Template,
-  MemberOfUnknownSpecialization)) {
-// Only annotate an undeclared template name as a template-id if the
-// following tokens have the form of a template argument list.
-if (TNK != TNK_Undeclared_template ||
-isTemplateArgumentList(1) != TPResult::False) {
-  // Consume the identifier.
-  ConsumeToken();
-  if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
-  TemplateName)) {
-// If an unrecoverable error occurred, we need to return true here,
-// because the token stream is in a damaged state.  We may not
-// return a valid identifier.
-return true;
-  }
-}
-  }
-}
-
 // The current token, which is either an identifier or a
 // template-id, is not part of the annotation. Fall through to
 // push that token back into the stream and complete the C++ scope
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 4a3a9a5 - [clang][deps] Sort submodules when calculating dependencies

2022-06-17 Thread Ben Langmuir via cfe-commits

Author: Ben Langmuir
Date: 2022-06-17T07:55:27-07:00
New Revision: 4a3a9a5fa0b2fd0e70672c35010fe2f00740f098

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

LOG: [clang][deps] Sort submodules when calculating dependencies

Dependency scanning does not care about the order of submodules for
correctness, so sort the submodules so that we get the same
command-lines to build the module across different TUs. The order of
inferred submodules can vary depending on the order of #includes in the
including TU.

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

Added: 
clang/test/ClangScanDeps/submodule-order.c

Modified: 
clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp

Removed: 




diff  --git a/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp 
b/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
index 8fad65c14e376..f7d96130b9712 100644
--- a/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
+++ b/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
@@ -317,13 +317,28 @@ ModuleID ModuleDepCollectorPP::handleTopLevelModule(const 
Module *M) {
   return MD.ID;
 }
 
+static void forEachSubmoduleSorted(const Module *M,
+   llvm::function_ref F) 
{
+  // Submodule order depends on order of header includes for inferred 
submodules
+  // we don't care about the exact order, so sort so that it's consistent 
across
+  // TUs to improve sharing.
+  SmallVector Submodules(M->submodule_begin(),
+ M->submodule_end());
+  llvm::stable_sort(Submodules, [](const Module *A, const Module *B) {
+return A->Name < B->Name;
+  });
+  for (const Module *SubM : Submodules)
+F(SubM);
+}
+
 void ModuleDepCollectorPP::addAllSubmodulePrebuiltDeps(
 const Module *M, ModuleDeps &MD,
 llvm::DenseSet &SeenSubmodules) {
   addModulePrebuiltDeps(M, MD, SeenSubmodules);
 
-  for (const Module *SubM : M->submodules())
+  forEachSubmoduleSorted(M, [&](const Module *SubM) {
 addAllSubmodulePrebuiltDeps(SubM, MD, SeenSubmodules);
+  });
 }
 
 void ModuleDepCollectorPP::addModulePrebuiltDeps(
@@ -341,8 +356,9 @@ void ModuleDepCollectorPP::addAllSubmoduleDeps(
 llvm::DenseSet &AddedModules) {
   addModuleDep(M, MD, AddedModules);
 
-  for (const Module *SubM : M->submodules())
+  forEachSubmoduleSorted(M, [&](const Module *SubM) {
 addAllSubmoduleDeps(SubM, MD, AddedModules);
+  });
 }
 
 void ModuleDepCollectorPP::addModuleDep(

diff  --git a/clang/test/ClangScanDeps/submodule-order.c 
b/clang/test/ClangScanDeps/submodule-order.c
new file mode 100644
index 0..9ab84c120356f
--- /dev/null
+++ b/clang/test/ClangScanDeps/submodule-order.c
@@ -0,0 +1,56 @@
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+// RUN: sed "s|DIR|%/t|g" %t/cdb.json.template > %t/cdb.json
+// RUN: clang-scan-deps -compilation-database %t/cdb.json -format 
experimental-full -generate-modules-path-args > %t/deps1.json
+// RUN: mv %t/tu2.c %t/tu.c
+// RUN: clang-scan-deps -compilation-database %t/cdb.json -format 
experimental-full -generate-modules-path-args > %t/deps2.json
+// RUN: 
diff  -u %t/deps1.json %t/deps2.json
+// RUN: FileCheck %s < %t/deps1.json
+
+// CHECK: "-fmodule-file={{.*}}Indirect1
+// CHECK-NOT: "-fmodule-file={{.*}}Indirect
+// CHECK: "-fmodule-file={{.*}}Indirect2
+// CHECK-NOT: "-fmodule-file={{.*}}Indirect
+
+//--- cdb.json.template
+[{
+  "directory": "DIR",
+  "command": "clang -fsyntax-only DIR/tu.c -fmodules -fimplicit-module-maps 
-fmodules-cache-path=DIR/cache",
+  "file": "DIR/tu.c"
+}]
+
+//--- module.modulemap
+module Indirect1 { header "Indirect1.h" }
+module Indirect2 { header "Indirect2.h" }
+module Mod {
+  umbrella "Mod"
+  module * { export * }
+}
+
+//--- Indirect1.h
+void indirect1(void);
+
+//--- Indirect2.h
+void indirect2(void);
+
+//--- Mod/SubMod1.h
+#include "../Indirect1.h"
+
+//--- Mod/SubMod2.h
+#include "../Indirect2.h"
+
+//--- tu.c
+#include "Mod/SubMod1.h"
+#include "Mod/SubMod2.h"
+void tu1(void) {
+  indirect1();
+  indirect2();
+}
+
+//--- tu2.c
+#include "Mod/SubMod2.h"
+#include "Mod/SubMod1.h"
+void tu1(void) {
+  indirect1();
+  indirect2();
+}
\ No newline at end of file



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


[PATCH] D128008: [clang][deps] Sort submodules when calculating dependencies

2022-06-17 Thread Ben Langmuir 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 rG4a3a9a5fa0b2: [clang][deps] Sort submodules when calculating 
dependencies (authored by benlangmuir).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128008

Files:
  clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
  clang/test/ClangScanDeps/submodule-order.c

Index: clang/test/ClangScanDeps/submodule-order.c
===
--- /dev/null
+++ clang/test/ClangScanDeps/submodule-order.c
@@ -0,0 +1,56 @@
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+// RUN: sed "s|DIR|%/t|g" %t/cdb.json.template > %t/cdb.json
+// RUN: clang-scan-deps -compilation-database %t/cdb.json -format experimental-full -generate-modules-path-args > %t/deps1.json
+// RUN: mv %t/tu2.c %t/tu.c
+// RUN: clang-scan-deps -compilation-database %t/cdb.json -format experimental-full -generate-modules-path-args > %t/deps2.json
+// RUN: diff -u %t/deps1.json %t/deps2.json
+// RUN: FileCheck %s < %t/deps1.json
+
+// CHECK: "-fmodule-file={{.*}}Indirect1
+// CHECK-NOT: "-fmodule-file={{.*}}Indirect
+// CHECK: "-fmodule-file={{.*}}Indirect2
+// CHECK-NOT: "-fmodule-file={{.*}}Indirect
+
+//--- cdb.json.template
+[{
+  "directory": "DIR",
+  "command": "clang -fsyntax-only DIR/tu.c -fmodules -fimplicit-module-maps -fmodules-cache-path=DIR/cache",
+  "file": "DIR/tu.c"
+}]
+
+//--- module.modulemap
+module Indirect1 { header "Indirect1.h" }
+module Indirect2 { header "Indirect2.h" }
+module Mod {
+  umbrella "Mod"
+  module * { export * }
+}
+
+//--- Indirect1.h
+void indirect1(void);
+
+//--- Indirect2.h
+void indirect2(void);
+
+//--- Mod/SubMod1.h
+#include "../Indirect1.h"
+
+//--- Mod/SubMod2.h
+#include "../Indirect2.h"
+
+//--- tu.c
+#include "Mod/SubMod1.h"
+#include "Mod/SubMod2.h"
+void tu1(void) {
+  indirect1();
+  indirect2();
+}
+
+//--- tu2.c
+#include "Mod/SubMod2.h"
+#include "Mod/SubMod1.h"
+void tu1(void) {
+  indirect1();
+  indirect2();
+}
\ No newline at end of file
Index: clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
===
--- clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
+++ clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
@@ -317,13 +317,28 @@
   return MD.ID;
 }
 
+static void forEachSubmoduleSorted(const Module *M,
+   llvm::function_ref F) {
+  // Submodule order depends on order of header includes for inferred submodules
+  // we don't care about the exact order, so sort so that it's consistent across
+  // TUs to improve sharing.
+  SmallVector Submodules(M->submodule_begin(),
+ M->submodule_end());
+  llvm::stable_sort(Submodules, [](const Module *A, const Module *B) {
+return A->Name < B->Name;
+  });
+  for (const Module *SubM : Submodules)
+F(SubM);
+}
+
 void ModuleDepCollectorPP::addAllSubmodulePrebuiltDeps(
 const Module *M, ModuleDeps &MD,
 llvm::DenseSet &SeenSubmodules) {
   addModulePrebuiltDeps(M, MD, SeenSubmodules);
 
-  for (const Module *SubM : M->submodules())
+  forEachSubmoduleSorted(M, [&](const Module *SubM) {
 addAllSubmodulePrebuiltDeps(SubM, MD, SeenSubmodules);
+  });
 }
 
 void ModuleDepCollectorPP::addModulePrebuiltDeps(
@@ -341,8 +356,9 @@
 llvm::DenseSet &AddedModules) {
   addModuleDep(M, MD, AddedModules);
 
-  for (const Module *SubM : M->submodules())
+  forEachSubmoduleSorted(M, [&](const Module *SubM) {
 addAllSubmoduleDeps(SubM, MD, AddedModules);
+  });
 }
 
 void ModuleDepCollectorPP::addModuleDep(
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D127142: [HIP] Link with clang_rt.builtins

2022-06-17 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl added a comment.

In D127142#3590874 , @yaxunl wrote:

> In D127142#3571260 , @MaskRay wrote:
>
>> In D127142#3570290 , @yaxunl wrote:
>>
>>> If I use --rtlib=compiler-rt, does that also requires --unwindlib=unwindlib 
>>> ?
>>
>> No. --unwindlib=libunwind requires --rtlib=compiler-rt. --rtlib=compiler-rt 
>> is compatible with both --unwindlib=libgcc and --unwindlib=libunwind.
>
> If only use -rtlib=compiler-rt without changing unwind lib, I will get 
> missing symbol:
>
> [2022-06-16T20:05:28.644Z] ld.lld: error: undefined symbol: _Unwind_Resume
>
> [2022-06-16T20:05:28.644Z] >>> referenced by main.cpp
>
> [2022-06-16T20:05:28.644Z] >>>   
> CMakeFiles/MIOpenDriver.dir/main.cpp.o:(generate_skipahead_file())
>
> [2022-06-16T20:05:28.644Z] >>> referenced by main.cpp
>
> [2022-06-16T20:05:28.644Z] >>>   
> CMakeFiles/MIOpenDriver.dir/main.cpp.o:(main)
>
> [2022-06-16T20:05:28.644Z] >>> referenced by main.cpp
>
> [2022-06-16T20:05:28.644Z] >>>   
> CMakeFiles/MIOpenDriver.dir/main.cpp.o:(std::function bool&)> reduce::ReduceOpFn2(miopenReduceTensorOp_t))
>
> [2022-06-16T20:05:28.644Z] >>> referenced 1246 more times
>
> [2022-06-16T20:05:28.644Z]
>
> [2022-06-16T20:05:28.644Z] ld.lld: error: ../lib/libMIOpen.so.1.0.50300: 
> undefined reference to _Unwind_Resume [--no-allow-shlib-undefined]
>
> [2022-06-16T20:05:28.644Z] ld.lld: error: ../lib/libMIOpen.so.1.0.50300: 
> undefined reference to _Unwind_Backtrace [--no-allow-shlib-undefined]
>
> [2022-06-16T20:05:28.644Z] ld.lld: error: ../lib/libMIOpen.so.1.0.50300: 
> undefined reference to _Unwind_GetIP [--no-allow-shlib-undefined]
>
> [2022-06-16T20:05:28.644Z] clang-15: error: linker command failed with exit 
> code 1 (use -v to see invocation)

If I use --rtlib=compiler-rt, do I have to explicitly add --unwindlib=libgcc or 
--unwindlib=libunwind? I suspect the linker is not linking the unwind library 
when -rtlib=compiler-rt is specified.


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

https://reviews.llvm.org/D127142

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


[PATCH] D128060: [clang][dataflow] Extend flow condition in the body of a for loop

2022-06-17 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel accepted this revision.
ymandel added a comment.

Mild preference for splitting into three tests, since it technically different 
code that's covered in each. But, up to you.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128060

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


[PATCH] D128060: [clang][dataflow] Extend flow condition in the body of a for loop

2022-06-17 Thread Stanislav Gatev via Phabricator via cfe-commits
sgatev updated this revision to Diff 437918.
sgatev added a comment.

Address comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128060

Files:
  clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
  clang/unittests/Analysis/FlowSensitive/TransferTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
@@ -3557,4 +3557,88 @@
   });
 }
 
+TEST_F(TransferTest, BranchesExtendFlowCondition) {
+  std::string IfBranchCode = R"(
+void target(bool Foo) {
+  if (Foo) {
+(void)0;
+// [[if_then]]
+  } else {
+(void)0;
+// [[if_else]]
+  }
+}
+  )";
+  runDataflow(
+  IfBranchCode,
+  [](llvm::ArrayRef<
+ std::pair>>
+ Results,
+ ASTContext &ASTCtx) {
+ASSERT_THAT(Results,
+ElementsAre(Pair("if_else", _), Pair("if_then", _)));
+const Environment &ThenEnv = Results[1].second.Env;
+const Environment &ElseEnv = Results[0].second.Env;
+
+const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo");
+ASSERT_THAT(FooDecl, NotNull());
+
+BoolValue &ThenFooVal =
+*cast(ThenEnv.getValue(*FooDecl, SkipPast::None));
+EXPECT_TRUE(ThenEnv.flowConditionImplies(ThenFooVal));
+
+BoolValue &ElseFooVal =
+*cast(ElseEnv.getValue(*FooDecl, SkipPast::None));
+EXPECT_TRUE(ElseEnv.flowConditionImplies(ElseEnv.makeNot(ElseFooVal)));
+  });
+
+  std::string WhileBranchCode = R"(
+void target(bool Foo) {
+  while (Foo) {
+(void)0;
+// [[while_branch]]
+  }
+}
+  )";
+  runDataflow(WhileBranchCode,
+  [](llvm::ArrayRef<
+ std::pair>>
+ Results,
+ ASTContext &ASTCtx) {
+ASSERT_THAT(Results, ElementsAre(Pair("while_branch", _)));
+const Environment &Env = Results[0].second.Env;
+
+const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo");
+ASSERT_THAT(FooDecl, NotNull());
+
+BoolValue &FooVal =
+*cast(Env.getValue(*FooDecl, SkipPast::None));
+EXPECT_TRUE(Env.flowConditionImplies(FooVal));
+  });
+
+  std::string ForBranchCode = R"(
+void target(bool Foo) {
+  for (; Foo;) {
+(void)0;
+// [[for_branch]]
+  }
+}
+  )";
+  runDataflow(ForBranchCode,
+  [](llvm::ArrayRef<
+ std::pair>>
+ Results,
+ ASTContext &ASTCtx) {
+ASSERT_THAT(Results, ElementsAre(Pair("for_branch", _)));
+const Environment &Env = Results[0].second.Env;
+
+const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo");
+ASSERT_THAT(FooDecl, NotNull());
+
+BoolValue &FooVal =
+*cast(Env.getValue(*FooDecl, SkipPast::None));
+EXPECT_TRUE(Env.flowConditionImplies(FooVal));
+  });
+}
+
 } // namespace
Index: clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
===
--- clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
+++ clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
@@ -89,6 +89,12 @@
 extendFlowCondition(*Cond);
   }
 
+  void VisitForStmt(const ForStmt *S) {
+auto *Cond = S->getCond();
+assert(Cond != nullptr);
+extendFlowCondition(*Cond);
+  }
+
   void VisitBinaryOperator(const BinaryOperator *S) {
 assert(S->getOpcode() == BO_LAnd || S->getOpcode() == BO_LOr);
 auto *LHS = S->getLHS();
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D122150: [clang][analyzer] Add checker for bad use of 'errno'.

2022-06-17 Thread Balázs Kéri via Phabricator via cfe-commits
balazske updated this revision to Diff 437922.
balazske marked 16 inline comments as done.
balazske added a comment.

Removed Errno_ prefix from ErrnoCheckState, documentation fixes, other small 
fixes.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122150

Files:
  clang/docs/ReleaseNotes.rst
  clang/docs/analyzer/checkers.rst
  clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
  clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
  clang/lib/StaticAnalyzer/Checkers/ErrnoChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/ErrnoModeling.cpp
  clang/lib/StaticAnalyzer/Checkers/ErrnoModeling.h
  clang/lib/StaticAnalyzer/Checkers/ErrnoTesterChecker.cpp
  clang/test/Analysis/analyzer-config.c
  clang/test/Analysis/errno-notes.c
  clang/test/Analysis/errno-options.c
  clang/test/Analysis/errno.c

Index: clang/test/Analysis/errno.c
===
--- clang/test/Analysis/errno.c
+++ clang/test/Analysis/errno.c
@@ -3,6 +3,7 @@
 // RUN:   -analyzer-checker=apiModeling.Errno \
 // RUN:   -analyzer-checker=debug.ExprInspection \
 // RUN:   -analyzer-checker=debug.ErrnoTest \
+// RUN:   -analyzer-checker=alpha.unix.Errno \
 // RUN:   -DERRNO_VAR
 
 // RUN: %clang_analyze_cc1 -verify %s \
@@ -10,8 +11,10 @@
 // RUN:   -analyzer-checker=apiModeling.Errno \
 // RUN:   -analyzer-checker=debug.ExprInspection \
 // RUN:   -analyzer-checker=debug.ErrnoTest \
+// RUN:   -analyzer-checker=alpha.unix.Errno \
 // RUN:   -DERRNO_FUNC
 
+#include "Inputs/system-header-simulator.h"
 #ifdef ERRNO_VAR
 #include "Inputs/errno_var.h"
 #endif
@@ -24,6 +27,7 @@
 int ErrnoTesterChecker_getErrno();
 int ErrnoTesterChecker_setErrnoIfError();
 int ErrnoTesterChecker_setErrnoIfErrorRange();
+int ErrnoTesterChecker_setErrnoCheckState();
 
 void something();
 
@@ -61,3 +65,199 @@
 clang_analyzer_eval(errno == 1); // expected-warning{{FALSE}} expected-warning{{TRUE}}
   }
 }
+
+void testErrnoCheck0() {
+  // If the function returns a success result code, value of 'errno'
+  // is unspecified and it is unsafe to make any decision with it.
+  // The function did not promise to not change 'errno' if no failure happens.
+  int X = ErrnoTesterChecker_setErrnoCheckState();
+  if (X == 0) {
+if (errno) { // expected-warning{{An undefined value may be read from 'errno' [alpha.unix.Errno]}}
+}
+if (errno) { // no warning for second time (analysis stops at the first warning)
+}
+  }
+  X = ErrnoTesterChecker_setErrnoCheckState();
+  if (X == 0) {
+if (errno) { // expected-warning{{An undefined value may be read from 'errno' [alpha.unix.Errno]}}
+}
+errno = 0;
+  }
+  X = ErrnoTesterChecker_setErrnoCheckState();
+  if (X == 0) {
+errno = 0;
+if (errno) { // no warning after overwritten 'errno'
+}
+  }
+}
+
+void testErrnoCheck1() {
+  // If the function returns error result code that is out-of-band (not a valid
+  // non-error return value) the value of 'errno' can be checked but it is not
+  // required to do so.
+  int X = ErrnoTesterChecker_setErrnoCheckState();
+  if (X == 1) {
+if (errno) { // no warning
+}
+  }
+  X = ErrnoTesterChecker_setErrnoCheckState();
+  if (X == 1) {
+errno = 0; // no warning
+  }
+}
+
+void testErrnoCheck2() {
+  // If the function returns an in-band error result the value of 'errno' is
+  // required to be checked to verify if error happened.
+  // The same applies to other functions that can indicate failure only by
+  // change of 'errno'.
+  int X = ErrnoTesterChecker_setErrnoCheckState();
+  if (X == 2) {
+errno = 0; // expected-warning{{Value of 'errno' was not checked and is overwritten here [alpha.unix.Errno]}}
+errno = 0;
+  }
+  X = ErrnoTesterChecker_setErrnoCheckState();
+  if (X == 2) {
+errno = 0; // expected-warning{{Value of 'errno' was not checked and is overwritten here [alpha.unix.Errno]}}
+if (errno) {
+}
+  }
+}
+
+void testErrnoCheck3() {
+  int X = ErrnoTesterChecker_setErrnoCheckState();
+  if (X == 2) {
+if (errno) {
+}
+errno = 0; // no warning after 'errno' was read
+  }
+  X = ErrnoTesterChecker_setErrnoCheckState();
+  if (X == 2) {
+int A = errno;
+errno = 0; // no warning after 'errno' was read
+  }
+}
+
+void testErrnoCheckUndefinedLoad() {
+  int X = ErrnoTesterChecker_setErrnoCheckState();
+  if (X == 0) {
+if (errno) { // expected-warning{{An undefined value may be read from 'errno' [alpha.unix.Errno]}}
+}
+  }
+}
+
+void testErrnoNotCheckedAtSystemCall() {
+  int X = ErrnoTesterChecker_setErrnoCheckState();
+  if (X == 2) {
+printf("%i", 1); // expected-warning{{Value of 'errno' was not checked and may be overwritten by function 'printf' [alpha.unix.Errno]}}
+printf("%i", 1); // no warning ('printf' does not change errno state)
+  }
+}
+
+void testErrnoCheckStateInvalidate() {
+  int X = ErrnoTesterChecker_setErrnoCheckState();
+  if (X == 0) 

[PATCH] D125400: [clang][Analyzer] Add errno state to standard functions modeling.

2022-06-17 Thread Balázs Kéri via Phabricator via cfe-commits
balazske updated this revision to Diff 437924.
balazske marked 2 inline comments as done.
balazske added a comment.

Small fixes.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125400

Files:
  clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
  clang/test/Analysis/errno-stdlibraryfunctions-notes.c
  clang/test/Analysis/errno-stdlibraryfunctions.c

Index: clang/test/Analysis/errno-stdlibraryfunctions.c
===
--- /dev/null
+++ clang/test/Analysis/errno-stdlibraryfunctions.c
@@ -0,0 +1,56 @@
+// RUN: %clang_analyze_cc1 -verify %s \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-checker=debug.ExprInspection \
+// RUN:   -analyzer-checker=apiModeling.StdCLibraryFunctions \
+// RUN:   -analyzer-checker=apiModeling.Errno \
+// RUN:   -analyzer-checker=alpha.unix.Errno \
+// RUN:   -analyzer-config apiModeling.StdCLibraryFunctions:ModelPOSIX=true
+
+#include "Inputs/errno_var.h"
+
+typedef typeof(sizeof(int)) size_t;
+typedef __typeof(sizeof(int)) off_t;
+typedef size_t ssize_t;
+ssize_t send(int sockfd, const void *buf, size_t len, int flags);
+off_t lseek(int fildes, off_t offset, int whence);
+
+void clang_analyzer_warnIfReached();
+void clang_analyzer_eval(int);
+
+int unsafe_errno_read(int sock, void *data, int data_size) {
+  if (send(sock, data, data_size, 0) != data_size) {
+if (errno == 1) {
+  // expected-warning@-1{{An undefined value may be read from 'errno'}}
+  return 0;
+}
+  }
+  return 1;
+}
+
+int errno_lseek(int fildes, off_t offset) {
+  off_t result = lseek(fildes, offset, 0);
+  if (result == (off_t)-1) {
+// Failure path.
+// check if the function is modeled
+clang_analyzer_eval(errno != 0); // expected-warning{{TRUE}}
+return 2;
+  }
+  if (result != offset) {
+// Not success path (?)
+// not sure if this is a valid case, allow to check 'errno'
+if (errno == 1) { // no warning
+  return 1;
+}
+clang_analyzer_warnIfReached(); // expected-warning{{REACHABLE}}
+  }
+  if (result == offset) {
+// The checker does not differentiate for this case.
+// In general case no relation exists between the arg 2 and the returned
+// value, only for SEEK_SET.
+if (errno == 1) { // no warning
+  return 1;
+}
+clang_analyzer_warnIfReached(); // expected-warning{{REACHABLE}}
+  }
+  return 0;
+}
Index: clang/test/Analysis/errno-stdlibraryfunctions-notes.c
===
--- /dev/null
+++ clang/test/Analysis/errno-stdlibraryfunctions-notes.c
@@ -0,0 +1,49 @@
+// RUN: %clang_analyze_cc1 -verify -analyzer-output text %s \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-checker=debug.ExprInspection \
+// RUN:   -analyzer-checker=apiModeling.StdCLibraryFunctions \
+// RUN:   -analyzer-checker=apiModeling.Errno \
+// RUN:   -analyzer-checker=alpha.unix.Errno \
+// RUN:   -analyzer-config apiModeling.StdCLibraryFunctions:ModelPOSIX=true
+
+#include "Inputs/errno_var.h"
+
+int access(const char *path, int amode);
+
+void clang_analyzer_warnIfReached();
+
+void test1() {
+  access("path", 0); // no note here
+  access("path", 0);
+  // expected-note@-1{{Assuming that function 'access' is successful, in this case the value 'errno' may be undefined after the call and should not be used}}
+  if (errno != 0) {
+// expected-warning@-1{{An undefined value may be read from 'errno'}}
+// expected-note@-2{{An undefined value may be read from 'errno'}}
+  }
+}
+
+void test2() {
+  if (access("path", 0) == -1) {
+// expected-note@-1{{Taking true branch}}
+// Failure path.
+if (errno != 0) {
+  // expected-note@-1{{'errno' is not equal to 0}}
+  // expected-note@-2{{Taking true branch}}
+  clang_analyzer_warnIfReached(); // expected-note {{REACHABLE}} expected-warning {{REACHABLE}}
+} else {
+  clang_analyzer_warnIfReached(); // no-warning: We are on the failure path.
+}
+  }
+}
+
+void test3() {
+  if (access("path", 0) != -1) {
+// Success path.
+// expected-note@-2{{Assuming that function 'access' is successful, in this case the value 'errno' may be undefined after the call and should not be used}}
+// expected-note@-3{{Taking true branch}}
+if (errno != 0) {
+  // expected-warning@-1{{An undefined value may be read from 'errno'}}
+  // expected-note@-2{{An undefined value may be read from 'errno'}}
+}
+  }
+}
Index: clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
@@ -40,6 +40,7 @@
 //
 //===--===//
 
+#include "ErrnoModeling.h"
 #include "clang/StaticAnal

[PATCH] D127277: [clang][analyzer] Fix StdLibraryFunctionsChecker 'mkdir' return value.

2022-06-17 Thread Balázs Kéri via Phabricator via cfe-commits
balazske updated this revision to Diff 437925.
balazske added a comment.

rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D127277

Files:
  clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp


Index: clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
@@ -1904,44 +1904,40 @@
 ArgumentCondition(1, WithinRange, Range(0, SizeMax;
 
 // int mkdir(const char *pathname, mode_t mode);
-// FIXME: returns 0 on success, ReturnsValidFileDescriptor is incorrect
 addToFunctionSummaryMap(
 "mkdir", Signature(ArgTypes{ConstCharPtrTy, Mode_tTy}, RetType{IntTy}),
 Summary(NoEvalCall)
-.Case(ReturnsValidFileDescriptor, ErrnoMustNotBeChecked)
+.Case(ReturnsZero, ErrnoMustNotBeChecked)
 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant)
 .ArgConstraint(NotNull(ArgNo(0;
 
 // int mkdirat(int dirfd, const char *pathname, mode_t mode);
-// FIXME: returns 0 on success, ReturnsValidFileDescriptor is incorrect
 addToFunctionSummaryMap(
 "mkdirat",
 Signature(ArgTypes{IntTy, ConstCharPtrTy, Mode_tTy}, RetType{IntTy}),
 Summary(NoEvalCall)
-.Case(ReturnsValidFileDescriptor, ErrnoMustNotBeChecked)
+.Case(ReturnsZero, ErrnoMustNotBeChecked)
 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant)
 .ArgConstraint(NotNull(ArgNo(1;
 
 Optional Dev_tTy = lookupTy("dev_t");
 
 // int mknod(const char *pathname, mode_t mode, dev_t dev);
-// FIXME: returns 0 on success, ReturnsValidFileDescriptor is incorrect
 addToFunctionSummaryMap(
 "mknod",
 Signature(ArgTypes{ConstCharPtrTy, Mode_tTy, Dev_tTy}, RetType{IntTy}),
 Summary(NoEvalCall)
-.Case(ReturnsValidFileDescriptor, ErrnoMustNotBeChecked)
+.Case(ReturnsZero, ErrnoMustNotBeChecked)
 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant)
 .ArgConstraint(NotNull(ArgNo(0;
 
 // int mknodat(int dirfd, const char *pathname, mode_t mode, dev_t dev);
-// FIXME: returns 0 on success, ReturnsValidFileDescriptor is incorrect
 addToFunctionSummaryMap(
 "mknodat",
 Signature(ArgTypes{IntTy, ConstCharPtrTy, Mode_tTy, Dev_tTy},
   RetType{IntTy}),
 Summary(NoEvalCall)
-.Case(ReturnsValidFileDescriptor, ErrnoMustNotBeChecked)
+.Case(ReturnsZero, ErrnoMustNotBeChecked)
 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant)
 .ArgConstraint(NotNull(ArgNo(1;
 


Index: clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
@@ -1904,44 +1904,40 @@
 ArgumentCondition(1, WithinRange, Range(0, SizeMax;
 
 // int mkdir(const char *pathname, mode_t mode);
-// FIXME: returns 0 on success, ReturnsValidFileDescriptor is incorrect
 addToFunctionSummaryMap(
 "mkdir", Signature(ArgTypes{ConstCharPtrTy, Mode_tTy}, RetType{IntTy}),
 Summary(NoEvalCall)
-.Case(ReturnsValidFileDescriptor, ErrnoMustNotBeChecked)
+.Case(ReturnsZero, ErrnoMustNotBeChecked)
 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant)
 .ArgConstraint(NotNull(ArgNo(0;
 
 // int mkdirat(int dirfd, const char *pathname, mode_t mode);
-// FIXME: returns 0 on success, ReturnsValidFileDescriptor is incorrect
 addToFunctionSummaryMap(
 "mkdirat",
 Signature(ArgTypes{IntTy, ConstCharPtrTy, Mode_tTy}, RetType{IntTy}),
 Summary(NoEvalCall)
-.Case(ReturnsValidFileDescriptor, ErrnoMustNotBeChecked)
+.Case(ReturnsZero, ErrnoMustNotBeChecked)
 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant)
 .ArgConstraint(NotNull(ArgNo(1;
 
 Optional Dev_tTy = lookupTy("dev_t");
 
 // int mknod(const char *pathname, mode_t mode, dev_t dev);
-// FIXME: returns 0 on success, ReturnsValidFileDescriptor is incorrect
 addToFunctionSummaryMap(
 "mknod",
 Signature(ArgTypes{ConstCharPtrTy, Mode_tTy, Dev_tTy}, RetType{IntTy}),
 Summary(NoEvalCall)
-.Case(ReturnsValidFileDescriptor, ErrnoMustNotBeChecked)
+.Case(ReturnsZero, ErrnoMustNotBeChecked)
 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant)
 .ArgConstraint(NotNull(ArgNo(0;
 
 // int mknodat(int dirfd, const char *pathname, mode_t mode, dev_t dev);
-// FIXME: returns 0 on success, Returns

[PATCH] D128068: [analyzer] Do not emit redundant SymbolCasts

2022-06-17 Thread Gabor Marton via Phabricator via cfe-commits
martong created this revision.
martong added reviewers: steakhal, NoQ, ASDenysPetrov.
Herald added subscribers: manas, gamesh411, dkrupp, donat.nagy, Szelethus, 
mikhail.ramalho, a.sidorin, rnkovacs, szepet, baloghadamsoftware, xazax.hun.
Herald added a reviewer: Szelethus.
Herald added a project: All.
martong requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

In RegionStore::getBinding we call `evalCast` unconditionally to align
the stored value's type to the one that is being queried. However, the
stored type might be the same, so we may end up having redundant
SymbolCasts emitted. The simplest solution is to check whether the `to`
and `from` type are the same in `makeNonLoc`. We can't just do that check
in `evalCast` because there are many additonal logic before we'd end up
in `makeNonLoc`.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D128068

Files:
  clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
  clang/test/Analysis/symbolcast-floatingpoint.cpp


Index: clang/test/Analysis/symbolcast-floatingpoint.cpp
===
--- /dev/null
+++ clang/test/Analysis/symbolcast-floatingpoint.cpp
@@ -0,0 +1,24 @@
+// RUN: %clang_analyze_cc1 -x c++ -analyzer-checker=debug.ExprInspection \
+// RUN:-analyzer-config support-symbolic-integer-casts=false \
+// RUN:-verify %s
+
+// RUN: %clang_analyze_cc1 -x c++ -analyzer-checker=debug.ExprInspection \
+// RUN:-analyzer-config support-symbolic-integer-casts=true \
+// RUN:-verify %s
+
+template 
+void clang_analyzer_dump(T);
+
+void test_no_redundant_floating_point_cast(int n) {
+
+  double D = n / 30;
+  clang_analyzer_dump(D); // expected-warning{{(double) ((reg_$0) / 
30)}}
+
+  // There are two cast operations evaluated above:
+  // 1. (n / 30) is cast to a double during the store of `D`.
+  // 2. Then in the next line, in RegionStore::getBinding during the load of 
`D`.
+  //
+  // We should not see in the dump of the SVal any redundant casts like
+  // (double) ((double) $n / 30)
+
+}
Index: clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
===
--- clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
+++ clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
@@ -113,6 +113,8 @@
   QualType fromTy, QualType toTy) {
   assert(operand);
   assert(!Loc::isLocType(toTy));
+  if (fromTy == toTy)
+return operand;
   return nonloc::SymbolVal(SymMgr.getCastSymbol(operand, fromTy, toTy));
 }
 


Index: clang/test/Analysis/symbolcast-floatingpoint.cpp
===
--- /dev/null
+++ clang/test/Analysis/symbolcast-floatingpoint.cpp
@@ -0,0 +1,24 @@
+// RUN: %clang_analyze_cc1 -x c++ -analyzer-checker=debug.ExprInspection \
+// RUN:-analyzer-config support-symbolic-integer-casts=false \
+// RUN:-verify %s
+
+// RUN: %clang_analyze_cc1 -x c++ -analyzer-checker=debug.ExprInspection \
+// RUN:-analyzer-config support-symbolic-integer-casts=true \
+// RUN:-verify %s
+
+template 
+void clang_analyzer_dump(T);
+
+void test_no_redundant_floating_point_cast(int n) {
+
+  double D = n / 30;
+  clang_analyzer_dump(D); // expected-warning{{(double) ((reg_$0) / 30)}}
+
+  // There are two cast operations evaluated above:
+  // 1. (n / 30) is cast to a double during the store of `D`.
+  // 2. Then in the next line, in RegionStore::getBinding during the load of `D`.
+  //
+  // We should not see in the dump of the SVal any redundant casts like
+  // (double) ((double) $n / 30)
+
+}
Index: clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
===
--- clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
+++ clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
@@ -113,6 +113,8 @@
   QualType fromTy, QualType toTy) {
   assert(operand);
   assert(!Loc::isLocType(toTy));
+  if (fromTy == toTy)
+return operand;
   return nonloc::SymbolVal(SymMgr.getCastSymbol(operand, fromTy, toTy));
 }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D127873: [clang-format] Fix misplacemnt of `*` in declaration of pointer to struct

2022-06-17 Thread Björn Schäpers via Phabricator via cfe-commits
HazardyKnusperkeks added a comment.

In D127873#3589465 , @jackhong12 
wrote:

> I think it's a good idea. When does `MatchingParen` bind? The value of 
> `PrevToken->MatchingParen` is still NULL in `determineStarAmpUsage` function.

What has changed, now you are using that.




Comment at: clang/lib/Format/TokenAnnotator.cpp:2314-2315
+if (PrevToken->is(tok::r_brace) && Tok.isOneOf(tok::amp, tok::ampamp) &&
+PrevToken->MatchingParen && PrevToken->MatchingParen->is(TT_Unknown))
+  return TT_BinaryOperator;
+

Unknown is everything, until some type is assigned. This way it should be 
clearer.

Also put that check above the other one and add the `r_brace` back.


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

https://reviews.llvm.org/D127873

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


[PATCH] D126779: [analyzer] Fix assertion in simplifySymbolCast

2022-06-17 Thread Gabor Marton via Phabricator via cfe-commits
martong updated this revision to Diff 437938.
martong added a comment.

- Rebase on dependent patch


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126779

Files:
  clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
  clang/test/Analysis/produce-symbolcast_x86.cpp


Index: clang/test/Analysis/produce-symbolcast_x86.cpp
===
--- clang/test/Analysis/produce-symbolcast_x86.cpp
+++ clang/test/Analysis/produce-symbolcast_x86.cpp
@@ -11,6 +11,15 @@
 template 
 void clang_analyzer_dump(T);
 
+void test_double(int n) {
+  double D = n / 30;
+  clang_analyzer_dump(D); // expected-warning{{(double) ((reg_$0) / 
30)}}
+  char C = D;
+  clang_analyzer_dump(C); // expected-warning{{(char) ((double) ((reg_$0) / 30))}}
+  int I = C; // assertion should not fail here!
+  clang_analyzer_dump(I); // expected-warning{{(int) ((char) ((double) 
((reg_$0) / 30)))}}
+}
+
 void test_schar(schar x) {
   clang_analyzer_dump(x); // expected-warning{{reg_$0}}
 
Index: clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
===
--- clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
+++ clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
@@ -1104,6 +1104,10 @@
   SymbolRef RootSym = cast(SE)->getOperand();
   QualType RT = RootSym->getType().getCanonicalType();
 
+  // FIXME support simplification from non-integers.
+  if (!RT->isIntegralOrEnumerationType())
+return makeNonLoc(SE, T, CastTy);
+
   BasicValueFactory &BVF = getBasicValueFactory();
   APSIntType CTy = BVF.getAPSIntType(CastTy);
   APSIntType TTy = BVF.getAPSIntType(T);


Index: clang/test/Analysis/produce-symbolcast_x86.cpp
===
--- clang/test/Analysis/produce-symbolcast_x86.cpp
+++ clang/test/Analysis/produce-symbolcast_x86.cpp
@@ -11,6 +11,15 @@
 template 
 void clang_analyzer_dump(T);
 
+void test_double(int n) {
+  double D = n / 30;
+  clang_analyzer_dump(D); // expected-warning{{(double) ((reg_$0) / 30)}}
+  char C = D;
+  clang_analyzer_dump(C); // expected-warning{{(char) ((double) ((reg_$0) / 30))}}
+  int I = C; // assertion should not fail here!
+  clang_analyzer_dump(I); // expected-warning{{(int) ((char) ((double) ((reg_$0) / 30)))}}
+}
+
 void test_schar(schar x) {
   clang_analyzer_dump(x); // expected-warning{{reg_$0}}
 
Index: clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
===
--- clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
+++ clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
@@ -1104,6 +1104,10 @@
   SymbolRef RootSym = cast(SE)->getOperand();
   QualType RT = RootSym->getType().getCanonicalType();
 
+  // FIXME support simplification from non-integers.
+  if (!RT->isIntegralOrEnumerationType())
+return makeNonLoc(SE, T, CastTy);
+
   BasicValueFactory &BVF = getBasicValueFactory();
   APSIntType CTy = BVF.getAPSIntType(CastTy);
   APSIntType TTy = BVF.getAPSIntType(T);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D126194: [Concepts] Implement overload resolution for destructors (P0848)

2022-06-17 Thread Roy Jacobson via Phabricator via cfe-commits
royjacobson updated this revision to Diff 437940.
royjacobson added a comment.

Fix the AST test on windows and rebase on HEAD.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126194

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/AST/Decl.h
  clang/include/clang/AST/DeclBase.h
  clang/include/clang/AST/DeclCXX.h
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/AST/Decl.cpp
  clang/lib/AST/DeclCXX.cpp
  clang/lib/AST/TextNodeDumper.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/lib/Sema/SemaTemplateInstantiate.cpp
  clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
  clang/test/AST/ast-dump-decl.cpp
  clang/test/AST/overloaded-destructors.cpp
  clang/test/CXX/class/class.dtor/p4.cpp
  clang/test/CXX/over/over.match/over.match.viable/p3.cpp
  clang/test/SemaTemplate/destructor-template.cpp

Index: clang/test/SemaTemplate/destructor-template.cpp
===
--- clang/test/SemaTemplate/destructor-template.cpp
+++ clang/test/SemaTemplate/destructor-template.cpp
@@ -98,7 +98,7 @@
   template 
   ~S(); // expected-error{{destructor cannot be declared as a template}}
 };
-struct T : S {// expected-note{{destructor of 'T' is implicitly deleted because base class 'PR38671::S' has no destructor}}
-  ~T() = default; // expected-warning{{explicitly defaulted destructor is implicitly deleted}}
+struct T : S {
+  ~T() = default;
 };
 } // namespace PR38671
Index: clang/test/CXX/over/over.match/over.match.viable/p3.cpp
===
--- clang/test/CXX/over/over.match/over.match.viable/p3.cpp
+++ clang/test/CXX/over/over.match/over.match.viable/p3.cpp
@@ -49,7 +49,6 @@
   S(A) requires false;
   S(double) requires true;
   ~S() requires false;
-  // expected-note@-1 2{{because 'false' evaluated to false}}
   ~S() requires true;
   operator int() requires true;
   operator int() requires false;
@@ -58,11 +57,7 @@
 void bar() {
   WrapsStatics::foo(A{});
   S{1.}.foo(A{});
-  // expected-error@-1{{invalid reference to function '~S': constraints not satisfied}}
-  // Note - this behavior w.r.t. constrained dtors is a consequence of current
-  // wording, which does not invoke overload resolution when a dtor is called.
-  // P0848 is set to address this issue.
+
   S s = 1;
-  // expected-error@-1{{invalid reference to function '~S': constraints not satisfied}}
   int a = s;
 }
Index: clang/test/CXX/class/class.dtor/p4.cpp
===
--- /dev/null
+++ clang/test/CXX/class/class.dtor/p4.cpp
@@ -0,0 +1,77 @@
+// RUN: %clang_cc1 -std=c++20 -verify %s
+
+template 
+struct A {
+  ~A() = delete;  // expected-note {{explicitly marked deleted}}
+  ~A() requires(N == 1) = delete; // expected-note {{explicitly marked deleted}}
+};
+
+// FIXME: We should probably make it illegal to mix virtual and non-virtual methods
+// this way. See CWG2488 and some discussion in https://gcc.gnu.org/bugzilla/show_bug.cgi?id=105699.
+template 
+struct B {
+  ~B() requires(N == 1) = delete; // expected-note {{explicitly marked deleted}}
+  virtual ~B() = delete;  // expected-note {{explicitly marked deleted}}
+};
+
+template 
+concept CO1 = N == 1;
+
+template 
+concept CO2 = N >
+0;
+
+template 
+struct C {
+  ~C() = delete; // expected-note {{explicitly marked deleted}}
+  ~C() requires(CO1) = delete;
+  ~C() requires(CO1 &&CO2) = delete; // expected-note {{explicitly marked deleted}}
+};
+
+template 
+struct D {
+  ~D() requires(N != 0) = delete; // expected-note {{explicitly marked deleted}}
+  // expected-note@-1 {{candidate function has been explicitly deleted}}
+  // expected-note@-2 {{candidate function not viable: constraints not satisfied}}
+  // expected-note@-3 {{evaluated to false}}
+  ~D() requires(N == 1) = delete;
+  // expected-note@-1 {{candidate function has been explicitly deleted}}
+  // expected-note@-2 {{candidate function not viable: constraints not satisfied}}
+  // expected-note@-3 {{evaluated to false}}
+};
+
+template 
+concept Foo = requires(T t) {
+  {t.foo()};
+};
+
+template 
+struct E {
+  void foo();
+  ~E();
+  ~E() requires Foo = delete; // expected-note {{explicitly marked deleted}}
+};
+
+template struct A<1>;
+template struct A<2>;
+template struct B<1>;
+template struct B<2>;
+template struct C<1>;
+template struct C<2>;
+template struct D<0>; // expected-error {{no viable destructor found for class 'D<0>'}} expected-note {{in instantiation of template}}
+template struct D<1>; // expected-error {{destructor of class 'D<1>' is ambiguous}} expected-note {{in instantiation of template}}
+template struct D<2>;
+template struct E<1>;
+
+int main() {
+  A<1> a1; // expected-error {{attempt to use a deleted function}}
+  A<2> a2; // expected-error {{attempt to use a deleted function}}
+  B<1> b1

[PATCH] D126779: [analyzer] Fix assertion in simplifySymbolCast

2022-06-17 Thread Gabor Marton via Phabricator via cfe-commits
martong marked 2 inline comments as done.
martong added inline comments.



Comment at: clang/lib/StaticAnalyzer/Core/SValBuilder.cpp:1082
+  // FIXME support cast from non-integers.
+  // E.g (char)(double)(double x) -> (char)(double x)
+  if (!RT->isIntegralOrEnumerationType())

steakhal wrote:
> Well, I would expect the same, but crosscheck this with the actual dump.
Please elaborate.



Comment at: clang/test/Analysis/produce-symbolcast_x86.cpp:16
+  double D = n / 30;
+  clang_analyzer_dump(D); // expected-warning{{(double) ((double) ((reg_$0) / 30))}}
+  char C = D;

steakhal wrote:
> Place here a FIXME that we should not have two double casts.
The `(double)(double)` problem is handled in the parent patch. Please check 
that out.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126779

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


[clang] fc6b228 - [Static Analyzer][CFG] Introducing the source array in the CFG of DecompositionDecl

2022-06-17 Thread via cfe-commits

Author: isuckatcs
Date: 2022-06-17T18:34:34+02:00
New Revision: fc6b2281bfd747b3e24d23e2ee8de189f741770f

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

LOG: [Static Analyzer][CFG] Introducing the source array in the CFG of 
DecompositionDecl

For DecompositionDecl, the array, which is being decomposed was not present in 
the
CFG, which lead to the liveness analysis falsely detecting it as a dead symbol.

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

Added: 


Modified: 
clang/lib/Analysis/CFG.cpp
clang/test/Analysis/cfg.cpp

Removed: 




diff  --git a/clang/lib/Analysis/CFG.cpp b/clang/lib/Analysis/CFG.cpp
index 8379e108fa27b..b16898d3ffa0b 100644
--- a/clang/lib/Analysis/CFG.cpp
+++ b/clang/lib/Analysis/CFG.cpp
@@ -609,6 +609,7 @@ class CFGBuilder {
   AddStmtChoice asc);
   CFGBlock *VisitUnaryOperator(UnaryOperator *U, AddStmtChoice asc);
   CFGBlock *VisitWhileStmt(WhileStmt *W);
+  CFGBlock *VisitArrayInitLoopExpr(ArrayInitLoopExpr *A, AddStmtChoice asc);
 
   CFGBlock *Visit(Stmt *S, AddStmtChoice asc = AddStmtChoice::NotAlwaysAdd,
   bool ExternallyDestructed = false);
@@ -2330,6 +2331,9 @@ CFGBlock *CFGBuilder::Visit(Stmt * S, AddStmtChoice asc,
 
 case Stmt::WhileStmtClass:
   return VisitWhileStmt(cast(S));
+
+case Stmt::ArrayInitLoopExprClass:
+  return VisitArrayInitLoopExpr(cast(S), asc);
   }
 }
 
@@ -3881,6 +3885,27 @@ CFGBlock *CFGBuilder::VisitWhileStmt(WhileStmt *W) {
   return EntryConditionBlock;
 }
 
+CFGBlock *CFGBuilder::VisitArrayInitLoopExpr(ArrayInitLoopExpr *A,
+ AddStmtChoice asc) {
+  if (asc.alwaysAdd(*this, A)) {
+autoCreateBlock();
+appendStmt(Block, A);
+  }
+
+  CFGBlock *B = Block;
+
+  if (CFGBlock *R = Visit(A->getSubExpr()))
+B = R;
+
+  auto *OVE = dyn_cast(A->getCommonExpr());
+  assert(OVE && "ArrayInitLoopExpr->getCommonExpr() should be wrapped in an "
+"OpaqueValueExpr!");
+  if (CFGBlock *R = Visit(OVE->getSourceExpr()))
+B = R;
+
+  return B;
+}
+
 CFGBlock *CFGBuilder::VisitObjCAtCatchStmt(ObjCAtCatchStmt *CS) {
   // ObjCAtCatchStmt are treated like labels, so they are the first statement
   // in a block.

diff  --git a/clang/test/Analysis/cfg.cpp b/clang/test/Analysis/cfg.cpp
index 333ea565287b2..df4c7b32fb685 100644
--- a/clang/test/Analysis/cfg.cpp
+++ b/clang/test/Analysis/cfg.cpp
@@ -650,6 +650,22 @@ int crash_with_thread_local(char *p, int *q) {
   return 0;
 }
 
+// CHECK-LABEL: void DecompositionDecl()
+// CHECK:   [B1]
+// CHECK-NEXT:1: int arr[2];
+// CHECK-NEXT:2: arr
+// CHECK-NEXT:3: [B1.2] (ImplicitCastExpr, ArrayToPointerDecay, int *)
+// CHECK-NEXT:4: *
+// CHECK-NEXT:5: [B1.3]{{\[\[}}B1.4]]
+// CHECK-NEXT:6: [B1.5] (ImplicitCastExpr, LValueToRValue, int)
+// CHECK-NEXT:7: {{\{}}[B1.6]{{(\})}}
+// CHECK-NEXT:8: auto = {{\{}}arr[*]{{(\})}};
+void DecompositionDecl() {
+  int arr[2];
+
+  auto [a, b] = arr;
+}
+
 // CHECK-LABEL: template<> int *PR18472()
 // CHECK: [B2 (ENTRY)]
 // CHECK-NEXT:   Succs (1): B1



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


[PATCH] D127993: [Static Analyzer][CFG] Introducing the source array in the CFG of DecompositionDecl

2022-06-17 Thread Domján Dániel 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 rGfc6b2281bfd7: [Static Analyzer][CFG] Introducing the source 
array in the CFG of… (authored by isuckatcs).
Herald added a subscriber: cfe-commits.

Changed prior to commit:
  https://reviews.llvm.org/D127993?vs=437859&id=437943#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D127993

Files:
  clang/lib/Analysis/CFG.cpp
  clang/test/Analysis/cfg.cpp


Index: clang/test/Analysis/cfg.cpp
===
--- clang/test/Analysis/cfg.cpp
+++ clang/test/Analysis/cfg.cpp
@@ -650,6 +650,22 @@
   return 0;
 }
 
+// CHECK-LABEL: void DecompositionDecl()
+// CHECK:   [B1]
+// CHECK-NEXT:1: int arr[2];
+// CHECK-NEXT:2: arr
+// CHECK-NEXT:3: [B1.2] (ImplicitCastExpr, ArrayToPointerDecay, int *)
+// CHECK-NEXT:4: *
+// CHECK-NEXT:5: [B1.3]{{\[\[}}B1.4]]
+// CHECK-NEXT:6: [B1.5] (ImplicitCastExpr, LValueToRValue, int)
+// CHECK-NEXT:7: {{\{}}[B1.6]{{(\})}}
+// CHECK-NEXT:8: auto = {{\{}}arr[*]{{(\})}};
+void DecompositionDecl() {
+  int arr[2];
+
+  auto [a, b] = arr;
+}
+
 // CHECK-LABEL: template<> int *PR18472()
 // CHECK: [B2 (ENTRY)]
 // CHECK-NEXT:   Succs (1): B1
Index: clang/lib/Analysis/CFG.cpp
===
--- clang/lib/Analysis/CFG.cpp
+++ clang/lib/Analysis/CFG.cpp
@@ -609,6 +609,7 @@
   AddStmtChoice asc);
   CFGBlock *VisitUnaryOperator(UnaryOperator *U, AddStmtChoice asc);
   CFGBlock *VisitWhileStmt(WhileStmt *W);
+  CFGBlock *VisitArrayInitLoopExpr(ArrayInitLoopExpr *A, AddStmtChoice asc);
 
   CFGBlock *Visit(Stmt *S, AddStmtChoice asc = AddStmtChoice::NotAlwaysAdd,
   bool ExternallyDestructed = false);
@@ -2330,6 +2331,9 @@
 
 case Stmt::WhileStmtClass:
   return VisitWhileStmt(cast(S));
+
+case Stmt::ArrayInitLoopExprClass:
+  return VisitArrayInitLoopExpr(cast(S), asc);
   }
 }
 
@@ -3881,6 +3885,27 @@
   return EntryConditionBlock;
 }
 
+CFGBlock *CFGBuilder::VisitArrayInitLoopExpr(ArrayInitLoopExpr *A,
+ AddStmtChoice asc) {
+  if (asc.alwaysAdd(*this, A)) {
+autoCreateBlock();
+appendStmt(Block, A);
+  }
+
+  CFGBlock *B = Block;
+
+  if (CFGBlock *R = Visit(A->getSubExpr()))
+B = R;
+
+  auto *OVE = dyn_cast(A->getCommonExpr());
+  assert(OVE && "ArrayInitLoopExpr->getCommonExpr() should be wrapped in an "
+"OpaqueValueExpr!");
+  if (CFGBlock *R = Visit(OVE->getSourceExpr()))
+B = R;
+
+  return B;
+}
+
 CFGBlock *CFGBuilder::VisitObjCAtCatchStmt(ObjCAtCatchStmt *CS) {
   // ObjCAtCatchStmt are treated like labels, so they are the first statement
   // in a block.


Index: clang/test/Analysis/cfg.cpp
===
--- clang/test/Analysis/cfg.cpp
+++ clang/test/Analysis/cfg.cpp
@@ -650,6 +650,22 @@
   return 0;
 }
 
+// CHECK-LABEL: void DecompositionDecl()
+// CHECK:   [B1]
+// CHECK-NEXT:1: int arr[2];
+// CHECK-NEXT:2: arr
+// CHECK-NEXT:3: [B1.2] (ImplicitCastExpr, ArrayToPointerDecay, int *)
+// CHECK-NEXT:4: *
+// CHECK-NEXT:5: [B1.3]{{\[\[}}B1.4]]
+// CHECK-NEXT:6: [B1.5] (ImplicitCastExpr, LValueToRValue, int)
+// CHECK-NEXT:7: {{\{}}[B1.6]{{(\})}}
+// CHECK-NEXT:8: auto = {{\{}}arr[*]{{(\})}};
+void DecompositionDecl() {
+  int arr[2];
+
+  auto [a, b] = arr;
+}
+
 // CHECK-LABEL: template<> int *PR18472()
 // CHECK: [B2 (ENTRY)]
 // CHECK-NEXT:   Succs (1): B1
Index: clang/lib/Analysis/CFG.cpp
===
--- clang/lib/Analysis/CFG.cpp
+++ clang/lib/Analysis/CFG.cpp
@@ -609,6 +609,7 @@
   AddStmtChoice asc);
   CFGBlock *VisitUnaryOperator(UnaryOperator *U, AddStmtChoice asc);
   CFGBlock *VisitWhileStmt(WhileStmt *W);
+  CFGBlock *VisitArrayInitLoopExpr(ArrayInitLoopExpr *A, AddStmtChoice asc);
 
   CFGBlock *Visit(Stmt *S, AddStmtChoice asc = AddStmtChoice::NotAlwaysAdd,
   bool ExternallyDestructed = false);
@@ -2330,6 +2331,9 @@
 
 case Stmt::WhileStmtClass:
   return VisitWhileStmt(cast(S));
+
+case Stmt::ArrayInitLoopExprClass:
+  return VisitArrayInitLoopExpr(cast(S), asc);
   }
 }
 
@@ -3881,6 +3885,27 @@
   return EntryConditionBlock;
 }
 
+CFGBlock *CFGBuilder::VisitArrayInitLoopExpr(ArrayInitLoopExpr *A,
+ AddStmtChoice asc) {
+  if (asc.alwaysAdd(*this, A)) {
+autoCreateBlock();
+appendStmt(Block, A);
+  }
+
+  CFGBlock *B = Block;
+
+  if (CFGBlock *R = Visit(A->getSubExpr()))
+B = R;
+
+  auto *OVE = dyn_cast(A->getCommonExpr());
+  assert(OVE && "ArrayInitLoopExpr->getCommonExpr() sho

[PATCH] D128060: [clang][dataflow] Extend flow condition in the body of a for loop

2022-06-17 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun accepted this revision.
xazax.hun added inline comments.



Comment at: clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp:92
 
+  void VisitForStmt(const ForStmt *S) {
+auto *Cond = S->getCond();

Do we support `DoStmt` or is that missing?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128060

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


[PATCH] D128056: [clang][dataflow] Singleton pointer values for null pointers.

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

I am wondering about the future plans regarding how pointers are represented.
What will be the expected behavior when the analysis discovers that the pointer 
has a null value? E.g.:

  if (p == nullptr)
  {

  }

Would we expect `p` in this case to have the same singleton value in the then 
block of the if statement?




Comment at: 
clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h:146
+  ///  `PointeeType`.
+  void setNullPointerVal(QualType PointeeType, PointerValue &Val) {
+assert(NullPointerVals.find(PointeeType.getAsString()) ==

Since you always want this function to create a null pointer value, I think it 
would be less error prone to ask for the location instead of an arbitrary 
value. Currently, a confused caller could put a non-null value into a table. 



Comment at: 
clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h:149
+   NullPointerVals.end());
+NullPointerVals[PointeeType.getAsString()] = &Val;
+  }

I think `getAsString` is considered expensive. Could you use `QualType` 
directly as the key?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128056

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


[clang] 92bf652 - [Static Analyzer] Small array binding policy

2022-06-17 Thread via cfe-commits

Author: isuckatcs
Date: 2022-06-17T18:56:13+02:00
New Revision: 92bf652d40740b947de6c41fe09f282ec0530dc5

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

LOG: [Static Analyzer] Small array binding policy

If a lazyCompoundVal to a struct is bound to the store, there is a policy which 
decides
whether a copy gets created instead.

This patch introduces a similar policy for arrays, which is required to model 
structured
binding to arrays without false negatives.

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

Added: 


Modified: 
clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
clang/lib/StaticAnalyzer/Core/RegionStore.cpp
clang/test/Analysis/analyzer-config.c

Removed: 




diff  --git a/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def 
b/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
index d7075fb39fc89..9974ea9392acb 100644
--- a/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
+++ b/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
@@ -440,11 +440,19 @@ ANALYZER_OPTION(
 ANALYZER_OPTION(
 unsigned, RegionStoreSmallStructLimit, "region-store-small-struct-limit",
 "The largest number of fields a struct can have and still be considered "
-"small This is currently used to decide whether or not it is worth forcing 
"
+"small. This is currently used to decide whether or not it is worth 
forcing "
 "a LazyCompoundVal on bind. To disable all small-struct-dependent "
 "behavior, set the option to 0.",
 2)
 
+ANALYZER_OPTION(
+unsigned, RegionStoreSmallArrayLimit, "region-store-small-array-limit",
+"The largest number of elements an array can have and still be considered "
+"small. This is currently used to decide whether or not it is worth 
forcing "
+"a LazyCompoundVal on bind. To disable all small-array-dependent "
+"behavior, set the option to 0.",
+5)
+
 
//===--===//
 // String analyzer options.
 
//===--===//

diff  --git a/clang/lib/StaticAnalyzer/Core/RegionStore.cpp 
b/clang/lib/StaticAnalyzer/Core/RegionStore.cpp
index 8a50cb27c8d3a..b432247bad7d8 100644
--- a/clang/lib/StaticAnalyzer/Core/RegionStore.cpp
+++ b/clang/lib/StaticAnalyzer/Core/RegionStore.cpp
@@ -345,6 +345,16 @@ class RegionStoreManager : public StoreManager {
   /// To disable all small-struct-dependent behavior, set the option to "0".
   unsigned SmallStructLimit;
 
+  /// The largest number of element an array can have and still be
+  /// considered "small".
+  ///
+  /// This is currently used to decide whether or not it is worth "forcing" a
+  /// LazyCompoundVal on bind.
+  ///
+  /// This is controlled by 'region-store-small-struct-limit' option.
+  /// To disable all small-struct-dependent behavior, set the option to "0".
+  unsigned SmallArrayLimit;
+
   /// A helper used to populate the work list with the given set of
   /// regions.
   void populateWorkList(InvalidateRegionsWorker &W,
@@ -354,10 +364,11 @@ class RegionStoreManager : public StoreManager {
 public:
   RegionStoreManager(ProgramStateManager &mgr)
   : StoreManager(mgr), RBFactory(mgr.getAllocator()),
-CBFactory(mgr.getAllocator()), SmallStructLimit(0) {
+CBFactory(mgr.getAllocator()), SmallStructLimit(0), SmallArrayLimit(0) 
{
 ExprEngine &Eng = StateMgr.getOwningEngine();
 AnalyzerOptions &Options = Eng.getAnalysisManager().options;
 SmallStructLimit = Options.RegionStoreSmallStructLimit;
+SmallArrayLimit = Options.RegionStoreSmallArrayLimit;
   }
 
   /// setImplicitDefaultValue - Set the default binding for the provided
@@ -487,6 +498,11 @@ class RegionStoreManager : public StoreManager {
   RegionBindingsRef bindVector(RegionBindingsConstRef B,
const TypedValueRegion* R, SVal V);
 
+  Optional tryBindSmallArray(RegionBindingsConstRef B,
+const TypedValueRegion *R,
+const ArrayType *AT,
+nonloc::LazyCompoundVal LCV);
+
   RegionBindingsRef bindArray(RegionBindingsConstRef B,
   const TypedValueRegion* R,
   SVal V);
@@ -2392,6 +2408,40 @@ 
RegionStoreManager::setImplicitDefaultValue(RegionBindingsConstRef B,
   return B.addBinding(R, BindingKey::Default, V);
 }
 
+Optional RegionStoreManager::tryBindSmallArray(
+RegionBindingsConstRef B, const TypedValueRegion *R, const ArrayType *AT,
+nonloc::LazyCompoundVal LCV) {
+
+  auto CAT = dyn_cast(AT);
+
+  // If we don't know the size, create a lazyCompoundVal

[PATCH] D128064: [Static Analyzer] Small array binding policy

2022-06-17 Thread Domján Dániel 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 rG92bf652d4074: [Static Analyzer] Small array binding policy 
(authored by isuckatcs).
Herald added a subscriber: cfe-commits.

Changed prior to commit:
  https://reviews.llvm.org/D128064?vs=437912&id=437950#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128064

Files:
  clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
  clang/lib/StaticAnalyzer/Core/RegionStore.cpp
  clang/test/Analysis/analyzer-config.c

Index: clang/test/Analysis/analyzer-config.c
===
--- clang/test/Analysis/analyzer-config.c
+++ clang/test/Analysis/analyzer-config.c
@@ -114,6 +114,7 @@
 // CHECK-NEXT: osx.NumberObjectConversion:Pedantic = false
 // CHECK-NEXT: osx.cocoa.RetainCount:TrackNSCFStartParam = false
 // CHECK-NEXT: prune-paths = true
+// CHECK-NEXT: region-store-small-array-limit = 5
 // CHECK-NEXT: region-store-small-struct-limit = 2
 // CHECK-NEXT: report-in-main-source-file = false
 // CHECK-NEXT: serialize-stats = false
Index: clang/lib/StaticAnalyzer/Core/RegionStore.cpp
===
--- clang/lib/StaticAnalyzer/Core/RegionStore.cpp
+++ clang/lib/StaticAnalyzer/Core/RegionStore.cpp
@@ -345,6 +345,16 @@
   /// To disable all small-struct-dependent behavior, set the option to "0".
   unsigned SmallStructLimit;
 
+  /// The largest number of element an array can have and still be
+  /// considered "small".
+  ///
+  /// This is currently used to decide whether or not it is worth "forcing" a
+  /// LazyCompoundVal on bind.
+  ///
+  /// This is controlled by 'region-store-small-struct-limit' option.
+  /// To disable all small-struct-dependent behavior, set the option to "0".
+  unsigned SmallArrayLimit;
+
   /// A helper used to populate the work list with the given set of
   /// regions.
   void populateWorkList(InvalidateRegionsWorker &W,
@@ -354,10 +364,11 @@
 public:
   RegionStoreManager(ProgramStateManager &mgr)
   : StoreManager(mgr), RBFactory(mgr.getAllocator()),
-CBFactory(mgr.getAllocator()), SmallStructLimit(0) {
+CBFactory(mgr.getAllocator()), SmallStructLimit(0), SmallArrayLimit(0) {
 ExprEngine &Eng = StateMgr.getOwningEngine();
 AnalyzerOptions &Options = Eng.getAnalysisManager().options;
 SmallStructLimit = Options.RegionStoreSmallStructLimit;
+SmallArrayLimit = Options.RegionStoreSmallArrayLimit;
   }
 
   /// setImplicitDefaultValue - Set the default binding for the provided
@@ -487,6 +498,11 @@
   RegionBindingsRef bindVector(RegionBindingsConstRef B,
const TypedValueRegion* R, SVal V);
 
+  Optional tryBindSmallArray(RegionBindingsConstRef B,
+const TypedValueRegion *R,
+const ArrayType *AT,
+nonloc::LazyCompoundVal LCV);
+
   RegionBindingsRef bindArray(RegionBindingsConstRef B,
   const TypedValueRegion* R,
   SVal V);
@@ -2392,6 +2408,40 @@
   return B.addBinding(R, BindingKey::Default, V);
 }
 
+Optional RegionStoreManager::tryBindSmallArray(
+RegionBindingsConstRef B, const TypedValueRegion *R, const ArrayType *AT,
+nonloc::LazyCompoundVal LCV) {
+
+  auto CAT = dyn_cast(AT);
+
+  // If we don't know the size, create a lazyCompoundVal instead.
+  if (!CAT)
+return None;
+
+  QualType Ty = CAT->getElementType();
+  if (!(Ty->isScalarType() || Ty->isReferenceType()))
+return None;
+
+  // If the array is too big, create a LCV instead.
+  uint64_t ArrSize = CAT->getSize().getLimitedValue();
+  if (ArrSize > SmallArrayLimit)
+return None;
+
+  RegionBindingsRef NewB = B;
+
+  for (uint64_t i = 0; i < ArrSize; ++i) {
+auto Idx = svalBuilder.makeArrayIndex(i);
+const ElementRegion *SrcER =
+MRMgr.getElementRegion(Ty, Idx, LCV.getRegion(), Ctx);
+SVal V = getBindingForElement(getRegionBindings(LCV.getStore()), SrcER);
+
+const ElementRegion *DstER = MRMgr.getElementRegion(Ty, Idx, R, Ctx);
+NewB = bind(NewB, loc::MemRegionVal(DstER), V);
+  }
+
+  return NewB;
+}
+
 RegionBindingsRef
 RegionStoreManager::bindArray(RegionBindingsConstRef B,
   const TypedValueRegion* R,
@@ -2413,8 +2463,13 @@
   }
 
   // Handle lazy compound values.
-  if (isa(Init))
+  if (Optional LCV =
+  Init.getAs()) {
+if (Optional NewB = tryBindSmallArray(B, R, AT, *LCV))
+  return *NewB;
+
 return bindAggregate(B, R, Init);
+  }
 
   if (Init.isUnknown())
 return bindAggregate(B, R, UnknownVal());
Index: clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
===

[PATCH] D127313: [libc++] Implement P0618R0 (Deprecating )

2022-06-17 Thread Nikolas Klauser via Phabricator via cfe-commits
philnik updated this revision to Diff 437951.
philnik added a comment.

- Try to fix CI


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D127313

Files:
  libcxx/docs/ReleaseNotes.rst
  libcxx/docs/Status/Cxx17Papers.csv
  libcxx/include/codecvt
  libcxx/include/locale
  libcxx/src/locale.cpp
  
libcxx/test/libcxx/localization/locales/locale.convenience/conversions/conversions.string/ctor_move.pass.cpp
  libcxx/test/std/localization/locale.stdcvt/codecvt_mode.pass.cpp
  libcxx/test/std/localization/locale.stdcvt/codecvt_utf16.pass.cpp
  
libcxx/test/std/localization/locale.stdcvt/codecvt_utf16_always_noconv.pass.cpp
  libcxx/test/std/localization/locale.stdcvt/codecvt_utf16_encoding.pass.cpp
  libcxx/test/std/localization/locale.stdcvt/codecvt_utf16_in.pass.cpp
  libcxx/test/std/localization/locale.stdcvt/codecvt_utf16_length.pass.cpp
  libcxx/test/std/localization/locale.stdcvt/codecvt_utf16_max_length.pass.cpp
  libcxx/test/std/localization/locale.stdcvt/codecvt_utf16_out.pass.cpp
  libcxx/test/std/localization/locale.stdcvt/codecvt_utf16_unshift.pass.cpp
  libcxx/test/std/localization/locale.stdcvt/codecvt_utf8.pass.cpp
  libcxx/test/std/localization/locale.stdcvt/codecvt_utf8_always_noconv.pass.cpp
  libcxx/test/std/localization/locale.stdcvt/codecvt_utf8_encoding.pass.cpp
  libcxx/test/std/localization/locale.stdcvt/codecvt_utf8_in.pass.cpp
  libcxx/test/std/localization/locale.stdcvt/codecvt_utf8_length.pass.cpp
  libcxx/test/std/localization/locale.stdcvt/codecvt_utf8_max_length.pass.cpp
  libcxx/test/std/localization/locale.stdcvt/codecvt_utf8_out.pass.cpp
  libcxx/test/std/localization/locale.stdcvt/codecvt_utf8_unshift.pass.cpp
  
libcxx/test/std/localization/locale.stdcvt/codecvt_utf8_utf16_always_noconv.pass.cpp
  
libcxx/test/std/localization/locale.stdcvt/codecvt_utf8_utf16_encoding.pass.cpp
  libcxx/test/std/localization/locale.stdcvt/codecvt_utf8_utf16_in.pass.cpp
  libcxx/test/std/localization/locale.stdcvt/codecvt_utf8_utf16_length.pass.cpp
  
libcxx/test/std/localization/locale.stdcvt/codecvt_utf8_utf16_max_length.pass.cpp
  libcxx/test/std/localization/locale.stdcvt/codecvt_utf8_utf16_out.pass.cpp
  libcxx/test/std/localization/locale.stdcvt/codecvt_utf8_utf16_unshift.pass.cpp
  libcxx/test/std/localization/locale.stdcvt/depr.verify.cpp
  
libcxx/test/std/localization/locales/locale.convenience/conversions/conversions.buffer/ctor.pass.cpp
  
libcxx/test/std/localization/locales/locale.convenience/conversions/conversions.buffer/depr.verify.cpp
  
libcxx/test/std/localization/locales/locale.convenience/conversions/conversions.buffer/overflow.pass.cpp
  
libcxx/test/std/localization/locales/locale.convenience/conversions/conversions.buffer/pbackfail.pass.cpp
  
libcxx/test/std/localization/locales/locale.convenience/conversions/conversions.buffer/rdbuf.pass.cpp
  
libcxx/test/std/localization/locales/locale.convenience/conversions/conversions.buffer/seekoff.pass.cpp
  
libcxx/test/std/localization/locales/locale.convenience/conversions/conversions.buffer/state.pass.cpp
  
libcxx/test/std/localization/locales/locale.convenience/conversions/conversions.buffer/test.pass.cpp
  
libcxx/test/std/localization/locales/locale.convenience/conversions/conversions.buffer/underflow.pass.cpp
  
libcxx/test/std/localization/locales/locale.convenience/conversions/conversions.string/converted.pass.cpp
  
libcxx/test/std/localization/locales/locale.convenience/conversions/conversions.string/ctor_codecvt.pass.cpp
  
libcxx/test/std/localization/locales/locale.convenience/conversions/conversions.string/ctor_codecvt_state.pass.cpp
  
libcxx/test/std/localization/locales/locale.convenience/conversions/conversions.string/ctor_copy.pass.cpp
  
libcxx/test/std/localization/locales/locale.convenience/conversions/conversions.string/ctor_err_string.pass.cpp
  
libcxx/test/std/localization/locales/locale.convenience/conversions/conversions.string/depr.verify.cpp
  
libcxx/test/std/localization/locales/locale.convenience/conversions/conversions.string/from_bytes.pass.cpp
  
libcxx/test/std/localization/locales/locale.convenience/conversions/conversions.string/state.pass.cpp
  
libcxx/test/std/localization/locales/locale.convenience/conversions/conversions.string/to_bytes.pass.cpp
  
libcxx/test/std/localization/locales/locale.convenience/conversions/conversions.string/types.pass.cpp
  libcxx/test/support/platform_support.h

Index: libcxx/test/support/platform_support.h
===
--- libcxx/test/support/platform_support.h
+++ libcxx/test/support/platform_support.h
@@ -14,6 +14,8 @@
 #ifndef PLATFORM_SUPPORT_H
 #define PLATFORM_SUPPORT_H
 
+#include "test_macros.h"
+
 // locale names
 #define LOCALE_en_US   "en_US"
 #define LOCALE_en_US_UTF_8 "en_US.UTF-8"
@@ -92,8 +94,11 @@
 inline
 std::wstring get_wide_temp_file_name()
 {
+TEST_DIAGNOSTIC_PUSH
+TEST_CLANG_DIAGNOSTIC_

[PATCH] D127509: Prefer `getCurrentFileOrBufferName` in `FrontendAction::EndSourceFile`

2022-06-17 Thread Yuki Okushi via Phabricator via cfe-commits
JohnTitor added a comment.

I've re-triggered it several times but it shows the same failure, maybe they're 
valid?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D127509

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


[PATCH] D127898: [clang][dataflow] Find unsafe locs after fixpoint

2022-06-17 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun added inline comments.



Comment at: 
clang-tools-extra/clang-tidy/bugprone/UncheckedOptionalAccessCheck.cpp:66
+  SourceLocations Locs;
+  for (const CFGBlock *Block : Context->getCFG()) {
+// Skip blocks that were not evaluated.

While doing yet another iteration after we reached the fixed point is a valid 
approach, many analyses have a monotonic property when it comes to emitting 
diagnostics. In this case, when the analysis discovered that an optional access 
is unsafe in one of the iterations I would not expect it to become safe in 
subsequent iterations. In most of the cases this makes collecting diagnostics 
eagerly a viable option and saves us from doing one more traversal of the CFG. 
On the other hand, we need to be careful to not to emit duplicate diagnostics.

I wonder whether, from a user point of view, not having to do one more 
iteration is a more ergonomic interface. 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D127898

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


[PATCH] D127873: [clang-format] Fix misplacemnt of `*` in declaration of pointer to struct

2022-06-17 Thread Jack Huang via Phabricator via cfe-commits
jackhong12 added inline comments.



Comment at: clang/lib/Format/TokenAnnotator.cpp:2314-2315
+if (PrevToken->is(tok::r_brace) && Tok.isOneOf(tok::amp, tok::ampamp) &&
+PrevToken->MatchingParen && PrevToken->MatchingParen->is(TT_Unknown))
+  return TT_BinaryOperator;
+

HazardyKnusperkeks wrote:
> Unknown is everything, until some type is assigned. This way it should be 
> clearer.
> 
> Also put that check above the other one and add the `r_brace` back.
There are other problems. Clang-format will split the input into multiple lines 
first. For instance, `struct {\n int n;\n} &&ptr={};` will be separated as 
`struct {`, `int n;` and `} &&ptr={};`. It only handles the relation in the 
line. When declaring a struct variable, the value of `MatchingParen` will 
always be NULL instead of pointing to the last left brace. So it will not enter 
that branch in this case.


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

https://reviews.llvm.org/D127873

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


[PATCH] D126973: [clang][dataflow] Relax assumption that `AggregateStorageLocations` correspond to struct type.

2022-06-17 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun added a comment.
Herald added a subscriber: martong.

With properties moved up in the hierarchy this could be abandoned now, right?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126973

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


[PATCH] D126973: [clang][dataflow] Relax assumption that `AggregateStorageLocations` correspond to struct type.

2022-06-17 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel abandoned this revision.
ymandel added a comment.

In D126973#3592537 , @xazax.hun wrote:

> With properties moved up in the hierarchy this could be abandoned now, right?

Yes, I think that would be best. Thanks for the reminder!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126973

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


[PATCH] D127873: [clang-format] Fix misplacemnt of `*` in declaration of pointer to struct

2022-06-17 Thread Jack Huang via Phabricator via cfe-commits
jackhong12 added inline comments.



Comment at: clang/lib/Format/TokenAnnotator.cpp:2314-2315
+if (PrevToken->is(tok::r_brace) && Tok.isOneOf(tok::amp, tok::ampamp) &&
+PrevToken->MatchingParen && PrevToken->MatchingParen->is(TT_Unknown))
+  return TT_BinaryOperator;
+

jackhong12 wrote:
> HazardyKnusperkeks wrote:
> > Unknown is everything, until some type is assigned. This way it should be 
> > clearer.
> > 
> > Also put that check above the other one and add the `r_brace` back.
> There are other problems. Clang-format will split the input into multiple 
> lines first. For instance, `struct {\n int n;\n} &&ptr={};` will be separated 
> as `struct {`, `int n;` and `} &&ptr={};`. It only handles the relation in 
> the line. When declaring a struct variable, the value of `MatchingParen` will 
> always be NULL instead of pointing to the last left brace. So it will not 
> enter that branch in this case.
```
if (PrevToken->is(tok::r_brace) && Tok.isOneOf(tok::amp, tok::ampamp) &&
PrevToken->MatchingParen) {
  if (PrevToken->MatchingParen->is(TT_RecordLBrace))
return TT_PointerOrReference;
  else
return TT_BinaryOperator;
}
```
How about this way? Although the branch of TT_PointerOrReference will not be 
taken, it's clearer for reading.


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

https://reviews.llvm.org/D127873

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


[PATCH] D128072: [clang-tidy] Organize test files into subdirectories by module (NFC)

2022-06-17 Thread Richard via Phabricator via cfe-commits
LegalizeAdulthood created this revision.
LegalizeAdulthood added reviewers: njames93, aaron.ballman.
LegalizeAdulthood added a project: clang-tools-extra.
Herald added subscribers: bzcheeseman, carlosgalvezp, abrachet, lebedev.ri, 
jdoerfert, arphaman, zzheng, kbarton, xazax.hun, nemanjai.
Herald added a reviewer: lebedev.ri.
Herald added a reviewer: lebedev.ri.
Herald added a project: All.
LegalizeAdulthood requested review of this revision.
Herald added a subscriber: aheejin.

Eliminate clutter by reorganizing the Lit test files for clang-tidy:

- Move checkers/-* to checkers//*.
- Move module specific inputs from Inputs to /Inputs.  Remove any 
module prefix from the file or subdirectory name as they are no longer needed.
- Introduce a Lit substitution %clang_tidy_headers for the system headers in 
checkers/Inputs/Headers and use this throughout.  This avoids referencing 
system headers through a relative path to the parent directory and makes it 
clear that these fake system headers are shared among all modules.
- Update add_new_check.py to follow the above conventions when creating the 
boiler plate test files for a new check.
- Update Contributing.rst to describe per-module Inputs directory and fix link 
to test source code.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D128072

Files:
  clang-tools-extra/clang-tidy/add_new_check.py
  clang-tools-extra/docs/clang-tidy/Contributing.rst
  clang-tools-extra/test/clang-tidy/checkers/Inputs/absl/external-file.h
  clang-tools-extra/test/clang-tidy/checkers/Inputs/absl/flags/internal-file.h
  clang-tools-extra/test/clang-tidy/checkers/Inputs/absl/strings/internal-file.h
  clang-tools-extra/test/clang-tidy/checkers/Inputs/absl/time/time.h
  clang-tools-extra/test/clang-tidy/checkers/Inputs/absl/types/optional.h
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/altera-kernel-name-restriction/Verilog.cl
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/altera-kernel-name-restriction/kernel.cl
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/altera-kernel-name-restriction/kernel.h
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/altera-kernel-name-restriction/other_Verilog.cl
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/altera-kernel-name-restriction/otherdir/vhdl.cl
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/altera-kernel-name-restriction/otherthing.cl
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/altera-kernel-name-restriction/some/dir/kernel.cl
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/altera-kernel-name-restriction/some/kernel.cl/foo.h
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/altera-kernel-name-restriction/some/verilog.cl/foo.h
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/altera-kernel-name-restriction/some/vhdl.cl/foo.h
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/altera-kernel-name-restriction/some_kernel.cl
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/altera-kernel-name-restriction/somedir/verilog.cl
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/altera-kernel-name-restriction/thing.h
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/altera-kernel-name-restriction/uppercase/KERNEL.cl
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/altera-kernel-name-restriction/uppercase/VHDL.cl
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/altera-kernel-name-restriction/uppercase/vERILOG.cl
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/altera-kernel-name-restriction/verilog.h
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/altera-kernel-name-restriction/vhdl.CL
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/altera-kernel-name-restriction/vhdl.h
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/altera-kernel-name-restriction/vhdl_number_two.cl
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/bugprone-argument-comment/header-with-decl.h
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/bugprone-argument-comment/system-header-with-decl.h
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/bugprone-not-null-terminated-result/not-null-terminated-result-c.h
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/bugprone-not-null-terminated-result/not-null-terminated-result-cxx.h
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/bugprone-reserved-identifier/system/system-header.h
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/bugprone-reserved-identifier/user-header.h
  clang-tools-extra/test/clang-tidy/checkers/Inputs/google-namespaces.h
  clang-tools-extra/test/clang-tidy/checkers/Inputs/gtest/gtest-typed-test.h
  clang-tools-extra/test/clang-tidy/checkers/Inputs/gtest/gtest.h
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/gtest/nosuite/gtest/gtest-typed-test.h
  clang-tools-extra/test/clang-tidy/checkers/Inputs/gtest/nosuite/gtest/gtest.h
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/llvmlibc/resource/include/stdatomic.h
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/llvmlibc/resource/include/st

[PATCH] D113107: Support of expression granularity for _Float16.

2022-06-17 Thread Zahira Ammarguellat via Phabricator via cfe-commits
zahiraam marked 2 inline comments as done.
zahiraam added inline comments.



Comment at: clang/lib/CodeGen/CGExprComplex.cpp:896
+
+ComplexPairTy ComplexExprEmitter::EmitPromoted(const Expr *E) {
+  if (auto *BinOp = dyn_cast(E->IgnoreParens())) {

rjmccall wrote:
> `EmitPromoted` should take the promotion type.
> 
> You are missing the logic in this file which handles *unpromoted* emission 
> (where you have a binary operator but the context wants an unpromoted value) 
> by recognizing that you need to do a promoted operation and then truncate.
Sorry but not sure what you mean here. A case where we don't want any promotion 
would be:

float _Complex add(float _Complex a, float _Complex b) {
  return a + b;
}

In this case, getPromotionType would return the null type and EmitBinOps would 
just go through the  "older" control path where there is no promotion.
Unless I misunderstood your comment?




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

https://reviews.llvm.org/D113107

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


[PATCH] D127270: [clang-format] Add space in placement new expression

2022-06-17 Thread omar ahmed via Phabricator via cfe-commits
omarahmed updated this revision to Diff 437966.
omarahmed marked an inline comment as not done.
omarahmed added a comment.

Refactor the tests and add new parsing logic for nested enums in 
dump_format_style.py


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D127270

Files:
  clang/docs/ClangFormatStyleOptions.rst
  clang/docs/tools/dump_format_style.py
  clang/include/clang/Format/Format.h
  clang/lib/Format/Format.cpp
  clang/lib/Format/TokenAnnotator.cpp
  clang/unittests/Format/FormatTest.cpp

Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -10130,6 +10130,42 @@
 "void delete(link p);\n",
 format("void new (link p);\n"
"void delete (link p);\n"));
+
+  FormatStyle AfterPlacementOperator = getLLVMStyle();
+  AfterPlacementOperator.SpaceBeforeParens = FormatStyle::SBPO_Custom;
+  EXPECT_EQ(
+  AfterPlacementOperator.SpaceBeforeParensOptions.AfterPlacementOperator,
+  FormatStyle::SpaceBeforeParensCustom::APO_Never);
+  verifyFormat("struct A {\n"
+   "  void *a;\n"
+   "  A(void *p) : a(new(p) int) {\n"
+   "new(p) int;\n"
+   "int *b = new(p) int;\n"
+   "int *c = new(p) int(3);\n"
+   "int *d = delete(p) int(3);\n"
+   "  }\n"
+   "};",
+   AfterPlacementOperator);
+  verifyFormat("void operator new(void *foo) ATTRIB;", AfterPlacementOperator);
+
+  AfterPlacementOperator.SpaceBeforeParensOptions.AfterPlacementOperator =
+  FormatStyle::SpaceBeforeParensCustom::APO_Always;
+  verifyFormat("struct A {\n"
+   "  void *a;\n"
+   "  A(void *p) : a(new (p) int) {\n"
+   "new (p) int;\n"
+   "int *b = new (p) int;\n"
+   "int *c = new (p) int(3);\n"
+   "int *d = delete (p) int(3);\n"
+   "  }\n"
+   "};",
+   AfterPlacementOperator);
+  verifyFormat("void operator new(void *foo) ATTRIB;", AfterPlacementOperator);
+
+  AfterPlacementOperator.SpaceBeforeParensOptions.AfterPlacementOperator =
+  FormatStyle::SpaceBeforeParensCustom::APO_Leave;
+  EXPECT_EQ("new (buf) int;", format("new (buf) int;", AfterPlacementOperator));
+  EXPECT_EQ("new(buf) int;", format("new(buf) int;", AfterPlacementOperator));
 }
 
 TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -3393,6 +3393,18 @@
 if (Left.is(TT_IfMacro))
   return Style.SpaceBeforeParensOptions.AfterIfMacros ||
  spaceRequiredBeforeParens(Right);
+if (Style.SpaceBeforeParens == FormatStyle::SBPO_Custom &&
+Left.isOneOf(tok::kw_new, tok::kw_delete) &&
+Right.isNot(TT_OverloadedOperatorLParen) &&
+!(Line.MightBeFunctionDecl && Left.is(TT_FunctionDeclarationName))) {
+  if (Style.SpaceBeforeParensOptions.AfterPlacementOperator ==
+  FormatStyle::SpaceBeforeParensCustom::APO_Always ||
+  (Style.SpaceBeforeParensOptions.AfterPlacementOperator ==
+   FormatStyle::SpaceBeforeParensCustom::APO_Leave &&
+   Right.hasWhitespaceBefore()))
+return true;
+  return false;
+}
 if (Line.Type == LT_ObjCDecl)
   return true;
 if (Left.is(tok::semi))
Index: clang/lib/Format/Format.cpp
===
--- clang/lib/Format/Format.cpp
+++ clang/lib/Format/Format.cpp
@@ -936,6 +936,7 @@
Spacing.AfterFunctionDeclarationName);
 IO.mapOptional("AfterIfMacros", Spacing.AfterIfMacros);
 IO.mapOptional("AfterOverloadedOperator", Spacing.AfterOverloadedOperator);
+IO.mapOptional("AfterPlacementOperator", Spacing.AfterPlacementOperator);
 IO.mapOptional("AfterRequiresInClause", Spacing.AfterRequiresInClause);
 IO.mapOptional("AfterRequiresInExpression",
Spacing.AfterRequiresInExpression);
@@ -944,6 +945,22 @@
   }
 };
 
+template <>
+struct MappingTraits<
+FormatStyle::SpaceBeforeParensCustom::AfterPlacementOperatorStyle> {
+  static void
+  mapping(IO &IO,
+  FormatStyle::SpaceBeforeParensCustom::AfterPlacementOperatorStyle
+  &Value) {
+IO.enumCase(Value, "Always",
+FormatStyle::SpaceBeforeParensCustom::APO_Always);
+IO.enumCase(Value, "Never",
+FormatStyle::SpaceBeforeParensCustom::APO_Never);
+IO.enumCase(Value, "Leave",
+FormatStyle::SpaceBeforeParensCustom::APO_Leave);
+  }
+};
+
 template <> struct MappingTraits {
   static void mapping(IO &IO, Format

[PATCH] D127270: [clang-format] Add space in placement new expression

2022-06-17 Thread omar ahmed via Phabricator via cfe-commits
omarahmed added a comment.

As I understand, the default behavior for when the user didn't use 
`SBPO_Custom` is to add a space in placement operators based on this issue 
. And, at the same time, the 
default behavior should be `APO_Never` when we have `SBPO_Custom` so that we 
handle other code that depends on that. the existing tests confirm this 
understanding. So, the current logic was added based on this understanding.




Comment at: clang/lib/Format/TokenAnnotator.cpp:3396
  spaceRequiredBeforeParens(Right);
+if (Style.SpaceBeforeParens == FormatStyle::SBPO_Custom &&
+Left.isOneOf(tok::kw_new, tok::kw_delete) &&

MyDeveloperDay wrote:
> shouldn't the very first part of this be? 
> 
> 
> ```
> if (Style.SpaceBeforeParensOptions.AfterPlacementOperator != 
> FormatStyle::SpaceBeforeParensCustom::APO_Leave)
> {
> 
> 
> 
> }
> ```
> 
> i.e. don't we want a zero change if someone says "Leave"
The current code logic, when we do not enter this suggested condition, will 
switch to [this 
condition](https://github.com/llvm/llvm-project/blob/c2bb2e5973acd24c45c1823e95e8e33003c59484/clang/lib/Format/TokenAnnotator.cpp#L3580).
 And will not leave the code as it is, but will change it.

I have thought of getting rid of this condition entirely, but it handles the 
default situation suggested here, not only for cpp but for other languages like 
js:
>>As I understand, the default behavior for when the user didn't use 
>>`SBPO_Custom` is to add a space in placement operators based on [this 
>>issue](https://github.com/llvm/llvm-project/issues/54703). And, at the same 
>>time, the default behavior should be `APO_Never` when we have `SBPO_Custom` 
>>so that we handle other code that depends on that. the existing tests confirm 
>>this understanding. So, the current logic was added based on this 
>>understanding.

I tried to add an extra condition to [this 
condition](https://github.com/llvm/llvm-project/blob/c2bb2e5973acd24c45c1823e95e8e33003c59484/clang/lib/Format/TokenAnnotator.cpp#L3580)
 to support the main logic that we are pursuing. so that it would be like that:
```
if (Style.SpaceBeforeParensOptions.AfterPlacementOperator != 
FormatStyle::SpaceBeforeParensCustom::APO_Leave && Left.isOneOf(tok::kw_new, 
tok::kw_delete))
```
But that wouldn't fix the leave situation, as it will be also at the end, reach 
[this 
part](https://github.com/llvm/llvm-project/blob/c2bb2e5973acd24c45c1823e95e8e33003c59484/clang/lib/Format/TokenAnnotator.cpp#L3598)
 which will  
```
return false
``` 
and force no space.

I think all of that was raised because all current 
"SpaceBeforeParanthesesOptions" are either true or false and this is the only 
enum

However, I completely agree with this logic which is to begin our checking for 
leave. But I think we should refactor all the "spaceBeforeParenthesesOptions" 
conditions to handle this and do that after all the options have been 
transformed to enums.



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D127270

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


[PATCH] D127277: [clang][analyzer] Fix StdLibraryFunctionsChecker 'mkdir' return value.

2022-06-17 Thread Balázs Benics via Phabricator via cfe-commits
steakhal accepted this revision.
steakhal added a comment.

It feels like the parent revision is not correct.
Land it.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D127277

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


[clang] ba53906 - [clang][dataflow] Add support for comma binary operator

2022-06-17 Thread Stanislav Gatev via cfe-commits

Author: Stanislav Gatev
Date: 2022-06-17T17:48:21Z
New Revision: ba53906ceff1e7979cac37ff6fdc27e976fc169a

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

LOG: [clang][dataflow] Add support for comma binary operator

Add support for comma binary operator.

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

Reviewed-by: ymandel, xazax.hun

Added: 


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

Removed: 




diff  --git a/clang/lib/Analysis/FlowSensitive/Transfer.cpp 
b/clang/lib/Analysis/FlowSensitive/Transfer.cpp
index a56e277f7962f..befd3c6263114 100644
--- a/clang/lib/Analysis/FlowSensitive/Transfer.cpp
+++ b/clang/lib/Analysis/FlowSensitive/Transfer.cpp
@@ -95,6 +95,11 @@ class TransferVisitor : public 
ConstStmtVisitor {
 : Env.makeNot(LHSEqRHSValue));
   break;
 }
+case BO_Comma: {
+  if (auto *Loc = Env.getStorageLocation(*RHS, SkipPast::None))
+Env.setStorageLocation(*S, *Loc);
+  break;
+}
 default:
   break;
 }

diff  --git a/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp 
b/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
index e3c97367b17ca..ab51bf2196b79 100644
--- a/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
+++ b/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
@@ -3557,4 +3557,35 @@ TEST_F(TransferTest, 
StructuredBindingAssignFromStructIntMembersToInts) {
   });
 }
 
+TEST_F(TransferTest, BinaryOperatorComma) {
+  std::string Code = R"(
+void target(int Foo, int Bar) {
+  int &Baz = (Foo, Bar);
+  // [[p]]
+}
+  )";
+  runDataflow(Code,
+  [](llvm::ArrayRef<
+ std::pair>>
+ Results,
+ ASTContext &ASTCtx) {
+ASSERT_THAT(Results, ElementsAre(Pair("p", _)));
+const Environment &Env = Results[0].second.Env;
+
+const ValueDecl *BarDecl = findValueDecl(ASTCtx, "Bar");
+ASSERT_THAT(BarDecl, NotNull());
+
+const ValueDecl *BazDecl = findValueDecl(ASTCtx, "Baz");
+ASSERT_THAT(BazDecl, NotNull());
+
+const StorageLocation *BarLoc =
+Env.getStorageLocation(*BarDecl, SkipPast::Reference);
+ASSERT_THAT(BarLoc, NotNull());
+
+const StorageLocation *BazLoc =
+Env.getStorageLocation(*BazDecl, SkipPast::Reference);
+EXPECT_EQ(BazLoc, BarLoc);
+  });
+}
+
 } // namespace



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


[PATCH] D128013: [clang][dataflow] Add support for comma binary operator

2022-06-17 Thread Stanislav Gatev 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 rGba53906ceff1: [clang][dataflow] Add support for comma binary 
operator (authored by sgatev).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128013

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


Index: clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
@@ -3557,4 +3557,35 @@
   });
 }
 
+TEST_F(TransferTest, BinaryOperatorComma) {
+  std::string Code = R"(
+void target(int Foo, int Bar) {
+  int &Baz = (Foo, Bar);
+  // [[p]]
+}
+  )";
+  runDataflow(Code,
+  [](llvm::ArrayRef<
+ std::pair>>
+ Results,
+ ASTContext &ASTCtx) {
+ASSERT_THAT(Results, ElementsAre(Pair("p", _)));
+const Environment &Env = Results[0].second.Env;
+
+const ValueDecl *BarDecl = findValueDecl(ASTCtx, "Bar");
+ASSERT_THAT(BarDecl, NotNull());
+
+const ValueDecl *BazDecl = findValueDecl(ASTCtx, "Baz");
+ASSERT_THAT(BazDecl, NotNull());
+
+const StorageLocation *BarLoc =
+Env.getStorageLocation(*BarDecl, SkipPast::Reference);
+ASSERT_THAT(BarLoc, NotNull());
+
+const StorageLocation *BazLoc =
+Env.getStorageLocation(*BazDecl, SkipPast::Reference);
+EXPECT_EQ(BazLoc, BarLoc);
+  });
+}
+
 } // namespace
Index: clang/lib/Analysis/FlowSensitive/Transfer.cpp
===
--- clang/lib/Analysis/FlowSensitive/Transfer.cpp
+++ clang/lib/Analysis/FlowSensitive/Transfer.cpp
@@ -95,6 +95,11 @@
 : Env.makeNot(LHSEqRHSValue));
   break;
 }
+case BO_Comma: {
+  if (auto *Loc = Env.getStorageLocation(*RHS, SkipPast::None))
+Env.setStorageLocation(*S, *Loc);
+  break;
+}
 default:
   break;
 }


Index: clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
@@ -3557,4 +3557,35 @@
   });
 }
 
+TEST_F(TransferTest, BinaryOperatorComma) {
+  std::string Code = R"(
+void target(int Foo, int Bar) {
+  int &Baz = (Foo, Bar);
+  // [[p]]
+}
+  )";
+  runDataflow(Code,
+  [](llvm::ArrayRef<
+ std::pair>>
+ Results,
+ ASTContext &ASTCtx) {
+ASSERT_THAT(Results, ElementsAre(Pair("p", _)));
+const Environment &Env = Results[0].second.Env;
+
+const ValueDecl *BarDecl = findValueDecl(ASTCtx, "Bar");
+ASSERT_THAT(BarDecl, NotNull());
+
+const ValueDecl *BazDecl = findValueDecl(ASTCtx, "Baz");
+ASSERT_THAT(BazDecl, NotNull());
+
+const StorageLocation *BarLoc =
+Env.getStorageLocation(*BarDecl, SkipPast::Reference);
+ASSERT_THAT(BarLoc, NotNull());
+
+const StorageLocation *BazLoc =
+Env.getStorageLocation(*BazDecl, SkipPast::Reference);
+EXPECT_EQ(BazLoc, BarLoc);
+  });
+}
+
 } // namespace
Index: clang/lib/Analysis/FlowSensitive/Transfer.cpp
===
--- clang/lib/Analysis/FlowSensitive/Transfer.cpp
+++ clang/lib/Analysis/FlowSensitive/Transfer.cpp
@@ -95,6 +95,11 @@
 : Env.makeNot(LHSEqRHSValue));
   break;
 }
+case BO_Comma: {
+  if (auto *Loc = Env.getStorageLocation(*RHS, SkipPast::None))
+Env.setStorageLocation(*S, *Loc);
+  break;
+}
 default:
   break;
 }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D128048: Add a new clang option "-ftime-trace-path"

2022-06-17 Thread Jamie Schmeiser via Phabricator via cfe-commits
jamieschmeiser requested changes to this revision.
jamieschmeiser added a comment.
This revision now requires changes to proceed.

This is a good start.  You should mention in the summary that when -c is not 
specified, the compiler is invoked with -o pointing at /tmp so the .json file 
will currently be placed there, which is confusing.




Comment at: clang/include/clang/Driver/Options.td:2832
+def ftime_trace_path : Joined<["-"], "ftime-trace-path=">, Group,
+  HelpText<"Path which stores the output files of time profiler">,
+  Flags<[CC1Option, CoreOption]>,

which specifies the output files for -ftime-trace



Comment at: clang/tools/driver/cc1_main.cpp:259
+
Path.append(llvm::sys::path::filename(Clang->getFrontendOpts().OutputFile));
+Path.append(".json");
 if (auto profilerOutput = Clang->createOutputFile(

What happens if the path specified does not exist?  This needs to be handled 
(if it isn't) and needs a lit test for this situation also.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128048

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


[clang] e77ac66 - [Static Analyzer] Structured binding to data members

2022-06-17 Thread via cfe-commits

Author: isuckatcs
Date: 2022-06-17T19:50:10+02:00
New Revision: e77ac66b8c1cf4f09f931d37749ed258f122d708

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

LOG: [Static Analyzer] Structured binding to data members

Introducing structured binding to data members.

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

Added: 
clang/test/Analysis/uninit-structured-binding-struct.cpp

Modified: 
clang/lib/StaticAnalyzer/Core/ExprEngine.cpp

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp 
b/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
index a0c7dda896ef2..6ba19d52488c7 100644
--- a/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
+++ b/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
@@ -2591,9 +2591,22 @@ void ExprEngine::VisitCommonDeclRefExpr(const Expr *Ex, 
const NamedDecl *D,
 // operator&.
 return;
   }
-  if (isa(D)) {
-// FIXME: proper support for bound declarations.
-// For now, let's just prevent crashing.
+  if (const auto *BD = dyn_cast(D)) {
+const auto *DD = cast(BD->getDecomposedDecl());
+
+if (const auto *ME = dyn_cast(BD->getBinding())) {
+  const auto *Field = cast(ME->getMemberDecl());
+
+  SVal Base = state->getLValue(DD, LCtx);
+  if (DD->getType()->isReferenceType()) {
+Base = state->getSVal(Base.getAsRegion());
+  }
+
+  SVal V = state->getLValue(Field, Base);
+
+  Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V));
+}
+
 return;
   }
 

diff  --git a/clang/test/Analysis/uninit-structured-binding-struct.cpp 
b/clang/test/Analysis/uninit-structured-binding-struct.cpp
new file mode 100644
index 0..fec82c0d8589d
--- /dev/null
+++ b/clang/test/Analysis/uninit-structured-binding-struct.cpp
@@ -0,0 +1,116 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.ExprInspection 
-std=c++17 -verify %s
+
+void clang_analyzer_eval(bool);
+
+struct s {
+  int a;
+  int b;
+};
+
+void a(void) {
+  s tst;
+
+  auto [i, j] = tst;
+
+  int x = i; // expected-warning{{Assigned value is garbage or undefined}}
+}
+
+void b(void) {
+  s tst;
+  tst.a = 1;
+
+  auto [i, j] = tst;
+
+  clang_analyzer_eval(i == 1); // expected-warning{{TRUE}}
+  int y = j;   // expected-warning{{Assigned value is garbage 
or undefined}}
+}
+
+void c(void) {
+  s tst;
+
+  auto &[i, j] = tst;
+
+  int x = i; // expected-warning{{Assigned value is garbage or undefined}}
+}
+
+void d(void) {
+  s tst;
+  tst.a = 1;
+
+  auto &[i, j] = tst;
+
+  clang_analyzer_eval(i == 1); // expected-warning{{TRUE}}
+  i = 2;
+  clang_analyzer_eval(tst.a == 2); // expected-warning{{TRUE}}
+
+  int y = j; // expected-warning{{Assigned value is garbage or undefined}}
+}
+
+void e(void) {
+  s tst;
+  tst.a = 1;
+
+  auto &[i, j] = tst;
+
+  clang_analyzer_eval(i == 1); // expected-warning{{TRUE}}
+
+  tst.b = 2;
+  clang_analyzer_eval(j == 2); // expected-warning{{TRUE}}
+}
+
+void f(void) {
+  s tst;
+
+  auto &&[i, j] = tst;
+
+  int x = i; // expected-warning{{Assigned value is garbage or undefined}}
+}
+
+void g(void) {
+  s tst;
+  tst.a = 1;
+
+  auto &&[i, j] = tst;
+
+  clang_analyzer_eval(i == 1); // expected-warning{{TRUE}}
+  int y = j;   // expected-warning{{Assigned value is garbage 
or undefined}}
+}
+
+struct s2 {
+  int a = 1;
+  int b = 2;
+};
+
+struct s3 {
+  s x;
+  s2 y;
+};
+
+void h(void) {
+  s3 tst;
+
+  clang_analyzer_eval(tst.y.a == 1); // expected-warning{{TRUE}}
+
+  auto [i, j] = tst;
+
+  // FIXME: These should be undefined, but we have to fix
+  // reading undefined from lazy compound values first.
+  clang_analyzer_eval(i.a); // expected-warning{{UNKNOWN}}
+  clang_analyzer_eval(i.b); // expected-warning{{UNKNOWN}}
+
+  clang_analyzer_eval(j.a == 1); // expected-warning{{TRUE}}
+  clang_analyzer_eval(j.b == 2); // expected-warning{{TRUE}}
+}
+
+void i(void) {
+  s3 tst;
+
+  clang_analyzer_eval(tst.y.a == 1); // expected-warning{{TRUE}}
+
+  auto &[i, j] = tst;
+  j.a = 3;
+
+  clang_analyzer_eval(tst.y.a == 3); // expected-warning{{TRUE}}
+  clang_analyzer_eval(tst.y.b == 2); // expected-warning{{TRUE}}
+  clang_analyzer_eval(j.b == 2); // expected-warning{{TRUE}}
+}



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


[PATCH] D127643: [Static Analyzer] Structured bindings to data members

2022-06-17 Thread Domján Dániel 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 rGe77ac66b8c1c: [Static Analyzer] Structured binding to data 
members (authored by isuckatcs).
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D127643

Files:
  clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
  clang/test/Analysis/uninit-structured-binding-struct.cpp

Index: clang/test/Analysis/uninit-structured-binding-struct.cpp
===
--- /dev/null
+++ clang/test/Analysis/uninit-structured-binding-struct.cpp
@@ -0,0 +1,116 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.ExprInspection -std=c++17 -verify %s
+
+void clang_analyzer_eval(bool);
+
+struct s {
+  int a;
+  int b;
+};
+
+void a(void) {
+  s tst;
+
+  auto [i, j] = tst;
+
+  int x = i; // expected-warning{{Assigned value is garbage or undefined}}
+}
+
+void b(void) {
+  s tst;
+  tst.a = 1;
+
+  auto [i, j] = tst;
+
+  clang_analyzer_eval(i == 1); // expected-warning{{TRUE}}
+  int y = j;   // expected-warning{{Assigned value is garbage or undefined}}
+}
+
+void c(void) {
+  s tst;
+
+  auto &[i, j] = tst;
+
+  int x = i; // expected-warning{{Assigned value is garbage or undefined}}
+}
+
+void d(void) {
+  s tst;
+  tst.a = 1;
+
+  auto &[i, j] = tst;
+
+  clang_analyzer_eval(i == 1); // expected-warning{{TRUE}}
+  i = 2;
+  clang_analyzer_eval(tst.a == 2); // expected-warning{{TRUE}}
+
+  int y = j; // expected-warning{{Assigned value is garbage or undefined}}
+}
+
+void e(void) {
+  s tst;
+  tst.a = 1;
+
+  auto &[i, j] = tst;
+
+  clang_analyzer_eval(i == 1); // expected-warning{{TRUE}}
+
+  tst.b = 2;
+  clang_analyzer_eval(j == 2); // expected-warning{{TRUE}}
+}
+
+void f(void) {
+  s tst;
+
+  auto &&[i, j] = tst;
+
+  int x = i; // expected-warning{{Assigned value is garbage or undefined}}
+}
+
+void g(void) {
+  s tst;
+  tst.a = 1;
+
+  auto &&[i, j] = tst;
+
+  clang_analyzer_eval(i == 1); // expected-warning{{TRUE}}
+  int y = j;   // expected-warning{{Assigned value is garbage or undefined}}
+}
+
+struct s2 {
+  int a = 1;
+  int b = 2;
+};
+
+struct s3 {
+  s x;
+  s2 y;
+};
+
+void h(void) {
+  s3 tst;
+
+  clang_analyzer_eval(tst.y.a == 1); // expected-warning{{TRUE}}
+
+  auto [i, j] = tst;
+
+  // FIXME: These should be undefined, but we have to fix
+  // reading undefined from lazy compound values first.
+  clang_analyzer_eval(i.a); // expected-warning{{UNKNOWN}}
+  clang_analyzer_eval(i.b); // expected-warning{{UNKNOWN}}
+
+  clang_analyzer_eval(j.a == 1); // expected-warning{{TRUE}}
+  clang_analyzer_eval(j.b == 2); // expected-warning{{TRUE}}
+}
+
+void i(void) {
+  s3 tst;
+
+  clang_analyzer_eval(tst.y.a == 1); // expected-warning{{TRUE}}
+
+  auto &[i, j] = tst;
+  j.a = 3;
+
+  clang_analyzer_eval(tst.y.a == 3); // expected-warning{{TRUE}}
+  clang_analyzer_eval(tst.y.b == 2); // expected-warning{{TRUE}}
+  clang_analyzer_eval(j.b == 2); // expected-warning{{TRUE}}
+}
Index: clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
===
--- clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
+++ clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
@@ -2591,9 +2591,22 @@
 // operator&.
 return;
   }
-  if (isa(D)) {
-// FIXME: proper support for bound declarations.
-// For now, let's just prevent crashing.
+  if (const auto *BD = dyn_cast(D)) {
+const auto *DD = cast(BD->getDecomposedDecl());
+
+if (const auto *ME = dyn_cast(BD->getBinding())) {
+  const auto *Field = cast(ME->getMemberDecl());
+
+  SVal Base = state->getLValue(DD, LCtx);
+  if (DD->getType()->isReferenceType()) {
+Base = state->getSVal(Base.getAsRegion());
+  }
+
+  SVal V = state->getLValue(Field, Base);
+
+  Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V));
+}
+
 return;
   }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D127923: [Diagnostics] Accept newline and format diag opts on first line

2022-06-17 Thread Scott Linder via Phabricator via cfe-commits
scott.linder added a comment.

Thank you for the patch! I will leave it to others with more knowledge of the 
history of diagnostics to comment on whether the premise is acceptable, but I 
have a few technical comments




Comment at: clang/lib/Frontend/TextDiagnosticPrinter.cpp:119-135
+  // If the diagnostic message is formatted into multiple lines, split the
+  // first line and feed it into printDiagnosticOptions so that we print the
+  // options only on the first line instead of the last line.
+  SmallString<100> InitStr;
+  size_t NewlinePos = OutStr.find_first_of('\n');
+  if (NewlinePos != StringRef::npos) {
+for (size_t I = 0; I != NewlinePos; ++I)

Nit: I'd remove the `if`s and just use the behavior of `slice(npos, ...)` 
returning the empty string

I also would reword "split the first line and feed it into 
printDiagnosticOptions", as it could be interpreted as meaning the first line 
is an input to `printDiagnosticOptions`



Comment at: clang/lib/StaticAnalyzer/Core/TextDiagnostics.cpp:99-103
+  size_t NewlinePos = PD->getShortDescription().find_first_of('\n');
+  if (NewlinePos != std::string::npos)
+OutStr = PD->getShortDescription().str().insert(NewlinePos, 
WarningMsg);
+  else
+OutStr = (PD->getShortDescription() + WarningMsg).str();

It's frustrating that `std::string::insert` doesn't follow the pattern of 
`npos==end-of-string`, but I'd still suggest only doing the actual 
insert/append once



Comment at: clang/lib/StaticAnalyzer/Core/TextDiagnostics.cpp:100
+  size_t NewlinePos = PD->getShortDescription().find_first_of('\n');
+  if (NewlinePos != std::string::npos)
+OutStr = PD->getShortDescription().str().insert(NewlinePos, 
WarningMsg);

I believe they are guaranteed to be equivalent, but this should be 
`StringRef::npos` or you should allocate the `std::string` sooner



Comment at: clang/lib/StaticAnalyzer/Core/TextDiagnostics.cpp:101
+  if (NewlinePos != std::string::npos)
+OutStr = PD->getShortDescription().str().insert(NewlinePos, 
WarningMsg);
+  else

I think you incur an extra copy assignment here, as the `insert` returns an 
lvalue-reference


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D127923

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


[PATCH] D127923: [Diagnostics] Accept newline and format diag opts on first line

2022-06-17 Thread Scott Linder via Phabricator via cfe-commits
scott.linder added inline comments.



Comment at: clang/lib/StaticAnalyzer/Core/TextDiagnostics.cpp:99-103
+  size_t NewlinePos = PD->getShortDescription().find_first_of('\n');
+  if (NewlinePos != std::string::npos)
+OutStr = PD->getShortDescription().str().insert(NewlinePos, 
WarningMsg);
+  else
+OutStr = (PD->getShortDescription() + WarningMsg).str();

scott.linder wrote:
> It's frustrating that `std::string::insert` doesn't follow the pattern of 
> `npos==end-of-string`, but I'd still suggest only doing the actual 
> insert/append once
Or to be more precise, I would try to only have one piece of code doing the 
insert/append


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D127923

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


[PATCH] D127270: [clang-format] Add space in placement new expression

2022-06-17 Thread omar ahmed via Phabricator via cfe-commits
omarahmed updated this revision to Diff 437980.
omarahmed added a comment.

Add Parse check


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D127270

Files:
  clang/docs/ClangFormatStyleOptions.rst
  clang/docs/tools/dump_format_style.py
  clang/include/clang/Format/Format.h
  clang/lib/Format/Format.cpp
  clang/lib/Format/TokenAnnotator.cpp
  clang/unittests/Format/FormatTest.cpp

Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -10130,6 +10130,42 @@
 "void delete(link p);\n",
 format("void new (link p);\n"
"void delete (link p);\n"));
+
+  FormatStyle AfterPlacementOperator = getLLVMStyle();
+  AfterPlacementOperator.SpaceBeforeParens = FormatStyle::SBPO_Custom;
+  EXPECT_EQ(
+  AfterPlacementOperator.SpaceBeforeParensOptions.AfterPlacementOperator,
+  FormatStyle::SpaceBeforeParensCustom::APO_Never);
+  verifyFormat("struct A {\n"
+   "  void *a;\n"
+   "  A(void *p) : a(new(p) int) {\n"
+   "new(p) int;\n"
+   "int *b = new(p) int;\n"
+   "int *c = new(p) int(3);\n"
+   "int *d = delete(p) int(3);\n"
+   "  }\n"
+   "};",
+   AfterPlacementOperator);
+  verifyFormat("void operator new(void *foo) ATTRIB;", AfterPlacementOperator);
+
+  AfterPlacementOperator.SpaceBeforeParensOptions.AfterPlacementOperator =
+  FormatStyle::SpaceBeforeParensCustom::APO_Always;
+  verifyFormat("struct A {\n"
+   "  void *a;\n"
+   "  A(void *p) : a(new (p) int) {\n"
+   "new (p) int;\n"
+   "int *b = new (p) int;\n"
+   "int *c = new (p) int(3);\n"
+   "int *d = delete (p) int(3);\n"
+   "  }\n"
+   "};",
+   AfterPlacementOperator);
+  verifyFormat("void operator new(void *foo) ATTRIB;", AfterPlacementOperator);
+
+  AfterPlacementOperator.SpaceBeforeParensOptions.AfterPlacementOperator =
+  FormatStyle::SpaceBeforeParensCustom::APO_Leave;
+  EXPECT_EQ("new (buf) int;", format("new (buf) int;", AfterPlacementOperator));
+  EXPECT_EQ("new(buf) int;", format("new(buf) int;", AfterPlacementOperator));
 }
 
 TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
@@ -20308,6 +20344,24 @@
   SpaceBeforeParens,
   FormatStyle::SBPO_ControlStatementsExceptControlMacros);
 
+  Style.SpaceBeforeParens = FormatStyle::SBPO_Custom;
+  Style.SpaceBeforeParensOptions.AfterPlacementOperator =
+  FormatStyle::SpaceBeforeParensCustom::APO_Always;
+  CHECK_PARSE("SpaceBeforeParensOptions:\n"
+  "  AfterPlacementOperator: Never",
+  SpaceBeforeParensOptions.AfterPlacementOperator,
+  FormatStyle::SpaceBeforeParensCustom::APO_Never);
+
+  CHECK_PARSE("SpaceBeforeParensOptions:\n"
+  "  AfterPlacementOperator: Always",
+  SpaceBeforeParensOptions.AfterPlacementOperator,
+  FormatStyle::SpaceBeforeParensCustom::APO_Always);
+
+  CHECK_PARSE("SpaceBeforeParensOptions:\n"
+  "  AfterPlacementOperator: Leave",
+  SpaceBeforeParensOptions.AfterPlacementOperator,
+  FormatStyle::SpaceBeforeParensCustom::APO_Leave);
+
   Style.ColumnLimit = 123;
   FormatStyle BaseStyle = getLLVMStyle();
   CHECK_PARSE("BasedOnStyle: LLVM", ColumnLimit, BaseStyle.ColumnLimit);
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -3393,6 +3393,18 @@
 if (Left.is(TT_IfMacro))
   return Style.SpaceBeforeParensOptions.AfterIfMacros ||
  spaceRequiredBeforeParens(Right);
+if (Style.SpaceBeforeParens == FormatStyle::SBPO_Custom &&
+Left.isOneOf(tok::kw_new, tok::kw_delete) &&
+Right.isNot(TT_OverloadedOperatorLParen) &&
+!(Line.MightBeFunctionDecl && Left.is(TT_FunctionDeclarationName))) {
+  if (Style.SpaceBeforeParensOptions.AfterPlacementOperator ==
+  FormatStyle::SpaceBeforeParensCustom::APO_Always ||
+  (Style.SpaceBeforeParensOptions.AfterPlacementOperator ==
+   FormatStyle::SpaceBeforeParensCustom::APO_Leave &&
+   Right.hasWhitespaceBefore()))
+return true;
+  return false;
+}
 if (Line.Type == LT_ObjCDecl)
   return true;
 if (Left.is(tok::semi))
Index: clang/lib/Format/Format.cpp
===
--- clang/lib/Format/Format.cpp
+++ clang/lib/Format/Format.cpp
@@ -936,6 +936,7 @@
Spacing.AfterFunctionDeclarationName);
 IO.mapOptional("AfterIfMacros", Spacing.AfterIfMacro

[clang] 0dd243f - wip

2022-06-17 Thread Chris Bieneman via cfe-commits

Author: Chris Bieneman
Date: 2022-06-17T13:34:21-05:00
New Revision: 0dd243fa8a4ec98d6cabbad16e6b485a093c6dea

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

LOG: wip

Added: 
clang/include/clang/Sema/HLSLExternalSemaSource.h
clang/lib/Sema/HLSLExternalSemaSource.cpp
clang/test/SemaHLSL/BuiltIns/vectors.hlsl

Modified: 
clang/lib/Frontend/FrontendAction.cpp
clang/lib/Headers/hlsl/hlsl_basic_types.h
clang/lib/Sema/CMakeLists.txt

Removed: 




diff  --git a/clang/include/clang/Sema/HLSLExternalSemaSource.h 
b/clang/include/clang/Sema/HLSLExternalSemaSource.h
new file mode 100644
index 0..23dd02ef611e3
--- /dev/null
+++ b/clang/include/clang/Sema/HLSLExternalSemaSource.h
@@ -0,0 +1,45 @@
+//===--- HLSLExternalSemaSource.h - HLSL Sema Source *- C++ 
-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+//  This file defines the HLSLExternalSemaSource interface.
+//
+//===--===//
+#ifndef CLANG_SEMA_HLSLEXTERNALSEMASOURCE_H
+#define CLANG_SEMA_HLSLEXTERNALSEMASOURCE_H
+
+#include "clang/Sema/ExternalSemaSource.h"
+
+namespace clang {
+class NamespaceDecl;
+class Sema;
+
+class HLSLExternalSemaSource : public ExternalSemaSource {
+  static char ID;
+
+  Sema *SemaPtr = nullptr;
+  NamespaceDecl *HLSLNamespace;
+
+  void defineHLSLVectorAlias();
+public:
+  ~HLSLExternalSemaSource() override;
+
+  /// Initialize the semantic source with the Sema instance
+  /// being used to perform semantic analysis on the abstract syntax
+  /// tree.
+  void InitializeSema(Sema &S) override;
+
+  /// Inform the semantic consumer that Sema is no longer available.
+  void ForgetSema() override {
+SemaPtr = nullptr;
+  }
+
+};
+
+} // namespace clang
+
+#endif // CLANG_SEMA_HLSLEXTERNALSEMASOURCE_H

diff  --git a/clang/lib/Frontend/FrontendAction.cpp 
b/clang/lib/Frontend/FrontendAction.cpp
index 6b1f6364b13c3..4a141e6200030 100644
--- a/clang/lib/Frontend/FrontendAction.cpp
+++ b/clang/lib/Frontend/FrontendAction.cpp
@@ -24,6 +24,7 @@
 #include "clang/Lex/Preprocessor.h"
 #include "clang/Lex/PreprocessorOptions.h"
 #include "clang/Parse/ParseAST.h"
+#include "clang/Sema/HLSLExternalSemaSource.h"
 #include "clang/Serialization/ASTDeserializationListener.h"
 #include "clang/Serialization/ASTReader.h"
 #include "clang/Serialization/GlobalModuleIndex.h"
@@ -1014,6 +1015,13 @@ bool FrontendAction::BeginSourceFile(CompilerInstance 
&CI,
 CI.getASTContext().setExternalSource(Override);
   }
 
+  // Setup HLSL External Sema Source
+  if (CI.getLangOpts().HLSL && CI.hasASTContext()) {
+IntrusiveRefCntPtr HLSLSema(
+new HLSLExternalSemaSource());
+CI.getASTContext().setExternalSource(HLSLSema);
+  }
+
   FailureCleanup.release();
   return true;
 }

diff  --git a/clang/lib/Headers/hlsl/hlsl_basic_types.h 
b/clang/lib/Headers/hlsl/hlsl_basic_types.h
index 2069990f5c06c..e68715f1a6a45 100644
--- a/clang/lib/Headers/hlsl/hlsl_basic_types.h
+++ b/clang/lib/Headers/hlsl/hlsl_basic_types.h
@@ -27,38 +27,38 @@ typedef long int64_t;
 // built-in vector data types:
 
 #ifdef __HLSL_ENABLE_16_BIT
-typedef int16_t int16_t2 __attribute__((ext_vector_type(2)));
-typedef int16_t int16_t3 __attribute__((ext_vector_type(3)));
-typedef int16_t int16_t4 __attribute__((ext_vector_type(4)));
-typedef uint16_t uint16_t2 __attribute__((ext_vector_type(2)));
-typedef uint16_t uint16_t3 __attribute__((ext_vector_type(3)));
-typedef uint16_t uint16_t4 __attribute__((ext_vector_type(4)));
+typedef vector int16_t2;
+typedef vector int16_t3;
+typedef vector int16_t4;
+typedef vector uint16_t2;
+typedef vector uint16_t3;
+typedef vector uint16_t4;
 #endif
 
-typedef int int2 __attribute__((ext_vector_type(2)));
-typedef int int3 __attribute__((ext_vector_type(3)));
-typedef int int4 __attribute__((ext_vector_type(4)));
-typedef uint uint2 __attribute__((ext_vector_type(2)));
-typedef uint uint3 __attribute__((ext_vector_type(3)));
-typedef uint uint4 __attribute__((ext_vector_type(4)));
-typedef int64_t int64_t2 __attribute__((ext_vector_type(2)));
-typedef int64_t int64_t3 __attribute__((ext_vector_type(3)));
-typedef int64_t int64_t4 __attribute__((ext_vector_type(4)));
-typedef uint64_t uint64_t2 __attribute__((ext_vector_type(2)));
-typedef uint64_t uint64_t3 __attribute__((ext_vector_type(3)));
-typedef uint64_t uint64_t4 __attribute__((ext_vector_type(4)));
+typedef vector int2;
+typedef vector int3;
+typedef vector int4;
+typedef vector uint2;
+typed

  1   2   >