[PATCH] D81336: [clang-tidy] simplify-bool-expr ignores template instantiations

2020-06-07 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri added a comment.

Thank you for looking into it!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D81336



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


[clang] 4affc44 - [Matrix] Implement * binary operator for MatrixType.

2020-06-07 Thread Florian Hahn via cfe-commits

Author: Florian Hahn
Date: 2020-06-07T11:11:27+01:00
New Revision: 4affc444b499ba2a12fee7f9ef0bb6ef33789c12

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

LOG: [Matrix] Implement * binary operator for MatrixType.

This patch implements the * binary operator for values of
MatrixType. It adds support for matrix * matrix, scalar * matrix and
matrix * scalar.

For the matrix, matrix case, the number of columns of the first operand
must match the number of rows of the second. For the scalar,matrix variants,
the element type of the matrix must match the scalar type.

Reviewers: rjmccall, anemet, Bigcheese, rsmith, martong

Reviewed By: rjmccall

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

Added: 


Modified: 
clang/include/clang/Sema/Sema.h
clang/lib/CodeGen/CGExprScalar.cpp
clang/lib/Sema/SemaExpr.cpp
clang/lib/Sema/SemaOverload.cpp
clang/test/CodeGen/matrix-type-operators.c
clang/test/CodeGenCXX/matrix-type-operators.cpp
clang/test/Sema/matrix-type-operators.c
clang/test/SemaCXX/matrix-type-operators.cpp
llvm/include/llvm/IR/MatrixBuilder.h

Removed: 




diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index cef25fc927aa..8f914ec451f6 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -11218,6 +11218,8 @@ class Sema final {
   QualType CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
   SourceLocation Loc,
   bool IsCompAssign);
+  QualType CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
+   SourceLocation Loc, bool IsCompAssign);
 
   bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType);
   bool isLaxVectorConversion(QualType srcType, QualType destType);

diff  --git a/clang/lib/CodeGen/CGExprScalar.cpp 
b/clang/lib/CodeGen/CGExprScalar.cpp
index b169462f535a..cabfe0cca281 100644
--- a/clang/lib/CodeGen/CGExprScalar.cpp
+++ b/clang/lib/CodeGen/CGExprScalar.cpp
@@ -741,6 +741,22 @@ class ScalarExprEmitter
   }
 }
 
+if (Ops.Ty->isConstantMatrixType()) {
+  llvm::MatrixBuilder MB(Builder);
+  // We need to check the types of the operands of the operator to get the
+  // correct matrix dimensions.
+  auto *BO = cast(Ops.E);
+  auto *LHSMatTy = dyn_cast(
+  BO->getLHS()->getType().getCanonicalType());
+  auto *RHSMatTy = dyn_cast(
+  BO->getRHS()->getType().getCanonicalType());
+  if (LHSMatTy && RHSMatTy)
+return MB.CreateMatrixMultiply(Ops.LHS, Ops.RHS, 
LHSMatTy->getNumRows(),
+   LHSMatTy->getNumColumns(),
+   RHSMatTy->getNumColumns());
+  return MB.CreateScalarMultiply(Ops.LHS, Ops.RHS);
+}
+
 if (Ops.Ty->isUnsignedIntegerType() &&
 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) &&
 !CanElideOverflowCheck(CGF.getContext(), Ops))

diff  --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index d7a39cf6a6b5..45c1acecbe94 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -10058,6 +10058,9 @@ QualType Sema::CheckMultiplyDivideOperands(ExprResult 
&LHS, ExprResult &RHS,
 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
/*AllowBothBool*/getLangOpts().AltiVec,
/*AllowBoolConversions*/false);
+  if (!IsDiv && (LHS.get()->getType()->isConstantMatrixType() ||
+ RHS.get()->getType()->isConstantMatrixType()))
+return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
 
   QualType compType = UsualArithmeticConversions(
   LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
@@ -12120,6 +12123,37 @@ QualType 
Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
   return InvalidOperands(Loc, LHS, RHS);
 }
 
+QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
+   SourceLocation Loc,
+   bool IsCompAssign) {
+  if (!IsCompAssign) {
+LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
+if (LHS.isInvalid())
+  return QualType();
+  }
+  RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
+  if (RHS.isInvalid())
+return QualType();
+
+  auto *LHSMatType = LHS.get()->getType()->getAs();
+  auto *RHSMatType = RHS.get()->getType()->getAs();
+  assert((LHSMatType || RHSMatType) && "At least one operand must be a 
matrix");
+
+  if (LHSMatType && RHSMatType) {
+if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
+  return InvalidOperands(Loc, L

[PATCH] D76794: [Matrix] Implement * binary operator for MatrixType.

2020-06-07 Thread Florian Hahn via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG4affc444b499: [Matrix] Implement * binary operator for 
MatrixType. (authored by fhahn).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76794

Files:
  clang/include/clang/Sema/Sema.h
  clang/lib/CodeGen/CGExprScalar.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaOverload.cpp
  clang/test/CodeGen/matrix-type-operators.c
  clang/test/CodeGenCXX/matrix-type-operators.cpp
  clang/test/Sema/matrix-type-operators.c
  clang/test/SemaCXX/matrix-type-operators.cpp
  llvm/include/llvm/IR/MatrixBuilder.h

Index: llvm/include/llvm/IR/MatrixBuilder.h
===
--- llvm/include/llvm/IR/MatrixBuilder.h
+++ llvm/include/llvm/IR/MatrixBuilder.h
@@ -33,6 +33,21 @@
   IRBuilderTy &B;
   Module *getModule() { return B.GetInsertBlock()->getParent()->getParent(); }
 
+  std::pair splatScalarOperandIfNeeded(Value *LHS,
+ Value *RHS) {
+assert((LHS->getType()->isVectorTy() || RHS->getType()->isVectorTy()) &&
+   "One of the operands must be a matrix (embedded in a vector)");
+if (LHS->getType()->isVectorTy() && !RHS->getType()->isVectorTy())
+  RHS = B.CreateVectorSplat(
+  cast(LHS->getType())->getNumElements(), RHS,
+  "scalar.splat");
+else if (!LHS->getType()->isVectorTy() && RHS->getType()->isVectorTy())
+  LHS = B.CreateVectorSplat(
+  cast(RHS->getType())->getNumElements(), LHS,
+  "scalar.splat");
+return {LHS, RHS};
+  }
+
 public:
   MatrixBuilder(IRBuilderTy &Builder) : B(Builder) {}
 
@@ -164,15 +179,13 @@
: B.CreateSub(LHS, RHS);
   }
 
-  /// Multiply matrix \p LHS with scalar \p RHS.
+  /// Multiply matrix \p LHS with scalar \p RHS or scalar \p LHS with matrix \p
+  /// RHS.
   Value *CreateScalarMultiply(Value *LHS, Value *RHS) {
-Value *ScalarVector =
-B.CreateVectorSplat(cast(LHS->getType())->getNumElements(),
-RHS, "scalar.splat");
-if (RHS->getType()->isFloatingPointTy())
-  return B.CreateFMul(LHS, ScalarVector);
-
-return B.CreateMul(LHS, ScalarVector);
+std::tie(LHS, RHS) = splatScalarOperandIfNeeded(LHS, RHS);
+if (LHS->getType()->getScalarType()->isFloatingPointTy())
+  return B.CreateFMul(LHS, RHS);
+return B.CreateMul(LHS, RHS);
   }
 
   /// Extracts the element at (\p RowIdx, \p ColumnIdx) from \p Matrix.
Index: clang/test/SemaCXX/matrix-type-operators.cpp
===
--- clang/test/SemaCXX/matrix-type-operators.cpp
+++ clang/test/SemaCXX/matrix-type-operators.cpp
@@ -65,6 +65,45 @@
   // expected-note@-1 {{in instantiation of function template specialization 'subtract' requested here}}
 }
 
+template 
+typename MyMatrix::matrix_t multiply(MyMatrix &A, MyMatrix &B) {
+  char *v1 = A.value * B.value;
+  // expected-error@-1 {{cannot initialize a variable of type 'char *' with an rvalue of type 'unsigned int __attribute__((matrix_type(2, 2)))'}}
+  // expected-error@-2 {{invalid operands to binary expression ('MyMatrix::matrix_t' (aka 'unsigned int __attribute__((matrix_type(3, 2)))') and 'MyMatrix::matrix_t' (aka 'unsigned int __attribute__((matrix_type(3, 3)))'))}}
+  // expected-error@-3 {{invalid operands to binary expression ('MyMatrix::matrix_t' (aka 'float __attribute__((matrix_type(2, 2)))') and 'MyMatrix::matrix_t' (aka 'unsigned int __attribute__((matrix_type(2, 2)))'))}}
+
+  MyMatrix m;
+  B.value = m.value * A.value;
+  // expected-error@-1 {{invalid operands to binary expression ('MyMatrix::matrix_t' (aka 'int __attribute__((matrix_type(5, 6)))') and 'MyMatrix::matrix_t' (aka 'unsigned int __attribute__((matrix_type(2, 2)))'))}}
+  // expected-error@-2 {{invalid operands to binary expression ('MyMatrix::matrix_t' (aka 'int __attribute__((matrix_type(5, 6)))') and 'MyMatrix::matrix_t' (aka 'unsigned int __attribute__((matrix_type(3, 2)))'))}}
+  // expected-error@-3 {{invalid operands to binary expression ('MyMatrix::matrix_t' (aka 'int __attribute__((matrix_type(5, 6)))') and 'MyMatrix::matrix_t' (aka 'float __attribute__((matrix_type(2, 2)))'))}}
+
+  return A.value * B.value;
+  // expected-error@-1 {{invalid operands to binary expression ('MyMatrix::matrix_t' (aka 'unsigned int __attribute__((matrix_type(3, 2)))') and 'MyMatrix::matrix_t' (aka 'unsigned int __attribute__((matrix_type(3, 3)))'))}}
+  // expected-error@-2 {{invalid operands to binary expression ('MyMatrix::matrix_t' (aka 'float __attribute__((matrix_type(2, 2)))') and 'MyMatrix::matrix_t' (aka 'unsigned int __attribute__((matrix_type(2, 2)))'))}}
+}
+
+void test_multiply_template(unsigned *Ptr1, float *Ptr2) {
+  MyMatrix Mat1;
+  MyMatrix Mat2;
+  MyMatrix Mat3;
+  Mat1.value = *((decltype(Mat1)::matrix_t *)Ptr1);
+  unsigned

[clang] 5945e97 - [clang][BFloat] Add reinterpret cast intrinsics

2020-06-07 Thread Ties Stuij via cfe-commits

Author: Ties Stuij
Date: 2020-06-07T14:32:37+01:00
New Revision: 5945e9799e77c30baffd0da4a9b735262cda3361

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

LOG: [clang][BFloat] Add reinterpret cast intrinsics

Summary:
This patch is part of a series implementing the Bfloat16 extension of the
Armv8.6-a architecture, as detailed here:

https://community.arm.com/developer/ip-products/processors/b/processors-ip-blog/posts/arm-architecture-developments-armv8-6-a

The bfloat type, and its properties is specified in the Arm C language
extension specification:

https://developer.arm.com/docs/ihi0055/d/procedure-call-standard-for-the-arm-64-bit-architecture

Subscribers: kristof.beyls, ilya-biryukov, MaskRay, jkorous, arphaman, 
kadircet, usaxena95, cfe-commits

Tags: #clang

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

The following people contributed to this patch:

- Luke Cheeseman
- Alexandros Lamprineas
- Luke Geeson
- Ties Stuij

Added: 
clang/test/CodeGen/aarch64-bf16-reinterpret-intrinsics.c
clang/test/CodeGen/arm-bf16-reinterpret-intrinsics.c

Modified: 
clang/include/clang/Basic/arm_neon.td
clang/include/clang/Basic/arm_neon_incl.td
clang/utils/TableGen/NeonEmitter.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/arm_neon.td 
b/clang/include/clang/Basic/arm_neon.td
index 98fda8b13142..12481cfb145d 100644
--- a/clang/include/clang/Basic/arm_neon.td
+++ b/clang/include/clang/Basic/arm_neon.td
@@ -635,11 +635,23 @@ def VZIP : WInst<"vzip", "2..", 
"csiUcUsUifPcPsQcQsQiQUcQUsQUiQfQPcQPs">;
 def VUZP : WInst<"vuzp", "2..", "csiUcUsUifPcPsQcQsQiQUcQUsQUiQfQPcQPs">;
 
 

+
+class REINTERPRET_CROSS_SELF :
+  NoTestOpInst<"vreinterpret", "..", Types, OP_REINT> {
+let CartesianProductWith = Types;
+}
+
+multiclass REINTERPRET_CROSS_TYPES {
+  def AXB: NoTestOpInst<"vreinterpret", "..", TypesA, OP_REINT> {
+let CartesianProductWith = TypesB;
+  }
+  def BXA: NoTestOpInst<"vreinterpret", "..", TypesB, OP_REINT> {
+let CartesianProductWith = TypesA;
+  }
+}
+
 // E.3.31 Vector reinterpret cast operations
-def VREINTERPRET
-  : NoTestOpInst<"vreinterpret", "..",
- "csilUcUsUiUlhfPcPsQcQsQiQlQUcQUsQUiQUlQhQfQPcQPs", OP_REINT> {
-  let CartesianProductOfTypes = 1;
+def VREINTERPRET : 
REINTERPRET_CROSS_SELF<"csilUcUsUiUlhfPcPsQcQsQiQlQUcQUsQUiQUlQhQfQPcQPs"> {
   let ArchGuard = "!defined(__aarch64__)";
   let BigEndianSafe = 1;
 }
@@ -1188,12 +1200,9 @@ def VQTBX4_A64 : WInst<"vqtbx4", "..(4Q)U", 
"UccPcQUcQcQPc">;
 // NeonEmitter implicitly takes the cartesian product of the type string with
 // itself during generation so, unlike all other intrinsics, this one should
 // include *all* types, not just additional ones.
-def VVREINTERPRET
-  : NoTestOpInst<"vreinterpret", "..",
-   "csilUcUsUiUlhfdPcPsPlQcQsQiQlQUcQUsQUiQUlQhQfQdQPcQPsQPlQPk", 
OP_REINT> {
-  let CartesianProductOfTypes = 1;
-  let BigEndianSafe = 1;
+def VVREINTERPRET : 
REINTERPRET_CROSS_SELF<"csilUcUsUiUlhfdPcPsPlQcQsQiQlQUcQUsQUiQUlQhQfQdQPcQPsQPlQPk">
 {
   let ArchGuard = "__ARM_ARCH >= 8 && defined(__aarch64__)";
+  let BigEndianSafe = 1;
 }
 
 

@@ -1891,3 +1900,17 @@ let ArchGuard = 
"defined(__ARM_FEATURE_BF16_VECTOR_ARITHMETIC) && defined(__aarc
 let isLaneQ = 1;
   }
 }
+
+let ArchGuard = "defined(__ARM_FEATURE_BF16) && !defined(__aarch64__)" in {
+  let BigEndianSafe = 1 in {
+defm VREINTERPRET_BF : REINTERPRET_CROSS_TYPES<
+"csilUcUsUiUlhfPcPsPlQcQsQiQlQUcQUsQUiQUlQhQfQPcQPsQPl", "bQb">;
+  }
+}
+
+let ArchGuard = "defined(__ARM_FEATURE_BF16) && defined(__aarch64__)" in {
+  let BigEndianSafe = 1 in {
+defm VVREINTERPRET_BF : REINTERPRET_CROSS_TYPES<
+"csilUcUsUiUlhfdPcPsPlQcQsQiQlQUcQUsQUiQUlQhQfQdQPcQPsQPlQPk", "bQb">;
+  }
+}

diff  --git a/clang/include/clang/Basic/arm_neon_incl.td 
b/clang/include/clang/Basic/arm_neon_incl.td
index a1031fe4ad4f..dd20b70433ef 100644
--- a/clang/include/clang/Basic/arm_neon_incl.td
+++ b/clang/include/clang/Basic/arm_neon_incl.td
@@ -267,7 +267,6 @@ class Inst  {
   string ArchGuard = "";
 
   Operation Operation = o;
-  bit CartesianProductOfTypes = 0;
   bit BigEndianSafe = 0;
   bit isShift = 0;
   bit isScalarShift = 0;
@@ -289,6 +288,8 @@ class Inst  {
   // this. Ex: vset_lane which outputs vmov instructions.
   bit isHiddenWInst = 0;
   bit isHiddenLInst = 0;
+
+  string CartesianProductWith = "";
 }
 
 // The following instruction classes are implemented via builtins.

diff  --git a/clang/test/CodeGen/aarch64-bf16-reinterpret-intrinsics.c 
b/clang/test/CodeGen/aarch64-bf16-reinterpret-intrinsics.c
new file mode 100644
index 000

[PATCH] D72778: [Matrix] Add __builtin_matrix_transpose to Clang.

2020-06-07 Thread Florian Hahn via Phabricator via cfe-commits
fhahn updated this revision to Diff 269050.
fhahn added a comment.

Simplify code as suggested, use DefaultLValueConversion instead of 
CheckPlaceholderExpr.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D72778

Files:
  clang/include/clang/Basic/Builtins.def
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Sema/Sema.h
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/Sema/SemaChecking.cpp
  clang/test/CodeGen/matrix-type-builtins.c
  clang/test/CodeGenCXX/matrix-type-builtins.cpp
  clang/test/CodeGenObjC/matrix-type-builtins.m
  clang/test/Sema/matrix-type-builtins.c
  clang/test/SemaCXX/matrix-type-builtins.cpp
  clang/test/SemaObjC/matrix-type-builtins.m

Index: clang/test/SemaObjC/matrix-type-builtins.m
===
--- /dev/null
+++ clang/test/SemaObjC/matrix-type-builtins.m
@@ -0,0 +1,21 @@
+// RUN: %clang_cc1 -fsyntax-only -verify -fenable-matrix %s
+
+typedef double double4x4 __attribute__((matrix_type(4, 4)));
+typedef unsigned u4x4 __attribute__((matrix_type(4, 4)));
+
+__attribute__((objc_root_class))
+@interface MatrixValue
+@property double4x4 value;
+@end
+
+void test_element_type_mismatch(u4x4 m, MatrixValue *mv) {
+  m = __builtin_matrix_transpose(mv.value);
+  // expected-error@-1 {{assigning to 'u4x4' (aka 'unsigned int __attribute__((matrix_type(4, 4)))') from incompatible type 'double __attribute__((matrix_type(4, 4)))'}}
+}
+
+typedef double double3x3 __attribute__((matrix_type(3, 3)));
+
+double test_dimension_mismatch(double3x3 m, MatrixValue *mv) {
+  m = __builtin_matrix_transpose(mv.value);
+  // expected-error@-1 {{assigning to 'double3x3' (aka 'double __attribute__((matrix_type(3, 3)))') from incompatible type 'double __attribute__((matrix_type(4, 4)))'}}
+}
Index: clang/test/SemaCXX/matrix-type-builtins.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/matrix-type-builtins.cpp
@@ -0,0 +1,41 @@
+// RUN: %clang_cc1 %s -fenable-matrix -pedantic -std=c++11 -verify -triple=x86_64-apple-darwin9
+
+template 
+struct MyMatrix {
+  using matrix_t = EltTy __attribute__((matrix_type(Rows, Columns)));
+
+  matrix_t value;
+};
+
+template 
+typename MyMatrix::matrix_t transpose(MyMatrix &A) {
+  char *v1 = __builtin_matrix_transpose(A.value);
+  // expected-error@-1 {{cannot initialize a variable of type 'char *' with an rvalue of type 'unsigned int __attribute__((matrix_type(3, 2)))'}}
+  // expected-error@-2 {{cannot initialize a variable of type 'char *' with an rvalue of type 'unsigned int __attribute__((matrix_type(3, 3)))'}}
+  // expected-error@-3 {{cannot initialize a variable of type 'char *' with an rvalue of type 'unsigned int __attribute__((matrix_type(3, 3)))'}}
+
+  __builtin_matrix_transpose(A);
+  // expected-error@-1 {{first argument must be a matrix}}
+  // expected-error@-2 {{first argument must be a matrix}}
+  // expected-error@-3 {{first argument must be a matrix}}
+
+  return __builtin_matrix_transpose(A.value);
+  // expected-error@-1 {{cannot initialize return object of type 'typename MyMatrix::matrix_t' (aka 'unsigned int __attribute__((matrix_type(2, 3)))') with an rvalue of type 'unsigned int __attribute__((matrix_type(3, 2)))'}}
+  // expected-error@-2 {{cannot initialize return object of type 'typename MyMatrix::matrix_t' (aka 'unsigned int __attribute__((matrix_type(2, 3)))') with an rvalue of type 'unsigned int __attribute__((matrix_type(3, 3)))'}}
+  // expected-error@-3 {{cannot initialize return object of type 'typename MyMatrix::matrix_t' (aka 'float __attribute__((matrix_type(3, 3)))') with an rvalue of type 'unsigned int __attribute__((matrix_type(3, 3)))'}}
+}
+
+void test_transpose_template(unsigned *Ptr1, float *Ptr2) {
+  MyMatrix Mat1;
+  MyMatrix Mat2;
+  Mat1.value = *((decltype(Mat1)::matrix_t *)Ptr1);
+  Mat1.value = transpose(Mat1);
+  // expected-note@-1 {{in instantiation of function template specialization 'transpose' requested here}}
+
+  Mat1.value = transpose(Mat2);
+  // expected-note@-1 {{in instantiation of function template specialization 'transpose' requested here}}
+
+  MyMatrix Mat3;
+  Mat3.value = transpose(Mat2);
+  // expected-note@-1 {{in instantiation of function template specialization 'transpose' requested here}}
+}
Index: clang/test/Sema/matrix-type-builtins.c
===
--- /dev/null
+++ clang/test/Sema/matrix-type-builtins.c
@@ -0,0 +1,22 @@
+// RUN: %clang_cc1 %s -fenable-matrix -pedantic -verify -triple=x86_64-apple-darwin9
+
+typedef float sx5x10_t __attribute__((matrix_type(5, 10)));
+typedef int ix3x2_t __attribute__((matrix_type(3, 2)));
+typedef double dx3x3 __attribute__((matrix_type(3, 3)));
+typedef unsigned ix3x3 __attribute__((matrix_type(3, 3)));
+
+void transpose(sx5x10_t a, ix3x2_t b, dx3x3 c, int *d, int e) {
+  a = __builtin_matrix

[PATCH] D72778: [Matrix] Add __builtin_matrix_transpose to Clang.

2020-06-07 Thread Florian Hahn via Phabricator via cfe-commits
fhahn marked 4 inline comments as done.
fhahn added inline comments.



Comment at: clang/lib/Sema/SemaChecking.cpp:15051
+
+  Expr *Arg = TheCall->getArg(0);
+  if (!Arg->getType()->isConstantMatrixType()) {

rjmccall wrote:
> fhahn wrote:
> > rjmccall wrote:
> > > When a builtin has custom type-checking (`t`), you need to handle 
> > > placeholders in the operands yourself, just like you would for an 
> > > operator.
> > I added placeholder handling and added additional tests.
> Oh, I'm sorry, I gave you poor advice: you do need to handle placeholders, 
> but more generally than that, you need an r-value.   Since you aren't doing 
> any further conversions, you just need to call DefaultLValueConversion, which 
> will also handle placeholders for you.
> 
> You will also need to store the checked argument back into the call, which 
> you can only really test with an IRGen test.  This is one of the few places 
> where we do actually directly mutate the AST.
Oh right, I wasn't sure about whether we need DefaultLValueConversion here or 
not. I tried to construct a C/C++ test case that would actually require it, but 
couldn't come up with a test. In any case, I updated it to use 
`DefaultLvalueConversion` instead and also adjust the argument before returning 
the updated call.



Comment at: clang/lib/Sema/SemaChecking.cpp:1918
+switch (BuiltinID) {
+case Builtin::BI__builtin_matrix_transpose:
+  return SemaBuiltinMatrixTransposeOverload(TheCall, TheCallResult);

rjmccall wrote:
> I didn't notice this before, but I think a single level of switch is fine; 
> there's probably nothing common about matrix builtins that you're going to 
> want to handle like this.
It's not required any more, after removing the `fenable_matrix` check. I 
dropped it.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D72778



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


[PATCH] D79869: [clang][BFloat] Add reinterpret cast intrinsics

2020-06-07 Thread Ties Stuij via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG5945e9799e77: [clang][BFloat] Add reinterpret cast 
intrinsics (authored by stuij).

Changed prior to commit:
  https://reviews.llvm.org/D79869?vs=264590&id=269052#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79869

Files:
  clang/include/clang/Basic/arm_neon.td
  clang/include/clang/Basic/arm_neon_incl.td
  clang/test/CodeGen/aarch64-bf16-reinterpret-intrinsics.c
  clang/test/CodeGen/arm-bf16-reinterpret-intrinsics.c
  clang/utils/TableGen/NeonEmitter.cpp

Index: clang/utils/TableGen/NeonEmitter.cpp
===
--- clang/utils/TableGen/NeonEmitter.cpp
+++ clang/utils/TableGen/NeonEmitter.cpp
@@ -311,7 +311,7 @@
   /// The unmangled name.
   std::string Name;
   /// The input and output typespecs. InTS == OutTS except when
-  /// CartesianProductOfTypes is 1 - this is the case for vreinterpret.
+  /// CartesianProductWith is non-empty - this is the case for vreinterpret.
   TypeSpec OutTS, InTS;
   /// The base class kind. Most intrinsics use ClassS, which has full type
   /// info for integers (s32/u32). Some use ClassI, which doesn't care about
@@ -344,7 +344,7 @@
   /// The set of intrinsics that this intrinsic uses/requires.
   std::set Dependencies;
   /// The "base type", which is Type('d', OutTS). InBaseType is only
-  /// different if CartesianProductOfTypes = 1 (for vreinterpret).
+  /// different if CartesianProductWith is non-empty (for vreinterpret).
   Type BaseType, InBaseType;
   /// The return variable.
   Variable RetVar;
@@ -1936,10 +1936,10 @@
   std::string Proto = std::string(R->getValueAsString("Prototype"));
   std::string Types = std::string(R->getValueAsString("Types"));
   Record *OperationRec = R->getValueAsDef("Operation");
-  bool CartesianProductOfTypes = R->getValueAsBit("CartesianProductOfTypes");
   bool BigEndianSafe  = R->getValueAsBit("BigEndianSafe");
   std::string Guard = std::string(R->getValueAsString("ArchGuard"));
   bool IsUnavailable = OperationRec->getValueAsBit("Unavailable");
+  std::string CartesianProductWith = std::string(R->getValueAsString("CartesianProductWith"));
 
   // Set the global current record. This allows assert_with_loc to produce
   // decent location information even when highly nested.
@@ -1954,17 +1954,20 @@
 CK = ClassMap[R->getSuperClasses()[1].first];
 
   std::vector> NewTypeSpecs;
-  for (auto TS : TypeSpecs) {
-if (CartesianProductOfTypes) {
+  if (!CartesianProductWith.empty()) {
+std::vector ProductTypeSpecs = TypeSpec::fromTypeSpecs(CartesianProductWith);
+for (auto TS : TypeSpecs) {
   Type DefaultT(TS, ".");
-  for (auto SrcTS : TypeSpecs) {
+  for (auto SrcTS : ProductTypeSpecs) {
 Type DefaultSrcT(SrcTS, ".");
 if (TS == SrcTS ||
 DefaultSrcT.getSizeInBits() != DefaultT.getSizeInBits())
   continue;
 NewTypeSpecs.push_back(std::make_pair(TS, SrcTS));
   }
-} else {
+}
+  } else {
+for (auto TS : TypeSpecs) {
   NewTypeSpecs.push_back(std::make_pair(TS, TS));
 }
   }
Index: clang/test/CodeGen/arm-bf16-reinterpret-intrinsics.c
===
--- /dev/null
+++ clang/test/CodeGen/arm-bf16-reinterpret-intrinsics.c
@@ -0,0 +1,314 @@
+// RUN: %clang_cc1 -triple armv8.2a-arm-none-eabi -target-feature +neon -target-feature +bf16 -mfloat-abi hard \
+// RUN: -disable-O0-optnone -S -emit-llvm -o - %s \
+// RUN: | opt -S -instcombine \
+// RUN: | FileCheck %s
+
+// REQUIRES: arm-registered-target
+
+#include 
+
+// CHECK-LABEL: @test_vreinterpret_bf16_s8(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[TMP0:%.*]] = bitcast <8 x i8> [[A:%.*]] to <4 x bfloat>
+// CHECK-NEXT:ret <4 x bfloat> [[TMP0]]
+//
+bfloat16x4_t test_vreinterpret_bf16_s8(int8x8_t a)  { return vreinterpret_bf16_s8(a);}
+// CHECK-LABEL: @test_vreinterpret_bf16_s16(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[TMP0:%.*]] = bitcast <4 x i16> [[A:%.*]] to <4 x bfloat>
+// CHECK-NEXT:ret <4 x bfloat> [[TMP0]]
+//
+bfloat16x4_t test_vreinterpret_bf16_s16(int16x4_t a){ return vreinterpret_bf16_s16(a);   }
+// CHECK-LABEL: @test_vreinterpret_bf16_s32(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[TMP0:%.*]] = bitcast <2 x i32> [[A:%.*]] to <4 x bfloat>
+// CHECK-NEXT:ret <4 x bfloat> [[A:%.*]]
+//
+bfloat16x4_t test_vreinterpret_bf16_s32(int32x2_t a){ return vreinterpret_bf16_s32(a);   }
+// CHECK-LABEL: @test_vreinterpret_bf16_f32(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[TMP0:%.*]] = bitcast <2 x float> [[A:%.*]] to <4 x bfloat>
+// CHECK-NEXT:ret <4 x bfloat> [[TMP0]]
+//
+bfloat16x4_t test_vreinterpret_bf16_f32(float32x2_t a)  { return vreinterpret_bf16_f32(a);   }
+// CHECK-LABEL: @test_vreinterpret_bf16_u8(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[TMP0:%.*

[clang] 0c3df70 - Remove global std::string. StringRef is sufficient. NFC.

2020-06-07 Thread Benjamin Kramer via cfe-commits

Author: Benjamin Kramer
Date: 2020-06-07T17:22:44+02:00
New Revision: 0c3df70fad83daba2384fab10e026288a9571901

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

LOG: Remove global std::string. StringRef is sufficient. NFC.

Added: 


Modified: 
clang/lib/Analysis/ExprMutationAnalyzer.cpp

Removed: 




diff  --git a/clang/lib/Analysis/ExprMutationAnalyzer.cpp 
b/clang/lib/Analysis/ExprMutationAnalyzer.cpp
index 5e305534c812..e57a425f802d 100644
--- a/clang/lib/Analysis/ExprMutationAnalyzer.cpp
+++ b/clang/lib/Analysis/ExprMutationAnalyzer.cpp
@@ -73,10 +73,8 @@ const auto isMoveOnly = [] {
 };
 
 template  struct NodeID;
-template <> struct NodeID { static const std::string value; };
-template <> struct NodeID { static const std::string value; };
-const std::string NodeID::value = "expr";
-const std::string NodeID::value = "decl";
+template <> struct NodeID { static constexpr StringRef value = "expr"; };
+template <> struct NodeID { static constexpr StringRef value = "decl"; };
 
 template 
 const Stmt *tryEachMatch(ArrayRef Matches,



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


[clang] 5a09808 - Put compilation phases from Types.def into a bit set

2020-06-07 Thread Benjamin Kramer via cfe-commits

Author: Benjamin Kramer
Date: 2020-06-07T17:22:44+02:00
New Revision: 5a098086f996ce143c9ea9500934cd88777191e9

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

LOG: Put compilation phases from Types.def into a bit set

This avoids a global constructor and is a bit more efficient for
"contained" queries. No functionality change intended.

Added: 


Modified: 
clang/include/clang/Driver/Phases.h
clang/lib/Driver/Types.cpp

Removed: 




diff  --git a/clang/include/clang/Driver/Phases.h 
b/clang/include/clang/Driver/Phases.h
index 63931c00c890..9003c5857351 100644
--- a/clang/include/clang/Driver/Phases.h
+++ b/clang/include/clang/Driver/Phases.h
@@ -25,7 +25,7 @@ namespace phases {
   };
 
   enum {
-MaxNumberOfPhases = Link + 1
+MaxNumberOfPhases = IfsMerge + 1
   };
 
   const char *getPhaseName(ID Id);

diff  --git a/clang/lib/Driver/Types.cpp b/clang/lib/Driver/Types.cpp
index df98835149e9..e330352c2368 100644
--- a/clang/lib/Driver/Types.cpp
+++ b/clang/lib/Driver/Types.cpp
@@ -24,10 +24,19 @@ struct TypeInfo {
   const char *Name;
   const char *TempSuffix;
   ID PreprocessedType;
-  const llvm::SmallVector Phases;
+  class PhasesBitSet {
+unsigned Bits = 0;
+
+  public:
+constexpr PhasesBitSet(const std::initializer_list &Phases) {
+  for (auto Id : Phases)
+Bits |= 1 << Id;
+}
+bool contains(phases::ID Id) const { return Bits & (1 << Id); }
+  } Phases;
 };
 
-static const TypeInfo TypeInfos[] = {
+static constexpr TypeInfo TypeInfos[] = {
 #define TYPE(NAME, ID, PP_TYPE, TEMP_SUFFIX, ...) \
   { NAME, TEMP_SUFFIX, TY_##PP_TYPE, { __VA_ARGS__ }, },
 #include "clang/Driver/Types.def"
@@ -46,18 +55,18 @@ const char *types::getTypeName(ID Id) {
 
 types::ID types::getPreprocessedType(ID Id) {
   ID PPT = getInfo(Id).PreprocessedType;
-  assert((llvm::is_contained(getInfo(Id).Phases, phases::Preprocess) !=
+  assert((getInfo(Id).Phases.contains(phases::Preprocess) !=
   (PPT == TY_INVALID)) &&
  "Unexpected Preprocess Type.");
   return PPT;
 }
 
-static bool isPrepeocessedModuleType(ID Id) {
+static bool isPreprocessedModuleType(ID Id) {
   return Id == TY_CXXModule || Id == TY_PP_CXXModule;
 }
 
 types::ID types::getPrecompiledType(ID Id) {
-  if (isPrepeocessedModuleType(Id))
+  if (isPreprocessedModuleType(Id))
 return TY_ModuleFile;
   if (onlyPrecompileType(Id))
 return TY_PCH;
@@ -82,14 +91,14 @@ const char *types::getTypeTempSuffix(ID Id, bool CLMode) {
 }
 
 bool types::onlyAssembleType(ID Id) {
-  return llvm::is_contained(getInfo(Id).Phases, phases::Assemble) &&
- !llvm::is_contained(getInfo(Id).Phases, phases::Compile) &&
- !llvm::is_contained(getInfo(Id).Phases, phases::Backend);
+  return getInfo(Id).Phases.contains(phases::Assemble) &&
+ !getInfo(Id).Phases.contains(phases::Compile) &&
+ !getInfo(Id).Phases.contains(phases::Backend);
 }
 
 bool types::onlyPrecompileType(ID Id) {
-  return llvm::is_contained(getInfo(Id).Phases, phases::Precompile) &&
- !isPrepeocessedModuleType(Id);
+  return getInfo(Id).Phases.contains(phases::Precompile) &&
+ !isPreprocessedModuleType(Id);
 }
 
 bool types::canTypeBeUserSpecified(ID Id) {
@@ -306,7 +315,10 @@ types::ID types::lookupTypeForTypeSpecifier(const char 
*Name) {
 // FIXME: The list is now in Types.def but for now this function will verify
 //the old behavior and a subsequent change will delete most of the 
body.
 void types::getCompilationPhases(ID Id, llvm::SmallVectorImpl &P) {
-  P = getInfo(Id).Phases;
+  const auto &Info = getInfo(Id);
+  for (int I = 0; I != phases::MaxNumberOfPhases; ++I)
+if (Info.Phases.contains(static_cast(I)))
+  P.push_back(static_cast(I));
   assert(0 < P.size() && "Not enough phases in list");
   assert(P.size() <= phases::MaxNumberOfPhases && "Too many phases in list");
 }



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


[PATCH] D81336: [clang-tidy] simplify-bool-expr ignores template instantiations

2020-06-07 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: 
clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp:425
   Finder->addMatcher(
-  ifStmt(isExpansionInMainFile(),
  hasCondition(cxxBoolLiteral(equals(Value)).bind(BooleanId)))

This is changing the behavior so that now it will diagnose in header files, no? 
Why is the correct change to replace this with 
`unless(isInTemplateInstantiation())` instead of adding the new matcher?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D81336



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


[PATCH] D71512: [clang-format] Fix short block when braking after control statement

2020-06-07 Thread Pablo Martin-Gomez via Phabricator via cfe-commits
Bouska added a comment.

@MyDeveloperDay I don't have commit rights, could you land this change for me 
please?


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

https://reviews.llvm.org/D71512



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


[PATCH] D79912: Assignment and Inc/Dec operators wouldn't register as a mutation when Implicit Paren Casts were present

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

LGTM!


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

https://reviews.llvm.org/D79912



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


[clang] c0c6a12 - Put back definitions. We're still not C++17 :/

2020-06-07 Thread Benjamin Kramer via cfe-commits

Author: Benjamin Kramer
Date: 2020-06-07T17:41:02+02:00
New Revision: c0c6a1277546068fa06f4cfd330a714db365e336

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

LOG: Put back definitions. We're still not C++17 :/

Added: 


Modified: 
clang/lib/Analysis/ExprMutationAnalyzer.cpp

Removed: 




diff  --git a/clang/lib/Analysis/ExprMutationAnalyzer.cpp 
b/clang/lib/Analysis/ExprMutationAnalyzer.cpp
index e57a425f802d..cb5cabfd3089 100644
--- a/clang/lib/Analysis/ExprMutationAnalyzer.cpp
+++ b/clang/lib/Analysis/ExprMutationAnalyzer.cpp
@@ -75,6 +75,8 @@ const auto isMoveOnly = [] {
 template  struct NodeID;
 template <> struct NodeID { static constexpr StringRef value = "expr"; };
 template <> struct NodeID { static constexpr StringRef value = "decl"; };
+constexpr StringRef NodeID::value;
+constexpr StringRef NodeID::value;
 
 template 
 const Stmt *tryEachMatch(ArrayRef Matches,



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


[PATCH] D81336: [clang-tidy] simplify-bool-expr ignores template instantiations

2020-06-07 Thread Nathan James via Phabricator via cfe-commits
njames93 marked an inline comment as done.
njames93 added inline comments.



Comment at: 
clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp:425
   Finder->addMatcher(
-  ifStmt(isExpansionInMainFile(),
  hasCondition(cxxBoolLiteral(equals(Value)).bind(BooleanId)))

aaron.ballman wrote:
> This is changing the behavior so that now it will diagnose in header files, 
> no? Why is the correct change to replace this with 
> `unless(isInTemplateInstantiation())` instead of adding the new matcher?
It's changing behaviour that arguably shouldn't have been in the first place. 
But perhaps that change should go on a new patch or update the description of 
this one


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D81336



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


[clang] 27e0077 - Try to make msvc crash less

2020-06-07 Thread Benjamin Kramer via cfe-commits

Author: Benjamin Kramer
Date: 2020-06-07T18:07:07+02:00
New Revision: 27e0077dcf0a868072fb31e68b0c1ca0e249e775

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

LOG: Try to make msvc crash less

llvm-project\clang\lib\Driver\Types.cpp(44): fatal error C1001: An internal 
error has occurred in the compiler.
(compiler file 'msc1.cpp', line 1518)

Added: 


Modified: 
clang/lib/Driver/Types.cpp

Removed: 




diff  --git a/clang/lib/Driver/Types.cpp b/clang/lib/Driver/Types.cpp
index e330352c2368..8e1236bd08ec 100644
--- a/clang/lib/Driver/Types.cpp
+++ b/clang/lib/Driver/Types.cpp
@@ -28,7 +28,7 @@ struct TypeInfo {
 unsigned Bits = 0;
 
   public:
-constexpr PhasesBitSet(const std::initializer_list &Phases) {
+constexpr PhasesBitSet(std::initializer_list Phases) {
   for (auto Id : Phases)
 Bits |= 1 << Id;
 }



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


[PATCH] D81336: [clang-tidy] simplify-bool-expr ignores template instantiations

2020-06-07 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: 
clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp:425
   Finder->addMatcher(
-  ifStmt(isExpansionInMainFile(),
  hasCondition(cxxBoolLiteral(equals(Value)).bind(BooleanId)))

njames93 wrote:
> aaron.ballman wrote:
> > This is changing the behavior so that now it will diagnose in header files, 
> > no? Why is the correct change to replace this with 
> > `unless(isInTemplateInstantiation())` instead of adding the new matcher?
> It's changing behaviour that arguably shouldn't have been in the first place. 
> But perhaps that change should go on a new patch or update the description of 
> this one
I'll admit that the original code seems a bit suspect to me. I sort of wonder 
if it was being used to suppress diagnosing macros unless they're considered to 
be under the user's control. e.g., macros in headers may not be plausible to 
change but macros in source files are.

If changes should be made here, I don't have strong opinions on whether it 
requires a separate patch or can be done in this one, but I'd like to better 
understand why the original code was incorrect (if it is in fact incorrect).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D81336



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


[PATCH] D81346: [KernelAddressSanitizer] Ensure global array size remains multiple of type-size

2020-06-07 Thread Marco Elver via Phabricator via cfe-commits
melver created this revision.
melver added reviewers: nathanchance, glider, andreyknvl.
Herald added subscribers: llvm-commits, cfe-commits, hiraditya.
Herald added a reviewer: aaron.ballman.
Herald added projects: clang, LLVM.

The kernel expects certain global arrays' size to remain a multiple of
the array type. In particular, for kernel modules some arrays of structs
shared with userspace are sanity-checked by modpost to have a size that
is a multiple of that type:

https://elixir.bootlin.com/linux/latest/source/scripts/mod/file2alias.c#L132

Since the AddressSanitizer takes a global and replaces it with a new one
that has the redzone appended to it, any information about the global as
well as the section size is increased. Therefore, to ensure we retain
the array-size-property required for globals, calculate the redzone size
to be a multiple of the original global's size.

To improve readability, the existing redzone size calculation is
refactored into its own function; no other functional change intended.

Report: https://github.com/ClangBuiltLinux/linux/issues/1045


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D81346

Files:
  clang/test/CodeGen/asan-globals.cpp
  llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp

Index: llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
===
--- llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
+++ llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
@@ -796,9 +796,10 @@
   StringRef getGlobalMetadataSection() const;
   void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
   void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
-  size_t MinRedzoneSizeForGlobal() const {
+  uint64_t getMinRedzoneSizeForGlobal() const {
 return RedzoneSizeForScale(Mapping.Scale);
   }
+  uint64_t getRedzoneSizeForGlobal(uint64_t SizeInBytes) const;
   int GetAsanVersion(const Module &M) const;
 
   const GlobalsMetadata &GlobalsMD;
@@ -1807,7 +1808,7 @@
   //   - Need to poison all copies, not just the main thread's one.
   if (G->isThreadLocal()) return false;
   // For now, just ignore this Global if the alignment is large.
-  if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
+  if (G->getAlignment() > getMinRedzoneSizeForGlobal()) return false;
 
   // For non-COFF targets, only instrument globals known to be defined by this
   // TU.
@@ -2276,7 +2277,6 @@
   M, M.getModuleIdentifier(), /*AllowMerging*/ false, kAsanGenPrefix);
 
   for (size_t i = 0; i < n; i++) {
-static const uint64_t kMaxGlobalRedzone = 1 << 18;
 GlobalVariable *G = GlobalsToChange[i];
 
 // FIXME: Metadata should be attched directly to the global directly instead
@@ -2290,16 +2290,8 @@
 /*AllowMerging*/ true, kAsanGenPrefix);
 
 Type *Ty = G->getValueType();
-uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
-uint64_t MinRZ = MinRedzoneSizeForGlobal();
-// MinRZ <= RZ <= kMaxGlobalRedzone
-// and trying to make RZ to be ~ 1/4 of SizeInBytes.
-uint64_t RZ = std::max(
-MinRZ, std::min(kMaxGlobalRedzone, (SizeInBytes / MinRZ / 4) * MinRZ));
-uint64_t RightRedzoneSize = RZ;
-// Round up to MinRZ
-if (SizeInBytes % MinRZ) RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
-assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
+const uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
+const uint64_t RightRedzoneSize = getRedzoneSizeForGlobal(SizeInBytes);
 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
 
 StructType *NewTy = StructType::get(Ty, RightRedZoneTy);
@@ -2315,7 +2307,7 @@
"", G, G->getThreadLocalMode());
 NewGlobal->copyAttributesFrom(G);
 NewGlobal->setComdat(G->getComdat());
-NewGlobal->setAlignment(MaybeAlign(MinRZ));
+NewGlobal->setAlignment(MaybeAlign(getMinRedzoneSizeForGlobal()));
 // Don't fold globals with redzones. ODR violation detector and redzone
 // poisoning implicitly creates a dependence on the global's address, so it
 // is no longer valid for it to be marked unnamed_addr.
@@ -2437,6 +2429,39 @@
   return true;
 }
 
+uint64_t
+ModuleAddressSanitizer::getRedzoneSizeForGlobal(uint64_t SizeInBytes) const {
+  const uint64_t MinRZ = getMinRedzoneSizeForGlobal();
+  // Limit redzone size when compiling the kernel.
+  const uint64_t MaxRZ = CompileKernel ? MinRZ * 2 : 1 << 18;
+
+  // Calculate RZ, where MinRZ <= RZ <= MaxRZ, and RZ ~ 1/4 * SizeInBytes.
+  uint64_t RZ =
+  std::max(MinRZ, std::min(MaxRZ, (SizeInBytes / MinRZ / 4) * MinRZ));
+
+  // Round up to multiple of MinRZ.
+  if (SizeInBytes % MinRZ)
+RZ += MinRZ - (SizeInBytes % MinRZ);
+  assert((RZ + SizeInBytes) % MinRZ == 0);
+
+  if (CompileKernel && SizeInBytes && RZ % SizeInBytes) {
+// When compiling the Linux kernel, ensure that the size of global+redzone
+// has the same divisors as b

[PATCH] D81336: [clang-tidy] simplify-bool-expr ignores template instantiations

2020-06-07 Thread Nathan James via Phabricator via cfe-commits
njames93 marked an inline comment as done.
njames93 added inline comments.



Comment at: 
clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp:425
   Finder->addMatcher(
-  ifStmt(isExpansionInMainFile(),
  hasCondition(cxxBoolLiteral(equals(Value)).bind(BooleanId)))

aaron.ballman wrote:
> njames93 wrote:
> > aaron.ballman wrote:
> > > This is changing the behavior so that now it will diagnose in header 
> > > files, no? Why is the correct change to replace this with 
> > > `unless(isInTemplateInstantiation())` instead of adding the new matcher?
> > It's changing behaviour that arguably shouldn't have been in the first 
> > place. But perhaps that change should go on a new patch or update the 
> > description of this one
> I'll admit that the original code seems a bit suspect to me. I sort of wonder 
> if it was being used to suppress diagnosing macros unless they're considered 
> to be under the user's control. e.g., macros in headers may not be plausible 
> to change but macros in source files are.
> 
> If changes should be made here, I don't have strong opinions on whether it 
> requires a separate patch or can be done in this one, but I'd like to better 
> understand why the original code was incorrect (if it is in fact incorrect).
So having a look in the archives shows this condition was on the [[ 
https://reviews.llvm.org/D7648?id=19976 | first draft for this check. ]] But I 
couldn't see any discussion about it.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D81336



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


[PATCH] D81336: [clang-tidy] simplify-bool-expr ignores template instantiations

2020-06-07 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a subscriber: LegalizeAdulthood.
aaron.ballman added inline comments.



Comment at: 
clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp:425
   Finder->addMatcher(
-  ifStmt(isExpansionInMainFile(),
  hasCondition(cxxBoolLiteral(equals(Value)).bind(BooleanId)))

njames93 wrote:
> aaron.ballman wrote:
> > njames93 wrote:
> > > aaron.ballman wrote:
> > > > This is changing the behavior so that now it will diagnose in header 
> > > > files, no? Why is the correct change to replace this with 
> > > > `unless(isInTemplateInstantiation())` instead of adding the new matcher?
> > > It's changing behaviour that arguably shouldn't have been in the first 
> > > place. But perhaps that change should go on a new patch or update the 
> > > description of this one
> > I'll admit that the original code seems a bit suspect to me. I sort of 
> > wonder if it was being used to suppress diagnosing macros unless they're 
> > considered to be under the user's control. e.g., macros in headers may not 
> > be plausible to change but macros in source files are.
> > 
> > If changes should be made here, I don't have strong opinions on whether it 
> > requires a separate patch or can be done in this one, but I'd like to 
> > better understand why the original code was incorrect (if it is in fact 
> > incorrect).
> So having a look in the archives shows this condition was on the [[ 
> https://reviews.llvm.org/D7648?id=19976 | first draft for this check. ]] But 
> I couldn't see any discussion about it.
Drat, that matches my digging too. I think the current patch should leave this 
requirement in place so we can get the bug fix in while we figure out what to 
do with this bit (assuming the bug fix doesn't rely on this change somehow). If 
you want to remove the main file requirement in another patch, I'd suggest 
adding @LegalizeAdulthood as a reviewer to see if they remember why this 
condition was in place and (I believe) wasn't tested.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D81336



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


[clang] 02e3583 - [Driver] Simplify code. NFCI.

2020-06-07 Thread Benjamin Kramer via cfe-commits

Author: Benjamin Kramer
Date: 2020-06-07T20:18:14+02:00
New Revision: 02e35832c301e9813b0bb18e94db2a31c4849a73

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

LOG: [Driver] Simplify code. NFCI.

Added: 


Modified: 
clang/include/clang/Driver/Phases.h
clang/include/clang/Driver/Types.h
clang/lib/Driver/Driver.cpp
clang/lib/Driver/Types.cpp

Removed: 




diff  --git a/clang/include/clang/Driver/Phases.h 
b/clang/include/clang/Driver/Phases.h
index 9003c5857351..ce914dd70514 100644
--- a/clang/include/clang/Driver/Phases.h
+++ b/clang/include/clang/Driver/Phases.h
@@ -22,10 +22,11 @@ namespace phases {
 Assemble,
 Link,
 IfsMerge,
+LastPhase = IfsMerge,
   };
 
   enum {
-MaxNumberOfPhases = IfsMerge + 1
+MaxNumberOfPhases = LastPhase + 1
   };
 
   const char *getPhaseName(ID Id);

diff  --git a/clang/include/clang/Driver/Types.h 
b/clang/include/clang/Driver/Types.h
index c7c38fa52593..97bf5fd672ab 100644
--- a/clang/include/clang/Driver/Types.h
+++ b/clang/include/clang/Driver/Types.h
@@ -45,9 +45,6 @@ namespace types {
   /// temp file of this type, or null if unspecified.
   const char *getTypeTempSuffix(ID Id, bool CLMode = false);
 
-  /// onlyAssembleType - Should this type only be assembled.
-  bool onlyAssembleType(ID Id);
-
   /// onlyPrecompileType - Should this type only be precompiled.
   bool onlyPrecompileType(ID Id);
 
@@ -101,13 +98,12 @@ namespace types {
   ID lookupTypeForTypeSpecifier(const char *Name);
 
   /// getCompilationPhases - Get the list of compilation phases ('Phases') to 
be
-  /// done for type 'Id'.
-  void getCompilationPhases(
-ID Id,
-llvm::SmallVectorImpl &Phases);
-  void getCompilationPhases(const clang::driver::Driver &Driver,
-llvm::opt::DerivedArgList &DAL, ID Id,
-llvm::SmallVectorImpl &Phases);
+  /// done for type 'Id' up until including LastPhase.
+  llvm::SmallVector
+  getCompilationPhases(ID Id, phases::ID LastPhase = phases::LastPhase);
+  llvm::SmallVector
+  getCompilationPhases(const clang::driver::Driver &Driver,
+   llvm::opt::DerivedArgList &DAL, ID Id);
 
   /// lookupCXXTypeForCType - Lookup CXX input type that corresponds to given
   /// C type (used for clang++ emulation of g++ behaviour)

diff  --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index 5c726b23148f..8cc5eceaa512 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -3276,8 +3276,7 @@ void Driver::handleArguments(Compilation &C, 
DerivedArgList &Args,
 types::ID InputType = I.first;
 const Arg *InputArg = I.second;
 
-llvm::SmallVector PL;
-types::getCompilationPhases(InputType, PL);
+auto PL = types::getCompilationPhases(InputType);
 LastPLSize = PL.size();
 
 // If the first step comes after the final phase we are doing as part of
@@ -3322,11 +3321,9 @@ void Driver::handleArguments(Compilation &C, 
DerivedArgList &Args,
   // Add a separate precompile phase for the compile phase.
   if (FinalPhase >= phases::Compile) {
 const types::ID HeaderType = lookupHeaderTypeForSourceType(InputType);
-llvm::SmallVector PCHPL;
-types::getCompilationPhases(HeaderType, PCHPL);
 // Build the pipeline for the pch file.
 Action *ClangClPch = C.MakeAction(*InputArg, HeaderType);
-for (phases::ID Phase : PCHPL)
+for (phases::ID Phase : types::getCompilationPhases(HeaderType))
   ClangClPch = ConstructPhaseAction(C, Args, Phase, ClangClPch);
 assert(ClangClPch);
 Actions.push_back(ClangClPch);
@@ -3409,13 +3406,11 @@ void Driver::BuildActions(Compilation &C, 
DerivedArgList &Args,
 types::ID InputType = I.first;
 const Arg *InputArg = I.second;
 
-llvm::SmallVector PL;
-types::getCompilationPhases(*this, Args, InputType, PL);
+auto PL = types::getCompilationPhases(*this, Args, InputType);
 if (PL.empty())
   continue;
 
-llvm::SmallVector FullPL;
-types::getCompilationPhases(InputType, FullPL);
+auto FullPL = types::getCompilationPhases(InputType);
 
 // Build the pipeline for this file.
 Action *Current = C.MakeAction(*InputArg, InputType);
@@ -3509,15 +3504,9 @@ void Driver::BuildActions(Compilation &C, DerivedArgList 
&Args,
 C.MakeAction(MergerInputs, types::TY_Image));
 
   if (Args.hasArg(options::OPT_emit_interface_stubs)) {
-llvm::SmallVector PhaseList;
-if (Args.hasArg(options::OPT_c)) {
-  llvm::SmallVector 
CompilePhaseList;
-  types::getCompilationPhases(types::TY_IFS_CPP, CompilePhaseList);
-  llvm::copy_if(CompilePhaseList, std::back_inserter(PhaseList),
-[&](phases::ID Phase) { return Phas

[PATCH] D81347: Make ASTFileSignature an array of 20 uint8_t instead of 5 uint32_t

2020-06-07 Thread Daniel Grumberg via Phabricator via cfe-commits
dang marked an inline comment as done.
dang added inline comments.



Comment at: clang/include/clang/Basic/Module.h:70
+
+  static ASTFileSignature createDISentinel() {
+ASTFileSignature Sentinel;

I couldn't find anywhere in the code base that checks the bit-pattern so I left 
it as is. If anyone knows if someone could point me to the code that checks 
this (if any code does check it) that would be nice.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D81347



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


[PATCH] D81347: Make ASTFileSignature an array of 20 uint8_t instead of 5 uint32_t

2020-06-07 Thread Daniel Grumberg via Phabricator via cfe-commits
dang created this revision.
dang added reviewers: aprantl, dexonsmith, Bigcheese.
Herald added subscribers: cfe-commits, arphaman.
Herald added a project: clang.
dang marked an inline comment as done.
dang added inline comments.



Comment at: clang/include/clang/Basic/Module.h:70
+
+  static ASTFileSignature createDISentinel() {
+ASTFileSignature Sentinel;

I couldn't find anywhere in the code base that checks the bit-pattern so I left 
it as is. If anyone knows if someone could point me to the code that checks 
this (if any code does check it) that would be nice.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D81347

Files:
  clang/include/clang/Basic/Module.h
  clang/lib/CodeGen/ObjectFilePCHContainerOperations.cpp
  clang/lib/Serialization/ASTReader.cpp
  clang/lib/Serialization/ASTWriter.cpp
  clang/lib/Serialization/GlobalModuleIndex.cpp

Index: clang/lib/Serialization/GlobalModuleIndex.cpp
===
--- clang/lib/Serialization/GlobalModuleIndex.cpp
+++ clang/lib/Serialization/GlobalModuleIndex.cpp
@@ -643,10 +643,10 @@
 
 // Skip the stored signature.
 // FIXME: we could read the signature out of the import and validate it.
-ASTFileSignature StoredSignature = {
-{{(uint32_t)Record[Idx++], (uint32_t)Record[Idx++],
-  (uint32_t)Record[Idx++], (uint32_t)Record[Idx++],
-  (uint32_t)Record[Idx++]}}};
+auto FirstSignatureByte = Record.begin() + Idx;
+ASTFileSignature StoredSignature = ASTFileSignature::create(
+FirstSignatureByte, FirstSignatureByte + ASTFileSignature::size);
+Idx += ASTFileSignature::size;
 
 // Skip the module name (currently this is only used for prebuilt
 // modules while here we are only dealing with cached).
@@ -704,9 +704,8 @@
 
 // Get Signature.
 if (State == DiagnosticOptionsBlock && Code == SIGNATURE)
-  getModuleFileInfo(File).Signature = {
-  {{(uint32_t)Record[0], (uint32_t)Record[1], (uint32_t)Record[2],
-(uint32_t)Record[3], (uint32_t)Record[4]}}};
+  getModuleFileInfo(File).Signature = ASTFileSignature::create(
+  Record.begin(), Record.begin() + ASTFileSignature::size);
 
 // We don't care about this record.
   }
Index: clang/lib/Serialization/ASTWriter.cpp
===
--- clang/lib/Serialization/ASTWriter.cpp
+++ clang/lib/Serialization/ASTWriter.cpp
@@ -1032,16 +1032,7 @@
   Hasher.update(ArrayRef(Bytes.bytes_begin(), Bytes.size()));
   auto Hash = Hasher.result();
 
-  // Convert to an array [5*i32].
-  ASTFileSignature Signature;
-  auto LShift = [&](unsigned char Val, unsigned Shift) {
-return (uint32_t)Val << Shift;
-  };
-  for (int I = 0; I != 5; ++I)
-Signature[I] = LShift(Hash[I * 4 + 0], 24) | LShift(Hash[I * 4 + 1], 16) |
-   LShift(Hash[I * 4 + 2], 8) | LShift(Hash[I * 4 + 3], 0);
-
-  return Signature;
+  return ASTFileSignature::create(Hash);
 }
 
 ASTFileSignature ASTWriter::writeUnhashedControlBlock(Preprocessor &PP,
Index: clang/lib/Serialization/ASTReader.cpp
===
--- clang/lib/Serialization/ASTReader.cpp
+++ clang/lib/Serialization/ASTReader.cpp
@@ -2791,10 +2791,10 @@
 ReadUntranslatedSourceLocation(Record[Idx++]);
 off_t StoredSize = (off_t)Record[Idx++];
 time_t StoredModTime = (time_t)Record[Idx++];
-ASTFileSignature StoredSignature = {
-{{(uint32_t)Record[Idx++], (uint32_t)Record[Idx++],
-  (uint32_t)Record[Idx++], (uint32_t)Record[Idx++],
-  (uint32_t)Record[Idx++]}}};
+auto FirstSignatureByte = Record.begin() + Idx;
+ASTFileSignature StoredSignature = ASTFileSignature::create(
+FirstSignatureByte, FirstSignatureByte + ASTFileSignature::size);
+Idx += ASTFileSignature::size;
 
 std::string ImportedName = ReadString(Record, Idx);
 std::string ImportedFile;
@@ -5023,8 +5023,8 @@
   return ASTFileSignature();
 }
 if (SIGNATURE == MaybeRecord.get())
-  return {{{(uint32_t)Record[0], (uint32_t)Record[1], (uint32_t)Record[2],
-(uint32_t)Record[3], (uint32_t)Record[4]}}};
+  return ASTFileSignature::create(Record.begin(),
+  Record.begin() + ASTFileSignature::size);
   }
 }
 
@@ -5322,7 +5322,9 @@
   unsigned Idx = 0, N = Record.size();
   while (Idx < N) {
 // Read information about the AST file.
-Idx += 1+1+1+1+5; // Kind, ImportLoc, Size, ModTime, Signature
+Idx +=
+1 + 1 + 1 + 1 +
+ASTFileSignature::size; // Kind, ImportLoc, Size, ModTime, Signature
 std::string ModuleName = ReadString(Record, Idx);
 std::string Filename = ReadString(Record, Idx);
 ResolveImportedPath(F

[clang] 336e1f0 - [Driver] Omit -mthread-model posix which is the CC1 default

2020-06-07 Thread Fangrui Song via cfe-commits

Author: Fangrui Song
Date: 2020-06-07T12:27:11-07:00
New Revision: 336e1f03d1bcda60cf02df09d2331a0ea9af3030

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

LOG: [Driver] Omit -mthread-model posix which is the CC1 default

Added: 


Modified: 
clang/lib/Driver/ToolChains/Clang.cpp
clang/test/Driver/thread-model.c

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 577733a112c4..63b9d0e14003 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -,15 +,20 @@ void Clang::ConstructJob(Compilation &C, const 
JobAction &JA,
 if (RelocationModel != llvm::Reloc::Static && !IsPIE)
   A->render(Args, CmdArgs);
 
-  CmdArgs.push_back("-mthread-model");
-  if (Arg *A = Args.getLastArg(options::OPT_mthread_model)) {
-if (!TC.isThreadModelSupported(A->getValue()))
-  D.Diag(diag::err_drv_invalid_thread_model_for_target)
-  << A->getValue() << A->getAsString(Args);
-CmdArgs.push_back(A->getValue());
+  {
+std::string Model;
+if (Arg *A = Args.getLastArg(options::OPT_mthread_model)) {
+  if (!TC.isThreadModelSupported(A->getValue()))
+D.Diag(diag::err_drv_invalid_thread_model_for_target)
+<< A->getValue() << A->getAsString(Args);
+  Model = A->getValue();
+} else
+  Model = TC.getThreadModel();
+if (Model != "posix") {
+  CmdArgs.push_back("-mthread-model");
+  CmdArgs.push_back(Args.MakeArgString(Model));
+}
   }
-  else
-CmdArgs.push_back(Args.MakeArgString(TC.getThreadModel()));
 
   Args.AddLastArg(CmdArgs, options::OPT_fveclib);
 

diff  --git a/clang/test/Driver/thread-model.c 
b/clang/test/Driver/thread-model.c
index d01ef1c1a47c..5bc2be2f7378 100644
--- a/clang/test/Driver/thread-model.c
+++ b/clang/test/Driver/thread-model.c
@@ -1,31 +1,16 @@
-// RUN: %clang -### -target arm-unknown-linux-gnu -c %s -mthread-model posix 
-v 2>&1 | FileCheck -check-prefix=CHECK-POSIX %s
-// RUN: %clang -### -target arm-unknown-linux-gnu -c %s -mthread-model single 
-v 2>&1 | FileCheck -check-prefix=CHECK-SINGLE %s
-// RUN: not %clang -target arm-unknown-linux-gnu -c %s -mthread-model silly -v 
2>&1 | FileCheck -check-prefix=CHECK-INVALID %s
-// CHECK-POSIX: "-mthread-model" "posix"
-// CHECK-SINGLE: "-mthread-model" "single"
-// CHECK-INVALID: error: invalid thread model 'silly' in '-mthread-model 
silly' for this target
+// RUN: %clang -### -target arm-unknown-linux-gnu -c %s -mthread-model posix 
-v 2>&1 | FileCheck %s
+// RUN: %clang -### -target arm-unknown-linux-gnu -c %s -v 2>&1 | FileCheck %s
+// RUN: %clang -### -target arm-unknown-linux-gnu -c %s -mthread-model single 
-v 2>&1 | FileCheck --check-prefix=SINGLE %s
+// RUN: not %clang -target arm-unknown-linux-gnu -c %s -mthread-model silly -v 
2>&1 | FileCheck --check-prefix=INVALID %s
 
-// RUN: %clang -### -target arm-unknown-linux-gnu -c %s -v 2>&1 | FileCheck 
-check-prefix=CHECK-LINUX-POSIX %s
-// RUN: %clang -### -target arm-unknown-linux-gnu -c %s -v -mthread-model 
single 2>&1 | FileCheck -check-prefix=CHECK-LINUX-SINGLE %s
-// RUN: %clang -### -target arm-unknown-linux-gnu -c %s -v -mthread-model 
silly 2>&1 | FileCheck -check-prefix=CHECK-LINUX-INVALID %s
-// CHECK-LINUX-POSIX: Thread model: posix
-// CHECK-LINUX-POSIX: "-mthread-model" "posix"
-// CHECK-LINUX-SINGLE: Thread model: single
-// CHECK-LINUX-SINGLE: "-mthread-model" "single"
-// CHECK-LINUX-INVALID-NOT: Thread model:
+// CHECK: Thread model: posix
+// CHECK-NOT: "-mthread-model"
+// SINGLE: Thread model: single
+// SINGLE: "-mthread-model" "single"
+// INVALID: error: invalid thread model 'silly' in '-mthread-model silly' for 
this target
 
-// RUN: %clang -### -target wasm32-unknown-linux-gnu -c %s -v 2>&1 | FileCheck 
-check-prefix=CHECK-WEBASSEMBLY-DEFAULT %s
-// RUN: %clang -### -target wasm32-unknown-linux-gnu -c %s -v -mthread-model 
single 2>&1 | FileCheck -check-prefix=CHECK-WEBASSEMBLY-SINGLE %s
-// RUN: %clang -### -target wasm32-unknown-linux-gnu -c %s -v -mthread-model 
posix 2>&1 | FileCheck -check-prefix=CHECK-WEBASSEMBLY-POSIX %s
-// RUN: %clang -### -target wasm32-unknown-linux-gnu -c %s -v -mthread-model 
silly 2>&1 | FileCheck -check-prefix=CHECK-WEBASSEMBLY-INVALID %s
-// RUN: %clang -### -target wasm64-unknown-linux-gnu -c %s -v 2>&1 | FileCheck 
-check-prefix=CHECK-WEBASSEMBLY-DEFAULT %s
-// RUN: %clang -### -target wasm64-unknown-linux-gnu -c %s -v -mthread-model 
single 2>&1 | FileCheck -check-prefix=CHECK-WEBASSEMBLY-SINGLE %s
-// RUN: %clang -### -target wasm64-unknown-linux-gnu -c %s -v -mthread-model 
posix 2>&1 | FileCheck -check-prefix=CHECK-WEBASSEMBLY-POSIX %s
-// RUN: %clang -### -target wasm64-unknown-linux-gnu -c %s -v -mthread-mode

[clang] b6e143a - Reland D80966 [codeview] Put !heapallocsite on calls to operator new

2020-06-07 Thread Fangrui Song via cfe-commits

Author: Fangrui Song
Date: 2020-06-07T13:35:20-07:00
New Revision: b6e143aa5448bbe29da7b045072e66a31813bced

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

LOG: Reland D80966 [codeview] Put !heapallocsite on calls to operator new

With a change to use `CGM.getCodeGenOpts().getDebugInfo() != 
codegenoptions::NoDebugInfo`
instead of `getDebugInfo()`,
to fix `Profile- :: instrprof-gcov-multithread_fork.test`

See CodeGenModule::CodeGenModule, `EmitGcovArcs || EmitGcovNotes` can
set `clang::CodeGen::CodeGenModule::DebugInfo`.

---

Clang marks calls to operator new as heap allocation sites, but the
operator declared at global scope returns a void pointer. There is no
explicit cast in the code, so the compiler has to write down the
allocated type itself.

Also generalize a cast to use CallBase, so that we mark heap alloc sites
when exceptions are enabled.

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

Added: 
clang/test/CodeGenCXX/debug-info-codeview-heapallocsite.cpp

Modified: 
clang/lib/CodeGen/CGCall.cpp
clang/lib/CodeGen/CGDebugInfo.cpp
clang/lib/CodeGen/CGDebugInfo.h
clang/lib/CodeGen/CGExprCXX.cpp
clang/lib/CodeGen/CGExprScalar.cpp
clang/test/CodeGen/debug-info-codeview-heapallocsite.c

Removed: 




diff  --git a/clang/lib/CodeGen/CGCall.cpp b/clang/lib/CodeGen/CGCall.cpp
index 6bde3124555b..136782fccf40 100644
--- a/clang/lib/CodeGen/CGCall.cpp
+++ b/clang/lib/CodeGen/CGCall.cpp
@@ -4951,7 +4951,7 @@ RValue CodeGenFunction::EmitCall(const CGFunctionInfo 
&CallInfo,
   // Add metadata for calls to MSAllocator functions
   if (getDebugInfo() && TargetDecl &&
   TargetDecl->hasAttr())
-getDebugInfo()->addHeapAllocSiteMetadata(CI, RetTy, Loc);
+getDebugInfo()->addHeapAllocSiteMetadata(CI, RetTy->getPointeeType(), Loc);
 
   // 4. Finish the call.
 

diff  --git a/clang/lib/CodeGen/CGDebugInfo.cpp 
b/clang/lib/CodeGen/CGDebugInfo.cpp
index cc50ec6a8c89..1737154d179a 100644
--- a/clang/lib/CodeGen/CGDebugInfo.cpp
+++ b/clang/lib/CodeGen/CGDebugInfo.cpp
@@ -2146,16 +2146,14 @@ llvm::DIType 
*CGDebugInfo::getOrCreateStandaloneType(QualType D,
   return T;
 }
 
-void CGDebugInfo::addHeapAllocSiteMetadata(llvm::Instruction *CI,
-   QualType D,
+void CGDebugInfo::addHeapAllocSiteMetadata(llvm::CallBase *CI,
+   QualType AllocatedTy,
SourceLocation Loc) {
   llvm::MDNode *node;
-  if (D.getTypePtr()->isVoidPointerType()) {
+  if (AllocatedTy->isVoidType())
 node = llvm::MDNode::get(CGM.getLLVMContext(), None);
-  } else {
-QualType PointeeTy = D.getTypePtr()->getPointeeType();
-node = getOrCreateType(PointeeTy, getOrCreateFile(Loc));
-  }
+  else
+node = getOrCreateType(AllocatedTy, getOrCreateFile(Loc));
 
   CI->setMetadata("heapallocsite", node);
 }

diff  --git a/clang/lib/CodeGen/CGDebugInfo.h b/clang/lib/CodeGen/CGDebugInfo.h
index 367047e79dc9..96ef6c7c1d27 100644
--- a/clang/lib/CodeGen/CGDebugInfo.h
+++ b/clang/lib/CodeGen/CGDebugInfo.h
@@ -509,7 +509,7 @@ class CGDebugInfo {
   llvm::DIType *getOrCreateStandaloneType(QualType Ty, SourceLocation Loc);
 
   /// Add heapallocsite metadata for MSAllocator calls.
-  void addHeapAllocSiteMetadata(llvm::Instruction *CallSite, QualType Ty,
+  void addHeapAllocSiteMetadata(llvm::CallBase *CallSite, QualType AllocatedTy,
 SourceLocation Loc);
 
   void completeType(const EnumDecl *ED);

diff  --git a/clang/lib/CodeGen/CGExprCXX.cpp b/clang/lib/CodeGen/CGExprCXX.cpp
index d0012337cdd3..23cc97bcdc9f 100644
--- a/clang/lib/CodeGen/CGExprCXX.cpp
+++ b/clang/lib/CodeGen/CGExprCXX.cpp
@@ -1638,6 +1638,12 @@ llvm::Value *CodeGenFunction::EmitCXXNewExpr(const 
CXXNewExpr *E) {
 RValue RV =
   EmitNewDeleteCall(*this, allocator, allocatorType, allocatorArgs);
 
+// Set !heapallocsite metadata on the call to operator new.
+if (CGM.getCodeGenOpts().getDebugInfo() != codegenoptions::NoDebugInfo)
+  if (auto *newCall = dyn_cast(RV.getScalarVal()))
+getDebugInfo()->addHeapAllocSiteMetadata(newCall, allocType,
+ E->getExprLoc());
+
 // If this was a call to a global replaceable allocation function that does
 // not take an alignment argument, the allocator is known to produce
 // storage that's suitably aligned for any object that fits, up to a known

diff  --git a/clang/lib/CodeGen/CGExprScalar.cpp 
b/clang/lib/CodeGen/CGExprScalar.cpp
index cabfe0cca281..4e61349cf4d5 100644
--- a/clang/lib/CodeGen/CGExprScalar.cpp
+++ b/clang/lib/CodeGen/CGExprScalar.cpp
@@ -2081,11 +2081,15 @@ Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) {
   }
 }
 

[clang] 3badd17 - SmallPtrSet::find -> SmallPtrSet::count

2020-06-07 Thread Benjamin Kramer via cfe-commits

Author: Benjamin Kramer
Date: 2020-06-07T22:38:08+02:00
New Revision: 3badd17b6989621b5aa2732800f697dabbda034d

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

LOG: SmallPtrSet::find -> SmallPtrSet::count

The latter is more readable and more efficient. While there clean up
some double lookups. NFCI.

Added: 


Modified: 
clang/lib/StaticAnalyzer/Core/PlistDiagnostics.cpp
lldb/source/Plugins/ExpressionParser/Clang/ClangASTImporter.cpp
llvm/lib/Analysis/DependenceGraphBuilder.cpp
llvm/lib/Analysis/StackSafetyAnalysis.cpp
llvm/lib/IR/Verifier.cpp
llvm/lib/Target/AMDGPU/GCNMinRegStrategy.cpp
llvm/lib/Transforms/Scalar/DeadStoreElimination.cpp
llvm/lib/Transforms/Scalar/LoopInterchange.cpp
llvm/lib/Transforms/Scalar/LowerMatrixIntrinsics.cpp
llvm/lib/Transforms/Utils/BypassSlowDivision.cpp
llvm/lib/Transforms/Utils/Local.cpp
llvm/lib/Transforms/Vectorize/LoopVectorize.cpp
llvm/tools/bugpoint/CrashDebugger.cpp

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Core/PlistDiagnostics.cpp 
b/clang/lib/StaticAnalyzer/Core/PlistDiagnostics.cpp
index 9b6369aee7a8..ed62778623a8 100644
--- a/clang/lib/StaticAnalyzer/Core/PlistDiagnostics.cpp
+++ b/clang/lib/StaticAnalyzer/Core/PlistDiagnostics.cpp
@@ -973,9 +973,8 @@ static std::string getMacroNameAndPrintExpansion(
   // in this case we don't get the full expansion text in the Plist file. See
   // the test file where "value" is expanded to "garbage_" instead of
   // "garbage_value".
-  if (AlreadyProcessedTokens.find(IDInfo) != AlreadyProcessedTokens.end())
+  if (!AlreadyProcessedTokens.insert(IDInfo).second)
 return Info.Name;
-  AlreadyProcessedTokens.insert(IDInfo);
 
   if (!Info.MI)
 return Info.Name;

diff  --git a/lldb/source/Plugins/ExpressionParser/Clang/ClangASTImporter.cpp 
b/lldb/source/Plugins/ExpressionParser/Clang/ClangASTImporter.cpp
index 2a21e5e0d7b9..27efad214476 100644
--- a/lldb/source/Plugins/ExpressionParser/Clang/ClangASTImporter.cpp
+++ b/lldb/source/Plugins/ExpressionParser/Clang/ClangASTImporter.cpp
@@ -1025,7 +1025,7 @@ void 
ClangASTImporter::ASTImporterDelegate::Imported(clang::Decl *from,
 
   // Some decls shouldn't be tracked here because they were not created by
   // copying 'from' to 'to'. Just exit early for those.
-  if (m_decls_to_ignore.find(to) != m_decls_to_ignore.end())
+  if (m_decls_to_ignore.count(to))
 return clang::ASTImporter::Imported(from, to);
 
   // Transfer module ownership information.

diff  --git a/llvm/lib/Analysis/DependenceGraphBuilder.cpp 
b/llvm/lib/Analysis/DependenceGraphBuilder.cpp
index 67304a495960..7a98d844e4cb 100644
--- a/llvm/lib/Analysis/DependenceGraphBuilder.cpp
+++ b/llvm/lib/Analysis/DependenceGraphBuilder.cpp
@@ -435,9 +435,8 @@ template  void 
AbstractDependenceGraphBuilder::simplify() {
 NodeType &Src = *Worklist.pop_back_val();
 // As nodes get merged, we need to skip any node that has been removed from
 // the candidate set (see below).
-if (CandidateSourceNodes.find(&Src) == CandidateSourceNodes.end())
+if (!CandidateSourceNodes.erase(&Src))
   continue;
-CandidateSourceNodes.erase(&Src);
 
 assert(Src.getEdges().size() == 1 &&
"Expected a single edge from the candidate src node.");
@@ -470,10 +469,9 @@ template  void 
AbstractDependenceGraphBuilder::simplify() {
 // We also need to remove the old target (b), from the worklist. We first
 // remove it from the candidate set here, and skip any item from the
 // worklist that is not in the set.
-if (CandidateSourceNodes.find(&Tgt) != CandidateSourceNodes.end()) {
+if (CandidateSourceNodes.erase(&Tgt)) {
   Worklist.push_back(&Src);
   CandidateSourceNodes.insert(&Src);
-  CandidateSourceNodes.erase(&Tgt);
   LLVM_DEBUG(dbgs() << "Putting " << &Src << " back in the worklist.\n");
 }
   }

diff  --git a/llvm/lib/Analysis/StackSafetyAnalysis.cpp 
b/llvm/lib/Analysis/StackSafetyAnalysis.cpp
index dd4ba86df7ca..9d96e9d5d075 100644
--- a/llvm/lib/Analysis/StackSafetyAnalysis.cpp
+++ b/llvm/lib/Analysis/StackSafetyAnalysis.cpp
@@ -684,7 +684,7 @@ StackSafetyGlobalInfo::~StackSafetyGlobalInfo() = default;
 
 bool StackSafetyGlobalInfo::isSafe(const AllocaInst &AI) const {
   const auto &Info = getInfo();
-  return Info.SafeAllocas.find(&AI) != Info.SafeAllocas.end();
+  return Info.SafeAllocas.count(&AI);
 }
 
 void StackSafetyGlobalInfo::print(raw_ostream &O) const {

diff  --git a/llvm/lib/IR/Verifier.cpp b/llvm/lib/IR/Verifier.cpp
index 1c9023a349c2..eae7c03d744e 100644
--- a/llvm/lib/IR/Verifier.cpp
+++ b/llvm/lib/IR/Verifier.cpp
@@ -2613,8 +2613,7 @@ void Verifier::visitCallBrInst(CallBrInst &CBI) {
   if (auto *BA = dyn_cast(V))
 ArgBBs.insert(BA->getBa

LLVM buildmaster will be updated and restarted tonight

2020-06-07 Thread Galina Kistanova via cfe-commits
Hello everyone,

LLVM buildmaster will be updated and restarted after 5PM PST today.

Thanks

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


[PATCH] D81336: [clang-tidy] simplify-bool-expr ignores template instantiations

2020-06-07 Thread Nathan James via Phabricator via cfe-commits
njames93 updated this revision to Diff 269076.
njames93 added a comment.

Added back isExpansionInMainFile check

Should put a follow up to query removing this check.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D81336

Files:
  clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
  clang-tools-extra/test/clang-tidy/checkers/readability-simplify-bool-expr.cpp


Index: 
clang-tools-extra/test/clang-tidy/checkers/readability-simplify-bool-expr.cpp
===
--- 
clang-tools-extra/test/clang-tidy/checkers/readability-simplify-bool-expr.cpp
+++ 
clang-tools-extra/test/clang-tidy/checkers/readability-simplify-bool-expr.cpp
@@ -948,3 +948,18 @@
 }
 // CHECK-MESSAGES: :[[@LINE-4]]:12: warning: {{.*}} in conditional return
 // CHECK-FIXES: S == (A)S;{{$}}
+
+template 
+void ignoreInstantiations() {
+  if (B) {
+return;
+  } else {
+return;
+  }
+}
+
+void instantiate() {
+  // Just make sure the check isn't fooled by template instantiations.
+  ignoreInstantiations();
+  ignoreInstantiations();
+}
Index: clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
===
--- clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
+++ clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
@@ -422,7 +422,7 @@
   bool Value,
   StringRef BooleanId) {
   Finder->addMatcher(
-  ifStmt(isExpansionInMainFile(),
+  ifStmt(isExpansionInMainFile(), unless(isInTemplateInstantiation()),
  hasCondition(cxxBoolLiteral(equals(Value)).bind(BooleanId)))
   .bind(IfStmtId),
   this);
@@ -433,6 +433,7 @@
   StringRef TernaryId) {
   Finder->addMatcher(
   conditionalOperator(isExpansionInMainFile(),
+  unless(isInTemplateInstantiation()),
   hasTrueExpression(cxxBoolLiteral(equals(Value))),
   hasFalseExpression(cxxBoolLiteral(equals(!Value
   .bind(TernaryId),
@@ -443,12 +444,14 @@
   bool Value, StringRef Id) {
   if (ChainedConditionalReturn)
 Finder->addMatcher(ifStmt(isExpansionInMainFile(),
+  unless(isInTemplateInstantiation()),
   hasThen(returnsBool(Value, ThenLiteralId)),
   hasElse(returnsBool(!Value)))
.bind(Id),
this);
   else
 Finder->addMatcher(ifStmt(isExpansionInMainFile(),
+  unless(isInTemplateInstantiation()),
   unless(hasParent(ifStmt())),
   hasThen(returnsBool(Value, ThenLiteralId)),
   hasElse(returnsBool(!Value)))
@@ -474,12 +477,16 @@
   auto Else = anyOf(SimpleElse, compoundStmt(statementCountIs(1),
  hasAnySubstatement(SimpleElse)));
   if (ChainedConditionalAssignment)
-Finder->addMatcher(ifStmt(hasThen(Then), hasElse(Else)).bind(Id), this);
+Finder->addMatcher(ifStmt(unless(isInTemplateInstantiation()),
+  hasThen(Then), hasElse(Else))
+   .bind(Id),
+   this);
   else
-Finder->addMatcher(
-ifStmt(unless(hasParent(ifStmt())), hasThen(Then), hasElse(Else))
-.bind(Id),
-this);
+Finder->addMatcher(ifStmt(unless(isInTemplateInstantiation()),
+  unless(hasParent(ifStmt())), hasThen(Then),
+  hasElse(Else))
+   .bind(Id),
+   this);
 }
 
 void SimplifyBooleanExprCheck::matchCompoundIfReturnsBool(MatchFinder *Finder,
@@ -487,6 +494,7 @@
   StringRef Id) {
   Finder->addMatcher(
   compoundStmt(
+  unless(isInTemplateInstantiation()),
   hasAnySubstatement(
   ifStmt(hasThen(returnsBool(Value)), unless(hasElse(stmt(),
   hasAnySubstatement(returnStmt(has(ignoringParenImpCasts(


Index: clang-tools-extra/test/clang-tidy/checkers/readability-simplify-bool-expr.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/readability-simplify-bool-expr.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/readability-simplify-bool-expr.cpp
@@ -948,3 +948,18 @@
 }
 // CHECK-MESSAGES: :[[@LINE-4]]:12: warning: {{.*}} in conditional return
 // CHECK-FIXES: S == (A)S;{{$}}
+
+template 
+void ignoreInstantiations() {
+  if (B) {
+return;
+  } else {
+return;
+  }
+}
+
+void instantia

[PATCH] D81351: [clangd] Parse std::make_unique, and emit template diagnostics at expansion.

2020-06-07 Thread Sam McCall via Phabricator via cfe-commits
sammccall created this revision.
sammccall added a reviewer: hokein.
Herald added subscribers: cfe-commits, usaxena95, kadircet, arphaman, jkorous, 
MaskRay, ilya-biryukov.
Herald added a reviewer: aaron.ballman.
Herald added a project: clang.

Parsing std::make_unique is an exception to the usual non-parsing of function
bodies in the preamble. (A hook is added to PreambleCallbacks to allow this).
This allows us to diagnose make_unique(wrong arg list), and opens the door
to providing signature help (by detecting where the arg list is forwarded to).
This function is trivial (checked libc++ and libstdc++) and doesn't result in
any extra templates being instantiated, so this should be cheap.

This uncovered a second issue (already visible with class templates)...

Errors produced by template instantiation have primary locations within the
template, with instantiation stack reported as notes.
For templates defined in headers, these end up reported at the #include
directive, which isn't terribly helpful as the header itself is probably fine.
This patch reports them at the instantiation site (the first location in the
instantiation stack that's in the main file). This in turn required a bit of
refactoring in Diagnostics so we can delay relocating the diagnostic until all
notes are available.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D81351

Files:
  clang-tools-extra/clangd/Diagnostics.cpp
  clang-tools-extra/clangd/Diagnostics.h
  clang-tools-extra/clangd/Preamble.cpp
  clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
  clang/include/clang/Frontend/PrecompiledPreamble.h
  clang/lib/Frontend/PrecompiledPreamble.cpp

Index: clang/lib/Frontend/PrecompiledPreamble.cpp
===
--- clang/lib/Frontend/PrecompiledPreamble.cpp
+++ clang/lib/Frontend/PrecompiledPreamble.cpp
@@ -189,6 +189,10 @@
 Action.setEmittedPreamblePCH(getWriter());
   }
 
+  bool shouldSkipFunctionBody(Decl *D) override {
+return Action.Callbacks.shouldSkipFunctionBody(D);
+  }
+
 private:
   PrecompilePreambleAction &Action;
   std::unique_ptr Out;
@@ -756,6 +760,7 @@
   return nullptr;
 }
 CommentHandler *PreambleCallbacks::getCommentHandler() { return nullptr; }
+bool PreambleCallbacks::shouldSkipFunctionBody(Decl *D) { return true; }
 
 static llvm::ManagedStatic BuildPreambleErrCategory;
 
Index: clang/include/clang/Frontend/PrecompiledPreamble.h
===
--- clang/include/clang/Frontend/PrecompiledPreamble.h
+++ clang/include/clang/Frontend/PrecompiledPreamble.h
@@ -34,6 +34,7 @@
 namespace clang {
 class CompilerInstance;
 class CompilerInvocation;
+class Decl;
 class DeclGroupRef;
 class PCHContainerOperations;
 
@@ -283,6 +284,8 @@
   virtual std::unique_ptr createPPCallbacks();
   /// The returned CommentHandler will be added to the preprocessor if not null.
   virtual CommentHandler *getCommentHandler();
+
+  virtual bool shouldSkipFunctionBody(Decl *D);
 };
 
 enum class BuildPreambleError {
Index: clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
===
--- clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
+++ clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
@@ -45,9 +45,9 @@
   return Field(&Diag::Fixes, UnorderedElementsAre(FixMatcher1, FixMatcher2));
 }
 
-::testing::Matcher
-WithNote(::testing::Matcher NoteMatcher) {
-  return Field(&Diag::Notes, ElementsAre(NoteMatcher));
+template 
+::testing::Matcher WithNote(NoteMatcherTypes... NoteMatcher) {
+  return Field(&Diag::Notes, ElementsAre(NoteMatcher...));
 }
 
 MATCHER_P2(Diag, Range, Message,
@@ -272,6 +272,51 @@
   "use a trailing return type for this function");
 }
 
+TEST(DiagnosticTest, TemplatesInHeaders) {
+  // Diagnostics from templates defined in headers are placed at the expansion.
+  Annotations Main(R"cpp(
+Derived [[y]]; // error-ok
+  )cpp");
+  Annotations Header(R"cpp(
+template 
+struct Derived : [[T]] {};"
+  )cpp");
+  TestTU TU = TestTU::withCode(Main.code());
+  TU.HeaderCode = Header.code().str();
+  EXPECT_THAT(
+  TU.build().getDiagnostics(),
+  ElementsAre(AllOf(
+  Diag(Main.range(), "in template: base specifier must name a class"),
+  WithNote(Diag(Header.range(), "error occurred here"),
+   Diag(Main.range(), "in instantiation of template class "
+  "'Derived' requested here");
+}
+
+TEST(DiagnosticTest, MakeUnique) {
+  // We usually miss diagnostics from header functions as we don't parse them.
+  // std::make_unique is an exception.
+  Annotations Main(R"cpp(
+struct S { S(char*); };
+auto x = std::[[make_unique]](42); // error-ok
+  )cpp");
+  TestTU TU = TestTU::withCode(Main.code());
+  TU.HeaderCode = R"cpp(
+namespace std {
+// These mocks aren't quite right - we omit unique_ptr for sim

[PATCH] D81346: [KernelAddressSanitizer] Ensure global array size remains multiple of type-size

2020-06-07 Thread Marco Elver via Phabricator via cfe-commits
melver updated this revision to Diff 269078.
melver added a comment.

Add 0-size array to test to check redzone calculation does not divide by 0.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D81346

Files:
  clang/test/CodeGen/asan-globals.cpp
  llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp

Index: llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
===
--- llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
+++ llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
@@ -796,9 +796,10 @@
   StringRef getGlobalMetadataSection() const;
   void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
   void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
-  size_t MinRedzoneSizeForGlobal() const {
+  uint64_t getMinRedzoneSizeForGlobal() const {
 return RedzoneSizeForScale(Mapping.Scale);
   }
+  uint64_t getRedzoneSizeForGlobal(uint64_t SizeInBytes) const;
   int GetAsanVersion(const Module &M) const;
 
   const GlobalsMetadata &GlobalsMD;
@@ -1807,7 +1808,7 @@
   //   - Need to poison all copies, not just the main thread's one.
   if (G->isThreadLocal()) return false;
   // For now, just ignore this Global if the alignment is large.
-  if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
+  if (G->getAlignment() > getMinRedzoneSizeForGlobal()) return false;
 
   // For non-COFF targets, only instrument globals known to be defined by this
   // TU.
@@ -2276,7 +2277,6 @@
   M, M.getModuleIdentifier(), /*AllowMerging*/ false, kAsanGenPrefix);
 
   for (size_t i = 0; i < n; i++) {
-static const uint64_t kMaxGlobalRedzone = 1 << 18;
 GlobalVariable *G = GlobalsToChange[i];
 
 // FIXME: Metadata should be attched directly to the global directly instead
@@ -2290,16 +2290,8 @@
 /*AllowMerging*/ true, kAsanGenPrefix);
 
 Type *Ty = G->getValueType();
-uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
-uint64_t MinRZ = MinRedzoneSizeForGlobal();
-// MinRZ <= RZ <= kMaxGlobalRedzone
-// and trying to make RZ to be ~ 1/4 of SizeInBytes.
-uint64_t RZ = std::max(
-MinRZ, std::min(kMaxGlobalRedzone, (SizeInBytes / MinRZ / 4) * MinRZ));
-uint64_t RightRedzoneSize = RZ;
-// Round up to MinRZ
-if (SizeInBytes % MinRZ) RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
-assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
+const uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
+const uint64_t RightRedzoneSize = getRedzoneSizeForGlobal(SizeInBytes);
 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
 
 StructType *NewTy = StructType::get(Ty, RightRedZoneTy);
@@ -2315,7 +2307,7 @@
"", G, G->getThreadLocalMode());
 NewGlobal->copyAttributesFrom(G);
 NewGlobal->setComdat(G->getComdat());
-NewGlobal->setAlignment(MaybeAlign(MinRZ));
+NewGlobal->setAlignment(MaybeAlign(getMinRedzoneSizeForGlobal()));
 // Don't fold globals with redzones. ODR violation detector and redzone
 // poisoning implicitly creates a dependence on the global's address, so it
 // is no longer valid for it to be marked unnamed_addr.
@@ -2437,6 +2429,39 @@
   return true;
 }
 
+uint64_t
+ModuleAddressSanitizer::getRedzoneSizeForGlobal(uint64_t SizeInBytes) const {
+  const uint64_t MinRZ = getMinRedzoneSizeForGlobal();
+  // Limit redzone size when compiling the kernel.
+  const uint64_t MaxRZ = CompileKernel ? MinRZ * 2 : 1 << 18;
+
+  // Calculate RZ, where MinRZ <= RZ <= MaxRZ, and RZ ~ 1/4 * SizeInBytes.
+  uint64_t RZ =
+  std::max(MinRZ, std::min(MaxRZ, (SizeInBytes / MinRZ / 4) * MinRZ));
+
+  // Round up to multiple of MinRZ.
+  if (SizeInBytes % MinRZ)
+RZ += MinRZ - (SizeInBytes % MinRZ);
+  assert((RZ + SizeInBytes) % MinRZ == 0);
+
+  if (CompileKernel && SizeInBytes && RZ % SizeInBytes) {
+// When compiling the Linux kernel, ensure that the size of global+redzone
+// has the same divisors as before. For certain arrays, the kernel expects
+// that the global's size remains a multiple of the type's size.
+//
+// For example, in kernel modules certain arrays of structs shared with
+// userspace are checked to be a multiple of sizeof(shared struct). These
+// checks happen on the final binary.
+//
+// We can ensure the checks do not fail by ensuring that the array's size
+// remains a multiple of the original size.
+RZ += SizeInBytes - (RZ % SizeInBytes);
+assert((RZ + SizeInBytes) % SizeInBytes == 0);
+  }
+
+  return RZ;
+}
+
 int ModuleAddressSanitizer::GetAsanVersion(const Module &M) const {
   int LongSize = M.getDataLayout().getPointerSizeInBits();
   bool isAndroid = Triple(M.getTargetTriple()).isAndroid();
Index: clang/test/CodeGen/asan-globals.cpp
=

[PATCH] D81352: Thread safety analysis: Add note for double unlock

2020-06-07 Thread Aaron Puchert via Phabricator via cfe-commits
aaronpuchert created this revision.
aaronpuchert added reviewers: aaron.ballman, delesley.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

When getting a warning that we release a capability that isn't held it's
sometimes not clear why. So just like we do for double locking, we add a
note on the previous release operation, which marks the point since when
the capability isn't held any longer.

We can find this previous release operation by looking up the
corresponding negative capability.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D81352

Files:
  clang/include/clang/Analysis/Analyses/ThreadSafety.h
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Analysis/ThreadSafety.cpp
  clang/lib/Sema/AnalysisBasedWarnings.cpp
  clang/test/Sema/warn-thread-safety-analysis.c
  clang/test/SemaCXX/warn-thread-safety-analysis.cpp

Index: clang/test/SemaCXX/warn-thread-safety-analysis.cpp
===
--- clang/test/SemaCXX/warn-thread-safety-analysis.cpp
+++ clang/test/SemaCXX/warn-thread-safety-analysis.cpp
@@ -2606,7 +2606,7 @@
 
 void Foo::test4() {
   ReleasableMutexLock rlock(&mu_);
-  rlock.Release();
+  rlock.Release();  // expected-note{{mutex released here}}
   rlock.Release();  // expected-warning {{releasing mutex 'mu_' that was not held}}
 }
 
@@ -2705,7 +2705,7 @@
 
 void doubleUnlock() {
   RelockableExclusiveMutexLock scope(&mu);
-  scope.Unlock();
+  scope.Unlock(); // expected-note{{mutex released here}}
   scope.Unlock(); // expected-warning {{releasing mutex 'mu' that was not held}}
 }
 
@@ -2866,7 +2866,7 @@
 }
 
 void doubleUnlock() EXCLUSIVE_LOCKS_REQUIRED(mu) {
-  MutexUnlock scope(&mu);
+  MutexUnlock scope(&mu); // expected-note{{mutex released here}}
   scope.Unlock(); // expected-warning {{releasing mutex 'mu' that was not held}}
 }
 
@@ -3181,7 +3181,7 @@
   mu_->Lock();  // expected-note 2 {{mutex acquired here}}
   mu_.get()->Lock();// expected-warning {{acquiring mutex 'mu_' that is already held}}
   (*mu_).Lock();// expected-warning {{acquiring mutex 'mu_' that is already held}}
-  mu_.get()->Unlock();
+  mu_.get()->Unlock();  // expected-note {{mutex released here}}
   Unlock(); // expected-warning {{releasing mutex 'mu_' that was not held}}
 }
 
@@ -3314,7 +3314,7 @@
 
   foo.lock(); // expected-note{{mutex acquired here}}
   foo.lock(); // expected-warning {{acquiring mutex 'foo' that is already held}}
-  foo.unlock();
+  foo.unlock();   // expected-note{{mutex released here}}
   foo.unlock();   // expected-warning {{releasing mutex 'foo' that was not held}}
 }
 
@@ -3328,7 +3328,7 @@
   foo.lock1();// expected-note{{mutex acquired here}}
   foo.lock1();// expected-warning {{acquiring mutex 'foo.mu1_' that is already held}}
   foo.a = 0;
-  foo.unlock1();
+  foo.unlock1();  // expected-note{{mutex released here}}
   foo.unlock1();  // expected-warning {{releasing mutex 'foo.mu1_' that was not held}}
 }
 
@@ -3342,7 +3342,7 @@
   foo.slock1();// expected-note{{mutex acquired here}}
   foo.slock1();// expected-warning {{acquiring mutex 'foo.mu1_' that is already held}}
   int d2 = foo.a;
-  foo.unlock1();
+  foo.unlock1();   // expected-note{{mutex released here}}
   foo.unlock1();   // expected-warning {{releasing mutex 'foo.mu1_' that was not held}}
   return d1 + d2;
 }
@@ -3364,7 +3364,7 @@
   foo.a = 0;
   foo.b = 0;
   foo.c = 0;
-  foo.unlock3();
+  foo.unlock3(); // expected-note 3 {{mutex released here}}
   foo.unlock3(); // \
 // expected-warning {{releasing mutex 'foo.mu1_' that was not held}} \
 // expected-warning {{releasing mutex 'foo.mu2_' that was not held}} \
@@ -3388,7 +3388,7 @@
   foo.a = 0;
   foo.b = 0;
   foo.c = 0;
-  foo.unlocklots();
+  foo.unlocklots(); // expected-note 3 {{mutex released here}}
   foo.unlocklots(); // \
 // expected-warning {{releasing mutex 'foo.mu1_' that was not held}} \
 // expected-warning {{releasing mutex 'foo.mu2_' that was not held}} \
Index: clang/test/Sema/warn-thread-safety-analysis.c
===
--- clang/test/Sema/warn-thread-safety-analysis.c
+++ clang/test/Sema/warn-thread-safety-analysis.c
@@ -119,10 +119,12 @@
 
   mutex_exclusive_lock(&mu1);// expected-note {{mutex acquired here}}
   mutex_shared_unlock(&mu1); // expected-warning {{releasing mutex 'mu1' using shared access, expected exclusive access}}
+ // expected-note@-1{{mutex released here}}
   mutex_exclusive_unlock(&mu1);  // expected-warning {{releasing mutex 'mu1' that was not held}}
 
   mutex_shared_lock(&mu1);  // expected-note {{mutex acquired here}}
   mutex_exclusive_unlock(&mu1); // expected-warning {{releasing mutex 'mu1' using exclusive access, expected shared access}}
+// expected-note@-1{{mutex released here}}
   mutex_shared_unlock(&mu1);

[PATCH] D81336: [clang-tidy] simplify-bool-expr ignores template instantiations

2020-06-07 Thread Stephen Kelly via Phabricator via cfe-commits
steveire added a comment.

This isn't needed if https://reviews.llvm.org/D80961 is merged.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D81336



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


[PATCH] D80961: Ignore template instantiations if not in AsIs mode

2020-06-07 Thread Stephen Kelly via Phabricator via cfe-commits
steveire updated this revision to Diff 269081.
steveire added a comment.
Herald added a subscriber: martong.
Herald added a reviewer: shafik.

Port unit tests


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80961

Files:
  clang-tools-extra/clang-tidy/abseil/TimeSubtractionCheck.cpp
  clang-tools-extra/clang-tidy/abseil/UpgradeDurationConversionsCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/SizeofExpressionCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/TooSmallLoopVariableCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/UndefinedMemoryManipulationCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/VirtualNearMissCheck.cpp
  clang-tools-extra/clang-tidy/google/UpgradeGoogletestCaseCheck.cpp
  clang-tools-extra/clang-tidy/hicpp/ExceptionBaseclassCheck.cpp
  clang-tools-extra/clang-tidy/modernize/DeprecatedIosBaseAliasesCheck.cpp
  clang-tools-extra/clang-tidy/modernize/MakeSmartPtrCheck.cpp
  clang-tools-extra/clang-tidy/modernize/ReplaceAutoPtrCheck.cpp
  clang-tools-extra/clang-tidy/modernize/UseOverrideCheck.cpp
  clang-tools-extra/clang-tidy/modernize/UseUncaughtExceptionsCheck.cpp
  clang-tools-extra/clang-tidy/performance/FasterStringFindCheck.cpp
  clang-tools-extra/clang-tidy/readability/ContainerSizeEmptyCheck.cpp
  clang-tools-extra/clang-tidy/readability/QualifiedAutoCheck.cpp
  
clang-tools-extra/clang-tidy/readability/StaticAccessedThroughInstanceCheck.cpp
  clang-tools-extra/clang-tidy/zircon/TemporaryObjectsCheck.cpp
  clang/include/clang/AST/ASTNodeTraverser.h
  clang/include/clang/ASTMatchers/ASTMatchersInternal.h
  clang/lib/AST/ASTDumper.cpp
  clang/lib/ASTMatchers/ASTMatchFinder.cpp
  clang/lib/ASTMatchers/ASTMatchersInternal.cpp
  clang/unittests/AST/ASTContextParentMapTest.cpp
  clang/unittests/AST/ASTImporterTest.cpp
  clang/unittests/AST/ASTTraverserTest.cpp
  clang/unittests/AST/SourceLocationTest.cpp
  clang/unittests/AST/StructuralEquivalenceTest.cpp
  clang/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp
  clang/unittests/ASTMatchers/ASTMatchersNodeTest.cpp
  clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
  clang/unittests/Sema/GslOwnerPointerInference.cpp
  clang/unittests/Tooling/TransformerTest.cpp

Index: clang/unittests/Tooling/TransformerTest.cpp
===
--- clang/unittests/Tooling/TransformerTest.cpp
+++ clang/unittests/Tooling/TransformerTest.cpp
@@ -695,6 +695,70 @@
   EXPECT_EQ(ErrorCount, 0);
 }
 
+TEST_F(TransformerTest, TemplateInstantiation) {
+
+  std::string NonTemplatesInput = R"cpp(
+struct S {
+  int m_i;
+};
+)cpp";
+  std::string NonTemplatesExpected = R"cpp(
+struct S {
+  safe_int m_i;
+};
+)cpp";
+
+  std::string TemplatesInput = R"cpp(
+template
+struct TemplStruct {
+  TemplStruct() {}
+  ~TemplStruct() {}
+
+private:
+  T m_t;
+};
+
+void instantiate()
+{
+  TemplStruct ti;
+}
+)cpp";
+
+  auto MatchedField = fieldDecl(hasType(asString("int"))).bind("theField");
+
+  // Changes the 'int' in 'S', but not the 'T' in 'TemplStruct':
+  testRule(makeRule(traverse(TK_IgnoreUnlessSpelledInSource, MatchedField),
+changeTo(cat("safe_int ", name("theField",
+   NonTemplatesInput + TemplatesInput,
+   NonTemplatesExpected + TemplatesInput);
+
+  // In AsIs mode, template instantiations are modified, which is
+  // often not desired:
+
+  std::string IncorrectTemplatesExpected = R"cpp(
+template
+struct TemplStruct {
+  TemplStruct() {}
+  ~TemplStruct() {}
+
+private:
+  safe_int m_t;
+};
+
+void instantiate()
+{
+  TemplStruct ti;
+}
+)cpp";
+
+  // Changes the 'int' in 'S', and (incorrectly) the 'T' in 'TemplStruct':
+  testRule(makeRule(traverse(TK_AsIs, MatchedField),
+changeTo(cat("safe_int ", name("theField",
+
+   NonTemplatesInput + TemplatesInput,
+   NonTemplatesExpected + IncorrectTemplatesExpected);
+}
+
 // Transformation of macro source text when the change encompasses the entirety
 // of the expanded text.
 TEST_F(TransformerTest, SimpleMacro) {
Index: clang/unittests/Sema/GslOwnerPointerInference.cpp
===
--- clang/unittests/Sema/GslOwnerPointerInference.cpp
+++ clang/unittests/Sema/GslOwnerPointerInference.cpp
@@ -21,8 +21,8 @@
   "class [[gsl::Owner]] C {};"
 
   "C c;",
-  classTemplateSpecializationDecl(
-  hasName("C"), hasAttr(clang::attr::Owner;
+  traverse(TK_AsIs, classTemplateSpecializationDecl(
+  hasName("C"), hasAttr(clang::attr::Owner);
 }
 
 TEST(OwnerPointer, ForwardDeclOnly) {
@@ -33,8 +33,8 @@
   "class C {};"
 
   "C c;",
-  classTemplateSpecializationDecl(
-  hasName("C"), hasAttr(clang::attr::Owner;
+   

[PATCH] D80961: Ignore template instantiations if not in AsIs mode

2020-06-07 Thread Stephen Kelly via Phabricator via cfe-commits
steveire added a comment.

In D80961#2074915 , @steveire wrote:

> I don't think that's true. You have to change the matchers you've written 
> which deliberately match the instantiation, but you can also (optionally) 
> simplify the others to remove `unless(isInTemplateInstantiation())` from 
> them. The third category of matchers are the ones where you haven't used 
> `unless(isInTemplateInstantiation())` even though you should have and you 
> have a bug that you don't know about yet. This change fixes those ones.


This seems to be an example of that third category: 
https://reviews.llvm.org/D81336

> 
> 
>> I love the idea of being able to control visitation of template 
>> instantiation.
>>  I am somewhat torn on whether it should be the default, and would like to 
>> see more data.
>>  I feel more strongly about needing AsIs when I want to match template 
>> instantiations.
> 
> I feel strongly that the default should not change code in a known-wrong way, 
> as the unit test demonstrates. It's not a novice-friendly default.

Any more feelings on this?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80961



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


[clang] a0de333 - [clang] Implement VectorType logic not operator.

2020-06-07 Thread Jun Ma via cfe-commits

Author: Jun Ma
Date: 2020-06-08T08:41:01+08:00
New Revision: a0de3335edcf19305dad592d21ebe402825184f6

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

LOG: [clang] Implement VectorType logic not operator.

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

Added: 
clang/test/CodeGen/vector-logic-not.cpp

Modified: 
clang/docs/LanguageExtensions.rst
clang/lib/CodeGen/CGExprScalar.cpp
clang/lib/Sema/SemaExpr.cpp
clang/test/Sema/vector-gcc-compat.cpp

Removed: 




diff  --git a/clang/docs/LanguageExtensions.rst 
b/clang/docs/LanguageExtensions.rst
index ba0a7d9cf95c..06ecc186c7dc 100644
--- a/clang/docs/LanguageExtensions.rst
+++ b/clang/docs/LanguageExtensions.rst
@@ -475,7 +475,7 @@ unary operators +, --yes yes   yes  
   --
 +,--,*,/,%   yes yes   yes --
 bitwise operators &,|,^,~yes yes   yes --
 >>,<, <, >=, <= yes yes   yes --
 =yes yes   yes yes
 ?: [#]_  yes --yes --
@@ -488,7 +488,6 @@ const_cast   no  nono   
   no
 
 See also :ref:`langext-__builtin_shufflevector`, 
:ref:`langext-__builtin_convertvector`.
 
-.. [#] unary operator ! is not implemented, however && and || are.
 .. [#] ternary operator(?:) has 
diff erent behaviors depending on condition
   operand's vector type. If the condition is a GNU vector (i.e. 
__vector_size__),
   it's only available in C++ and uses normal bool conversions (that is, != 0).

diff  --git a/clang/lib/CodeGen/CGExprScalar.cpp 
b/clang/lib/CodeGen/CGExprScalar.cpp
index 4e61349cf4d5..b2bc38b329ef 100644
--- a/clang/lib/CodeGen/CGExprScalar.cpp
+++ b/clang/lib/CodeGen/CGExprScalar.cpp
@@ -2762,7 +2762,9 @@ Value *ScalarExprEmitter::VisitUnaryNot(const 
UnaryOperator *E) {
 
 Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
   // Perform vector logical not on comparison with zero vector.
-  if (E->getType()->isExtVectorType()) {
+  if (E->getType()->isVectorType() &&
+  E->getType()->castAs()->getVectorKind() ==
+  VectorType::GenericVector) {
 Value *Oper = Visit(E->getSubExpr());
 Value *Zero = llvm::Constant::getNullValue(Oper->getType());
 Value *Result;

diff  --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index 45c1acecbe94..4bec413f3042 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -14481,12 +14481,19 @@ ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation 
OpLoc,
   return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
<< resultType << Input.get()->getSourceRange());
   }
+  // Vector logical not returns the signed variant of the operand type.
+  resultType = GetSignedVectorType(resultType);
+  break;
+} else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) {
+  const VectorType *VTy = resultType->castAs();
+  if (VTy->getVectorKind() != VectorType::GenericVector)
+return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
+ << resultType << Input.get()->getSourceRange());
+
   // Vector logical not returns the signed variant of the operand type.
   resultType = GetSignedVectorType(resultType);
   break;
 } else {
-  // FIXME: GCC's vector extension permits the usage of '!' with a vector
-  //type in C++. We should allow that here too.
   return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
 << resultType << Input.get()->getSourceRange());
 }

diff  --git a/clang/test/CodeGen/vector-logic-not.cpp 
b/clang/test/CodeGen/vector-logic-not.cpp
new file mode 100644
index ..2ac026711e82
--- /dev/null
+++ b/clang/test/CodeGen/vector-logic-not.cpp
@@ -0,0 +1,21 @@
+// RUN: %clang_cc1 -emit-llvm %s -o - | FileCheck %s
+
+typedef __attribute__((__vector_size__(16))) float float4;
+typedef __attribute__((__vector_size__(16))) int int4;
+typedef __attribute__((__vector_size__(16))) unsigned int uint4;
+
+// CHECK: @_Z5test1Dv4_j
+int4 test1(uint4 V0) {
+  // CHECK: [[CMP0:%.*]] = icmp eq <4 x i32> [[V0:%.*]], zeroinitializer
+  // CHECK-NEXT: [[V1:%.*]] = sext <4 x i1> [[CMP0]] to <4 x i32>
+  int4 V = !V0;
+  return V;
+}
+
+// CHECK: @_Z5test2Dv4_fS_
+int4 test2(float4 V0, float4 V1) {
+  // CHECK: [[CMP0:%.*]] = fcmp oeq <4 x float> [[V0:%.*]], zeroinitializer
+  // CHECK-NEXT: [[V1:%.*]] = sext <4 x i1> [

[PATCH] D80979: [clang] Implement VectorType logic not operator.

2020-06-07 Thread JunMa via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGa0de3335edcf: [clang] Implement VectorType logic not 
operator. (authored by junparser).

Changed prior to commit:
  https://reviews.llvm.org/D80979?vs=268649&id=269084#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80979

Files:
  clang/docs/LanguageExtensions.rst
  clang/lib/CodeGen/CGExprScalar.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/test/CodeGen/vector-logic-not.cpp
  clang/test/Sema/vector-gcc-compat.cpp


Index: clang/test/Sema/vector-gcc-compat.cpp
===
--- clang/test/Sema/vector-gcc-compat.cpp
+++ clang/test/Sema/vector-gcc-compat.cpp
@@ -83,7 +83,7 @@
   v2i64 v2i64_c = (v2i64){3, 1}; // expected-warning {{compound literals are a 
C99-specific feature}}
   v2i64 v2i64_r;
 
-  v2i64_r = !v2i64_a;  // expected-error {{invalid argument type 'v2i64' 
(vector of 2 'long long' values) to unary expression}}
+  v2i64_r = !v2i64_a;
   v2i64_r = ~v2i64_a;
 
   v2i64_r = v2i64_a ? v2i64_b : v2i64_c;
Index: clang/test/CodeGen/vector-logic-not.cpp
===
--- /dev/null
+++ clang/test/CodeGen/vector-logic-not.cpp
@@ -0,0 +1,21 @@
+// RUN: %clang_cc1 -emit-llvm %s -o - | FileCheck %s
+
+typedef __attribute__((__vector_size__(16))) float float4;
+typedef __attribute__((__vector_size__(16))) int int4;
+typedef __attribute__((__vector_size__(16))) unsigned int uint4;
+
+// CHECK: @_Z5test1Dv4_j
+int4 test1(uint4 V0) {
+  // CHECK: [[CMP0:%.*]] = icmp eq <4 x i32> [[V0:%.*]], zeroinitializer
+  // CHECK-NEXT: [[V1:%.*]] = sext <4 x i1> [[CMP0]] to <4 x i32>
+  int4 V = !V0;
+  return V;
+}
+
+// CHECK: @_Z5test2Dv4_fS_
+int4 test2(float4 V0, float4 V1) {
+  // CHECK: [[CMP0:%.*]] = fcmp oeq <4 x float> [[V0:%.*]], zeroinitializer
+  // CHECK-NEXT: [[V1:%.*]] = sext <4 x i1> [[CMP0]] to <4 x i32>
+  int4 V = !V0;
+  return V;
+}
Index: clang/lib/Sema/SemaExpr.cpp
===
--- clang/lib/Sema/SemaExpr.cpp
+++ clang/lib/Sema/SemaExpr.cpp
@@ -14484,9 +14484,16 @@
   // Vector logical not returns the signed variant of the operand type.
   resultType = GetSignedVectorType(resultType);
   break;
+} else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) {
+  const VectorType *VTy = resultType->castAs();
+  if (VTy->getVectorKind() != VectorType::GenericVector)
+return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
+ << resultType << Input.get()->getSourceRange());
+
+  // Vector logical not returns the signed variant of the operand type.
+  resultType = GetSignedVectorType(resultType);
+  break;
 } else {
-  // FIXME: GCC's vector extension permits the usage of '!' with a vector
-  //type in C++. We should allow that here too.
   return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
 << resultType << Input.get()->getSourceRange());
 }
Index: clang/lib/CodeGen/CGExprScalar.cpp
===
--- clang/lib/CodeGen/CGExprScalar.cpp
+++ clang/lib/CodeGen/CGExprScalar.cpp
@@ -2762,7 +2762,9 @@
 
 Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
   // Perform vector logical not on comparison with zero vector.
-  if (E->getType()->isExtVectorType()) {
+  if (E->getType()->isVectorType() &&
+  E->getType()->castAs()->getVectorKind() ==
+  VectorType::GenericVector) {
 Value *Oper = Visit(E->getSubExpr());
 Value *Zero = llvm::Constant::getNullValue(Oper->getType());
 Value *Result;
Index: clang/docs/LanguageExtensions.rst
===
--- clang/docs/LanguageExtensions.rst
+++ clang/docs/LanguageExtensions.rst
@@ -475,7 +475,7 @@
 +,--,*,/,%   yes yes   yes --
 bitwise operators &,|,^,~yes yes   yes --
 >>,<, <, >=, <= yes yes   yes --
 =yes yes   yes yes
 ?: [#]_  yes --yes --
@@ -488,7 +488,6 @@
 
 See also :ref:`langext-__builtin_shufflevector`, 
:ref:`langext-__builtin_convertvector`.
 
-.. [#] unary operator ! is not implemented, however && and || are.
 .. [#] ternary operator(?:) has different behaviors depending on condition
   operand's vector type. If the condition is a GNU vector (i.e. 
__vector_size__),
   it's only available in C++ and uses normal bool conversions (that is, != 0).


Index: clang/test/Sema

[PATCH] D80952: [FPEnv][Clang][Driver][WIP] Disable constrained floating point on targets lacking support.

2020-06-07 Thread Qing Shan Zhang via Phabricator via cfe-commits
steven.zhang added a comment.

The PowerPC backend is also adding the constraint float point support and 
almost done.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80952



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


[PATCH] D80723: [PowerPC] Convert vec_splats functions to macros

2020-06-07 Thread Qing Shan Zhang via Phabricator via cfe-commits
steven.zhang added a comment.

It LGTM now except one comment on the test. And it seems that, we still have 
many other builtins implementation that didn't use the _Generic.




Comment at: clang/test/CodeGen/ppc-emmintrin.c:1
-// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py
 // REQUIRES: powerpc-registered-target

So, why this line of comments is removed ? It seems that, the old test was 
generated by the script while the new one isn't. I expect both should generate 
by script. 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80723



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


[PATCH] D81355: [PowerPC] Enable -fstack-clash-protection option for ppc64

2020-06-07 Thread Kai Luo via Phabricator via cfe-commits
lkail created this revision.
lkail added reviewers: PowerPC, hfinkel, jonpa, serge-sans-paille.
Herald added subscribers: cfe-commits, shchenz, kbarton, nemanjai.
Herald added a project: clang.

Open `-fstack-clash-protection` option in clang for ppc64 arch.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D81355

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/Basic/Targets/PPC.h
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/test/CodeGen/stack-clash-protection.c


Index: clang/test/CodeGen/stack-clash-protection.c
===
--- clang/test/CodeGen/stack-clash-protection.c
+++ clang/test/CodeGen/stack-clash-protection.c
@@ -1,6 +1,8 @@
 // Check the correct function attributes are generated
 // RUN: %clang_cc1 -triple x86_64-linux -O0 -S -emit-llvm -o- %s 
-fstack-clash-protection | FileCheck %s
 // RUN: %clang_cc1 -triple s390x-linux-gnu -O0 -S -emit-llvm -o- %s 
-fstack-clash-protection | FileCheck %s
+// RUN: %clang_cc1 -triple powerpc64le-linux-gnu -O0 -S -emit-llvm -o- %s 
-fstack-clash-protection | FileCheck %s
+// RUN: %clang_cc1 -triple powerpc64-linux-gnu -O0 -S -emit-llvm -o- %s 
-fstack-clash-protection | FileCheck %s
 
 // CHECK: define void @large_stack() #[[A:.*]] {
 void large_stack() {
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -2999,7 +2999,8 @@
   if (!EffectiveTriple.isOSLinux())
 return;
 
-  if (!EffectiveTriple.isX86() && !EffectiveTriple.isSystemZ())
+  if (!EffectiveTriple.isX86() && !EffectiveTriple.isSystemZ() &&
+  !EffectiveTriple.isPPC64())
 return;
 
   if (Args.hasFlag(options::OPT_fstack_clash_protection,
Index: clang/lib/Basic/Targets/PPC.h
===
--- clang/lib/Basic/Targets/PPC.h
+++ clang/lib/Basic/Targets/PPC.h
@@ -342,6 +342,10 @@
   const char *getFloat128Mangling() const override { return "u9__ieee128"; }
 
   bool hasExtIntType() const override { return true; }
+
+  bool isSPRegName(StringRef RegName) const override {
+return RegName.equals("r1") || RegName.equals("x1");
+  }
 };
 
 class LLVM_LIBRARY_VISIBILITY PPC32TargetInfo : public PPCTargetInfo {
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -94,8 +94,8 @@
 --
 
 - -fstack-clash-protection will provide a protection against the stack clash
-  attack for x86 and s390x architectures through automatic probing of each page
-  of allocated stack.
+  attack for x86, s390x and ppc64 architectures through automatic
+  probing of each page of allocated stack.
 
 - -ffp-exception-behavior={ignore,maytrap,strict} allows the user to specify
   the floating-point exception behavior. The default setting is ``ignore``.


Index: clang/test/CodeGen/stack-clash-protection.c
===
--- clang/test/CodeGen/stack-clash-protection.c
+++ clang/test/CodeGen/stack-clash-protection.c
@@ -1,6 +1,8 @@
 // Check the correct function attributes are generated
 // RUN: %clang_cc1 -triple x86_64-linux -O0 -S -emit-llvm -o- %s -fstack-clash-protection | FileCheck %s
 // RUN: %clang_cc1 -triple s390x-linux-gnu -O0 -S -emit-llvm -o- %s -fstack-clash-protection | FileCheck %s
+// RUN: %clang_cc1 -triple powerpc64le-linux-gnu -O0 -S -emit-llvm -o- %s -fstack-clash-protection | FileCheck %s
+// RUN: %clang_cc1 -triple powerpc64-linux-gnu -O0 -S -emit-llvm -o- %s -fstack-clash-protection | FileCheck %s
 
 // CHECK: define void @large_stack() #[[A:.*]] {
 void large_stack() {
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -2999,7 +2999,8 @@
   if (!EffectiveTriple.isOSLinux())
 return;
 
-  if (!EffectiveTriple.isX86() && !EffectiveTriple.isSystemZ())
+  if (!EffectiveTriple.isX86() && !EffectiveTriple.isSystemZ() &&
+  !EffectiveTriple.isPPC64())
 return;
 
   if (Args.hasFlag(options::OPT_fstack_clash_protection,
Index: clang/lib/Basic/Targets/PPC.h
===
--- clang/lib/Basic/Targets/PPC.h
+++ clang/lib/Basic/Targets/PPC.h
@@ -342,6 +342,10 @@
   const char *getFloat128Mangling() const override { return "u9__ieee128"; }
 
   bool hasExtIntType() const override { return true; }
+
+  bool isSPRegName(StringRef RegName) const override {
+return RegName.equals("r1") || RegName.equals("x1");
+  }
 };
 
 class LLVM_LIBRARY_VISIBILITY PPC32TargetInfo : public PPCTargetInfo {
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseN

[PATCH] D81355: [PowerPC] Enable -fstack-clash-protection option for ppc64

2020-06-07 Thread Qing Shan Zhang via Phabricator via cfe-commits
steven.zhang added a comment.
Herald added a subscriber: wuzish.

Shouldn't this be the last patch to commit after the backend supporting this 
feature ?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D81355



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


[PATCH] D80979: [clang] Implement VectorType logic not operator.

2020-06-07 Thread Nico Weber via Phabricator via cfe-commits
thakis added a comment.

This breaks tests on Windows: http://45.33.8.238/win/17077/step_7.txt

Please take a look and revert if it takes a while to fix.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80979



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


[PATCH] D77168: Add a flag to debug automatic variable initialization

2020-06-07 Thread Jian Cai via Phabricator via cfe-commits
jcai19 added a comment.

In D77168#2073736 , @jfb wrote:

> Can you add a test for the diagnostic firing after the correct number of 
> initializations? This should include a few types of auto-init, including VLAs.


Thank you for the comments! It turned out the patch did not cover VLAs, which I 
have addressed in the latest version along other issues you brought up. Thanks.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D77168



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


[PATCH] D81355: [PowerPC] Enable -fstack-clash-protection option for ppc64

2020-06-07 Thread Kai Luo via Phabricator via cfe-commits
lkail added a comment.

In D81355#2078752 , @steven.zhang 
wrote:

> Shouldn't this be the last patch to commit after the backend supporting this 
> feature ?


Yes, I've updated the parent revision.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D81355



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


[PATCH] D77168: Add a flag to debug automatic variable initialization

2020-06-07 Thread Jian Cai via Phabricator via cfe-commits
jcai19 added a comment.

> If we have a mechanism bisecting pragmas, this option will not be needed.

Yes we would have not had to start to work on this patch if such mechanism had 
been implemented. We can always migrate to that approach if said mechanism is 
implemented in the future. I think it should not be too difficult.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D77168



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


[PATCH] D77168: Add a flag to debug automatic variable initialization

2020-06-07 Thread Jian Cai via Phabricator via cfe-commits
jcai19 updated this revision to Diff 269103.
jcai19 marked 4 inline comments as done.
jcai19 added a comment.

Cover VLAs.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D77168

Files:
  clang/include/clang/Basic/DiagnosticDriverKinds.td
  clang/include/clang/Basic/LangOptions.def
  clang/include/clang/Driver/Options.td
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/CodeGen/CGDecl.cpp
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/lib/CodeGen/CodeGenModule.h
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/test/CodeGenCXX/auto-var-init-stop-after.cpp
  clang/test/Driver/clang_f_opts.c

Index: clang/test/Driver/clang_f_opts.c
===
--- clang/test/Driver/clang_f_opts.c
+++ clang/test/Driver/clang_f_opts.c
@@ -579,5 +579,18 @@
 // CHECK-TRIVIAL-ZERO-GOOD-NOT: hasn't been enabled
 // CHECK-TRIVIAL-ZERO-BAD: hasn't been enabled
 
+// RUN: %clang -### -S -ftrivial-auto-var-init=pattern -ftrivial-auto-var-init-stop-after=1 %s 2>&1 | FileCheck -check-prefix=CHECK-TRIVIAL-PATTERN-STOP-AFTER %s
+// RUN: %clang -### -S -ftrivial-auto-var-init=zero -enable-trivial-auto-var-init-zero-knowing-it-will-be-removed-from-clang -ftrivial-auto-var-init-stop-after=1 %s 2>&1 | FileCheck -check-prefix=CHECK-TRIVIAL-ZERO-STOP-AFTER %s
+// RUN: %clang -### -S -ftrivial-auto-var-init-stop-after=0 %s 2>&1 | FileCheck -check-prefix=CHECK-TRIVIAL-STOP-AFTER-MISSING-DEPENDENCY %s
+// RUN: %clang -### -S -ftrivial-auto-var-init=pattern -ftrivial-auto-var-init-stop-after=0 %s 2>&1 | FileCheck -check-prefix=CHECK-TRIVIAL-PATTERN-STOP-AFTER-INVALID-VALUE %s
+// RUN: %clang -### -S -ftrivial-auto-var-init=zero -enable-trivial-auto-var-init-zero-knowing-it-will-be-removed-from-clang -ftrivial-auto-var-init-stop-after=0 %s 2>&1 | FileCheck -check-prefix=CHECK-TRIVIAL-ZERO-STOP-AFTER-INVALID-VALUE %s
+// CHECK-TRIVIAL-PATTERN-STOP-AFTER-NOT: is used without -ftrivial-auto-var-init
+// CHECK-TRIVIAL-PATTERN-STOP-AFTER-NOT: only accpets positive integers
+// CHECK-TRIVIAL-ZERO-STOP-AFTER-NOT: is used without -ftrivial-auto-var-init
+// CHECK-TRIVIAL-ZERO-STOP-AFTER-NOT: only accpets positive integers
+// CHECK-TRIVIAL-STOP-AFTER-MISSING-DEPENDENCY: used without -ftrivial-auto-var-init
+// CHECK-TRIVIAL-PATTERN-STOP-AFTER-INVALID-VALUE: only accpets positive integers
+// CHECK-TRIVIAL-ZERO-STOP-AFTER-INVALID-VALUE: only accpets positive integers
+
 // RUN: %clang -### -S -fno-temp-file %s 2>&1 | FileCheck -check-prefix=CHECK-NO-TEMP-FILE %s
 // CHECK-NO-TEMP-FILE: "-fno-temp-file"
Index: clang/test/CodeGenCXX/auto-var-init-stop-after.cpp
===
--- /dev/null
+++ clang/test/CodeGenCXX/auto-var-init-stop-after.cpp
@@ -0,0 +1,58 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -ftrivial-auto-var-init=pattern -ftrivial-auto-var-init-stop-after=1 %s -emit-llvm -o - | FileCheck %s -check-prefix=PATTERN-STOP-AFTER-1-SCALAR
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -ftrivial-auto-var-init=pattern -ftrivial-auto-var-init-stop-after=2 %s -emit-llvm -o - | FileCheck %s -check-prefix=PATTERN-STOP-AFTER-2-ARRAY
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -ftrivial-auto-var-init=pattern -ftrivial-auto-var-init-stop-after=3 %s -emit-llvm -o - | FileCheck %s -check-prefix=PATTERN-STOP-AFTER-3-VLA
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -ftrivial-auto-var-init=pattern -ftrivial-auto-var-init-stop-after=4 %s -emit-llvm -o - | FileCheck %s -check-prefix=PATTERN-STOP-AFTER-4-POINTER
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -ftrivial-auto-var-init=pattern -ftrivial-auto-var-init-stop-after=5 %s -emit-llvm -o - | FileCheck %s -check-prefix=PATTERN-STOP-AFTER-5-BUILTIN
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -ftrivial-auto-var-init=zero -ftrivial-auto-var-init-stop-after=1 %s -emit-llvm -o - | FileCheck %s -check-prefix=ZERO-STOP-AFTER-1-SCALAR
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -ftrivial-auto-var-init=zero -ftrivial-auto-var-init-stop-after=2 %s -emit-llvm -o - | FileCheck %s -check-prefix=ZERO-STOP-AFTER-2-ARRAY
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -ftrivial-auto-var-init=zero -ftrivial-auto-var-init-stop-after=3 %s -emit-llvm -o - | FileCheck %s -check-prefix=ZERO-STOP-AFTER-3-VLA
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -ftrivial-auto-var-init=zero -ftrivial-auto-var-init-stop-after=4 %s -emit-llvm -o - | FileCheck %s -check-prefix=ZERO-STOP-AFTER-4-POINTER
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -ftrivial-auto-var-init=zero -ftrivial-auto-var-init-stop-after=5 %s -emit-llvm -o - | FileCheck %s -check-prefix=ZERO-STOP-AFTER-5-BUILTIN
+
+#define ARRLEN 10
+
+typedef struct {
+  int i;
+  char c;
+} S;
+
+int foo(unsigned n) {
+  // scalar variable
+  long a = 888;
+  // array
+  S arr[ARRLEN];
+  // VLA
+  S vla[n];
+  /