[PATCH] D126189: [C++20][Modules] Build module static initializers per P1874R1.

2022-05-26 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu added inline comments.



Comment at: clang/include/clang/AST/ASTContext.h:476
+  /// For module code-gen cases, this is the top-level module we are building.
+  mutable Module *PrimaryModule = nullptr;
+

The name `PrimaryModule` looks confusing. PrimaryModule looks like primary 
module interface unit to me. I think it refers to current module unit only. I 
think it is better to rename to `CurrentModuleUnit`.

Then why is it mutable? I don't find it is changed in a const member function.



Comment at: clang/include/clang/AST/ASTContext.h:1085
+  /// Get module under construction, nullptr if this is not a C++20 module.
+  Module *getModuleForCodeGen() { return PrimaryModule; }
+





Comment at: clang/lib/CodeGen/CGDeclCXX.cpp:621
 
+void CodeGenModule::EmitCXXModuleInitFunc(Module *Primary) {
+  while (!CXXGlobalInits.empty() && !CXXGlobalInits.back())

Recommend to comment related part in your summary. It should be much helpful 
for other to read the codes.



Comment at: clang/lib/CodeGen/CGDeclCXX.cpp:645-646
+  llvm::raw_svector_ostream Out(FnName);
+  cast(getCXXABI().getMangleContext())
+  .mangleModuleInitializer(M, Out);
+}

mangleModuleInitializer is virtual function and we don't need to cast it.



Comment at: clang/lib/CodeGen/CGDeclCXX.cpp:671
+ModuleInits.push_back(I->second);
+}
+PrioritizedCXXGlobalInits.clear();

I find the process here for `PrioritizedCXXGlobalInits` is much simpler than 
the one done in `CodeGenModule::EmitCXXGlobalInitFunc()`. It would generate 
more global init function. Doesn't it matter?



Comment at: clang/lib/CodeGen/CGDeclCXX.cpp:684
+  // We now build the initialiser for this module, which has a mangled name
+  // as per the Itanium ABI .  The action of the initializer is guarded so that
+  // each init is run just once (even though a module might be imported

Given CodeGenModule is designed as ABI independent, I feel better to avoid see 
Itanium ABI in this function. (Although we don't have other ABI for modules 
now..)



Comment at: clang/lib/CodeGen/CGDeclCXX.cpp:692-693
+llvm::raw_svector_ostream Out(InitFnName);
+cast(getCXXABI().getMangleContext())
+.mangleModuleInitializer(getContext().getModuleForCodeGen(), Out);
+Fn = CreateGlobalInitOrCleanUpFunction(





Comment at: clang/lib/CodeGen/CGDeclCXX.cpp:699
+Guard = new llvm::GlobalVariable(getModule(), Int8Ty, /*isConstant=*/false,
+ llvm::GlobalVariable::InternalLinkage,
+ llvm::ConstantInt::get(Int8Ty, 0),

Should the Guard be internal linkage? I image that it is possible to be 
manipulated by different TUs. So I feel like it might be better to be linkonce 
or linkonce_odr?



Comment at: clang/lib/CodeGen/CGDeclCXX.cpp:706-722
+  CodeGenFunction(*this).GenerateCXXGlobalInitFunc(
+  Fn, ModuleInits, ConstantAddress(Guard, Int8Ty, GuardAlign));
+  AddGlobalCtor(Fn);
+
+  // See the comment in EmitCXXGlobalInitFunc about OpenCL global init
+  // functions.
+  if (getLangOpts().OpenCL) {

The codes look highly similar to CodeGenModule::EmitCXXGlobalInitFunc. I feel 
it is better to hoist a new function to avoid repeating the same logic twice.



Comment at: clang/lib/CodeGen/CGDeclCXX.cpp:846
+
+  CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn, ModuleInits);
   AddGlobalCtor(Fn);

This looks odd since it might be possible to not handling modules. But I 
understand it might be time-consuming if we want to use `CXXGloablInits` and we 
want `ModuleInits` to be front.



Comment at: clang/lib/CodeGen/CodeGenModule.cpp:2489
+  // source, first Global Module Fragments, if present.
+  if (auto GMF = Primary->findSubmodule("")) {
+for (Decl *D : getContext().getModuleInitializers(GMF)) {

Nit: I feel better to add methods like `Module 
*Module::getGlobalModuleFragment()`. I feel odd to use magic string here. But I 
am OK with it since there many magic string in CodeGen codes and we got in 
consensus before that we would need to do a lot of refactor work in the future.



Comment at: clang/lib/CodeGen/CodeGenModule.cpp:2503
+  // Third any associated with the Privat eMOdule Fragment, if present.
+  if (auto PMF = Primary->findSubmodule("")) {
+for (Decl *D : getContext().getModuleInitializers(PMF)) {

Nit: with above: `Module *Module::getPrivateModuleFragment()`.



Comment at: clang/lib/CodeGen/CodeGenModule.cpp:2933-2935
+  // llvm::dbgs() << "deferring: ";
+  // VD->dump();
+  return false;





Comment at: clang/lib/C

[PATCH] D126189: [C++20][Modules] Build module static initializers per P1874R1.

2022-05-26 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu added inline comments.



Comment at: clang/lib/CodeGen/CGDeclCXX.cpp:699
+Guard = new llvm::GlobalVariable(getModule(), Int8Ty, /*isConstant=*/false,
+ llvm::GlobalVariable::InternalLinkage,
+ llvm::ConstantInt::get(Int8Ty, 0),

ChuanqiXu wrote:
> Should the Guard be internal linkage? I image that it is possible to be 
> manipulated by different TUs. So I feel like it might be better to be 
> linkonce or linkonce_odr?
Oh, I realized I'm wrong. Don't remind this one.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126189

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


[PATCH] D126377: [clang][AArch64][SVE] Improve diagnostics for SVE operators

2022-05-26 Thread Cullen Rhodes via Phabricator via cfe-commits
c-rhodes added inline comments.



Comment at: clang/lib/Sema/SemaExpr.cpp:10609-10614
-  if (RHSType->isVLSTBuiltinType() && !LHSType->isVLSTBuiltinType()) {
-auto DestType = tryScalableVectorConvert((IsCompAssign ? nullptr : &LHS),
- LHSType, RHSType);
-if (DestType == QualType())
-  return InvalidOperands(Loc, LHS, RHS);
-return DestType;

why is this removed?



Comment at: clang/lib/Sema/SemaExpr.cpp:10614
+  (!RHSType->isVLSTBuiltinType() && !RHSType->isRealType())) {
+Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
+<< LHSType << RHSType << LHS.get()->getSourceRange()

missing a test for this?



Comment at: clang/test/Sema/aarch64-sve-vector-arith-ops.c:23
-  (void)(i8 + f64); // expected-error{{invalid operands to binary expression}}
-  (void)(i8 + 0);   // expected-error{{invalid operands to binary expression}}
-  (void)(i8 + 0l);  // expected-error{{invalid operands to binary expression}}

I think these vector + imm tests should be removed in D126380 but fine to keep 
here if it's easier


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126377

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


[PATCH] D126451: [Clang][CSKY] Add support about CSKYABIInfo

2022-05-26 Thread Zixuan Wu via Phabricator via cfe-commits
zixuan-wu created this revision.
zixuan-wu added reviewers: rengolin, DavidSpickett.
Herald added a project: All.
zixuan-wu requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

According to the CSKY ABIv2 document 
,
 construct the ABIInfo to handle argument passing and return of clang data 
type. It also includes how to emit and expand VAArg intrinsic.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D126451

Files:
  clang/lib/CodeGen/TargetInfo.cpp
  clang/test/CodeGen/CSKY/csky-abi.c
  clang/test/CodeGen/CSKY/csky-hard-abi.c

Index: clang/test/CodeGen/CSKY/csky-hard-abi.c
===
--- /dev/null
+++ clang/test/CodeGen/CSKY/csky-hard-abi.c
@@ -0,0 +1,394 @@
+// RUN: %clang_cc1 -no-opaque-pointers -triple csky -target-feature +fpuv2_sf -target-feature +fpuv2_df -target-feature +hard-float-abi -target-feature +hard-float -emit-llvm %s -o - | FileCheck %s
+
+#include 
+
+// Verify that the tracking of used GPRs and FPRs works correctly by checking
+// that small integers are sign/zero extended when passed in registers.
+
+// Doubles are passed in FPRs, so argument 'i' will be passed zero-extended
+// because it will be passed in a GPR.
+
+// CHECK: define{{.*}} void @f_fpr_tracking(double noundef %a, double noundef %b, double noundef %c, double noundef %d, i8 noundef zeroext %i)
+void f_fpr_tracking(double a, double b, double c, double d, uint8_t i) {}
+
+// A struct containing just one floating-point real is passed as though it
+// were a standalone floating-point real.
+struct double_s {
+  double f;
+};
+
+// CHECK: define{{.*}} void @f_double_s_arg(double %a.coerce)
+void f_double_s_arg(struct double_s a) {}
+
+// CHECK: define{{.*}} double @f_ret_double_s()
+struct double_s f_ret_double_s(void) {
+  return (struct double_s){1.0};
+}
+
+// A struct containing a double and any number of zero-width bitfields is
+// passed as though it were a standalone floating-point real.
+
+struct zbf_double_s {
+  int : 0;
+  double f;
+};
+struct zbf_double_zbf_s {
+  int : 0;
+  double f;
+  int : 0;
+};
+
+// CHECK: define{{.*}} void @f_zbf_double_s_arg(double %a.coerce)
+void f_zbf_double_s_arg(struct zbf_double_s a) {}
+
+// CHECK: define{{.*}} double @f_ret_zbf_double_s()
+struct zbf_double_s f_ret_zbf_double_s(void) {
+  return (struct zbf_double_s){1.0};
+}
+
+// CHECK: define{{.*}} void @f_zbf_double_zbf_s_arg(double %a.coerce)
+void f_zbf_double_zbf_s_arg(struct zbf_double_zbf_s a) {}
+
+// CHECK: define{{.*}} double @f_ret_zbf_double_zbf_s()
+struct zbf_double_zbf_s f_ret_zbf_double_zbf_s(void) {
+  return (struct zbf_double_zbf_s){1.0};
+}
+
+// For argument type, the first 4*XLen parts of aggregate will be passed
+// in registers, and the rest will be passed in stack.
+// So we can coerce to integers directly and let backend handle it correctly.
+// For return type, aggregate which <= 2*XLen will be returned in registers.
+// Otherwise, aggregate will be returned indirectly.
+
+struct double_double_s {
+  double f;
+  double g;
+};
+struct double_float_s {
+  double f;
+  float g;
+};
+
+// CHECK: define{{.*}} void @f_double_double_s_arg([4 x i32] %a.coerce)
+void f_double_double_s_arg(struct double_double_s a) {}
+
+// CHECK: define{{.*}} void @f_ret_double_double_s(%struct.double_double_s* noalias sret(%struct.double_double_s) align 4 %agg.result)
+struct double_double_s f_ret_double_double_s(void) {
+  return (struct double_double_s){1.0, 2.0};
+}
+
+// CHECK: define{{.*}} void @f_double_float_s_arg([3 x i32] %a.coerce)
+void f_double_float_s_arg(struct double_float_s a) {}
+
+// CHECK: define{{.*}} void @f_ret_double_float_s(%struct.double_float_s* noalias sret(%struct.double_float_s) align 4 %agg.result)
+struct double_float_s f_ret_double_float_s(void) {
+  return (struct double_float_s){1.0, 2.0};
+}
+
+// CHECK: define{{.*}} void @f_double_double_s_arg_insufficient_fprs(float noundef %a, double noundef %b, double noundef %c, double noundef %d, double noundef %e, double noundef %f, double noundef %g, double noundef %i, [4 x i32] %h.coerce)
+void f_double_double_s_arg_insufficient_fprs(float a, double b, double c, double d,
+ double e, double f, double g, double i, struct double_double_s h) {}
+
+struct double_int8_s {
+  double f;
+  int8_t i;
+};
+struct double_uint8_s {
+  double f;
+  uint8_t i;
+};
+struct double_int32_s {
+  double f;
+  int32_t i;
+};
+struct double_int64_s {
+  double f;
+  int64_t i;
+};
+struct double_int64bf_s {
+  double f;
+  int64_t i : 32;
+};
+struct double_int8_zbf_s {
+  double f;
+  int8_t i;
+  int : 0;
+};
+
+// CHECK: define{{.*}}  @f_double_int8_s_arg([3 x i32] %a.coerce)
+void f_double_int8_s_arg(struct double_int8_s a) {}
+
+// CHECK: define{{.*}} void @f_ret_double_int8_s(%struc

[PATCH] D126380: [clang][AArch64][SVE] Implicit conversions for vector-scalar operations

2022-05-26 Thread Cullen Rhodes via Phabricator via cfe-commits
c-rhodes added inline comments.



Comment at: clang/lib/Sema/SemaChecking.cpp:13534-13556
   // Strip vector types.
   if (isa(Source)) {
 if (Target->isVLSTBuiltinType() &&
 (S.Context.areCompatibleSveTypes(QualType(Target, 0),
  QualType(Source, 0)) ||
  S.Context.areLaxCompatibleSveTypes(QualType(Target, 0),
 QualType(Source, 0

a lot of this is duplicated by what you've added below



Comment at: clang/lib/Sema/SemaChecking.cpp:13582
+// Need the original target type for vector type checks
+const Type *OriginalTarget = S.Context.getCanonicalType(T).getTypePtr();
+// Handle conversion from scalable to fixed when msve-vector-bits is

this is the same as `Target` defined on line 13473



Comment at: clang/lib/Sema/SemaExpr.cpp:10267
+
+  if (VT) {
+VectorEltTy = VT->getElementType();

how about:

```  if (const auto *VT = VectorTy->getAs()) {
assert(!isa(VT) &&
   "ExtVectorTypes should not be handled here!");
...
  ```

?



Comment at: clang/lib/Sema/SemaExpr.cpp:10270-10271
+  } else if (VectorTy->isVLSTBuiltinType()) {
+const auto *BuiltinTy = VectorTy->castAs();
+VectorEltTy = BuiltinTy->getSveEltType(S.getASTContext());
+  } else {

```VectorEltTy =
VectorTy->castAs()->getSveEltType(S.getASTContext());```



Comment at: clang/lib/Sema/SemaExpr.cpp:10273
+  } else {
+llvm_unreachable("Only Fixed-Length and SVE Vector types are handled 
here");
+  }

nit: fixed-length



Comment at: clang/test/CodeGen/aarch64-sve-vector-arith-ops.c:336
+//
+svint8_t add_i8_ilit(svint8_t a) {
+  return a + 0;

took me a moment to realise lit -> literal, maybe add an underscore to make it 
clearer? I.e. `add_i8_i_lit`



Comment at: clang/test/Sema/aarch64-sve-vector-scalar-ops.c:1
+// RUN: %clang_cc1 -verify -triple aarch64-none-linux-gnu -target-feature +sve 
-target-feature +neon -fallow-half-arguments-and-returns -fsyntax-only %s
+

There's so few tests in here is it not worth add them to 
`clang/test/Sema/aarch64-sve-vector-arith-ops.c`?



Comment at: clang/test/Sema/aarch64-sve-vector-scalar-ops.c:5
+
+#include 
+#include 

what's NEON needed for in this test?



Comment at: clang/test/Sema/aarch64-sve-vector-scalar-ops.c:12
+
+void add_nonscalar(svint32_t i32, struct T a32, svbool_t b) {
+  (void)(i32 + a32); // expected-error{{cannot convert between vector and 
non-scalar values ('svint32_t' (aka '__SVInt32_t') and 'struct T')}}

unused



Comment at: clang/test/Sema/aarch64-sve-vector-scalar-ops.c:17
+void add_bool(svbool_t b) {
+  (void)(b + b); // expected-error{{invalid operands to binary expression 
('svbool_t' (aka '__SVBool_t') and 'svbool_t')}}
+}

there's already a test for this in 
`clang/test/Sema/aarch64-sve-vector-arith-ops.c`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126380

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


[PATCH] D126365: [git-clang-format] Stop ignoring changes for files with space in path

2022-05-26 Thread Eitot via Phabricator via cfe-commits
Eitot updated this revision to Diff 432221.
Eitot added a comment.

I have uploaded a complete diff.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126365

Files:
  clang/tools/clang-format/git-clang-format


Index: clang/tools/clang-format/git-clang-format
===
--- clang/tools/clang-format/git-clang-format
+++ clang/tools/clang-format/git-clang-format
@@ -345,7 +345,7 @@
 line = convert_string(line)
 match = re.search(r'^\+\+\+\ [^/]+/(.*)', line)
 if match:
-  filename = match.group(1).rstrip('\r\n')
+  filename = match.group(1).rstrip('\r\n\t')
 match = re.search(r'^@@ -[0-9,]+ \+(\d+)(,(\d+))?', line)
 if match:
   start_line = int(match.group(1))


Index: clang/tools/clang-format/git-clang-format
===
--- clang/tools/clang-format/git-clang-format
+++ clang/tools/clang-format/git-clang-format
@@ -345,7 +345,7 @@
 line = convert_string(line)
 match = re.search(r'^\+\+\+\ [^/]+/(.*)', line)
 if match:
-  filename = match.group(1).rstrip('\r\n')
+  filename = match.group(1).rstrip('\r\n\t')
 match = re.search(r'^@@ -[0-9,]+ \+(\d+)(,(\d+))?', line)
 if match:
   start_line = int(match.group(1))
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D126451: [Clang][CSKY] Add support about CSKYABIInfo

2022-05-26 Thread David Spickett via Phabricator via cfe-commits
DavidSpickett added a comment.

Can you reupload with more context? See 
https://llvm.org/docs/Phabricator.html#requesting-a-review-via-the-web-interface

I doubt I'll be able to give any in depth review but if things look good 
generally I'm sure you'll find the issues through your own testing as time goes 
on.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126451

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


[PATCH] D126406: [analyzer] Return from reAssume if State is posteriorly overconstrained

2022-05-26 Thread Gabor Marton via Phabricator via cfe-commits
martong updated this revision to Diff 432225.
martong marked 5 inline comments as done.
martong added a comment.

- Make reAssume friend, pin the target in the test


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126406

Files:
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
  clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
  clang/test/Analysis/runtime-regression.c

Index: clang/test/Analysis/runtime-regression.c
===
--- /dev/null
+++ clang/test/Analysis/runtime-regression.c
@@ -0,0 +1,55 @@
+// RUN: %clang_analyze_cc1 %s \
+// RUN:   -analyzer-checker=core,alpha.security.ArrayBoundV2 \
+// RUN:   -analyzer-checker=debug.ExprInspection \
+// RUN:   -triple x86_64-unknown-linux-gnu \
+// RUN:   -verify
+
+// This test is here to check if there is no significant run-time regression
+// related to the assume machinery. The analysis should finish in less than 10
+// seconds.
+
+// expected-no-diagnostics
+
+typedef unsigned char uint8_t;
+typedef unsigned short uint16_t;
+typedef unsigned long uint64_t;
+
+int filter_slice_word(int sat_linesize, int sigma, int radius, uint64_t *sat,
+  uint64_t *square_sat, int width, int height,
+  int src_linesize, int dst_linesize, const uint16_t *src,
+  uint16_t *dst, int jobnr, int nb_jobs) {
+  const int starty = height * jobnr / nb_jobs;
+  const int endy = height * (jobnr + 1) / nb_jobs;
+
+  for (int y = starty; y < endy; y++) {
+
+int lower_y = y - radius < 0 ? 0 : y - radius;
+int higher_y = y + radius + 1 > height ? height : y + radius + 1;
+int dist_y = higher_y - lower_y;
+
+for (int x = 0; x < width; x++) {
+
+  int lower_x = x - radius < 0 ? 0 : x - radius;
+  int higher_x = x + radius + 1 > width ? width : x + radius + 1;
+  int count = dist_y * (higher_x - lower_x);
+
+  // The below hunk caused significant regression in run-time.
+#if 1
+  uint64_t sum = sat[higher_y * sat_linesize + higher_x] -
+ sat[higher_y * sat_linesize + lower_x] -
+ sat[lower_y * sat_linesize + higher_x] +
+ sat[lower_y * sat_linesize + lower_x];
+  uint64_t square_sum = square_sat[higher_y * sat_linesize + higher_x] -
+square_sat[higher_y * sat_linesize + lower_x] -
+square_sat[lower_y * sat_linesize + higher_x] +
+square_sat[lower_y * sat_linesize + lower_x];
+  uint64_t mean = sum / count;
+  uint64_t var = (square_sum - sum * sum / count) / count;
+  dst[y * dst_linesize + x] =
+  (sigma * mean + var * src[y * src_linesize + x]) / (sigma + var);
+#endif
+
+}
+  }
+  return 0;
+}
Index: clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
===
--- clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
+++ clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
@@ -2530,10 +2530,19 @@
   return State;
 }
 
+// We must declare reAssume in clang::ento, otherwise we could not declare that
+// as a friend in ProgramState. More precisely, the call of reAssume would be
+// ambiguous (one in the global namespace and an other which is declared in
+// ProgramState is in clang::ento).
+namespace clang {
+namespace ento {
 // Re-evaluate an SVal with top-level `State->assume` logic.
 LLVM_NODISCARD ProgramStateRef reAssume(ProgramStateRef State,
 const RangeSet *Constraint,
 SVal TheValue) {
+  assert(State);
+  if (State->isPosteriorlyOverconstrained())
+return nullptr;
   if (!Constraint)
 return State;
 
@@ -2556,6 +2565,8 @@
   return State->assumeInclusiveRange(DefinedVal, Constraint->getMinValue(),
  Constraint->getMaxValue(), true);
 }
+} // namespace ento
+} // namespace clang
 
 // Iterate over all symbols and try to simplify them. Once a symbol is
 // simplified then we check if we can merge the simplified symbol's equivalence
Index: clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
===
--- clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
+++ clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
@@ -55,6 +55,8 @@
   }
 };
 
+class RangeSet;
+
 /// \class ProgramState
 /// ProgramState - This class encapsulates:
 ///
@@ -79,7 +81,6 @@
   friend class ExplodedGraph;
   friend class ExplodedNode;
   friend class NodeBuilder;
-  friend class ConstraintManager;
 
   ProgramStateManager *stateMgr;
   Environment Env;   // Maps a Stmt to its current SVal.
@@ -113,6 +114,16 @@
   // posteriorly over-constrained. These parents are hand

[PATCH] D126406: [analyzer] Return from reAssume if State is posteriorly overconstrained

2022-05-26 Thread Gabor Marton via Phabricator via cfe-commits
martong added inline comments.



Comment at: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h:127
+
+public:
   bool isPosteriorlyOverconstrained() const {

steakhal wrote:
> This shouldnt be the way.
> Consider fwd declaring and making it friend instead.
> I really dont want to expose this api.
Okay, I've made it a friend.



Comment at: clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp:2547
   if (Constraint->encodesFalseRange())
 return State->assume(DefinedVal, false);
 

steakhal wrote:
> martong wrote:
> > I am wondering, that maybe it would be better to check for 
> > `isPosteriorlyOverconstrained` here. Because only `State->assume` can 
> > return such States, and by checking it here, we could spare some 
> > instructions.
> Play with it.
Yeah, I will, but I don't know how much time that would take to assess. So, in 
the meantime let's proceed with this version.



Comment at: clang/test/Analysis/runtime-regression.c:7
+// This test is here to check if there is no significant run-time regression
+// related to the assume machinery. This is an automatically reduced code. The
+// analysis should finish in less than 10 seconds.

steakhal wrote:
> Sadly, I had to manually track this down xD.
Ok, I removed the sentence.



Comment at: clang/test/Analysis/runtime-regression.c:8
+// related to the assume machinery. This is an automatically reduced code. The
+// analysis should finish in less than 10 seconds.
+

steakhal wrote:
> Maybe the test infra has something to specify a timeout.
I could not find how to set a timeout in the test file. There is a lit cli 
option that might be used, however, that would affect all other test cases. 
https://llvm.org/docs/CommandGuide/lit.html#cmdoption-lit-timeout



Comment at: clang/test/Analysis/runtime-regression.c:12
+
+typedef unsigned char uint8_t;
+typedef unsigned short uint16_t;

steakhal wrote:
> Pin the tartget triple.
Ok, done.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126406

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


[PATCH] D126451: [Clang][CSKY] Add support about CSKYABIInfo

2022-05-26 Thread Zixuan Wu via Phabricator via cfe-commits
zixuan-wu updated this revision to Diff 432228.

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

https://reviews.llvm.org/D126451

Files:
  clang/lib/CodeGen/TargetInfo.cpp
  clang/test/CodeGen/CSKY/csky-abi.c
  clang/test/CodeGen/CSKY/csky-hard-abi.c

Index: clang/test/CodeGen/CSKY/csky-hard-abi.c
===
--- /dev/null
+++ clang/test/CodeGen/CSKY/csky-hard-abi.c
@@ -0,0 +1,394 @@
+// RUN: %clang_cc1 -no-opaque-pointers -triple csky -target-feature +fpuv2_sf -target-feature +fpuv2_df -target-feature +hard-float-abi -target-feature +hard-float -emit-llvm %s -o - | FileCheck %s
+
+#include 
+
+// Verify that the tracking of used GPRs and FPRs works correctly by checking
+// that small integers are sign/zero extended when passed in registers.
+
+// Doubles are passed in FPRs, so argument 'i' will be passed zero-extended
+// because it will be passed in a GPR.
+
+// CHECK: define{{.*}} void @f_fpr_tracking(double noundef %a, double noundef %b, double noundef %c, double noundef %d, i8 noundef zeroext %i)
+void f_fpr_tracking(double a, double b, double c, double d, uint8_t i) {}
+
+// A struct containing just one floating-point real is passed as though it
+// were a standalone floating-point real.
+struct double_s {
+  double f;
+};
+
+// CHECK: define{{.*}} void @f_double_s_arg(double %a.coerce)
+void f_double_s_arg(struct double_s a) {}
+
+// CHECK: define{{.*}} double @f_ret_double_s()
+struct double_s f_ret_double_s(void) {
+  return (struct double_s){1.0};
+}
+
+// A struct containing a double and any number of zero-width bitfields is
+// passed as though it were a standalone floating-point real.
+
+struct zbf_double_s {
+  int : 0;
+  double f;
+};
+struct zbf_double_zbf_s {
+  int : 0;
+  double f;
+  int : 0;
+};
+
+// CHECK: define{{.*}} void @f_zbf_double_s_arg(double %a.coerce)
+void f_zbf_double_s_arg(struct zbf_double_s a) {}
+
+// CHECK: define{{.*}} double @f_ret_zbf_double_s()
+struct zbf_double_s f_ret_zbf_double_s(void) {
+  return (struct zbf_double_s){1.0};
+}
+
+// CHECK: define{{.*}} void @f_zbf_double_zbf_s_arg(double %a.coerce)
+void f_zbf_double_zbf_s_arg(struct zbf_double_zbf_s a) {}
+
+// CHECK: define{{.*}} double @f_ret_zbf_double_zbf_s()
+struct zbf_double_zbf_s f_ret_zbf_double_zbf_s(void) {
+  return (struct zbf_double_zbf_s){1.0};
+}
+
+// For argument type, the first 4*XLen parts of aggregate will be passed
+// in registers, and the rest will be passed in stack.
+// So we can coerce to integers directly and let backend handle it correctly.
+// For return type, aggregate which <= 2*XLen will be returned in registers.
+// Otherwise, aggregate will be returned indirectly.
+
+struct double_double_s {
+  double f;
+  double g;
+};
+struct double_float_s {
+  double f;
+  float g;
+};
+
+// CHECK: define{{.*}} void @f_double_double_s_arg([4 x i32] %a.coerce)
+void f_double_double_s_arg(struct double_double_s a) {}
+
+// CHECK: define{{.*}} void @f_ret_double_double_s(%struct.double_double_s* noalias sret(%struct.double_double_s) align 4 %agg.result)
+struct double_double_s f_ret_double_double_s(void) {
+  return (struct double_double_s){1.0, 2.0};
+}
+
+// CHECK: define{{.*}} void @f_double_float_s_arg([3 x i32] %a.coerce)
+void f_double_float_s_arg(struct double_float_s a) {}
+
+// CHECK: define{{.*}} void @f_ret_double_float_s(%struct.double_float_s* noalias sret(%struct.double_float_s) align 4 %agg.result)
+struct double_float_s f_ret_double_float_s(void) {
+  return (struct double_float_s){1.0, 2.0};
+}
+
+// CHECK: define{{.*}} void @f_double_double_s_arg_insufficient_fprs(float noundef %a, double noundef %b, double noundef %c, double noundef %d, double noundef %e, double noundef %f, double noundef %g, double noundef %i, [4 x i32] %h.coerce)
+void f_double_double_s_arg_insufficient_fprs(float a, double b, double c, double d,
+ double e, double f, double g, double i, struct double_double_s h) {}
+
+struct double_int8_s {
+  double f;
+  int8_t i;
+};
+struct double_uint8_s {
+  double f;
+  uint8_t i;
+};
+struct double_int32_s {
+  double f;
+  int32_t i;
+};
+struct double_int64_s {
+  double f;
+  int64_t i;
+};
+struct double_int64bf_s {
+  double f;
+  int64_t i : 32;
+};
+struct double_int8_zbf_s {
+  double f;
+  int8_t i;
+  int : 0;
+};
+
+// CHECK: define{{.*}}  @f_double_int8_s_arg([3 x i32] %a.coerce)
+void f_double_int8_s_arg(struct double_int8_s a) {}
+
+// CHECK: define{{.*}} void @f_ret_double_int8_s(%struct.double_int8_s* noalias sret(%struct.double_int8_s) align 4 %agg.result)
+struct double_int8_s f_ret_double_int8_s(void) {
+  return (struct double_int8_s){1.0, 2};
+}
+
+// CHECK: define{{.*}} void @f_double_uint8_s_arg([3 x i32] %a.coerce)
+void f_double_uint8_s_arg(struct double_uint8_s a) {}
+
+// CHECK: define{{.*}} void @f_ret_double_uint8_s(%struct.double_uint8_s* noalias sret(%struct.double_uint8_s) align 4 %agg.result)
+struct doubl

[PATCH] D126451: [Clang][CSKY] Add support about CSKYABIInfo

2022-05-26 Thread Zixuan Wu via Phabricator via cfe-commits
zixuan-wu added a comment.

In D126451#3539512 , @DavidSpickett 
wrote:

> Can you reupload with more context? See 
> https://llvm.org/docs/Phabricator.html#requesting-a-review-via-the-web-interface
>
> I doubt I'll be able to give any in depth review but if things look good 
> generally I'm sure you'll find the issues through your own testing as time 
> goes on.

Well, sorry that I forgot to add -U99 option.


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

https://reviews.llvm.org/D126451

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


[clang] ad1d60c - [FileCheck] Catch missspelled directives.

2022-05-26 Thread Ivan Kosarev via cfe-commits

Author: Ivan Kosarev
Date: 2022-05-26T11:37:19+01:00
New Revision: ad1d60c3befd606d6864b367f939238e50fb0f7e

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

LOG: [FileCheck] Catch missspelled directives.

Reviewed By: MaskRay

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

Added: 
llvm/test/FileCheck/missspelled-directive.txt

Modified: 
clang/test/CodeGenCXX/attr-mustprogress.cpp
clang/test/CodeGenCXX/eh-aggregate-copy-destroy.cpp
clang/test/CodeGenCXX/inheriting-constructor.cpp
clang/test/CodeGenObjC/non-runtime-protocol.m
clang/test/OpenMP/master_taskloop_private_codegen.cpp
clang/test/OpenMP/master_taskloop_simd_private_codegen.cpp
clang/test/OpenMP/parallel_master_taskloop_private_codegen.cpp
clang/test/OpenMP/parallel_master_taskloop_simd_private_codegen.cpp
clang/test/OpenMP/task_private_codegen.cpp
clang/test/OpenMP/taskgroup_task_reduction_codegen.cpp
clang/test/OpenMP/taskloop_private_codegen.cpp
clang/test/OpenMP/taskloop_simd_private_codegen.cpp
flang/test/Fir/convert-to-llvm.fir
flang/test/Lower/Intrinsics/not.f90
llvm/include/llvm/FileCheck/FileCheck.h
llvm/lib/FileCheck/FileCheck.cpp
llvm/test/Analysis/MemorySSA/phi-translation.ll
llvm/test/Analysis/RegionInfo/infinite_loop_4.ll
llvm/test/CodeGen/AMDGPU/divergence-driven-bfe-isel.ll
llvm/test/CodeGen/AMDGPU/hoist-cond.ll
llvm/test/CodeGen/AMDGPU/llvm.amdgcn.ps.live.ll
llvm/test/CodeGen/AMDGPU/mode-register.mir
llvm/test/CodeGen/AMDGPU/smrd.ll
llvm/test/CodeGen/ARM/cmpxchg-O0-be.ll
llvm/test/CodeGen/AVR/atomics/fence.ll
llvm/test/CodeGen/BPF/CORE/offset-reloc-middle-chain.ll
llvm/test/CodeGen/WebAssembly/libcalls.ll
llvm/test/DebugInfo/NVPTX/debug-info.ll
llvm/test/MC/AMDGPU/data.s
llvm/test/MC/AsmParser/directive_file-g.s
llvm/test/MC/PowerPC/ppc64-reloc-directive-pcrel.s
llvm/test/MC/WebAssembly/unnamed-data.ll
llvm/test/Transforms/Inline/inline-strictfp.ll
llvm/test/Transforms/LoopVectorize/X86/gather-vs-interleave.ll
llvm/test/Transforms/MergeFunc/alias.ll
llvm/test/Transforms/PGOProfile/PR41279.ll
llvm/test/Transforms/PGOProfile/memop_clone.ll
llvm/test/Transforms/PGOProfile/memop_size_from_strlen.ll
llvm/test/tools/llvm-dwp/X86/tu_units_v5.s
llvm/test/tools/llvm-dwp/X86/type_dedup_v5.test
llvm/test/tools/llvm-objdump/MachO/disassemble-all.test
llvm/test/tools/llvm-readobj/COFF/unwind-arm64-windows.test
mlir/test/Dialect/Affine/loop-coalescing.mlir
mlir/test/Dialect/Linalg/fuse-with-reshape-by-collapsing.mlir
mlir/test/Dialect/Linalg/tile-and-fuse-no-fuse.mlir
mlir/test/Dialect/MemRef/canonicalize.mlir
mlir/test/Dialect/SPIRV/IR/memory-ops.mlir
mlir/test/Dialect/Vector/vector-transfer-full-partial-split.mlir
mlir/test/IR/dynamic.mlir
mlir/test/mlir-tblgen/op-decl-and-defs.td
polly/test/ScopDetect/dot-scops-npm.ll

Removed: 




diff  --git a/clang/test/CodeGenCXX/attr-mustprogress.cpp 
b/clang/test/CodeGenCXX/attr-mustprogress.cpp
index 592ebd537cc73..4dac0a4b93b0d 100644
--- a/clang/test/CodeGenCXX/attr-mustprogress.cpp
+++ b/clang/test/CodeGenCXX/attr-mustprogress.cpp
@@ -125,7 +125,7 @@ void F() {
 // CHECK-NEXT:[[CMP:%.*]] = icmp eq i32 [[TMP0]], [[TMP1]]
 // CHECK-NEXT:br i1 [[CMP]], label %for.body, label %for.end
 // CHECK:   for.body:
-// CXX98_NOT: br {{.*}} !llvm.loop
+// CXX98-NOT: br {{.*}} !llvm.loop
 // CXX11-NEXT:br label %for.cond, !llvm.loop [[LOOP6:!.*]]
 // FINITE-NEXT:   br label %for.cond, !llvm.loop [[LOOP6:!.*]]
 // CHECK:   for.end:

diff  --git a/clang/test/CodeGenCXX/eh-aggregate-copy-destroy.cpp 
b/clang/test/CodeGenCXX/eh-aggregate-copy-destroy.cpp
index 9f0f36c875618..37d5b8654eee0 100644
--- a/clang/test/CodeGenCXX/eh-aggregate-copy-destroy.cpp
+++ b/clang/test/CodeGenCXX/eh-aggregate-copy-destroy.cpp
@@ -23,7 +23,7 @@ struct Container {
 int main () {
   try {
 Container c1;
-// CHECK_LABEL: main
+// CHECK-LABEL: main
 // CHECK-NOT: call void @_ZN9ThrowCopyC1ERKS_
 // CHECK: invoke void @_ZN9ThrowCopyC1ERKS_
 // CHECK98: invoke void @_ZN12ImplicitCopyD1Ev

diff  --git a/clang/test/CodeGenCXX/inheriting-constructor.cpp 
b/clang/test/CodeGenCXX/inheriting-constructor.cpp
index dffd13d9bfbcd..751604fad194c 100644
--- a/clang/test/CodeGenCXX/inheriting-constructor.cpp
+++ b/clang/test/CodeGenCXX/inheriting-constructor.cpp
@@ -93,7 +93,7 @@ namespace noninline_virt {
   C c(1, 2, &c);
   // Complete object ctor forwards to A ctor, then calls B's base inheriting
   // constructor, which takes no arguments other than the this pointer and VTT.
-  // ITANIUM_LABEL: define linkonce_odr void 
@_ZN14noninline_virt1CCI1NS_1AEEiO1QPvU

[PATCH] D125604: [FileCheck] Catch missspelled directives.

2022-05-26 Thread Ivan Kosarev via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGad1d60c3befd: [FileCheck] Catch missspelled directives. 
(authored by kosarev).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125604

Files:
  clang/test/CodeGenCXX/attr-mustprogress.cpp
  clang/test/CodeGenCXX/eh-aggregate-copy-destroy.cpp
  clang/test/CodeGenCXX/inheriting-constructor.cpp
  clang/test/CodeGenObjC/non-runtime-protocol.m
  clang/test/OpenMP/master_taskloop_private_codegen.cpp
  clang/test/OpenMP/master_taskloop_simd_private_codegen.cpp
  clang/test/OpenMP/parallel_master_taskloop_private_codegen.cpp
  clang/test/OpenMP/parallel_master_taskloop_simd_private_codegen.cpp
  clang/test/OpenMP/task_private_codegen.cpp
  clang/test/OpenMP/taskgroup_task_reduction_codegen.cpp
  clang/test/OpenMP/taskloop_private_codegen.cpp
  clang/test/OpenMP/taskloop_simd_private_codegen.cpp
  flang/test/Fir/convert-to-llvm.fir
  flang/test/Lower/Intrinsics/not.f90
  llvm/include/llvm/FileCheck/FileCheck.h
  llvm/lib/FileCheck/FileCheck.cpp
  llvm/test/Analysis/MemorySSA/phi-translation.ll
  llvm/test/Analysis/RegionInfo/infinite_loop_4.ll
  llvm/test/CodeGen/AMDGPU/divergence-driven-bfe-isel.ll
  llvm/test/CodeGen/AMDGPU/hoist-cond.ll
  llvm/test/CodeGen/AMDGPU/llvm.amdgcn.ps.live.ll
  llvm/test/CodeGen/AMDGPU/mode-register.mir
  llvm/test/CodeGen/AMDGPU/smrd.ll
  llvm/test/CodeGen/ARM/cmpxchg-O0-be.ll
  llvm/test/CodeGen/AVR/atomics/fence.ll
  llvm/test/CodeGen/BPF/CORE/offset-reloc-middle-chain.ll
  llvm/test/CodeGen/WebAssembly/libcalls.ll
  llvm/test/DebugInfo/NVPTX/debug-info.ll
  llvm/test/FileCheck/missspelled-directive.txt
  llvm/test/MC/AMDGPU/data.s
  llvm/test/MC/AsmParser/directive_file-g.s
  llvm/test/MC/PowerPC/ppc64-reloc-directive-pcrel.s
  llvm/test/MC/WebAssembly/unnamed-data.ll
  llvm/test/Transforms/Inline/inline-strictfp.ll
  llvm/test/Transforms/LoopVectorize/X86/gather-vs-interleave.ll
  llvm/test/Transforms/MergeFunc/alias.ll
  llvm/test/Transforms/PGOProfile/PR41279.ll
  llvm/test/Transforms/PGOProfile/memop_clone.ll
  llvm/test/Transforms/PGOProfile/memop_size_from_strlen.ll
  llvm/test/tools/llvm-dwp/X86/tu_units_v5.s
  llvm/test/tools/llvm-dwp/X86/type_dedup_v5.test
  llvm/test/tools/llvm-objdump/MachO/disassemble-all.test
  llvm/test/tools/llvm-readobj/COFF/unwind-arm64-windows.test
  mlir/test/Dialect/Affine/loop-coalescing.mlir
  mlir/test/Dialect/Linalg/fuse-with-reshape-by-collapsing.mlir
  mlir/test/Dialect/Linalg/tile-and-fuse-no-fuse.mlir
  mlir/test/Dialect/MemRef/canonicalize.mlir
  mlir/test/Dialect/SPIRV/IR/memory-ops.mlir
  mlir/test/Dialect/Vector/vector-transfer-full-partial-split.mlir
  mlir/test/IR/dynamic.mlir
  mlir/test/mlir-tblgen/op-decl-and-defs.td
  polly/test/ScopDetect/dot-scops-npm.ll

Index: polly/test/ScopDetect/dot-scops-npm.ll
===
--- polly/test/ScopDetect/dot-scops-npm.ll
+++ polly/test/ScopDetect/dot-scops-npm.ll
@@ -30,35 +30,35 @@
 ; CHECK-NEXT: Node0x[[OUTER_EXIT]] -> Node0x[[RETURN_ID:.*]];
 ; CHECK-NEXT: Node0x[[RETURN_ID]] [shape=record,label="{return:
 ; CHECK-NEXT: colorscheme = "paired12"
-; CHECK_NEXT: subgraph cluster_0x[[:.*]] {
-; CHECK_NEXT: label = "";
-; CHECK_NEXT: style = solid;
-; CHECK_NEXT: color = 1
-; CHECK_NEXT: subgraph cluster_0x[[:.*]] {
-; CHECK_NEXT: label = "";
-; CHECK_NEXT: style = filled;
-; CHECK_NEXT: color = 3subgraph cluster_0x7152c40 {
-; CHECK_NEXT: label = "";
-; CHECK_NEXT: style = solid;
-; CHECK_NEXT: color = 5
-; CHECK_NEXT: subgraph cluster_0x[[:.*]] {
-; CHECK_NEXT: label = "";
-; CHECK_NEXT: style = solid;
-; CHECK_NEXT: color = 7
-; CHECK_NEXT: Node0x[[INNER_FOR_ID]];
-; CHECK_NEXT: Node0x[[BABY1_ID]];
-; CHECK_NEXT: Node0x[[INNER_INC_ID]];
-; CHECK_NEXT: }
-; CHECK_NEXT: Node0x[[OUTER_FOR_ID]];
-; CHECK_NEXT: Node0x[[INNER_EXIT_ID]];
-; CHECK_NEXT: Node0x[[OUTER_INC_ID]];
-; CHECK_NEXT: }
-; CHECK_NEXT: Node0x[[OUTER_EXIT]];
-; CHECK_NEXT: }
-; CHECK_NEXT: Node0x[[EntryID]];
-; CHECK_NEXT: Node0x[[RETURN_ID]];
-; CHECK_NEXT: }
-; CHECK_NEXT: }
+; CHECK-NEXT: subgraph cluster_0x{{.*}} {
+; CHECK-NEXT: label = "";
+; CHECK-NEXT: style = solid;
+; CHECK-NEXT: color = 1
+; CHECK-NEXT: subgraph cluster_0x{{.*}} {
+; CHECK-NEXT: label = "";
+; CHECK-NEXT: style = filled;
+; CHECK-NEXT: color = 3subgraph cluster_0x{{.*}} {
+; CHECK-NEXT: label = "";
+; CHECK-NEXT: style = solid;
+; CHECK-NEXT: color = 5
+; CHECK-NEXT: subgraph cluster_0x{{.*}} {
+; CHECK-NEXT: label = "";
+; CHECK-NEXT: style = solid;
+; CHECK-NEXT: color = 7
+; CHECK-NEXT: Node0x[[INNER_FOR_ID]];
+; CHECK-NEXT: Node0x[[BABY1_ID]];
+; CHECK-NEXT: Node0x[[INNER_INC_ID]];
+; CHECK-NEXT: }
+; CHECK-NEXT: Node0x[[OUTER_FOR_ID]];
+; CHECK-NEXT: Node0x[[INNER_EXIT_ID]];
+; CHECK-NEXT: Node0x[[OUTER_INC_ID]];
+; CHECK-NEXT: }
+; CHE

[PATCH] D126406: [analyzer] Return from reAssume if State is posteriorly overconstrained

2022-05-26 Thread Balázs Benics via Phabricator via cfe-commits
steakhal accepted this revision.
steakhal added a comment.
This revision is now accepted and ready to land.

Typo; other than that LGTM




Comment at: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h:118
+  // Make internal constraint solver entities friends so they can access the
+  // overconstrained related functions. We want to keep this API inaccessible
+  // for Checkers.





Comment at: clang/test/Analysis/runtime-regression.c:8
+// related to the assume machinery. This is an automatically reduced code. The
+// analysis should finish in less than 10 seconds.
+

martong wrote:
> steakhal wrote:
> > Maybe the test infra has something to specify a timeout.
> I could not find how to set a timeout in the test file. There is a lit cli 
> option that might be used, however, that would affect all other test cases. 
> https://llvm.org/docs/CommandGuide/lit.html#cmdoption-lit-timeout
Why you could do is to call `RUN {lit} --max-time XX` Then do a `FileCheck` 
against the output of that.
Alternatively, we can craft something to make the situation worse, to the point 
that we will notice, and effectively hang the test suite. Either way, I'm fine 
with how things look ATM.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126406

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


[PATCH] D126189: [C++20][Modules] Build module static initializers per P1874R1.

2022-05-26 Thread Iain Sandoe via Phabricator via cfe-commits
iains updated this revision to Diff 432241.
iains marked 14 inline comments as done.
iains added a comment.

address review comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126189

Files:
  clang/include/clang/AST/ASTContext.h
  clang/include/clang/Basic/Module.h
  clang/include/clang/Sema/Sema.h
  clang/lib/CodeGen/CGDeclCXX.cpp
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/lib/CodeGen/CodeGenModule.h
  clang/lib/Parse/ParseAST.cpp
  clang/test/CodeGen/module-intializer-pmf.cpp
  clang/test/CodeGen/module-intializer.cpp

Index: clang/test/CodeGen/module-intializer.cpp
===
--- /dev/null
+++ clang/test/CodeGen/module-intializer.cpp
@@ -0,0 +1,172 @@
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+// RUN: cd %t
+
+// RUN: %clang_cc1 -triple %itanium_abi_triple -std=c++20 N.cpp \
+// RUN:-emit-module-interface -o N.pcm
+// RUN: %clang_cc1 -triple %itanium_abi_triple -std=c++20 N.pcm -S -emit-llvm \
+// RUN:  -o - | FileCheck %s --check-prefix=CHECK-N
+
+// RUN: %clang_cc1 -triple %itanium_abi_triple -std=c++20 O.cpp \
+// RUN:-emit-module-interface -o O.pcm
+// RUN: %clang_cc1 -triple %itanium_abi_triple -std=c++20 O.pcm -S -emit-llvm \
+// RUN:  -o - | FileCheck %s --check-prefix=CHECK-O
+
+// RUN: %clang_cc1 -triple %itanium_abi_triple -std=c++20 M-part.cpp \
+// RUN:-emit-module-interface -o M-part.pcm
+// RUN: %clang_cc1 -triple %itanium_abi_triple -std=c++20 M-part.pcm -S \
+// RUN: -emit-llvm -o - | FileCheck %s --check-prefix=CHECK-P
+
+// RUN: %clang_cc1 -triple %itanium_abi_triple -std=c++20 M.cpp \
+// RUN: -fmodule-file=N.pcm -fmodule-file=O.pcm -fmodule-file=M-part.pcm \
+// RUN:-emit-module-interface -o M.pcm
+// RUN: %clang_cc1 -triple %itanium_abi_triple -std=c++20 M.pcm -S -emit-llvm \
+// RUN:  -o - | FileCheck %s --check-prefix=CHECK-M
+
+// RUN: %clang_cc1 -triple %itanium_abi_triple -std=c++20 useM.cpp \
+// RUN: -fmodule-file=M.pcm -S -emit-llvm  -o - \
+// RUN: | FileCheck %s --check-prefix=CHECK-USE
+
+//--- N-h.h
+
+struct Oink {
+  Oink(){};
+};
+
+Oink Hog;
+
+//--- N.cpp
+
+module;
+#include "N-h.h"
+
+export module N;
+
+export struct Quack {
+  Quack(){};
+};
+
+export Quack Duck;
+
+// CHECK-N: define internal void @__cxx_global_var_init
+// CHECK-N: call void @_ZN4OinkC1Ev
+// CHECK-N: define internal void @__cxx_global_var_init
+// CHECK-N: call void @_ZNW1N5QuackC1Ev
+// CHECK-N: define void @_ZGIW1N
+// CHECK-N: store i8 1, ptr @_ZGIW1N__in_chrg
+// CHECK-N: call void @__cxx_global_var_init
+// CHECK-N: call void @__cxx_global_var_init
+
+//--- O-h.h
+
+struct Meow {
+  Meow(){};
+};
+
+Meow Cat;
+
+//--- O.cpp
+
+module;
+#include "O-h.h"
+
+export module O;
+
+export struct Bark {
+  Bark(){};
+};
+
+export Bark Dog;
+
+// CHECK-O: define internal void @__cxx_global_var_init
+// CHECK-O: call void @_ZN4MeowC2Ev
+// CHECK-O: define internal void @__cxx_global_var_init
+// CHECK-O: call void @_ZNW1O4BarkC1Ev
+// CHECK-O: define void @_ZGIW1O
+// CHECK-O: store i8 1, ptr @_ZGIW1O__in_chrg
+// CHECK-O: call void @__cxx_global_var_init
+// CHECK-O: call void @__cxx_global_var_init
+
+//--- P-h.h
+
+struct Croak {
+  Croak(){};
+};
+
+Croak Frog;
+
+//--- M-part.cpp
+
+module;
+#include "P-h.h"
+
+module M:Part;
+
+struct Squawk {
+  Squawk(){};
+};
+
+Squawk parrot;
+
+// CHECK-P: define internal void @__cxx_global_var_init
+// CHECK-P: call void @_ZN5CroakC1Ev
+// CHECK-P: define internal void @__cxx_global_var_init
+// CHECK-P: call void @_ZNW1M6SquawkC1Ev
+// CHECK-P: define void @_ZGIW1MWP4Part
+// CHECK-P: store i8 1, ptr @_ZGIW1MWP4Part__in_chrg
+// CHECK-P: call void @__cxx_global_var_init
+// CHECK-P: call void @__cxx_global_var_init
+
+//--- M-h.h
+
+struct Moo {
+  Moo(){};
+};
+
+Moo Cow;
+
+//--- M.cpp
+
+module;
+#include "M-h.h"
+
+export module M;
+import N;
+export import O;
+import :Part;
+
+export struct Baa {
+  int x;
+  Baa(){};
+  Baa(int x) : x(x) {}
+  int getX() { return x; }
+};
+
+export Baa Sheep(10);
+
+// CHECK-M: define internal void @__cxx_global_var_init
+// CHECK-M: call void @_ZN3MooC1Ev
+// CHECK-M: define internal void @__cxx_global_var_init
+// CHECK-M: call void @_ZNW1M3BaaC1Ei
+// CHECK-M: declare void @_ZGIW1O()
+// CHECK-M: declare void @_ZGIW1N()
+// CHECK-M: declare void @_ZGIW1MWP4Part()
+// CHECK-M: define void @_ZGIW1M
+// CHECK-M: store i8 1, ptr @_ZGIW1M__in_chrg
+// CHECK-M: call void @_ZGIW1O()
+// CHECK-M: call void @_ZGIW1N()
+// CHECK-M: call void @_ZGIW1MWP4Part()
+// CHECK-M: call void @__cxx_global_var_init
+// CHECK-M: call void @__cxx_global_var_init
+
+//--- useM.cpp
+
+import M;
+
+int main() {
+  return Sheep.getX();
+}
+
+// CHECK-USE: declare void @_ZGIW1M
+// CHECK-USE: define internal void @_GLOBAL__sub_I_useM.cpp
+// CHECK-USE: call void @_ZGIW1M()
Index: clang/test/CodeGen/module-intializer-pmf.cpp
=

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

2022-05-26 Thread Serge Pavlov via Phabricator via cfe-commits
sepavloff added a comment.

In D126364#3537964 , @efriedma wrote:

> Could you lay out the expected interaction between "STDC FENV_ACCESS", "clang 
> fp exceptions", "float_control", and "fenv_access"?  If there's some way to 
> map everything to "#pragma clang fp", please lay that out; if that isn't 
> possible, please explain why.

`pragma fenv_access` is same as `pragma STDC FENV_ACCESS`.
`pragma float_control(except, ...)` is same as `pragma clang fp exception` 
amended with possibility to maintain stack of the directives using `push` token.
So indeed, all cases can be mapped to the interaction of  `pragma STDC 
FENV_ACCESS` with `pragma clang fp exception`.
Possible combinations are:

1. No access to FP environment:

#pragma STDC FENV_ACCESS OFF
#pragma clang fp exception(ignore)  // maytrap or strict is not allowed

2. Strict exception mode:

#pragma STDC FENV_ACCESS ON
#pragma clang fp exception(strict)

3. MayTrap exception mode:

#pragma STDC FENV_ACCESS ON
#pragma clang fp exception(maytrap)

4. Ignore exception mode

#pragma STDC FENV_ACCESS ON
#pragma clang fp exception(ignore)

In this mode the code may change FP control modes, like rounding mode, but FP 
exceptions are ignored.
All of them must be supported.

> As far as I can tell, "STDC FENV_ACCESS" and "STDC FENV_ROUND" don't directly 
> interact.  FENV_ROUND just overrides the rounding mode for specific 
> floating-point operations; it doesn't impact whether environment access is 
> allowed.  So the call to setRoundingModeOverride seems dubious.

According to the latest standard draft 
http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2731.pdf:

  7.6.2p2
  The FENV_ROUND pragma provides a means to specify a constant rounding 
direction for floating-point
  operations for standard floating types ...
  
  7.6.2p4
  ... Within the scope of an FENV_ROUND pragma establishing a mode other than 
FE_DYNAMIC, floating-point operators, implicit conversions ..., and invocations 
of functions indicated in the table below, ...  shall be evaluated according to 
the specified constant rounding mode (as though no constant mode was specified 
and the corresponding dynamic rounding mode had been established by a call to 
fesetround).

So indeed the pragmas are independent, with the exception:

  7.6.2p3
  ... If the FE_DYNAMIC mode is specified and FENV_ACCESS is "off", the 
translator may assume that the default rounding mode is in effect.

If target allows specifying rounding mode in instruction (like RISCV), 
FENV_ROUND may be implemented without changing FP environment. However for 
targets, where change of rounding mode requires modification of a control 
register, there is no other way. The standard explicitly allows it in:

  7.6.2p5
  NOTE Constant rounding modes (other than FE_DYNAMIC) could be implemented 
using dynamic rounding modes as
  illustrated in the following example:
  {
  #pragma STDC FENV_ROUND direction
  // compiler inserts:
  // #pragma STDC FENV_ACCESS ON
  // int __savedrnd;
  // __savedrnd = __swapround(direction);
  ... operations affected by constant rounding mode ...
  // compiler inserts:
  // __savedrnd = __swapround(__savedrnd);
  ... operations not affected by constant rounding mode ...
  // compiler inserts:
  // __savedrnd = __swapround(__savedrnd);
  ... operations affected by constant rounding mode ...
  // compiler inserts:
  // __swapround(__savedrnd);
  }
  
  where __swapround is defined by:
  
  static inline int __swapround(const int new) {
  const int old = fegetround();
  fesetround(new);
  return old;
  }

As it follows from the standard, FENV_ROUND in general case changes FP 
environment (sets rounding mode). Also it affects any FP operation in the scope 
of the pragma, which is modelled as current rounding mode in clang. So the call 
to setRoundingModeOverride seems necessary.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126364

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


[PATCH] D126189: [C++20][Modules] Build module static initializers per P1874R1.

2022-05-26 Thread Iain Sandoe via Phabricator via cfe-commits
iains added a comment.

not sure why the Debian clang-format is complaining - I am using llvm-14's 
clang-format with git clang-format + arc.




Comment at: clang/include/clang/AST/ASTContext.h:476
+  /// For module code-gen cases, this is the top-level module we are building.
+  mutable Module *PrimaryModule = nullptr;
+

ChuanqiXu wrote:
> The name `PrimaryModule` looks confusing. PrimaryModule looks like primary 
> module interface unit to me. I think it refers to current module unit only. I 
> think it is better to rename to `CurrentModuleUnit`.
> 
> Then why is it mutable? I don't find it is changed in a const member function.
> The name `PrimaryModule` looks confusing. PrimaryModule looks like primary 
> module interface unit to me. I think it refers to current module unit only. I 
> think it is better to rename to `CurrentModuleUnit`.

I think we want to be clear that this is the Top Level Module (and not some 
dependent or sub-module) - so I have renamed to "TopLevelModule".

> Then why is it mutable? I don't find it is changed in a const member function.

Ah well caught; the implementation went through several iterations and I missed 
to remove this.



Comment at: clang/lib/CodeGen/CGDeclCXX.cpp:621
 
+void CodeGenModule::EmitCXXModuleInitFunc(Module *Primary) {
+  while (!CXXGlobalInits.empty() && !CXXGlobalInits.back())

ChuanqiXu wrote:
> Recommend to comment related part in your summary. It should be much helpful 
> for other to read the codes.
Hmm. I am not sure exactly what you mean here - there is a comment about the 
purpose of the method, where the method is declared.
The commit message describes what this method does in the first part.  I'm 
happy to make things more clear, but not sure where you want to see some change,



Comment at: clang/lib/CodeGen/CGDeclCXX.cpp:626-627
+  // We create the function, even if it is empty, since an importer of this
+  // module will refer to it unconditionally (there is no way for an importer
+  // to know if the function could be omitted at this time).
+

urnathan wrote:
> 'at this time' is ambiguous.  I think it means 'the current compiler 
> implementation state', but it could also mean 'at this point in the 
> compilation'.  I don't  think there's a general problem with such an 
> optimization -- we could emit a flag into the BMI.  It's just we don't have 
> the smarts to do that just yet.  right?
yeah, I meant "as currently implemented" - adding flags to the BMI attracts 
concomitant churn in the serialisation, so probably better done separately.  
Amended the comment.



Comment at: clang/lib/CodeGen/CGDeclCXX.cpp:629
+
+  // Module initialisers for imported modules are emitted first.
+  // Collect the modules that we import

urnathan wrote:
> I'm with Morse about this, even before coming to live where I do.  You've 
> used both 'ise' and 'ize'. s/ise/ize/
tools tools ... my editor wants "ise" unless I remember to set it to USian .. 
and sometimes I miss a change,, hopefully will catch them all as I go.



Comment at: clang/lib/CodeGen/CGDeclCXX.cpp:645-646
+  llvm::raw_svector_ostream Out(FnName);
+  cast(getCXXABI().getMangleContext())
+  .mangleModuleInitializer(M, Out);
+}

ChuanqiXu wrote:
> mangleModuleInitializer is virtual function and we don't need to cast it.
Actually, 'mangleModuleInitializer' is not a virtual function of the 
'MangleContext' class, only of the 'ItaniumMangleContext'.
(see D122741).

This because we do not know the mangling for MS and, in principle, there might 
never be such a mangling (e.g. that implementation might deal with P1874 in 
some different way).

I did have a version of this where I amended the mangling to make the function 
virtual in the 'MangleContext' class, but then that means generating a dummy MS 
version that, as noted above, might never exist in reality.




Comment at: clang/lib/CodeGen/CGDeclCXX.cpp:671
+ModuleInits.push_back(I->second);
+}
+PrioritizedCXXGlobalInits.clear();

ChuanqiXu wrote:
> I find the process here for `PrioritizedCXXGlobalInits` is much simpler than 
> the one done in `CodeGenModule::EmitCXXGlobalInitFunc()`. It would generate 
> more global init function. Doesn't it matter?
In the general CXX initializer the prioritized inits are grouped into functions 
named in a way that allows them to be collated by other tools (e.g. the static 
linker) so that init priority can be honoured over multiple TUs. 

This is not feasible for module initializers, there is no way to fuze them 
across TUs (it would have no meaning).  So I think all we need to do here is to 
emit the calls in the correct order (in the end there are no more initializer 
functions, we just skip the intermediated grouping functions,

Of course, init priority is not mentioned in the standard

[PATCH] D126451: [Clang][CSKY] Add support about CSKYABIInfo

2022-05-26 Thread Renato Golin via Phabricator via cfe-commits
rengolin added a comment.

This looks good to me, but wait to make sure others see it, too.

My reasons are: it is largely similar to RISCV implementation, it seems to 
follow what I expected of the ABI (which is similar to other targets) and has a 
large corpus of tests.

I can't comment on the specifics of the ABI implementation (I haven't read the 
ABI document *that* thoroughly), but as David said, issues will be picked up by 
tests until the target reaches maturity.


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

https://reviews.llvm.org/D126451

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


[PATCH] D125604: [FileCheck] Catch missspelled directives.

2022-05-26 Thread Ivan Kosarev via Phabricator via cfe-commits
kosarev added a comment.

Committing this revealed some more failures, fixed in 
rG8894c05b0d351f998b1836542ba791247394bd12 
.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125604

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


[clang] 85750de - Use the canonical type when matching a generic selection association

2022-05-26 Thread Aaron Ballman via cfe-commits

Author: Aaron Ballman
Date: 2022-05-26T07:42:13-04:00
New Revision: 85750de685f543443ec38c407392d9d7cdc19451

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

LOG: Use the canonical type when matching a generic selection association

This ensures that a deduced type like __auto_type matches the correct
association instead of matching all associations.

This addresses a regression from e4a42c5b64d044ae28d9483b0ebd12038d5b5917

Fixes #55702

Added: 


Modified: 
clang/lib/Sema/SemaExpr.cpp
clang/test/Sema/auto-type.c

Removed: 




diff  --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index 9d9cb99085f33..3e8bd63e89ae9 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -1753,10 +1753,14 @@ Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
 
   SmallVector CompatIndices;
   unsigned DefaultIndex = -1U;
+  // Look at the canonical type of the controlling expression in case it was a
+  // deduced type like __auto_type. However, when issuing diagnostics, use the
+  // type the user wrote in source rather than the canonical one.
   for (unsigned i = 0; i < NumAssocs; ++i) {
 if (!Types[i])
   DefaultIndex = i;
-else if (Context.typesAreCompatible(ControllingExpr->getType(),
+else if (Context.typesAreCompatible(
+ ControllingExpr->getType().getCanonicalType(),
 Types[i]->getType()))
   CompatIndices.push_back(i);
   }

diff  --git a/clang/test/Sema/auto-type.c b/clang/test/Sema/auto-type.c
index 4e85eecc6b057..1170c687c96aa 100644
--- a/clang/test/Sema/auto-type.c
+++ b/clang/test/Sema/auto-type.c
@@ -78,3 +78,13 @@ void Issue53652(void) {
  __typeof__(i) : 0,   // expected-note {{compatible type 
'typeof (i)' (aka 'int') specified here}}
  __typeof__(a) : 1);  // expected-error {{type 'typeof (a)' 
(aka 'int') in generic association compatible with previously specified type 
'typeof (i)' (aka 'int')}}
 }
+
+void Issue55702(void) {
+  // A controlling expression which uses __auto_type should not be
+  // automatically compatible with every association; we should be using the
+  // canonical type for that comparison.
+  void *ptr = 0;
+  __auto_type v = ptr;
+  (void)_Generic(v, long double : 0, double : 0, default : 1); // OK
+  _Static_assert(_Generic(v, long double : 0, default : 1) == 1, "fail");
+}



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


[clang] ca3d962 - [analyzer] Return from reAssume if State is posteriorly overconstrained

2022-05-26 Thread Gabor Marton via cfe-commits

Author: Gabor Marton
Date: 2022-05-26T13:50:40+02:00
New Revision: ca3d962548b9699d69157d102e071607d27ba126

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

LOG: [analyzer] Return from reAssume if State is posteriorly overconstrained

Depends on D124758. That patch introduced serious regression in the run-time in
some special cases. This fixes that.

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

Added: 
clang/test/Analysis/runtime-regression.c

Modified: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp

Removed: 




diff  --git 
a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
index cb6540ff7e7c4..f36ba70babc71 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
@@ -55,6 +55,8 @@ template  struct ProgramStateTrait {
   }
 };
 
+class RangeSet;
+
 /// \class ProgramState
 /// ProgramState - This class encapsulates:
 ///
@@ -79,7 +81,6 @@ class ProgramState : public llvm::FoldingSetNode {
   friend class ExplodedGraph;
   friend class ExplodedNode;
   friend class NodeBuilder;
-  friend class ConstraintManager;
 
   ProgramStateManager *stateMgr;
   Environment Env;   // Maps a Stmt to its current SVal.
@@ -113,6 +114,16 @@ class ProgramState : public llvm::FoldingSetNode {
   // posteriorly over-constrained. These parents are handled with special care:
   // we do not allow transitions to exploded nodes with such states.
   bool PosteriorlyOverconstrained = false;
+  // Make internal constraint solver entities friends so they can access the
+  // overconstrained-related functions. We want to keep this API inaccessible
+  // for Checkers.
+  friend class ConstraintManager;
+  friend ProgramStateRef reAssume(ProgramStateRef State,
+  const RangeSet *Constraint, SVal TheValue);
+  bool isPosteriorlyOverconstrained() const {
+return PosteriorlyOverconstrained;
+  }
+  ProgramStateRef cloneAsPosteriorlyOverconstrained() const;
 
   unsigned refCount;
 
@@ -122,11 +133,6 @@ class ProgramState : public llvm::FoldingSetNode {
 
   void setStore(const StoreRef &storeRef);
 
-  ProgramStateRef cloneAsPosteriorlyOverconstrained() const;
-  bool isPosteriorlyOverconstrained() const {
-return PosteriorlyOverconstrained;
-  }
-
 public:
   /// This ctor is used when creating the first ProgramState object.
   ProgramState(ProgramStateManager *mgr, const Environment& env,

diff  --git a/clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp 
b/clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
index e0ceac51d14f3..3d8d8aeafaec6 100644
--- a/clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
+++ b/clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
@@ -2530,10 +2530,19 @@ EquivalenceClass::removeMember(ProgramStateRef State, 
const SymbolRef Old) {
   return State;
 }
 
+// We must declare reAssume in clang::ento, otherwise we could not declare that
+// as a friend in ProgramState. More precisely, the call of reAssume would be
+// ambiguous (one in the global namespace and an other which is declared in
+// ProgramState is in clang::ento).
+namespace clang {
+namespace ento {
 // Re-evaluate an SVal with top-level `State->assume` logic.
 LLVM_NODISCARD ProgramStateRef reAssume(ProgramStateRef State,
 const RangeSet *Constraint,
 SVal TheValue) {
+  assert(State);
+  if (State->isPosteriorlyOverconstrained())
+return nullptr;
   if (!Constraint)
 return State;
 
@@ -2556,6 +2565,8 @@ LLVM_NODISCARD ProgramStateRef reAssume(ProgramStateRef 
State,
   return State->assumeInclusiveRange(DefinedVal, Constraint->getMinValue(),
  Constraint->getMaxValue(), true);
 }
+} // namespace ento
+} // namespace clang
 
 // Iterate over all symbols and try to simplify them. Once a symbol is
 // simplified then we check if we can merge the simplified symbol's equivalence

diff  --git a/clang/test/Analysis/runtime-regression.c 
b/clang/test/Analysis/runtime-regression.c
new file mode 100644
index 0..55988e9df5ee0
--- /dev/null
+++ b/clang/test/Analysis/runtime-regression.c
@@ -0,0 +1,55 @@
+// RUN: %clang_analyze_cc1 %s \
+// RUN:   -analyzer-checker=core,alpha.security.ArrayBoundV2 \
+// RUN:   -analyzer-checker=debug.ExprInspection \
+// RUN:   -triple x86_64-unknown-linux-gnu \
+// RUN:   -verify
+
+// This test is here to check if there is no significant run-time regression
+// related to the assume machinery. The analysis 

[PATCH] D126406: [analyzer] Return from reAssume if State is posteriorly overconstrained

2022-05-26 Thread Gabor Marton via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
martong marked an inline comment as done.
Closed by commit rGca3d962548b9: [analyzer] Return from reAssume if State is 
posteriorly overconstrained (authored by martong).

Changed prior to commit:
  https://reviews.llvm.org/D126406?vs=432225&id=432245#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126406

Files:
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
  clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
  clang/test/Analysis/runtime-regression.c

Index: clang/test/Analysis/runtime-regression.c
===
--- /dev/null
+++ clang/test/Analysis/runtime-regression.c
@@ -0,0 +1,55 @@
+// RUN: %clang_analyze_cc1 %s \
+// RUN:   -analyzer-checker=core,alpha.security.ArrayBoundV2 \
+// RUN:   -analyzer-checker=debug.ExprInspection \
+// RUN:   -triple x86_64-unknown-linux-gnu \
+// RUN:   -verify
+
+// This test is here to check if there is no significant run-time regression
+// related to the assume machinery. The analysis should finish in less than 10
+// seconds.
+
+// expected-no-diagnostics
+
+typedef unsigned char uint8_t;
+typedef unsigned short uint16_t;
+typedef unsigned long uint64_t;
+
+int filter_slice_word(int sat_linesize, int sigma, int radius, uint64_t *sat,
+  uint64_t *square_sat, int width, int height,
+  int src_linesize, int dst_linesize, const uint16_t *src,
+  uint16_t *dst, int jobnr, int nb_jobs) {
+  const int starty = height * jobnr / nb_jobs;
+  const int endy = height * (jobnr + 1) / nb_jobs;
+
+  for (int y = starty; y < endy; y++) {
+
+int lower_y = y - radius < 0 ? 0 : y - radius;
+int higher_y = y + radius + 1 > height ? height : y + radius + 1;
+int dist_y = higher_y - lower_y;
+
+for (int x = 0; x < width; x++) {
+
+  int lower_x = x - radius < 0 ? 0 : x - radius;
+  int higher_x = x + radius + 1 > width ? width : x + radius + 1;
+  int count = dist_y * (higher_x - lower_x);
+
+  // The below hunk caused significant regression in run-time.
+#if 1
+  uint64_t sum = sat[higher_y * sat_linesize + higher_x] -
+ sat[higher_y * sat_linesize + lower_x] -
+ sat[lower_y * sat_linesize + higher_x] +
+ sat[lower_y * sat_linesize + lower_x];
+  uint64_t square_sum = square_sat[higher_y * sat_linesize + higher_x] -
+square_sat[higher_y * sat_linesize + lower_x] -
+square_sat[lower_y * sat_linesize + higher_x] +
+square_sat[lower_y * sat_linesize + lower_x];
+  uint64_t mean = sum / count;
+  uint64_t var = (square_sum - sum * sum / count) / count;
+  dst[y * dst_linesize + x] =
+  (sigma * mean + var * src[y * src_linesize + x]) / (sigma + var);
+#endif
+
+}
+  }
+  return 0;
+}
Index: clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
===
--- clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
+++ clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
@@ -2530,10 +2530,19 @@
   return State;
 }
 
+// We must declare reAssume in clang::ento, otherwise we could not declare that
+// as a friend in ProgramState. More precisely, the call of reAssume would be
+// ambiguous (one in the global namespace and an other which is declared in
+// ProgramState is in clang::ento).
+namespace clang {
+namespace ento {
 // Re-evaluate an SVal with top-level `State->assume` logic.
 LLVM_NODISCARD ProgramStateRef reAssume(ProgramStateRef State,
 const RangeSet *Constraint,
 SVal TheValue) {
+  assert(State);
+  if (State->isPosteriorlyOverconstrained())
+return nullptr;
   if (!Constraint)
 return State;
 
@@ -2556,6 +2565,8 @@
   return State->assumeInclusiveRange(DefinedVal, Constraint->getMinValue(),
  Constraint->getMaxValue(), true);
 }
+} // namespace ento
+} // namespace clang
 
 // Iterate over all symbols and try to simplify them. Once a symbol is
 // simplified then we check if we can merge the simplified symbol's equivalence
Index: clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
===
--- clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
+++ clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
@@ -55,6 +55,8 @@
   }
 };
 
+class RangeSet;
+
 /// \class ProgramState
 /// ProgramState - This class encapsulates:
 ///
@@ -79,7 +81,6 @@
   friend class ExplodedGraph;
   friend class ExplodedNode;
   friend class NodeBuild

[PATCH] D126406: [analyzer] Return from reAssume if State is posteriorly overconstrained

2022-05-26 Thread Gabor Marton via Phabricator via cfe-commits
martong added inline comments.



Comment at: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h:118
+  // Make internal constraint solver entities friends so they can access the
+  // overconstrained related functions. We want to keep this API inaccessible
+  // for Checkers.

steakhal wrote:
> 
Fixed, thx.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126406

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


[PATCH] D126137: [X86] Add support for `-mharden-sls=all`

2022-05-26 Thread Phoebe Wang via Phabricator via cfe-commits
pengfei updated this revision to Diff 432247.
pengfei marked 6 inline comments as done.
pengfei added a comment.

Address @nickdesaulniers 's comments. Thanks for the review!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126137

Files:
  clang/docs/ClangCommandLineReference.rst
  clang/docs/ReleaseNotes.rst
  clang/lib/Driver/ToolChains/Arch/X86.cpp
  clang/test/Driver/x86-target-features.c
  llvm/lib/Target/X86/X86.td
  llvm/lib/Target/X86/X86AsmPrinter.cpp
  llvm/lib/Target/X86/X86AsmPrinter.h
  llvm/test/CodeGen/X86/speculation-hardening-sls.ll

Index: llvm/test/CodeGen/X86/speculation-hardening-sls.ll
===
--- /dev/null
+++ llvm/test/CodeGen/X86/speculation-hardening-sls.ll
@@ -0,0 +1,97 @@
+; RUN: llc -mattr=harden-sls-ret -verify-machineinstrs -mtriple=x86_64-unknown-unknown < %s | FileCheck %s -check-prefixes=CHECK,RET
+; RUN: llc -mattr=harden-sls-ind -verify-machineinstrs -mtriple=x86_64-unknown-unknown < %s | FileCheck %s -check-prefixes=CHECK,IND
+
+define dso_local i32 @double_return(i32 %a, i32 %b) local_unnamed_addr {
+; CHECK-LABEL: double_return:
+; CHECK: jle
+; CHECK-NOT: int3
+; CHECK: retq
+; RET-NEXT:  int3
+; IND-NOT:   int3
+; CHECK: retq
+; RET-NEXT:  int3
+; IND-NOT:   int3
+entry:
+  %cmp = icmp sgt i32 %a, 0
+  br i1 %cmp, label %if.then, label %if.else
+
+if.then:  ; preds = %entry
+  %div = sdiv i32 %a, %b
+  ret i32 %div
+
+if.else:  ; preds = %entry
+  %div1 = sdiv i32 %b, %a
+  ret i32 %div1
+}
+
+@__const.indirect_branch.ptr = private unnamed_addr constant [2 x i8*] [i8* blockaddress(@indirect_branch, %return), i8* blockaddress(@indirect_branch, %l2)], align 8
+
+; Function Attrs: norecurse nounwind readnone
+define dso_local i32 @indirect_branch(i32 %a, i32 %b, i32 %i) {
+; CHECK-LABEL: indirect_branch:
+; CHECK: jmpq *
+; RET-NOT:   int3
+; IND-NEXT:  int3
+; CHECK: retq
+; RET-NEXT:  int3
+; IND-NOT:   int3
+; CHECK: retq
+; RET-NEXT:  int3
+; IND-NOT:   int3
+entry:
+  %idxprom = sext i32 %i to i64
+  %arrayidx = getelementptr inbounds [2 x i8*], [2 x i8*]* @__const.indirect_branch.ptr, i64 0, i64 %idxprom
+  %0 = load i8*, i8** %arrayidx, align 8
+  indirectbr i8* %0, [label %return, label %l2]
+
+l2:   ; preds = %entry
+  br label %return
+
+return:   ; preds = %entry, %l2
+  %retval.0 = phi i32 [ 1, %l2 ], [ 0, %entry ]
+  ret i32 %retval.0
+}
+
+define i32 @asmgoto() {
+; CHECK-LABEL: asmgoto:
+; CHECK:   # %bb.0: # %entry
+; CHECK: jmp .L
+; CHECK-NOT: int3
+; CHECK: retq
+; RET-NEXT:  int3
+; IND-NOT:   int3
+; CHECK: retq
+; RET-NEXT:  int3
+; IND-NOT:   int3
+entry:
+  callbr void asm sideeffect "jmp $0", "X"(i8* blockaddress(@asmgoto, %d))
+to label %asm.fallthrough [label %d]
+ ; The asm goto above produces a direct branch:
+
+asm.fallthrough:   ; preds = %entry
+  ret i32 0
+
+d: ; preds = %asm.fallthrough, %entry
+  ret i32 1
+}
+
+define void @bar(void ()* %0) {
+; CHECK-LABEL: bar:
+; CHECK: jmpq *
+; RET-NOT:   int3
+; IND-NEXT:  int3
+; CHECK-NOT: ret
+  tail call void %0()
+  ret void
+}
+
+declare dso_local void @foo()
+
+define dso_local void @bar2() {
+; CHECK-LABEL: bar2:
+; CHECK: jmp foo
+; CHECK-NOT: int3
+; CHECK-NOT: ret
+  tail call void @foo()
+  ret void
+}
Index: llvm/lib/Target/X86/X86AsmPrinter.h
===
--- llvm/lib/Target/X86/X86AsmPrinter.h
+++ llvm/lib/Target/X86/X86AsmPrinter.h
@@ -131,10 +131,7 @@
 
   void emitInstruction(const MachineInstr *MI) override;
 
-  void emitBasicBlockEnd(const MachineBasicBlock &MBB) override {
-AsmPrinter::emitBasicBlockEnd(MBB);
-SMShadowTracker.emitShadowPadding(*OutStreamer, getSubtargetInfo());
-  }
+  void emitBasicBlockEnd(const MachineBasicBlock &MBB) override;
 
   bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
const char *ExtraCode, raw_ostream &O) override;
Index: llvm/lib/Target/X86/X86AsmPrinter.cpp
===
--- llvm/lib/Target/X86/X86AsmPrinter.cpp
+++ llvm/lib/Target/X86/X86AsmPrinter.cpp
@@ -336,6 +336,37 @@
   }
 }
 
+static bool isSimpleReturn(const MachineInstr &MI) {
+  // We exclude all tail calls here which set both isReturn and isCall.
+  return MI.getDesc().isReturn() && !MI.getDesc().isCall();
+}
+
+static bool isIndirectBranchOrTailCall(const MachineInstr &MI) {
+  unsigned Opc = MI.getOpcode();
+  return MI.getDesc().isIndirectBranch() /*Make below code in a good shape*/ ||
+

[PATCH] D126137: [X86] Add support for `-mharden-sls=all`

2022-05-26 Thread Phoebe Wang via Phabricator via cfe-commits
pengfei added inline comments.



Comment at: llvm/lib/Target/X86/X86AsmPrinter.cpp:346
+  auto IsIndirectTailCall = [I, &Desc]() {
+return Desc.isCall() && Desc.isReturn() && Desc.isBarrier() &&
+   !I->getOperand(0).isGlobal();

nickdesaulniers wrote:
> Why `isBarrier`? Maybe add a comment that mentions a specific TableGen record 
> from llvm/lib/Target/X86/X86InstrControl.td?  That would help me verify that 
> `isBarrier()` is correct here.
> 
> I'm guessing this is:
> 
> 363 let isCall = 1, isTerminator = 1, isReturn = 1, isBarrier = 1,
>   
> 364 isCodeGenOnly = 1, Uses = [RSP, SSP] in {
> 
> block in llvm/lib/Target/X86/X86InstrControl.td.
> 
> Otherwise llvm/lib/Target/X86/X86FrameLowering.cpp has a static function that 
> I think is precisely what we want here, called ` isTailCallOpcode`. Perhaps 
> move that to a header shared between the two translation units then reuse it 
> here?  A few other backends have an `IsTailCall` method though they're 
> inconsistent where they define it. It still would be good though to try to 
> match existing conventions which makes jumping between backends easier.
> Why `isBarrier`?

Because we have conditional tail calls, see defination of `TCRETURNdicc`.

> Perhaps move that to a header shared between the two translation units then 
> reuse it here?

We can't. They are not overlapped.

> A few other backends have an `IsTailCall` method though they're inconsistent 
> where they define it

`IsTailCall` is an attribute of call instruction in IR. We lost it in MIR phase.



Comment at: llvm/lib/Target/X86/X86AsmPrinter.cpp:347
+return Desc.isCall() && Desc.isReturn() && Desc.isBarrier() &&
+   !I->getOperand(0).isGlobal();
+  };

nickdesaulniers wrote:
> Rather than `!...isGlobal()`, would it be more precise to use 
> `getOperand(0).isReg()`?  Looking at all of the values of `enum 
> MachineOperandType`, I think it would be more precise if we check the operand 
> is of one type, rather than "not one type."
OK, check opcode instead.



Comment at: llvm/test/CodeGen/X86/speculation-hardening-sls.ll:7
+; CHECK: jle
+; CEHCK-NOT: int3
+; CHECK: retq

nickdesaulniers wrote:
> typo
Good catch!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126137

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


[PATCH] D126420: [clang][dataflow] Remove private-field filtering from `StorageLocation` creation.

2022-05-26 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel updated this revision to Diff 432249.
ymandel added a comment.

address review comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126420

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

Index: clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
@@ -1153,8 +1153,8 @@
 // two.
 
 // Base-class fields.
-EXPECT_THAT(FooVal.getChild(*ADefaultDecl), IsNull());
-EXPECT_THAT(FooVal.getChild(*APrivateDecl), IsNull());
+EXPECT_THAT(FooVal.getChild(*ADefaultDecl), NotNull());
+EXPECT_THAT(FooVal.getChild(*APrivateDecl), NotNull());
 
 EXPECT_THAT(FooVal.getChild(*AProtectedDecl), NotNull());
 EXPECT_EQ(Env.getValue(FooLoc.getChild(*APublicDecl)),
@@ -1176,6 +1176,40 @@
   });
 }
 
+static void derivedBaseMemberExpectations(
+llvm::ArrayRef>>
+Results,
+ASTContext &ASTCtx) {
+  ASSERT_THAT(Results, ElementsAre(Pair("p", _)));
+  const Environment &Env = Results[0].second.Env;
+
+  const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo");
+  ASSERT_THAT(FooDecl, NotNull());
+
+  ASSERT_TRUE(FooDecl->getType()->isRecordType());
+  const FieldDecl *BarDecl = nullptr;
+  for (const clang::CXXBaseSpecifier &Base :
+   FooDecl->getType()->getAsCXXRecordDecl()->bases()) {
+QualType BaseType = Base.getType();
+ASSERT_TRUE(BaseType->isStructureType());
+
+for (const FieldDecl *Field : BaseType->getAsRecordDecl()->fields()) {
+  if (Field->getNameAsString() == "Bar") {
+BarDecl = Field;
+  } else {
+FAIL() << "Unexpected field: " << Field->getNameAsString();
+  }
+}
+  }
+  ASSERT_THAT(BarDecl, NotNull());
+
+  const auto &FooLoc = *cast(
+  Env.getStorageLocation(*FooDecl, SkipPast::None));
+  const auto &FooVal = *cast(Env.getValue(FooLoc));
+  EXPECT_THAT(FooVal.getChild(*BarDecl), NotNull());
+  EXPECT_EQ(Env.getValue(FooLoc.getChild(*BarDecl)), FooVal.getChild(*BarDecl));
+}
+
 TEST_F(TransferTest, DerivedBaseMemberStructDefault) {
   std::string Code = R"(
 struct A {
@@ -1189,41 +1223,28 @@
   // [[p]]
 }
   )";
-  runDataflow(
-  Code, [](llvm::ArrayRef<
-   std::pair>>
-   Results,
-   ASTContext &ASTCtx) {
-ASSERT_THAT(Results, ElementsAre(Pair("p", _)));
-const Environment &Env = Results[0].second.Env;
-
-const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo");
-ASSERT_THAT(FooDecl, NotNull());
-
-ASSERT_TRUE(FooDecl->getType()->isRecordType());
-const FieldDecl *BarDecl = nullptr;
-for (const clang::CXXBaseSpecifier &Base :
- FooDecl->getType()->getAsCXXRecordDecl()->bases()) {
-  QualType BaseType = Base.getType();
-  ASSERT_TRUE(BaseType->isStructureType());
+  runDataflow(Code, derivedBaseMemberExpectations);
+}
 
-  for (const FieldDecl *Field : BaseType->getAsRecordDecl()->fields()) {
-if (Field->getNameAsString() == "Bar") {
-  BarDecl = Field;
-} else {
-  FAIL() << "Unexpected field: " << Field->getNameAsString();
-}
-  }
-}
-ASSERT_THAT(BarDecl, NotNull());
+TEST_F(TransferTest, DerivedBaseMemberPrivateFriend) {
+  // Include an access to `Foo.Bar` to verify the analysis doesn't crash on that
+  // access.
+  std::string Code = R"(
+struct A {
+private:
+  friend void target();
+  int Bar;
+};
+struct B : public A {
+};
 
-const auto &FooLoc = *cast(
-Env.getStorageLocation(*FooDecl, SkipPast::None));
-const auto &FooVal = *cast(Env.getValue(FooLoc));
-EXPECT_THAT(FooVal.getChild(*BarDecl), NotNull());
-EXPECT_EQ(Env.getValue(FooLoc.getChild(*BarDecl)),
-  FooVal.getChild(*BarDecl));
-  });
+void target() {
+  B Foo;
+  (void)Foo.Bar;
+  // [[p]]
+}
+  )";
+  runDataflow(Code, derivedBaseMemberExpectations);
 }
 
 TEST_F(TransferTest, ClassMember) {
Index: clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
===
--- clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
+++ clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
@@ -148,39 +148,26 @@
   }
 }
 
+// FIXME: Does not precisely handle non-virtual diamond inheritance. A single
+// field decl will be modeled for all instances of the inherited field.
 static void
-getFieldsFromClassHierarchy(QualType Type, bool IgnorePrivateFields,
+getFieldsFromClassHierarchy(QualType Type,
 llvm::DenseSet &Fields) {
   if (Type->i

[PATCH] D126420: [clang][dataflow] Remove private-field filtering from `StorageLocation` creation.

2022-05-26 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel marked 3 inline comments as done.
ymandel added inline comments.



Comment at: clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp:407
 
 for (const FieldDecl *Field : getAccessibleObjectFields(Type)) {
   assert(Field != nullptr);

sgatev wrote:
> Why not use `getObjectFields` here too?
We could. I figured it was still worth the optimization on the values. Usually, 
its correct and otherwise we lose some precision. But, now that you asked, I'm 
inclined to get rid of it altogether -- seems like we should have evidence of 
the benefit in practice before adopt an approach that we know costs us 
precision (in potentially surprising ways).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126420

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


[PATCH] D126084: [Sema] Reject implicit conversions between different scoped enum types in list initialization

2022-05-26 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/lib/Sema/SemaInit.cpp:4506
 !S.Context.hasSameUnqualifiedType(E->getType(), DestType) &&
-(E->getType()->isIntegralOrEnumerationType() ||
+(E->getType()->isIntegralOrUnscopedEnumerationType() ||
  E->getType()->isFloatingType())) {

ahatanak wrote:
> aaron.ballman wrote:
> > This doesn't match the comments immediately above here and I don't think is 
> > the correct fix.
> > 
> > We're handling this case: http://eel.is/c++draft/dcl.init.list#3.8
> > 
> > A scoped enumeration has a fixed underlying type 
> > (https://eel.is/c++draft/dcl.enum#5.sentence-5). The initializer list has a 
> > single element and that element can be implicitly converted to the 
> > underlying type (`int` in all of the test cases changed in this patch). And 
> > this is a direct initialization case, so I think we should be performing 
> > the conversion here rather than skipping to the next bullet.
> Can scoped enums be implicitly converted to integer types? Unscoped enums can 
> be converted to an integer type, but I don't see any mention of scoped enums 
> here: https://eel.is/c++draft/conv.integral
> 
> It seems that the original paper was trying to change the rules about 
> conversions from the underlying type to a scoped enum. It doesn't look like 
> it's allowing conversion from a scope enum to another scope enum.
> 
> https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0138r2.pdf
> Can scoped enums be implicitly converted to integer types? Unscoped enums can 
> be converted to an integer type, but I don't see any mention of scoped enums 
> here: https://eel.is/c++draft/conv.integral

Correct, they cannot be implicitly converted to an integer.

> It seems that the original paper was trying to change the rules about 
> conversions from the underlying type to a scoped enum. It doesn't look like 
> it's allowing conversion from a scope enum to another scope enum.

Agreed, however, I think where we want this to fail is below in the attempt at 
conversion. "v can be implicitly converted to U" is the part that should be 
failing here, and we're now skipping over the bit of code that's checking 
whether the implicit conversion is valid.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126084

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


[clang] b5b2aec - [analyzer] Add UnarySymExpr

2022-05-26 Thread Gabor Marton via cfe-commits

Author: Gabor Marton
Date: 2022-05-26T14:00:27+02:00
New Revision: b5b2aec1ff51197343dede9741ea377f8314d41b

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

LOG: [analyzer] Add UnarySymExpr

This patch adds a new descendant to the SymExpr hierarchy. This way, now
we can assign constraints to symbolic unary expressions. Only the unary
minus and bitwise negation are handled.

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

Added: 
clang/test/Analysis/unary-sym-expr.c

Modified: 
clang/include/clang/StaticAnalyzer/Checkers/SValExplainer.h
clang/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h
clang/include/clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h
clang/include/clang/StaticAnalyzer/Core/PathSensitive/Symbols.def
clang/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp
clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
clang/lib/StaticAnalyzer/Core/SymbolManager.cpp
clang/test/Analysis/explain-svals.cpp
clang/test/Analysis/expr-inspection.cpp

Removed: 




diff  --git a/clang/include/clang/StaticAnalyzer/Checkers/SValExplainer.h 
b/clang/include/clang/StaticAnalyzer/Checkers/SValExplainer.h
index ad64cfc742dca..4c9c8239113e3 100644
--- a/clang/include/clang/StaticAnalyzer/Checkers/SValExplainer.h
+++ b/clang/include/clang/StaticAnalyzer/Checkers/SValExplainer.h
@@ -135,6 +135,11 @@ class SValExplainer : public 
FullSValVisitor {
" (" + Visit(S->getRHS()) + ")";
   }
 
+  std::string VisitUnarySymExpr(const UnarySymExpr *S) {
+return std::string(UnaryOperator::getOpcodeStr(S->getOpcode())) + " (" +
+   Visit(S->getOperand()) + ")";
+  }
+
   // TODO: SymbolCast doesn't appear in practice.
   // Add the relevant code once it does.
 

diff  --git 
a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h
index d0bbf1750d7e5..2154a1dedeeeb 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h
@@ -153,6 +153,9 @@ class SValBuilder {
   SVal makeSymExprValNN(BinaryOperator::Opcode op,
 NonLoc lhs, NonLoc rhs, QualType resultTy);
 
+  SVal evalUnaryOp(ProgramStateRef state, UnaryOperator::Opcode opc,
+ SVal operand, QualType type);
+
   SVal evalBinOp(ProgramStateRef state, BinaryOperator::Opcode op,
  SVal lhs, SVal rhs, QualType type);
 
@@ -350,6 +353,9 @@ class SValBuilder {
   nonloc::SymbolVal makeNonLoc(const SymExpr *lhs, BinaryOperator::Opcode op,
const SymExpr *rhs, QualType type);
 
+  NonLoc makeNonLoc(const SymExpr *operand, UnaryOperator::Opcode op,
+QualType type);
+
   /// Create a NonLoc value for cast.
   nonloc::SymbolVal makeNonLoc(const SymExpr *operand, QualType fromTy,
QualType toTy);

diff  --git 
a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h
index c71cb88f5574c..3ba3aa5c01566 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h
@@ -309,6 +309,55 @@ class SymbolCast : public SymExpr {
   }
 };
 
+/// Represents a symbolic expression involving a unary operator.
+class UnarySymExpr : public SymExpr {
+  const SymExpr *Operand;
+  UnaryOperator::Opcode Op;
+  QualType T;
+
+public:
+  UnarySymExpr(const SymExpr *In, UnaryOperator::Opcode Op, QualType T)
+  : SymExpr(UnarySymExprKind), Operand(In), Op(Op), T(T) {
+// Note, some unary operators are modeled as a binary operator. E.g. ++x is
+// modeled as x + 1.
+assert((Op == UO_Minus || Op == UO_Not) && "non-supported unary 
expression");
+// Unary expressions are results of arithmetic. Pointer arithmetic is not
+// handled by unary expressions, but it is instead handled by applying
+// sub-regions to regions.
+assert(isValidTypeForSymbol(T) && "non-valid type for unary symbol");
+assert(!Loc::isLocType(T) && "unary symbol should be nonloc");
+  }
+
+  unsigned computeComplexity() const override {
+if (Complexity == 0)
+  Complexity = 1 + Operand->computeComplexity();
+return Complexity;
+  }
+
+  const SymExpr *getOperand() const { return Operand; }
+  UnaryOperator::Opcode getOpcode() const { return Op; }
+  QualType getType() const override { return T; }
+
+  void dumpToStream(raw_ostream &os) const override;
+
+  static void Profile(llvm::FoldingSetNodeID &ID, const SymExpr *In,
+  Un

[clang] 88abc50 - [analyzer][solver] Handle UnarySymExpr in RangeConstraintSolver

2022-05-26 Thread Gabor Marton via cfe-commits

Author: Gabor Marton
Date: 2022-05-26T14:09:46+02:00
New Revision: 88abc50398eb26d536518270b91939ce18687305

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

LOG: [analyzer][solver] Handle UnarySymExpr in RangeConstraintSolver

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

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

Added: 
clang/test/Analysis/constraint_manager_negate.c
clang/test/Analysis/unary-sym-expr-no-crash.c

Modified: 
clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
clang/test/Analysis/constraint_manager_negate_difference.c
clang/test/Analysis/unary-sym-expr.c

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp 
b/clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
index 3d8d8aeafaec..bf535a8d0205 100644
--- a/clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
+++ b/clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
@@ -1443,30 +1443,35 @@ class SymbolicRangeInferrer
 return RangeFactory.deletePoint(Domain, IntType.getZeroValue());
   }
 
-  // FIXME: Once SValBuilder supports unary minus, we should use SValBuilder to
-  //obtain the negated symbolic expression instead of constructing the
-  //symbol manually. This will allow us to support finding ranges of 
not
-  //only negated SymSymExpr-type expressions, but also of other, 
simpler
-  //expressions which we currently do not know how to negate.
   Optional getRangeForNegatedSub(SymbolRef Sym) {
-if (const SymSymExpr *SSE = dyn_cast(Sym)) {
+// Do not negate if the type cannot be meaningfully negated.
+if (!Sym->getType()->isUnsignedIntegerOrEnumerationType() &&
+!Sym->getType()->isSignedIntegerOrEnumerationType())
+  return llvm::None;
+
+const RangeSet *NegatedRange = nullptr;
+SymbolManager &SymMgr = State->getSymbolManager();
+if (const auto *USE = dyn_cast(Sym)) {
+  if (USE->getOpcode() == UO_Minus) {
+// Just get the operand when we negate a symbol that is already 
negated.
+// -(-a) == a
+NegatedRange = getConstraint(State, USE->getOperand());
+  }
+} else if (const SymSymExpr *SSE = dyn_cast(Sym)) {
   if (SSE->getOpcode() == BO_Sub) {
 QualType T = Sym->getType();
-
-// Do not negate unsigned ranges
-if (!T->isUnsignedIntegerOrEnumerationType() &&
-!T->isSignedIntegerOrEnumerationType())
-  return llvm::None;
-
-SymbolManager &SymMgr = State->getSymbolManager();
 SymbolRef NegatedSym =
 SymMgr.getSymSymExpr(SSE->getRHS(), BO_Sub, SSE->getLHS(), T);
-
-if (const RangeSet *NegatedRange = getConstraint(State, NegatedSym)) {
-  return RangeFactory.negate(*NegatedRange);
-}
+NegatedRange = getConstraint(State, NegatedSym);
   }
+} else {
+  SymbolRef NegatedSym =
+  SymMgr.getUnarySymExpr(Sym, UO_Minus, Sym->getType());
+  NegatedRange = getConstraint(State, NegatedSym);
 }
+
+if (NegatedRange)
+  return RangeFactory.negate(*NegatedRange);
 return llvm::None;
   }
 

diff  --git a/clang/test/Analysis/constraint_manager_negate.c 
b/clang/test/Analysis/constraint_manager_negate.c
new file mode 100644
index ..d955973e1911
--- /dev/null
+++ b/clang/test/Analysis/constraint_manager_negate.c
@@ -0,0 +1,113 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=debug.ExprInspection,core.builtin 
\
+// RUN:   -analyzer-config eagerly-assume=false \
+// RUN:   -verify %s
+
+void clang_analyzer_eval(int);
+void clang_analyzer_dump(int);
+
+void exit(int);
+
+#define UINT_MIN (0U)
+#define UINT_MAX (~UINT_MIN)
+#define UINT_MID (UINT_MAX / 2 + 1)
+#define INT_MAX (UINT_MAX & (UINT_MAX >> 1))
+#define INT_MIN (UINT_MAX & ~(UINT_MAX >> 1))
+
+extern void abort() __attribute__((__noreturn__));
+#define assert(expr) ((expr) ? (void)(0) : abort())
+
+void negate_positive_range(int a) {
+  assert(-a > 0);
+  // -a: [1, INT_MAX]
+  // a: [INT_MIN + 1, -1]
+  clang_analyzer_eval(a < 0); // expected-warning{{TRUE}}
+  clang_analyzer_eval(a > INT_MIN); // expected-warning{{TRUE}}
+}
+
+void negate_positive_range2(int a) {
+  assert(a > 0);
+  // a: [1, INT_MAX]
+  // -a: [INT_MIN + 1, -1]
+  clang_analyzer_eval(-a < 0); // expected-warning{{TRUE}}
+  clang_analyzer_eval(-a > INT_MIN); // expected-warning{{TRUE}}
+}
+
+// INT_MIN equals 0b100...00.
+// Its two's compelement is 0b011...11 + 1 = 0b100...00 (itself).
+_Static_assert(INT_MIN == -INT_MIN, "");
+void negate_int_min(int a) {
+  assert(a == INT_MIN);
+  clang_analyzer_eval(-a == INT_MIN); // expected-warning{{TRUE}}
+}
+
+void negate_mixed(int a) {
+  assert(a > 0 || a == INT_MIN);
+  clang_analyzer_eval(-a <= 0); // expect

[PATCH] D125318: [analyzer] Add UnarySymExpr

2022-05-26 Thread Gabor Marton via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
martong marked 2 inline comments as done.
Closed by commit rGb5b2aec1ff51: [analyzer] Add UnarySymExpr (authored by 
martong).

Changed prior to commit:
  https://reviews.llvm.org/D125318?vs=429207&id=432250#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125318

Files:
  clang/include/clang/StaticAnalyzer/Checkers/SValExplainer.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/Symbols.def
  clang/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp
  clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
  clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
  clang/lib/StaticAnalyzer/Core/SymbolManager.cpp
  clang/test/Analysis/explain-svals.cpp
  clang/test/Analysis/expr-inspection.cpp
  clang/test/Analysis/unary-sym-expr.c

Index: clang/test/Analysis/unary-sym-expr.c
===
--- /dev/null
+++ clang/test/Analysis/unary-sym-expr.c
@@ -0,0 +1,38 @@
+// RUN: %clang_analyze_cc1 %s \
+// RUN:   -analyzer-checker=core,debug.ExprInspection \
+// RUN:   -analyzer-config eagerly-assume=false \
+// RUN:   -verify
+
+void clang_analyzer_eval(int);
+void clang_analyzer_dump(int);
+
+int test(int x, int y) {
+
+  clang_analyzer_dump(-x);   // expected-warning{{-reg_$0}}
+  clang_analyzer_dump(~x);   // expected-warning{{~reg_$0}}
+  int z = x + y;
+  clang_analyzer_dump(-z);   // expected-warning{{-((reg_$0) + (reg_$1))}}
+  clang_analyzer_dump(-(x + y)); // expected-warning{{-((reg_$0) + (reg_$1))}}
+  clang_analyzer_dump(-x + y);   // expected-warning{{(-reg_$0) + (reg_$1)}}
+
+  if (-x == 0) {
+clang_analyzer_eval(-x == 0); // expected-warning{{TRUE}}
+clang_analyzer_eval(-x > 0);  // expected-warning{{FALSE}}
+clang_analyzer_eval(-x < 0);  // expected-warning{{FALSE}}
+  }
+  if (~y == 0) {
+clang_analyzer_eval(~y == 0); // expected-warning{{TRUE}}
+clang_analyzer_eval(~y > 0);  // expected-warning{{FALSE}}
+clang_analyzer_eval(~y < 0);  // expected-warning{{FALSE}}
+  }
+  (void)(x);
+  return 42;
+}
+
+void test_svalbuilder_simplification(int x, int y) {
+  if (x + y != 3)
+return;
+  clang_analyzer_eval(-(x + y) == -3); // expected-warning{{TRUE}}
+  // FIXME Commutativity is not supported yet.
+  clang_analyzer_eval(-(y + x) == -3); // expected-warning{{UNKNOWN}}
+}
Index: clang/test/Analysis/expr-inspection.cpp
===
--- clang/test/Analysis/expr-inspection.cpp
+++ clang/test/Analysis/expr-inspection.cpp
@@ -18,6 +18,8 @@
   clang_analyzer_express(x); // expected-warning{{Unable to express}}
 
   clang_analyzer_denote(x, "$x");
+  clang_analyzer_express(-x); // expected-warning{{-$x}}
+
   clang_analyzer_denote(y, "$y");
   clang_analyzer_express(x + y); // expected-warning{{$x + $y}}
 
Index: clang/test/Analysis/explain-svals.cpp
===
--- clang/test/Analysis/explain-svals.cpp
+++ clang/test/Analysis/explain-svals.cpp
@@ -72,6 +72,7 @@
 void test_4(int x, int y) {
   int z;
   static int stat;
+  clang_analyzer_explain(-x);// expected-warning-re^\- \(argument 'x'\)$
   clang_analyzer_explain(x + 1); // expected-warning-re^\(argument 'x'\) \+ 1$
   clang_analyzer_explain(1 + y); // expected-warning-re^\(argument 'y'\) \+ 1$
   clang_analyzer_explain(x + y); // expected-warning-re^\(argument 'x'\) \+ \(argument 'y'\)$
Index: clang/lib/StaticAnalyzer/Core/SymbolManager.cpp
===
--- clang/lib/StaticAnalyzer/Core/SymbolManager.cpp
+++ clang/lib/StaticAnalyzer/Core/SymbolManager.cpp
@@ -70,6 +70,16 @@
   os << ')';
 }
 
+void UnarySymExpr::dumpToStream(raw_ostream &os) const {
+  os << UnaryOperator::getOpcodeStr(Op);
+  bool Binary = isa(Operand);
+  if (Binary)
+os << '(';
+  Operand->dumpToStream(os);
+  if (Binary)
+os << ')';
+}
+
 void SymbolConjured::dumpToStream(raw_ostream &os) const {
   os << getKindStr() << getSymbolID() << '{' << T << ", LC" << LCtx->getID();
   if (S)
@@ -134,6 +144,9 @@
 case SymExpr::SymbolCastKind:
   itr.push_back(cast(SE)->getOperand());
   return;
+case SymExpr::UnarySymExprKind:
+  itr.push_back(cast(SE)->getOperand());
+  return;
 case SymExpr::SymIntExprKind:
   itr.push_back(cast(SE)->getLHS());
   return;
@@ -306,6 +319,22 @@
   return cast(data);
 }
 
+const UnarySymExpr *SymbolManager::getUnarySymExpr(const SymExpr *Operand,
+   UnaryOperator::Opcode Opc,
+   Qua

[clang] cd5783d - [analyzer][solver] Handle UnarySymExpr in SMTConv

2022-05-26 Thread Gabor Marton via cfe-commits

Author: Gabor Marton
Date: 2022-05-26T14:14:10+02:00
New Revision: cd5783d3e82b98bfa140853fee95170852fd3c74

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

LOG: [analyzer][solver] Handle UnarySymExpr in SMTConv

Dependent patch adds UnarySymExpr, now I'd like to handle that for SMT
conversions like refutation.

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

Added: 
clang/test/Analysis/unary-sym-expr-z3-refutation.c

Modified: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConv.h
clang/test/Analysis/z3-crosscheck.c

Removed: 




diff  --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConv.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConv.h
index 2d0f169260a4..bc38a54533be 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConv.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConv.h
@@ -446,6 +446,28 @@ class SMTConv {
   return getCastExpr(Solver, Ctx, Exp, FromTy, Sym->getType());
 }
 
+if (const UnarySymExpr *USE = dyn_cast(Sym)) {
+  if (RetTy)
+*RetTy = Sym->getType();
+
+  QualType OperandTy;
+  llvm::SMTExprRef OperandExp =
+  getSymExpr(Solver, Ctx, USE->getOperand(), &OperandTy, 
hasComparison);
+  llvm::SMTExprRef UnaryExp =
+  fromUnOp(Solver, USE->getOpcode(), OperandExp);
+
+  // Currently, without the `support-symbolic-integer-casts=true` option,
+  // we do not emit `SymbolCast`s for implicit casts.
+  // One such implicit cast is missing if the operand of the unary operator
+  // has a 
diff erent type than the unary itself.
+  if (Ctx.getTypeSize(OperandTy) != Ctx.getTypeSize(Sym->getType())) {
+if (hasComparison)
+  *hasComparison = false;
+return getCastExpr(Solver, Ctx, UnaryExp, OperandTy, Sym->getType());
+  }
+  return UnaryExp;
+}
+
 if (const BinarySymExpr *BSE = dyn_cast(Sym)) {
   llvm::SMTExprRef Exp =
   getSymBinExpr(Solver, Ctx, BSE, hasComparison, RetTy);

diff  --git a/clang/test/Analysis/unary-sym-expr-z3-refutation.c 
b/clang/test/Analysis/unary-sym-expr-z3-refutation.c
new file mode 100644
index ..33585236232a
--- /dev/null
+++ b/clang/test/Analysis/unary-sym-expr-z3-refutation.c
@@ -0,0 +1,33 @@
+// RUN: %clang_analyze_cc1 %s \
+// RUN:   -analyzer-checker=core,debug.ExprInspection \
+// RUN:   -analyzer-config eagerly-assume=true \
+// RUN:   -verify
+
+// RUN: %clang_analyze_cc1 %s \
+// RUN:   -analyzer-checker=core,debug.ExprInspection \
+// RUN:   -analyzer-config eagerly-assume=true \
+// RUN:   -analyzer-config support-symbolic-integer-casts=true \
+// RUN:   -verify
+
+// RUN: %clang_analyze_cc1 %s \
+// RUN:   -analyzer-checker=core,debug.ExprInspection \
+// RUN:   -analyzer-config eagerly-assume=true \
+// RUN:   -analyzer-config crosscheck-with-z3=true \
+// RUN:   -verify
+
+// RUN: %clang_analyze_cc1 %s \
+// RUN:   -analyzer-checker=core,debug.ExprInspection \
+// RUN:   -analyzer-config eagerly-assume=true \
+// RUN:   -analyzer-config crosscheck-with-z3=true \
+// RUN:   -analyzer-config support-symbolic-integer-casts=true \
+// RUN:   -verify
+
+// REQUIRES: z3
+
+void k(long L) {
+  int g = L;
+  int h = g + 1;
+  int j;
+  j += -h < 0; // should not crash
+  // expected-warning@-1{{garbage}}
+}

diff  --git a/clang/test/Analysis/z3-crosscheck.c 
b/clang/test/Analysis/z3-crosscheck.c
index 67d410434fbb..7711597eb9ec 100644
--- a/clang/test/Analysis/z3-crosscheck.c
+++ b/clang/test/Analysis/z3-crosscheck.c
@@ -14,6 +14,20 @@ int foo(int x)
   return 0;
 }
 
+int unary(int x, long l)
+{
+  int *z = 0;
+  int y = l;
+  if ((x & 1) && ((x & 1) ^ 1))
+if (-y)
+#ifdef NO_CROSSCHECK
+return *z; // expected-warning {{Dereference of null pointer (loaded 
from variable 'z')}}
+#else
+return *z; // no-warning
+#endif
+  return 0;
+}
+
 void g(int d);
 
 void f(int *a, int *b) {



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


[PATCH] D125395: [analyzer][solver] Handle UnarySymExpr in RangeConstraintSolver

2022-05-26 Thread Gabor Marton via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG88abc50398eb: [analyzer][solver] Handle UnarySymExpr in 
RangeConstraintSolver (authored by martong).

Changed prior to commit:
  https://reviews.llvm.org/D125395?vs=429208&id=432251#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125395

Files:
  clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
  clang/test/Analysis/constraint_manager_negate.c
  clang/test/Analysis/constraint_manager_negate_difference.c
  clang/test/Analysis/unary-sym-expr-no-crash.c
  clang/test/Analysis/unary-sym-expr.c

Index: clang/test/Analysis/unary-sym-expr.c
===
--- clang/test/Analysis/unary-sym-expr.c
+++ clang/test/Analysis/unary-sym-expr.c
@@ -36,3 +36,12 @@
   // FIXME Commutativity is not supported yet.
   clang_analyzer_eval(-(y + x) == -3); // expected-warning{{UNKNOWN}}
 }
+
+int test_fp(int flag) {
+  int value;
+  if (flag == 0)
+value = 1;
+  if (-flag == 0)
+return value; // no-warning
+  return 42;
+}
Index: clang/test/Analysis/unary-sym-expr-no-crash.c
===
--- /dev/null
+++ clang/test/Analysis/unary-sym-expr-no-crash.c
@@ -0,0 +1,23 @@
+// RUN: %clang_analyze_cc1 %s \
+// RUN:   -analyzer-checker=core,debug.ExprInspection \
+// RUN:   -analyzer-config eagerly-assume=false \
+// RUN:   -analyzer-config support-symbolic-integer-casts=false \
+// RUN:   -verify
+
+// RUN: %clang_analyze_cc1 %s \
+// RUN:   -analyzer-checker=core,debug.ExprInspection \
+// RUN:   -analyzer-config eagerly-assume=false \
+// RUN:   -analyzer-config support-symbolic-integer-casts=true \
+// RUN:   -verify
+
+// expected-no-diagnostics
+
+void clang_analyzer_eval(int);
+void clang_analyzer_dump(int);
+
+void crash(int b, long c) {
+  b = c;
+  if (b > 0)
+if(-b) // should not crash here
+  ;
+}
Index: clang/test/Analysis/constraint_manager_negate_difference.c
===
--- clang/test/Analysis/constraint_manager_negate_difference.c
+++ clang/test/Analysis/constraint_manager_negate_difference.c
@@ -1,4 +1,6 @@
-// RUN: %clang_analyze_cc1 -analyzer-checker=debug.ExprInspection,core.builtin -analyzer-config aggressive-binary-operation-simplification=true -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=debug.ExprInspection,core.builtin \
+// RUN:   -analyzer-config eagerly-assume=false \
+// RUN:   -verify %s
 
 void clang_analyzer_eval(int);
 
@@ -10,11 +12,8 @@
 #define INT_MAX (UINT_MAX & (UINT_MAX >> 1))
 #define INT_MIN (UINT_MAX & ~(UINT_MAX >> 1))
 
-extern void __assert_fail (__const char *__assertion, __const char *__file,
-unsigned int __line, __const char *__function)
- __attribute__ ((__noreturn__));
-#define assert(expr) \
-  ((expr)  ? (void)(0)  : __assert_fail (#expr, __FILE__, __LINE__, __func__))
+extern void abort() __attribute__((__noreturn__));
+#define assert(expr) ((expr) ? (void)(0) : abort())
 
 void assert_in_range(int x) {
   assert(x <= ((int)INT_MAX / 4));
@@ -33,69 +32,60 @@
 
 void equal(int m, int n) {
   assert_in_range_2(m, n);
-  if (m != n)
-return;
+  assert(m == n);
   assert_in_wide_range(m - n);
   clang_analyzer_eval(n == m); // expected-warning{{TRUE}}
 }
 
 void non_equal(int m, int n) {
   assert_in_range_2(m, n);
-  if (m == n)
-return;
+  assert(m != n);
   assert_in_wide_range(m - n);
   clang_analyzer_eval(n != m); // expected-warning{{TRUE}}
 }
 
 void less_or_equal(int m, int n) {
   assert_in_range_2(m, n);
-  if (m < n)
-return;
+  assert(m >= n);
   assert_in_wide_range(m - n);
   clang_analyzer_eval(n <= m); // expected-warning{{TRUE}}
 }
 
 void less(int m, int n) {
   assert_in_range_2(m, n);
-  if (m <= n)
-return;
+  assert(m > n);
   assert_in_wide_range(m - n);
   clang_analyzer_eval(n < m); // expected-warning{{TRUE}}
 }
 
 void greater_or_equal(int m, int n) {
   assert_in_range_2(m, n);
-  if (m > n)
-return;
+  assert(m <= n);
   assert_in_wide_range(m - n);
   clang_analyzer_eval(n >= m); // expected-warning{{TRUE}}
 }
 
 void greater(int m, int n) {
   assert_in_range_2(m, n);
-  if (m >= n)
-return;
+  assert(m < n);
   assert_in_wide_range(m - n);
   clang_analyzer_eval(n > m); // expected-warning{{TRUE}}
 }
 
 void negate_positive_range(int m, int n) {
-  if (m - n <= 0)
-return;
+  assert(m - n > 0);
   clang_analyzer_eval(n - m < 0); // expected-warning{{TRUE}}
   clang_analyzer_eval(n - m > INT_MIN); // expected-warning{{TRUE}}
-  clang_analyzer_eval(n - m == INT_MIN); // expected-warning{{FALSE}}
 }
 
+_Static_assert(INT_MIN == -INT_MIN, "");
 void negate_int_min(int m, int n) {
-  if (m - n != INT_MIN)
-return;
+  assert(m - n == INT_MIN);
   clang_analyzer_eval(n - m == INT_MIN); // ex

[PATCH] D125547: [analyzer][solver] Handle UnarySymExpr in SMTConv

2022-05-26 Thread Gabor Marton via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGcd5783d3e82b: [analyzer][solver] Handle UnarySymExpr in 
SMTConv (authored by martong).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125547

Files:
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConv.h
  clang/test/Analysis/unary-sym-expr-z3-refutation.c
  clang/test/Analysis/z3-crosscheck.c


Index: clang/test/Analysis/z3-crosscheck.c
===
--- clang/test/Analysis/z3-crosscheck.c
+++ clang/test/Analysis/z3-crosscheck.c
@@ -14,6 +14,20 @@
   return 0;
 }
 
+int unary(int x, long l)
+{
+  int *z = 0;
+  int y = l;
+  if ((x & 1) && ((x & 1) ^ 1))
+if (-y)
+#ifdef NO_CROSSCHECK
+return *z; // expected-warning {{Dereference of null pointer (loaded 
from variable 'z')}}
+#else
+return *z; // no-warning
+#endif
+  return 0;
+}
+
 void g(int d);
 
 void f(int *a, int *b) {
Index: clang/test/Analysis/unary-sym-expr-z3-refutation.c
===
--- /dev/null
+++ clang/test/Analysis/unary-sym-expr-z3-refutation.c
@@ -0,0 +1,33 @@
+// RUN: %clang_analyze_cc1 %s \
+// RUN:   -analyzer-checker=core,debug.ExprInspection \
+// RUN:   -analyzer-config eagerly-assume=true \
+// RUN:   -verify
+
+// RUN: %clang_analyze_cc1 %s \
+// RUN:   -analyzer-checker=core,debug.ExprInspection \
+// RUN:   -analyzer-config eagerly-assume=true \
+// RUN:   -analyzer-config support-symbolic-integer-casts=true \
+// RUN:   -verify
+
+// RUN: %clang_analyze_cc1 %s \
+// RUN:   -analyzer-checker=core,debug.ExprInspection \
+// RUN:   -analyzer-config eagerly-assume=true \
+// RUN:   -analyzer-config crosscheck-with-z3=true \
+// RUN:   -verify
+
+// RUN: %clang_analyze_cc1 %s \
+// RUN:   -analyzer-checker=core,debug.ExprInspection \
+// RUN:   -analyzer-config eagerly-assume=true \
+// RUN:   -analyzer-config crosscheck-with-z3=true \
+// RUN:   -analyzer-config support-symbolic-integer-casts=true \
+// RUN:   -verify
+
+// REQUIRES: z3
+
+void k(long L) {
+  int g = L;
+  int h = g + 1;
+  int j;
+  j += -h < 0; // should not crash
+  // expected-warning@-1{{garbage}}
+}
Index: clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConv.h
===
--- clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConv.h
+++ clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConv.h
@@ -446,6 +446,28 @@
   return getCastExpr(Solver, Ctx, Exp, FromTy, Sym->getType());
 }
 
+if (const UnarySymExpr *USE = dyn_cast(Sym)) {
+  if (RetTy)
+*RetTy = Sym->getType();
+
+  QualType OperandTy;
+  llvm::SMTExprRef OperandExp =
+  getSymExpr(Solver, Ctx, USE->getOperand(), &OperandTy, 
hasComparison);
+  llvm::SMTExprRef UnaryExp =
+  fromUnOp(Solver, USE->getOpcode(), OperandExp);
+
+  // Currently, without the `support-symbolic-integer-casts=true` option,
+  // we do not emit `SymbolCast`s for implicit casts.
+  // One such implicit cast is missing if the operand of the unary operator
+  // has a different type than the unary itself.
+  if (Ctx.getTypeSize(OperandTy) != Ctx.getTypeSize(Sym->getType())) {
+if (hasComparison)
+  *hasComparison = false;
+return getCastExpr(Solver, Ctx, UnaryExp, OperandTy, Sym->getType());
+  }
+  return UnaryExp;
+}
+
 if (const BinarySymExpr *BSE = dyn_cast(Sym)) {
   llvm::SMTExprRef Exp =
   getSymBinExpr(Solver, Ctx, BSE, hasComparison, RetTy);


Index: clang/test/Analysis/z3-crosscheck.c
===
--- clang/test/Analysis/z3-crosscheck.c
+++ clang/test/Analysis/z3-crosscheck.c
@@ -14,6 +14,20 @@
   return 0;
 }
 
+int unary(int x, long l)
+{
+  int *z = 0;
+  int y = l;
+  if ((x & 1) && ((x & 1) ^ 1))
+if (-y)
+#ifdef NO_CROSSCHECK
+return *z; // expected-warning {{Dereference of null pointer (loaded from variable 'z')}}
+#else
+return *z; // no-warning
+#endif
+  return 0;
+}
+
 void g(int d);
 
 void f(int *a, int *b) {
Index: clang/test/Analysis/unary-sym-expr-z3-refutation.c
===
--- /dev/null
+++ clang/test/Analysis/unary-sym-expr-z3-refutation.c
@@ -0,0 +1,33 @@
+// RUN: %clang_analyze_cc1 %s \
+// RUN:   -analyzer-checker=core,debug.ExprInspection \
+// RUN:   -analyzer-config eagerly-assume=true \
+// RUN:   -verify
+
+// RUN: %clang_analyze_cc1 %s \
+// RUN:   -analyzer-checker=core,debug.ExprInspection \
+// RUN:   -analyzer-config eagerly-assume=true \
+// RUN:   -analyzer-config support-symbolic-integer-casts=true \
+// RUN:   -verify
+
+// RUN: %clang_analyze_cc1 %s \
+// RUN:   -analyzer-checker=core,d

[PATCH] D125318: [analyzer] Add UnarySymExpr

2022-05-26 Thread Gabor Marton via Phabricator via cfe-commits
martong added inline comments.



Comment at: clang/test/Analysis/unary-sym-expr.c:35
+return;
+  clang_analyzer_eval(-(x + y) == -3); // expected-warning{{TRUE}}
+}

steakhal wrote:
> martong wrote:
> > steakhal wrote:
> > > Does it work if you swap x and y?
> > No, that does not. And the reason of that is we cannot handle commutativity 
> > (yet).
> We could still test it, and put there a FIXME.
Ok, added a fixme.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125318

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


[PATCH] D125814: Improve the strict prototype diagnostic behavior

2022-05-26 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman marked an inline comment as done.
aaron.ballman added inline comments.



Comment at: clang/lib/Sema/SemaDecl.cpp:3959
+  // it's a user-visible declaration. There is one exception to this:
+  // when the new declaration is one without a prototype, the old
+  // declaration with a prototype is not the cause of the issue, and

jyknight wrote:
> "when the new declaration is a definition without a prototype" perhaps?
Done!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125814

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


[clang] 681c50c - Improve the strict prototype diagnostic behavior

2022-05-26 Thread Aaron Ballman via cfe-commits

Author: Aaron Ballman
Date: 2022-05-26T08:35:56-04:00
New Revision: 681c50c62e9338afdf58ebfd663f8e3ff43439fb

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

LOG: Improve the strict prototype diagnostic behavior

Post-commit feedback on https://reviews.llvm.org/D122895 pointed out
that the diagnostic wording for some code was using "declaration" in a
confusing way, such as:

int foo(); // warning: a function declaration without a prototype is deprecated 
in all versions of C and is not supported in C2x

int foo(int arg) { // warning: a function declaration without a prototype is 
deprecated in all versions of C and is not supported in C2x
  return 5;
}

And that we had other minor issues with the diagnostics being somewhat
confusing.

This patch addresses the confusion by reworking the implementation to
be a bit more simple and a bit less chatty. Specifically, it changes
the warning and note diagnostics to be able to specify "declaration" or
"definition" as appropriate, and it changes the function merging logic
so that the function without a prototype is always what gets warned on,
and the function with a prototype is sometimes what gets noted.
Additionally, when diagnosing a K&R C definition that is preceded by a
function without a prototype, we don't note the prior declaration, we
warn on it because it will also be changing behavior in C2x.

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

Added: 


Modified: 
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/lib/Sema/SemaDecl.cpp
clang/test/C/drs/dr0xx.c
clang/test/CodeGen/2009-06-01-addrofknr.c
clang/test/Parser/declarators.c
clang/test/Sema/arg-duplicate.c
clang/test/Sema/knr-def-call.c
clang/test/Sema/knr-variadic-def.c
clang/test/Sema/warn-deprecated-non-prototype.c
clang/test/Sema/warn-strict-prototypes.c

Removed: 




diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 3168c20969e1..0f8ed0a6e8c3 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -5589,10 +5589,12 @@ def warn_strict_prototypes : Extension<
   "a %select{function|block}0 declaration without a prototype is deprecated "
   "%select{in all versions of C|}0">, InGroup;
 def warn_non_prototype_changes_behavior : Warning<
-  "a function declaration without a prototype is deprecated in all versions of 
"
-  "C and is not supported in C2x">, InGroup;
-def note_func_decl_changes_behavior : Note<
-  "a function declaration without a prototype is not supported in C2x">;
+  "a function %select{declaration|definition}0 without a prototype is "
+  "deprecated in all versions of C %select{and is not supported in C2x|and is "
+  "treated as a zero-parameter prototype in C2x, conflicting with a "
+  "%select{previous|subsequent}2 %select{declaration|definition}3}1">,
+  InGroup;
+def note_conflicting_prototype : Note<"conflicting prototype is here">;
 def warn_missing_variable_declarations : Warning<
   "no previous extern declaration for non-static variable %0">,
   InGroup>, DefaultIgnore;

diff  --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index c5d4075a49e2..d68d1f3ff070 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -3940,59 +3940,29 @@ bool Sema::MergeFunctionDecl(FunctionDecl *New, 
NamedDecl *&OldD, Scope *S,
   }
 
   if (WithProto->getNumParams() != 0) {
-// The function definition has parameters, so this will change
-// behavior in C2x.
-//
-// If we already warned about about the function without a prototype
-// being deprecated, add a note that it also changes behavior. If we
-// didn't warn about it being deprecated (because the diagnostic is
-// not enabled), warn now that it is deprecated and changes behavior.
-bool AddNote = false;
-if (Diags.isIgnored(diag::warn_strict_prototypes,
-WithoutProto->getLocation())) {
-  if (WithoutProto->getBuiltinID() == 0 &&
-  !WithoutProto->isImplicit() &&
-  SourceMgr.isBeforeInTranslationUnit(WithoutProto->getLocation(),
-  WithProto->getLocation())) {
-PartialDiagnostic PD =
-PDiag(diag::warn_non_prototype_changes_behavior);
-if (TypeSourceInfo *TSI = WithoutProto->getTypeSourceInfo()) {
-  if (auto FTL = TSI->getTypeLoc().getAs())
-PD << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
-}
-Diag(WithoutProto->getLocation(), PD);
-  }
-} else {
-  AddNote = true;
-}
-

[PATCH] D125814: Improve the strict prototype diagnostic behavior

2022-05-26 Thread Aaron Ballman via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
aaron.ballman marked an inline comment as done.
Closed by commit rG681c50c62e93: Improve the strict prototype diagnostic 
behavior (authored by aaron.ballman).

Changed prior to commit:
  https://reviews.llvm.org/D125814?vs=432020&id=432254#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125814

Files:
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaDecl.cpp
  clang/test/C/drs/dr0xx.c
  clang/test/CodeGen/2009-06-01-addrofknr.c
  clang/test/Parser/declarators.c
  clang/test/Sema/arg-duplicate.c
  clang/test/Sema/knr-def-call.c
  clang/test/Sema/knr-variadic-def.c
  clang/test/Sema/warn-deprecated-non-prototype.c
  clang/test/Sema/warn-strict-prototypes.c

Index: clang/test/Sema/warn-strict-prototypes.c
===
--- clang/test/Sema/warn-strict-prototypes.c
+++ clang/test/Sema/warn-strict-prototypes.c
@@ -48,7 +48,7 @@
 }
 
 // K&R function definition not preceded by full prototype
-int foo9(a, b) // expected-warning {{a function declaration without a prototype is deprecated in all versions of C and is not supported in C2x}}
+int foo9(a, b) // expected-warning {{a function definition without a prototype is deprecated in all versions of C and is not supported in C2x}}
   int a, b;
 {
   return a + b;
@@ -56,17 +56,17 @@
 
 // Function declaration with no types
 void foo10(); // expected-warning {{a function declaration without a prototype is deprecated in all versions of C}} \
- expected-note {{a function declaration without a prototype is not supported in C2x}}
+ expected-warning {{a function declaration without a prototype is deprecated in all versions of C and is treated as a zero-parameter prototype in C2x, conflicting with a subsequent definition}}
   // CHECK: fix-it:"{{.*}}":{[[@LINE-2]]:12-[[@LINE-2]]:12}:"void"
 // K&R function definition with incomplete param list declared
-void foo10(p, p2) void *p; {} // expected-warning {{a function declaration without a prototype is deprecated in all versions of C and is not supported in C2x}} \
+void foo10(p, p2) void *p; {} // expected-warning {{a function definition without a prototype is deprecated in all versions of C and is not supported in C2x}} \
  expected-warning {{parameter 'p2' was not declared, defaults to 'int'; ISO C99 and later do not support implicit int}}
 
 void foo11(int p, int p2);
-void foo11(p, p2) int p; int p2; {} // expected-warning {{a function declaration without a prototype is deprecated in all versions of C and is not supported in C2x}}
+void foo11(p, p2) int p; int p2; {} // expected-warning {{a function definition without a prototype is deprecated in all versions of C and is not supported in C2x}}
 
 // PR31020
-void __attribute__((cdecl)) foo12(d) // expected-warning {{a function declaration without a prototype is deprecated in all versions of C and is not supported in C2x}}
+void __attribute__((cdecl)) foo12(d) // expected-warning {{a function definition without a prototype is deprecated in all versions of C and is not supported in C2x}}
   short d;
 {}
 
Index: clang/test/Sema/warn-deprecated-non-prototype.c
===
--- clang/test/Sema/warn-deprecated-non-prototype.c
+++ clang/test/Sema/warn-deprecated-non-prototype.c
@@ -23,15 +23,14 @@
 void again() {} // strict-warning {{a function declaration without a prototype is deprecated in all versions of C}}
 
 // On by default warnings
-void func(); // expected-warning {{a function declaration without a prototype is deprecated in all versions of C and is not supported in C2x}} \
-strict-warning {{a function declaration without a prototype is deprecated in all versions of C}} \
-strict-note {{a function declaration without a prototype is not supported in C2x}}
-void func(a, b) int a, b; {} // both-warning {{a function declaration without a prototype is deprecated in all versions of C and is not supported in C2x}}
+void func(); // both-warning {{a function declaration without a prototype is deprecated in all versions of C and is treated as a zero-parameter prototype in C2x, conflicting with a subsequent definition}} \
+strict-warning {{a function declaration without a prototype is deprecated in all versions of C}}
+void func(a, b) int a, b; {} // both-warning {{a function definition without a prototype is deprecated in all versions of C and is not supported in C2x}}
 
-void one_more(a, b) int a, b; {} // both-warning {{a function declaration without a prototype is deprecated in all versions of C and is not supported in C2x}}
+voi

[PATCH] D126451: [Clang][CSKY] Add support about CSKYABIInfo

2022-05-26 Thread David Spickett via Phabricator via cfe-commits
DavidSpickett added a comment.

Looks good to me. Can you just clarify how the tests are split? My guess is 
that one is stuff that doesn't vary with hard/soft float and the other is the 
bits that change when hardfloat is enabled. If so is it worth checking those 
situations with soft float too or have you already done that.




Comment at: clang/lib/CodeGen/TargetInfo.cpp:11708
+  case llvm::Triple::csky: {
+bool IsSoftFloat = !getTarget().hasFeature("hard-float-abi");
+bool hasFP64 = getTarget().hasFeature("fpuv2_df") ||

I see a "hard-float" and "hard-float-abi" in this change. Is it safe to check 
just for "hard-float-abi" here?

Just checking, I assume it's fine. You could have hardware with hard float but 
you want to compile for soft float abi. This allows that.



Comment at: clang/lib/CodeGen/TargetInfo.cpp:11710
+bool hasFP64 = getTarget().hasFeature("fpuv2_df") ||
+   getTarget().hasFeature("fpuv3_df");
+return SetCGInfo(new CSKYTargetCodeGenInfo(Types, IsSoftFloat ? 0

Silly question, was/is there an fpuv1 and was it 32 bit only? (I assume so)



Comment at: clang/test/CodeGen/CSKY/csky-abi.c:3
+// RUN: %clang_cc1 -no-opaque-pointers -triple csky -target-feature +fpuv2_df 
-target-feature +fpuv2_sf \
+// RUN:   -target-feature +hard-float -target-feature +hard-float-abi 
-emit-llvm %s -o -   | FileCheck %s
+

Is this file checking things that don't vary between hard float/not hard float? 
If so please add a comment that states that.


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

https://reviews.llvm.org/D126451

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


[clang] 6056511 - Fix failing test case with strict prototype changes

2022-05-26 Thread Aaron Ballman via cfe-commits

Author: Aaron Ballman
Date: 2022-05-26T08:46:11-04:00
New Revision: 605651135b4c37e423825a9201b06a16ff6160a1

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

LOG: Fix failing test case with strict prototype changes

Amends 681c50c62e9338afdf58ebfd663f8e3ff43439fb and hopefully fixes:

https://lab.llvm.org/buildbot/#/builders/109/builds/39347
https://lab.llvm.org/buildbot/#/builders/188/builds/14634
and others

Added: 


Modified: 
clang/test/SemaObjC/nonnull.m

Removed: 




diff  --git a/clang/test/SemaObjC/nonnull.m b/clang/test/SemaObjC/nonnull.m
index 3b087b096d8f..218aad85e673 100644
--- a/clang/test/SemaObjC/nonnull.m
+++ b/clang/test/SemaObjC/nonnull.m
@@ -22,7 +22,7 @@ extern void func3 (void (^block1)(), int, void (^block2)(), 
int)
 extern void func4 (void (^block1)(), void (^block2)()) 
__attribute__((nonnull(1)))
 __attribute__((nonnull(2)));
 
-void func6(); // expected-warning {{a function declaration without a prototype 
is deprecated in all versions of C and is not supported in C2x}}
+void func6(); // expected-warning {{a function declaration without a prototype 
is deprecated in all versions of C and is treated as a zero-parameter prototype 
in C2x, conflicting with a subsequent definition}}
 void func7();
 
 void
@@ -60,7 +60,7 @@ extern void func4 (void (^block1)(), void (^block2)()) 
__attribute__((nonnull(1)
 __attribute__((nonnull))
 void _dispatch_queue_push_list(dispatch_object_t _head); // no warning
 
-void func6(dispatch_object_t _head) { // expected-warning {{a function 
declaration without a prototype is deprecated in all versions of C and is not 
supported in C2x}}
+void func6(dispatch_object_t _head) { // expected-note {{conflicting prototype 
is here}}
   _dispatch_queue_push_list(0); // expected-warning {{null passed to a callee 
that requires a non-null argument}}
   _dispatch_queue_push_list(_head._do);  // no warning
 }



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


[PATCH] D126289: [Clang][Driver] Fix include paths for `--sysroot /` on Linux

2022-05-26 Thread Egor Zhdan via Phabricator via cfe-commits
egorzhdan updated this revision to Diff 432256.
egorzhdan added a comment.

- Remove unnecessary trailing `/`
- Add `-SAME` in tests


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126289

Files:
  clang/include/clang/Driver/ToolChain.h
  clang/lib/Driver/ToolChain.cpp
  clang/lib/Driver/ToolChains/Gnu.cpp
  clang/lib/Driver/ToolChains/Hurd.cpp
  clang/lib/Driver/ToolChains/Hurd.h
  clang/lib/Driver/ToolChains/Linux.cpp
  clang/lib/Driver/ToolChains/Linux.h
  clang/lib/Driver/ToolChains/WebAssembly.cpp
  clang/lib/Driver/ToolChains/WebAssembly.h
  clang/test/Driver/Inputs/basic_linux_libstdcxx_tree/usr/bin/.keep
  
clang/test/Driver/Inputs/basic_linux_libstdcxx_tree/usr/lib/gcc/x86_64-unknown-linux-gnu/4.8/crtbegin.o
  clang/test/Driver/linux-header-search.cpp

Index: clang/test/Driver/linux-header-search.cpp
===
--- clang/test/Driver/linux-header-search.cpp
+++ clang/test/Driver/linux-header-search.cpp
@@ -16,6 +16,22 @@
 // CHECK-BASIC-LIBCXX-SYSROOT: "-internal-isystem" "[[SYSROOT]]/usr/include/x86_64-unknown-linux-gnu/c++/v1"
 // CHECK-BASIC-LIBCXX-SYSROOT: "-internal-isystem" "[[SYSROOT]]/usr/include/c++/v1"
 // CHECK-BASIC-LIBCXX-SYSROOT: "-internal-isystem" "[[SYSROOT]]/usr/local/include"
+//
+// Test include paths when the sysroot path ends with `/`.
+// RUN: %clang -### %s -fsyntax-only 2>&1 \
+// RUN: --target=x86_64-unknown-linux-gnu \
+// RUN: -stdlib=libc++ \
+// RUN: -ccc-install-dir %S/Inputs/basic_linux_tree/usr/bin \
+// RUN: -resource-dir=%S/Inputs/resource_dir \
+// RUN: --sysroot=%S/Inputs/basic_linux_libcxx_tree/ \
+// RUN: --gcc-toolchain="" \
+// RUN:   | FileCheck --check-prefix=CHECK-BASIC-LIBCXX-SYSROOT-SLASH %s
+// CHECK-BASIC-LIBCXX-SYSROOT-SLASH: "-cc1"
+// CHECK-BASIC-LIBCXX-SYSROOT-SLASH-SAME: "-isysroot" "[[SYSROOT:[^"]+/]]"
+// CHECK-BASIC-LIBCXX-SYSROOT-SLASH-SAME: "-internal-isystem" "[[SYSROOT]]usr/include/x86_64-unknown-linux-gnu/c++/v1"
+// CHECK-BASIC-LIBCXX-SYSROOT-SLASH-SAME: "-internal-isystem" "[[SYSROOT]]usr/include/c++/v1"
+// CHECK-BASIC-LIBCXX-SYSROOT-SLASH-SAME: "-internal-isystem" "[[SYSROOT]]usr/local/include"
+//
 // RUN: %clang -### %s -fsyntax-only 2>&1 \
 // RUN: --target=x86_64-unknown-linux-gnu \
 // RUN: -stdlib=libc++ \
@@ -56,6 +72,32 @@
 // CHECK-BASIC-LIBCXXV2-INSTALL: "-internal-isystem" "[[SYSROOT]]/usr/bin/../include/x86_64-unknown-linux-gnu/c++/v2"
 // CHECK-BASIC-LIBCXXV2-INSTALL: "-internal-isystem" "[[SYSROOT]]/usr/bin/../include/c++/v2"
 // CHECK-BASIC-LIBCXXV2-INSTALL: "-internal-isystem" "[[SYSROOT]]/usr/local/include"
+
+// Test Linux with libstdc++.
+// RUN: %clang -### %s -fsyntax-only 2>&1 \
+// RUN: --target=x86_64-unknown-linux-gnu \
+// RUN: -stdlib=libstdc++ \
+// RUN: -ccc-install-dir %S/Inputs/basic_linux_tree/usr/bin \
+// RUN: -resource-dir=%S/Inputs/resource_dir \
+// RUN: --sysroot=%S/Inputs/basic_linux_libstdcxx_tree \
+// RUN: --gcc-toolchain="" \
+// RUN:   | FileCheck --check-prefix=CHECK-BASIC-LIBSTDCXX-SYSROOT %s
+// CHECK-BASIC-LIBSTDCXX-SYSROOT: "-cc1"
+// CHECK-BASIC-LIBSTDCXX-SYSROOT-SAME: "-isysroot" "[[SYSROOT:[^"]+]]"
+// CHECK-BASIC-LIBSTDCXX-SYSROOT-SAME: "-internal-isystem" "[[SYSROOT]]/usr/lib/gcc/x86_64-unknown-linux-gnu/4.8/../../../../x86_64-unknown-linux-gnu/include"
+//
+// Test Linux with libstdc++ when the sysroot path ends with `/`.
+// RUN: %clang -### %s -fsyntax-only 2>&1 \
+// RUN: --target=x86_64-unknown-linux-gnu \
+// RUN: -stdlib=libstdc++ \
+// RUN: -ccc-install-dir %S/Inputs/basic_linux_tree/usr/bin \
+// RUN: -resource-dir=%S/Inputs/resource_dir \
+// RUN: --sysroot=%S/Inputs/basic_linux_libstdcxx_tree/ \
+// RUN: --gcc-toolchain="" \
+// RUN:   | FileCheck --check-prefix=CHECK-BASIC-LIBSTDCXX-SYSROOT-SLASH %s
+// CHECK-BASIC-LIBSTDCXX-SYSROOT-SLASH: "-cc1"
+// CHECK-BASIC-LIBSTDCXX-SYSROOT-SLASH-SAME: "-isysroot" "[[SYSROOT:[^"]+/]]"
+// CHECK-BASIC-LIBSTDCXX-SYSROOT-SLASH-SAME: "-internal-isystem" "[[SYSROOT]]usr/lib/gcc/x86_64-unknown-linux-gnu/4.8/../../../../x86_64-unknown-linux-gnu/include"
 //
 // Test Linux with both libc++ and libstdc++ installed.
 // RUN: %clang -### %s -fsyntax-only 2>&1 \
Index: clang/lib/Driver/ToolChains/WebAssembly.h
===
--- clang/lib/Driver/ToolChains/WebAssembly.h
+++ clang/lib/Driver/ToolChains/WebAssembly.h
@@ -78,7 +78,7 @@
 
   std::string getMultiarchTriple(const Driver &D,
  const llvm::Triple &TargetTriple,
- StringRef SysRoot) const override;
+ const std::string &SysRoot) const override;
 
   void addLibCxxIncludePaths(const llvm::opt::ArgList &DriverArgs,
  llvm::opt::ArgStringList &CC1Args) const;
Index: clang/lib/Driver/ToolChains/We

[PATCH] D126461: [RISCV] Extract and store new vl of vleff iff destination isn't null

2022-05-26 Thread Wang Pengcheng via Phabricator via cfe-commits
pcwang-thead created this revision.
pcwang-thead added reviewers: khchen, kito-cheng, craig.topper, asb.
Herald added subscribers: sunshaoce, VincentWu, luke957, StephenFan, vkmr, 
frasercrmck, evandro, luismarques, apazos, sameer.abuasal, s.egerton, Jim, 
benna, psnobl, jocewei, PkmX, the_o, brucehoult, MartinMosbeck, rogfer01, 
edward-jones, zzheng, jrtc27, shiva0217, niosHD, sabuasal, simoncook, 
johnrusso, rbar, arichardson.
Herald added a project: All.
pcwang-thead requested review of this revision.
Herald added subscribers: cfe-commits, eopXD, MaskRay.
Herald added a project: clang.

Store to null will be changed to unreachable, so all instructions
after vleff intrinsic call will be deleted and it causes runtime
errors. If destination to store is null, we won't extract and store
the new vl.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D126461

Files:
  clang/include/clang/Basic/riscv_vector.td
  clang/test/CodeGen/RISCV/rvv-intrinsics/vleff.c


Index: clang/test/CodeGen/RISCV/rvv-intrinsics/vleff.c
===
--- clang/test/CodeGen/RISCV/rvv-intrinsics/vleff.c
+++ clang/test/CodeGen/RISCV/rvv-intrinsics/vleff.c
@@ -6,6 +6,17 @@
 
 #include 
 
+// CHECK-RV64-LABEL: @test_vleff_save_new_vl_to_nullptr(
+// CHECK-RV64-NEXT:  entry:
+// CHECK-RV64-NEXT:[[TMP0:%.*]] = bitcast i8* [[BASE:%.*]] to *
+// CHECK-RV64-NEXT:[[TMP1:%.*]] = call { , i64 } 
@llvm.riscv.vleff.nxv1i8.i64( undef, * 
[[TMP0]], i64 [[VL:%.*]])
+// CHECK-RV64-NEXT:[[TMP2:%.*]] = extractvalue { , i64 } 
[[TMP1]], 0
+// CHECK-RV64-NEXT:ret  [[TMP2]]
+//
+vint8mf8_t test_vleff_save_new_vl_to_nullptr (const int8_t *base, size_t vl) {
+  return vle8ff_v_i8mf8(base, NULL, vl);
+}
+
 // CHECK-RV64-LABEL: @test_vle8ff_v_i8mf8(
 // CHECK-RV64-NEXT:  entry:
 // CHECK-RV64-NEXT:[[TMP0:%.*]] = bitcast i8* [[BASE:%.*]] to *
Index: clang/include/clang/Basic/riscv_vector.td
===
--- clang/include/clang/Basic/riscv_vector.td
+++ clang/include/clang/Basic/riscv_vector.td
@@ -643,10 +643,12 @@
 llvm::Value *LoadValue = Builder.CreateCall(F, Ops, "");
 llvm::Value *V = Builder.CreateExtractValue(LoadValue, {0});
 // Store new_vl.
-clang::CharUnits Align =
-CGM.getNaturalPointeeTypeAlignment(E->getArg(1)->getType());
-llvm::Value *Val = Builder.CreateExtractValue(LoadValue, {1});
-Builder.CreateStore(Val, Address(NewVL, Val->getType(), Align));
+if (!isa(NewVL)) {
+  clang::CharUnits Align =
+  CGM.getNaturalPointeeTypeAlignment(E->getArg(1)->getType());
+  llvm::Value *Val = Builder.CreateExtractValue(LoadValue, {1});
+  Builder.CreateStore(Val, Address(NewVL, Val->getType(), Align));
+}
 return V;
   }
   }],
@@ -663,10 +665,12 @@
 llvm::Value *LoadValue = Builder.CreateCall(F, Ops, "");
 llvm::Value *V = Builder.CreateExtractValue(LoadValue, {0});
 // Store new_vl.
-clang::CharUnits Align =
-CGM.getNaturalPointeeTypeAlignment(E->getArg(3)->getType());
-llvm::Value *Val = Builder.CreateExtractValue(LoadValue, {1});
-Builder.CreateStore(Val, Address(NewVL, Val->getType(), Align));
+if (!isa(NewVL)) {
+  clang::CharUnits Align =
+  CGM.getNaturalPointeeTypeAlignment(E->getArg(3)->getType());
+  llvm::Value *Val = Builder.CreateExtractValue(LoadValue, {1});
+  Builder.CreateStore(Val, Address(NewVL, Val->getType(), Align));
+}
 return V;
   }
   }] in {


Index: clang/test/CodeGen/RISCV/rvv-intrinsics/vleff.c
===
--- clang/test/CodeGen/RISCV/rvv-intrinsics/vleff.c
+++ clang/test/CodeGen/RISCV/rvv-intrinsics/vleff.c
@@ -6,6 +6,17 @@
 
 #include 
 
+// CHECK-RV64-LABEL: @test_vleff_save_new_vl_to_nullptr(
+// CHECK-RV64-NEXT:  entry:
+// CHECK-RV64-NEXT:[[TMP0:%.*]] = bitcast i8* [[BASE:%.*]] to *
+// CHECK-RV64-NEXT:[[TMP1:%.*]] = call { , i64 } @llvm.riscv.vleff.nxv1i8.i64( undef, * [[TMP0]], i64 [[VL:%.*]])
+// CHECK-RV64-NEXT:[[TMP2:%.*]] = extractvalue { , i64 } [[TMP1]], 0
+// CHECK-RV64-NEXT:ret  [[TMP2]]
+//
+vint8mf8_t test_vleff_save_new_vl_to_nullptr (const int8_t *base, size_t vl) {
+  return vle8ff_v_i8mf8(base, NULL, vl);
+}
+
 // CHECK-RV64-LABEL: @test_vle8ff_v_i8mf8(
 // CHECK-RV64-NEXT:  entry:
 // CHECK-RV64-NEXT:[[TMP0:%.*]] = bitcast i8* [[BASE:%.*]] to *
Index: clang/include/clang/Basic/riscv_vector.td
===
--- clang/include/clang/Basic/riscv_vector.td
+++ clang/include/clang/Basic/riscv_vector.td
@@ -643,10 +643,12 @@
 llvm::Value *LoadValue = Builder.CreateCall(F, Ops, "");
 llvm::Value *V = Builder.CreateExtractValue(LoadValue, {0});
 // Store new_vl.
-   

[clang] d4d28f2 - [clang-format] Fix QualifierAlignment with global namespace qualified types.

2022-05-26 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-05-26T15:02:33+02:00
New Revision: d4d28f2ace764a0420a33462628b43a1c71fc3dc

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

LOG: [clang-format] Fix QualifierAlignment with global namespace qualified 
types.

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

Reviewed By: MyDeveloperDay

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

Added: 


Modified: 
clang/lib/Format/QualifierAlignmentFixer.cpp
clang/unittests/Format/QualifierFixerTest.cpp

Removed: 




diff  --git a/clang/lib/Format/QualifierAlignmentFixer.cpp 
b/clang/lib/Format/QualifierAlignmentFixer.cpp
index dd12298a57ff..61f17cae383e 100644
--- a/clang/lib/Format/QualifierAlignmentFixer.cpp
+++ b/clang/lib/Format/QualifierAlignmentFixer.cpp
@@ -216,6 +216,29 @@ const FormatToken 
*LeftRightQualifierAlignmentFixer::analyzeRight(
   if (LeftRightQualifierAlignmentFixer::isPossibleMacro(Tok->Next))
 return Tok;
 
+  auto AnalyzeTemplate =
+  [&](const FormatToken *Tok,
+  const FormatToken *StartTemplate) -> const FormatToken * {
+// Read from the TemplateOpener to TemplateCloser.
+FormatToken *EndTemplate = StartTemplate->MatchingParen;
+if (EndTemplate) {
+  // Move to the end of any template class members e.g.
+  // `Foo::iterator`.
+  if (EndTemplate->startsSequence(TT_TemplateCloser, tok::coloncolon,
+  tok::identifier)) {
+EndTemplate = EndTemplate->Next->Next;
+  }
+}
+if (EndTemplate && EndTemplate->Next &&
+!EndTemplate->Next->isOneOf(tok::equal, tok::l_paren)) {
+  insertQualifierAfter(SourceMgr, Fixes, EndTemplate, Qualifier);
+  // Remove the qualifier.
+  removeToken(SourceMgr, Fixes, Tok);
+  return Tok;
+}
+return nullptr;
+  };
+
   FormatToken *Qual = Tok->Next;
   FormatToken *LastQual = Qual;
   while (Qual && isQualifierOrType(Qual, ConfiguredQualifierTokens)) {
@@ -233,27 +256,24 @@ const FormatToken 
*LeftRightQualifierAlignmentFixer::analyzeRight(
 return Tok;
   } else if (Tok->startsSequence(QualifierType, tok::identifier,
  TT_TemplateOpener)) {
-// Read from the TemplateOpener to
-// TemplateCloser as in const ArrayRef a; const ArrayRef &a;
-FormatToken *EndTemplate = Tok->Next->Next->MatchingParen;
-if (EndTemplate) {
-  // Move to the end of any template class members e.g.
-  // `Foo::iterator`.
-  if (EndTemplate->startsSequence(TT_TemplateCloser, tok::coloncolon,
-  tok::identifier)) {
-EndTemplate = EndTemplate->Next->Next;
-  }
-}
-if (EndTemplate && EndTemplate->Next &&
-!EndTemplate->Next->isOneOf(tok::equal, tok::l_paren)) {
-  insertQualifierAfter(SourceMgr, Fixes, EndTemplate, Qualifier);
-  // Remove the qualifier.
-  removeToken(SourceMgr, Fixes, Tok);
-  return Tok;
-}
-  } else if (Tok->startsSequence(QualifierType, tok::identifier)) {
+// `const ArrayRef a;`
+// `const ArrayRef &a;`
+const FormatToken *NewTok = AnalyzeTemplate(Tok, Tok->Next->Next);
+if (NewTok)
+  return NewTok;
+  } else if (Tok->startsSequence(QualifierType, tok::coloncolon,
+ tok::identifier, TT_TemplateOpener)) {
+// `const ::ArrayRef a;`
+// `const ::ArrayRef &a;`
+const FormatToken *NewTok = AnalyzeTemplate(Tok, Tok->Next->Next->Next);
+if (NewTok)
+  return NewTok;
+  } else if (Tok->startsSequence(QualifierType, tok::identifier) ||
+ Tok->startsSequence(QualifierType, tok::coloncolon,
+ tok::identifier)) {
 FormatToken *Next = Tok->Next;
 // The case  `const Foo` -> `Foo const`
+// The case  `const ::Foo` -> `::Foo const`
 // The case  `const Foo *` -> `Foo const *`
 // The case  `const Foo &` -> `Foo const &`
 // The case  `const Foo &&` -> `Foo const &&`
@@ -331,7 +351,9 @@ const FormatToken 
*LeftRightQualifierAlignmentFixer::analyzeLeft(
   Tok->Next->Next && Tok->Next->Next->is(QualifierType)) {
 rotateTokens(SourceMgr, Fixes, Tok->Next, Tok->Next->Next, /*Left=*/true);
   }
-  if (Tok->startsSequence(tok::identifier) && Tok->Next) {
+  if ((Tok->startsSequence(tok::coloncolon, tok::identifier) ||
+   Tok->is(tok::identifier)) &&
+  Tok->Next) {
 if (Tok->Previous &&
 Tok->Previous->isOneOf(tok::star, tok::ampamp, tok::amp)) {
   return Tok;

diff  --git a/clang/unittests/Format/QualifierFixerTest.cpp 
b/clang/unittests/Format/QualifierFixerTest.cpp
index fc7e932af440..b01aff53150d 100755
--- a/clang/unittests/Format/QualifierFixerTest.cpp
+++ b/clang/unittests/Format/QualifierFixerTest.cpp
@@ -318,6 +31

[PATCH] D126096: [clang-format] Fix QualifierAlignment with global namespace qualified types.

2022-05-26 Thread Marek Kurdej via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGd4d28f2ace76: [clang-format] Fix QualifierAlignment with 
global namespace qualified types. (authored by curdeius).

Changed prior to commit:
  https://reviews.llvm.org/D126096?vs=431074&id=432258#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126096

Files:
  clang/lib/Format/QualifierAlignmentFixer.cpp
  clang/unittests/Format/QualifierFixerTest.cpp

Index: clang/unittests/Format/QualifierFixerTest.cpp
===
--- clang/unittests/Format/QualifierFixerTest.cpp
+++ clang/unittests/Format/QualifierFixerTest.cpp
@@ -318,6 +318,8 @@
   verifyFormat("Foo const &a", "const Foo &a", Style);
   verifyFormat("Foo::iterator const &a", "const Foo::iterator &a",
Style);
+  verifyFormat("::Foo::iterator const &a", "const ::Foo::iterator &a",
+   Style);
 
   verifyFormat("Foo(int a, "
"unsigned b, // c-style args\n"
@@ -355,6 +357,8 @@
 
   verifyFormat("void fn(Foo const &i);", "void fn(const Foo &i);", Style);
   verifyFormat("void fns(ns::S const &s);", "void fns(const ns::S &s);", Style);
+  verifyFormat("void fns(::ns::S const &s);", "void fns(const ::ns::S &s);",
+   Style);
   verifyFormat("void fn(ns::Foo const &i);", "void fn(const ns::Foo &i);",
Style);
   verifyFormat("void fns(ns::ns2::S const &s);",
@@ -445,6 +449,8 @@
   verifyFormat("const Foo &a", "Foo const &a", Style);
   verifyFormat("const Foo::iterator &a", "Foo::iterator const &a",
Style);
+  verifyFormat("const ::Foo::iterator &a", "::Foo::iterator const &a",
+   Style);
 
   verifyFormat("const int a;", "int const a;", Style);
   verifyFormat("const int *a;", "int const *a;", Style);
@@ -508,6 +514,8 @@
 
   verifyFormat("void fn(const Foo &i);", "void fn(Foo const &i);", Style);
   verifyFormat("void fns(const ns::S &s);", "void fns(ns::S const &s);", Style);
+  verifyFormat("void fns(const ::ns::S &s);", "void fns(::ns::S const &s);",
+   Style);
   verifyFormat("void fn(const ns::Foo &i);", "void fn(ns::Foo const &i);",
Style);
   verifyFormat("void fns(const ns::ns2::S &s);",
Index: clang/lib/Format/QualifierAlignmentFixer.cpp
===
--- clang/lib/Format/QualifierAlignmentFixer.cpp
+++ clang/lib/Format/QualifierAlignmentFixer.cpp
@@ -216,6 +216,29 @@
   if (LeftRightQualifierAlignmentFixer::isPossibleMacro(Tok->Next))
 return Tok;
 
+  auto AnalyzeTemplate =
+  [&](const FormatToken *Tok,
+  const FormatToken *StartTemplate) -> const FormatToken * {
+// Read from the TemplateOpener to TemplateCloser.
+FormatToken *EndTemplate = StartTemplate->MatchingParen;
+if (EndTemplate) {
+  // Move to the end of any template class members e.g.
+  // `Foo::iterator`.
+  if (EndTemplate->startsSequence(TT_TemplateCloser, tok::coloncolon,
+  tok::identifier)) {
+EndTemplate = EndTemplate->Next->Next;
+  }
+}
+if (EndTemplate && EndTemplate->Next &&
+!EndTemplate->Next->isOneOf(tok::equal, tok::l_paren)) {
+  insertQualifierAfter(SourceMgr, Fixes, EndTemplate, Qualifier);
+  // Remove the qualifier.
+  removeToken(SourceMgr, Fixes, Tok);
+  return Tok;
+}
+return nullptr;
+  };
+
   FormatToken *Qual = Tok->Next;
   FormatToken *LastQual = Qual;
   while (Qual && isQualifierOrType(Qual, ConfiguredQualifierTokens)) {
@@ -233,27 +256,24 @@
 return Tok;
   } else if (Tok->startsSequence(QualifierType, tok::identifier,
  TT_TemplateOpener)) {
-// Read from the TemplateOpener to
-// TemplateCloser as in const ArrayRef a; const ArrayRef &a;
-FormatToken *EndTemplate = Tok->Next->Next->MatchingParen;
-if (EndTemplate) {
-  // Move to the end of any template class members e.g.
-  // `Foo::iterator`.
-  if (EndTemplate->startsSequence(TT_TemplateCloser, tok::coloncolon,
-  tok::identifier)) {
-EndTemplate = EndTemplate->Next->Next;
-  }
-}
-if (EndTemplate && EndTemplate->Next &&
-!EndTemplate->Next->isOneOf(tok::equal, tok::l_paren)) {
-  insertQualifierAfter(SourceMgr, Fixes, EndTemplate, Qualifier);
-  // Remove the qualifier.
-  removeToken(SourceMgr, Fixes, Tok);
-  return Tok;
-}
-  } else if (Tok->startsSequence(QualifierType, tok::identifier)) {
+// `const ArrayRef a;`
+// `const ArrayRef &a;`
+const FormatToken *NewTok = AnalyzeTemplate(Tok, Tok->Next->Next);
+if (NewTok)
+  return NewTok;
+  } else if (Tok->startsSequence(QualifierType, tok::coloncolon,
+ tok::identifier, TT_TemplateOpener)) {
+// `const 

[PATCH] D125986: [clang][ASTImporter] Add support for import of UsingPackDecl.

2022-05-26 Thread Gabor Marton via Phabricator via cfe-commits
martong accepted this revision.
martong added a comment.
This revision is now accepted and ready to land.

LGTM! Thanks! And sorry for the delay in the review, please ping me next time.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125986

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


[PATCH] D102122: Support warn_unused_result on typedefs

2022-05-26 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D102122#3538668 , @dblaikie wrote:

> Sorry, with all the layers in the previous messages I'm not sure what the 
> summary is. Sounds like the summary is "this is OK to continue work in the 
> direction of supporting [[clang::warn_unused_result]] (only that spelling) 
> for typedefs in C and C++ (for compatibility with C/so that C headers, like 
> LLVM C's APIs can still be parsed as C++), while considering some of the 
> complications raised in the WG21 discussion"?

Yup! Though I agree with Richard's later comment that we could maybe also 
extend the `__attribute__((warn_unused_result))` spelling as well.

> OK, so I updated this patch with a very first draft/attempt at that - I 
> wasn't sure how to add typedef support to only the clang spelling - so I 
> created a new attribute name in the .td file (is there a better/more suitable 
> way?)

I would not go that route. Instead, I'd add it as a subject to the existing 
attribute, and then add a spelling-based restriction in 
`handleWarnUnusedResult()` to give an appropriate diagnostic if the subject is 
wrong based on the spelling used. Something like:

  if ((!AL.isGNUAttributeSyntax() || !(AL.isStandardAttributeSyntax() && 
AL.isClangScope())) && isa(D))
Diag(...);

(Note, you may need to extend ParsedAttr somewhat, I don't recall if we have 
all those helper functions explicitly.)

> and that seems to have created one follow-on issue (partly because of my 
> other choice: Clang still only /instantiates WarnUnusedResultAttr class, not 
> the new WarnUnusedResultClangAttr class - even for the clang spelling, it 
> uses the non-clang attribute class, so /most/ of the code looking at the 
> attribute class type continues to work) - that issue is in  
> SemaCXX/cxx11-attr-print.cpp it doesn't print the attribute spelling 
> correctly, it chooses the C++ standard spelling when trying to reproduce the 
> Clang spelling, I guess because the ClangAttr class isn't used. (but of 
> course if I change the code to actually instantiate the 
> WarnUnusedResultClangAttr class - then all the existing code that handles the 
> attribute class/implements the warning has to be updated to test both 
> attribute classes... )
>
> Is there another way I should be approaching this?

I'd try to stick with just the one attribute definition in Attr.td, that should 
resolve a lot of these issues.

> (oh, and there was something about a supported version number for the `has 
> attribute` checking - where would that factor into all this?)

That's likely to get involved to address. Some of the `Spelling` objects have a 
version field you can set (like `CXX11` and `C2x` spellings); that's the value 
returned by `__has_cpp_attribute` and `__has_c_attribute`. We don't have such a 
field for the `GNU` spelling and `__has_attribute`, or the `GCC` and `Clang` 
spellings. Adding one would involve going into ClangAttrEmitter.cpp and 
updating the tablegen code to support it.

I'd say we should prove that we like the feature to ourselves, and worry about 
the version number either later in this patch or in a follow-up.




Comment at: clang/include/clang/Basic/Attr.td:2943
+def WarnUnusedResultClang : InheritableAttr {
+  let Spellings = [CXX11<"clang", "warn_unused_result">];
+  let Subjects = SubjectList<[ObjCMethod, Enum, Record, FunctionLike, 
TypedefName]>;

rsmith wrote:
> Should we allow this new behavior for the GNU attribute spelling too? (Not 
> `[[gnu::..]]` but `__attribute__((warn_unused_result))`). We don't generally 
> avoid extending the meaning of `__attribute__((...))` compared to GCC.
I'd be okay with that.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D102122

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


[PATCH] D125904: [Cuda] Use fallback method to mangle externalized decls if no CUID given

2022-05-26 Thread Joseph Huber via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG1bae02b77335: [Cuda] Use fallback method to mangle 
externalized decls if no CUID given (authored by jhuber6).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125904

Files:
  clang/lib/CodeGen/CGCUDANV.cpp
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/lib/CodeGen/CodeGenModule.h
  clang/test/CodeGenCUDA/device-fun-linkage.cu
  clang/test/CodeGenCUDA/static-device-var-rdc.cu

Index: clang/test/CodeGenCUDA/static-device-var-rdc.cu
===
--- clang/test/CodeGenCUDA/static-device-var-rdc.cu
+++ clang/test/CodeGenCUDA/static-device-var-rdc.cu
@@ -2,12 +2,12 @@
 // REQUIRES: amdgpu-registered-target
 
 // RUN: %clang_cc1 -no-opaque-pointers -triple amdgcn-amd-amdhsa -fcuda-is-device \
-// RUN:   -std=c++11 -fgpu-rdc -emit-llvm -o - -x hip %s | FileCheck \
-// RUN:   -check-prefixes=DEV,INT-DEV %s
+// RUN:   -std=c++11 -fgpu-rdc -emit-llvm -o %t.nocuid.dev -x hip %s
+// RUN: cat %t.nocuid.dev | FileCheck -check-prefixes=DEV,INT-DEV %s
 
 // RUN: %clang_cc1 -no-opaque-pointers -triple x86_64-gnu-linux \
-// RUN:   -std=c++11 -fgpu-rdc -emit-llvm -o - -x hip %s | FileCheck \
-// RUN:   -check-prefixes=HOST,INT-HOST %s
+// RUN:   -std=c++11 -fgpu-rdc -emit-llvm -o %t.nocuid.host -x hip %s
+// RUN: cat %t.nocuid.host | FileCheck -check-prefixes=HOST,INT-HOST %s
 
 // RUN: %clang_cc1 -no-opaque-pointers -triple amdgcn-amd-amdhsa -fcuda-is-device -cuid=abc \
 // RUN:   -std=c++11 -fgpu-rdc -emit-llvm -o - -x hip %s > %t.dev
@@ -21,6 +21,7 @@
 // variable names.
 
 // RUN: cat %t.dev %t.host | FileCheck -check-prefix=POSTFIX %s
+// RUN: cat %t.nocuid.dev %t.nocuid.host | FileCheck -check-prefix=POSTFIX-ID %s
 
 // Negative tests.
 
@@ -48,6 +49,9 @@
 
 #include "Inputs/cuda.h"
 
+// Make sure we can still mangle with a line directive.
+#line 0 "-"
+
 // Test function scope static device variable, which should not be externalized.
 // DEV-DAG: @_ZZ6kernelPiPPKiE1w = internal addrspace(4) constant i32 1
 
@@ -56,8 +60,8 @@
 // HOST-DAG: @_ZL1y = internal global i32 undef
 
 // Test normal static device variables
-// INT-DEV-DAG: @_ZL1x = addrspace(1) externally_initialized global i32 0
-// INT-HOST-DAG: @[[DEVNAMEX:[0-9]+]] = {{.*}}c"_ZL1x\00"
+// INT-DEV-DAG: @_ZL1x[[FILEID:.*]] = addrspace(1) externally_initialized global i32 0
+// INT-HOST-DAG: @[[DEVNAMEX:[0-9]+]] = {{.*}}c"_ZL1x[[FILEID:.*]]\00"
 
 // Test externalized static device variables
 // EXT-DEV-DAG: @_ZL1x.static.[[HASH:.*]] = addrspace(1) externally_initialized global i32 0
@@ -66,6 +70,8 @@
 
 // POSTFIX: @_ZL1x.static.[[HASH:.*]] = addrspace(1) externally_initialized global i32 0
 // POSTFIX: @[[DEVNAMEX:[0-9]+]] = {{.*}}c"_ZL1x.static.[[HASH]]\00"
+// POSTFIX-ID: @_ZL1x.static.[[FILEID:.*]] = addrspace(1) externally_initialized global i32 0
+// POSTFIX-ID: @[[DEVNAMEX:[0-9]+]] = {{.*}}c"_ZL1x.static.[[FILEID]]\00"
 
 static __device__ int x;
 
@@ -75,8 +81,8 @@
 static __device__ int x2;
 
 // Test normal static device variables
-// INT-DEV-DAG: @_ZL1y = addrspace(4) externally_initialized global i32 0
-// INT-HOST-DAG: @[[DEVNAMEY:[0-9]+]] = {{.*}}c"_ZL1y\00"
+// INT-DEV-DAG: @_ZL1y[[FILEID:.*]] = addrspace(4) externally_initialized global i32 0
+// INT-HOST-DAG: @[[DEVNAMEY:[0-9]+]] = {{.*}}c"_ZL1y[[FILEID:.*]]\00"
 
 // Test externalized static device variables
 // EXT-DEV-DAG: @_ZL1y.static.[[HASH]] = addrspace(4) externally_initialized global i32 0
Index: clang/test/CodeGenCUDA/device-fun-linkage.cu
===
--- clang/test/CodeGenCUDA/device-fun-linkage.cu
+++ clang/test/CodeGenCUDA/device-fun-linkage.cu
@@ -23,10 +23,10 @@
 // Ensure that unused static device function is eliminated
 static __device__ void static_func() {}
 // NORDC-NEG-NOT: define{{.*}} void @_ZL13static_funcv()
-// RDC-NEG-NOT:   define{{.*}} void @_ZL13static_funcv()
+// RDC-NEG-NOT:   define{{.*}} void @_ZL13static_funcv[[FILEID:.*]]()
 
 // Ensure that kernel function has external or weak_odr
 // linkage regardless static specifier
 static __global__ void static_kernel() {}
 // NORDC: define void @_ZL13static_kernelv()
-// RDC:   define weak_odr void @_ZL13static_kernelv()
+// RDC:   define weak_odr void @_ZL13static_kernelv[[FILEID:.*]]()
Index: clang/lib/CodeGen/CodeGenModule.h
===
--- clang/lib/CodeGen/CodeGenModule.h
+++ clang/lib/CodeGen/CodeGenModule.h
@@ -1467,7 +1467,10 @@
   bool stopAutoInit();
 
   /// Print the postfix for externalized static variable or kernels for single
-  /// source offloading languages CUDA and HIP.
+  /// source offloading languages CUDA and HIP. The unique postfix is created
+  /// using either the CUID argument, or th

[clang] 1bae02b - [Cuda] Use fallback method to mangle externalized decls if no CUID given

2022-05-26 Thread Joseph Huber via cfe-commits

Author: Joseph Huber
Date: 2022-05-26T09:18:22-04:00
New Revision: 1bae02b77335eb1a01d9a0bb36c2b2a29dfdd5d9

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

LOG: [Cuda] Use fallback method to mangle externalized decls if no CUID given

CUDA requires that static variables be visible to the host when
offloading. However, The standard semantics of a stiatc variable dictate
that it should not be visible outside of the current file. In order to
access it from the host we need to perform "externalization" on the
static variable on the device. This requires generating a semi-unique
name that can be affixed to the variable as to not cause linker errors.

This is currently done using the CUID functionality, an MD5 hash value
set up by the clang driver. This allows us to achieve is mostly unique
ID that is unique even between multiple compilations of the same file.
However, this is not always availible. Instead, this patch uses the
unique ID from the file to generate a unique symbol name. This will
create a unique name that is consistent between the host and device side
compilations without requiring the CUID to be entered by the driver. The
one downside to this is that we are no longer stable under multiple
compilations of the same file. However, this is a very niche use-case
and is not supported by Nvidia's CUDA compiler so it likely to be good
enough.

Reviewed By: tra

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

Added: 


Modified: 
clang/lib/CodeGen/CGCUDANV.cpp
clang/lib/CodeGen/CodeGenModule.cpp
clang/lib/CodeGen/CodeGenModule.h
clang/test/CodeGenCUDA/device-fun-linkage.cu
clang/test/CodeGenCUDA/static-device-var-rdc.cu

Removed: 




diff  --git a/clang/lib/CodeGen/CGCUDANV.cpp b/clang/lib/CodeGen/CGCUDANV.cpp
index 10f8bd222b7e7..6f2679cb15e4c 100644
--- a/clang/lib/CodeGen/CGCUDANV.cpp
+++ b/clang/lib/CodeGen/CGCUDANV.cpp
@@ -285,8 +285,7 @@ std::string CGNVCUDARuntime::getDeviceSideName(const 
NamedDecl *ND) {
 
   // Make unique name for device side static file-scope variable for HIP.
   if (CGM.getContext().shouldExternalize(ND) &&
-  CGM.getLangOpts().GPURelocatableDeviceCode &&
-  !CGM.getLangOpts().CUID.empty()) {
+  CGM.getLangOpts().GPURelocatableDeviceCode) {
 SmallString<256> Buffer;
 llvm::raw_svector_ostream Out(Buffer);
 Out << DeviceSideName;

diff  --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index 703cf4edf5f56..a035e5ddd9e6d 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -1416,8 +1416,9 @@ static std::string getMangledNameImpl(CodeGenModule &CGM, 
GlobalDecl GD,
   // Make unique name for device side static file-scope variable for HIP.
   if (CGM.getContext().shouldExternalize(ND) &&
   CGM.getLangOpts().GPURelocatableDeviceCode &&
-  CGM.getLangOpts().CUDAIsDevice && !CGM.getLangOpts().CUID.empty())
+  CGM.getLangOpts().CUDAIsDevice)
 CGM.printPostfixForExternalizedDecl(Out, ND);
+
   return std::string(Out.str());
 }
 
@@ -6825,12 +6826,38 @@ bool CodeGenModule::stopAutoInit() {
 
 void CodeGenModule::printPostfixForExternalizedDecl(llvm::raw_ostream &OS,
 const Decl *D) const {
-  StringRef Tag;
   // ptxas does not allow '.' in symbol names. On the other hand, HIP prefers
   // postfix beginning with '.' since the symbol name can be demangled.
   if (LangOpts.HIP)
-Tag = (isa(D) ? ".static." : ".intern.");
+OS << (isa(D) ? ".static." : ".intern.");
   else
-Tag = (isa(D) ? "__static__" : "__intern__");
-  OS << Tag << getContext().getCUIDHash();
+OS << (isa(D) ? "__static__" : "__intern__");
+
+  // If the CUID is not specified we try to generate a unique postfix.
+  if (getLangOpts().CUID.empty()) {
+SourceManager &SM = getContext().getSourceManager();
+PresumedLoc PLoc = SM.getPresumedLoc(D->getLocation());
+assert(PLoc.isValid() && "Source location is expected to be valid.");
+
+// Get the hash of the user defined macros.
+llvm::MD5 Hash;
+llvm::MD5::MD5Result Result;
+for (const auto &Arg : PreprocessorOpts.Macros)
+  Hash.update(Arg.first);
+Hash.final(Result);
+
+// Get the UniqueID for the file containing the decl.
+llvm::sys::fs::UniqueID ID;
+if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID)) {
+  PLoc = SM.getPresumedLoc(D->getLocation(), /*UseLineDirectives=*/false);
+  assert(PLoc.isValid() && "Source location is expected to be valid.");
+  if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
+SM.getDiagnostics().Report(diag::err_cannot_open_file)
+<< PLoc.getFilename() << EC.message();
+}
+OS << llvm::format("%x

[PATCH] D126377: [clang][AArch64][SVE] Improve diagnostics for SVE operators

2022-05-26 Thread David Truby via Phabricator via cfe-commits
DavidTruby added inline comments.



Comment at: clang/lib/Sema/SemaExpr.cpp:10609-10614
-  if (RHSType->isVLSTBuiltinType() && !LHSType->isVLSTBuiltinType()) {
-auto DestType = tryScalableVectorConvert((IsCompAssign ? nullptr : &LHS),
- LHSType, RHSType);
-if (DestType == QualType())
-  return InvalidOperands(Loc, LHS, RHS);
-return DestType;

c-rhodes wrote:
> why is this removed?
This is sort of an artefact of splitting this and D126380; essentially that 
patch was motivated by the fact that this code here doesn't really do anything 
meaningful for scalable vectors. I added it for symmetry with non-scalable 
vectors but the triggers for conversions here don't really fire in meaningful 
code.
Doing this properly is resolved in D126380 so I could remove it there instead 
but this code didn't really work and doesn't have tests anyway.



Comment at: clang/test/Sema/aarch64-sve-vector-arith-ops.c:23
-  (void)(i8 + f64); // expected-error{{invalid operands to binary expression}}
-  (void)(i8 + 0);   // expected-error{{invalid operands to binary expression}}
-  (void)(i8 + 0l);  // expected-error{{invalid operands to binary expression}}

c-rhodes wrote:
> I think these vector + imm tests should be removed in D126380 but fine to 
> keep here if it's easier
Ah yes I missed this, you're correct but I will be pushing the two patches at 
the same time so I guess it doesn't matter much except for correct history? 
Happy to change it though.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126377

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


[PATCH] D126377: [clang][AArch64][SVE] Improve diagnostics for SVE operators

2022-05-26 Thread David Truby via Phabricator via cfe-commits
DavidTruby added inline comments.



Comment at: clang/lib/Sema/SemaExpr.cpp:10614
+  (!RHSType->isVLSTBuiltinType() && !RHSType->isRealType())) {
+Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
+<< LHSType << RHSType << LHS.get()->getSourceRange()

c-rhodes wrote:
> missing a test for this?
I wrote this test but seem to have forgotten to add it... Will do that! 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126377

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


[PATCH] D120244: [clang][sema] Enable first-class bool support for C2x

2022-05-26 Thread Louis Dionne via Phabricator via cfe-commits
ldionne added a comment.

In D120244#3538660 , @aaron.ballman 
wrote:

> In D120244#3538380 , @ldionne wrote:
>
>> We've started having several internal user complaints because their system 
>> headers are suddenly triggering a warning for using ``. This 
>> seems to be caused by the fact that `#warning` is surfaced to users even 
>> when the `#warning` is present in a system header (which makes sense, 
>> because otherwise there would be no way to issue a `#warning` from a system 
>> header). This ends up causing problems because users have no way to suppress 
>> the warning in the system headers they use without also disabling 
>> deprecation warnings in their own code. Is this intended? Instead, it seems 
>> to me like what we'd want is some way to mark the header as deprecated such 
>> that Clang will not flag uses of `` from within system headers, 
>> but will flag them from user code. This would be consistent with how the 
>> deprecated attributes work for classes and functions.
>>
>> Thoughts?
>
> This is what `_CLANG_DISABLE_CRT_DEPRECATION_WARNINGS` is for. We documented 
> it here: 
> https://clang.llvm.org/docs/UsersManual.html#controlling-deprecation-diagnostics-in-clang-provided-c-runtime-headers
>  but the basic idea is, if that's defined before including the header, we 
> don't issue those warnings. Does that suffice?

Well, the problem is that a user that is using some system header like 
`Foundation.h` (which includes ``) will be forced to define 
`_CLANG_DISABLE_CRT_DEPRECATION_WARNINGS`, which has two drawbacks:

1. It's annoying to them because they never used `` in their own code
2. It turns off deprecation warnings in their own code as well

In other words, the fact that this `#warning` gets out of system headers means 
that it's going to "spam" users who have no control over what their system 
headers are doing. So while the long-long term fix is for all system headers 
(like `Foundation.h`) to be C2x friendly and not include `` in newer 
standard modes, the current migration path involves a lot of spammy warnings 
for end users in the meantime. Since such a migration may or may not happen 
completely everywhere, it also means that this is probably not a "bite the 
bullet for 3 months" situation.

FWIW, although libc++ is fairly aggressive on marking functions and classes as 
deprecated, we do not try to warn for *headers* that are deprecated, because 
there is no satisfying way of doing so right now. Personally, my opinion is 
that unless we have a way to mark headers as deprecated in a way that the 
compiler can understand the semantics and have it behave roughly like a 
"deprecated attribute but on a header" (which means that this warning would 
behave just like all other compiler warnings w.r.t. system headers), it is not 
a great idea to do this. I'm very keen on deprecating stuff, however I think 
this `#warning` is not the right tool for it, because of the downsides I 
mentioned.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120244

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


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

2022-05-26 Thread Gabor Marton via Phabricator via cfe-commits
martong added a comment.

Nice work, looks promising! Once this 
https://reviews.llvm.org/D125400?vs=431909&id=431924#inline-1206369 is 
addressed I will accept.




Comment at: 
clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp:2273
+// here) may indicate failure. For this reason we do not enforce the errno
+// check (can cause false positive).
 addToFunctionSummaryMap(

You mean the enforced errno check could cause false positive?



Comment at: clang/test/Analysis/errno-stdlibraryfunctions.c:20-24
+void test2() {
+  if (access("path", 0) == -1) {
+if (errno != 0) { }
+  }
+}

steakhal wrote:
> 
+1 for @steakhal's recommendation.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125400

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


[clang] 6b8c6f1 - [clang][PR55406] CFG for coroutine

2022-05-26 Thread Nathan Sidwell via cfe-commits

Author: Nathan Sidwell
Date: 2022-05-26T06:40:43-07:00
New Revision: 6b8c6f15fdd8c147dfb7b0beb6f3d6eb98bf5772

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

LOG: [clang][PR55406] CFG for coroutine

CoreturnStmt needs to keep the operand value distinct from its use in
any return_value call, so that instantiation may rebuild the latter.
But it also needs to keep the operand value separate in the case of
calling return_void.  Code generation checks the operand value form to
determine whether it is a distincte entity to the promise call.  This
adds the same logic to CFG generation.

Reviewed By: bruno

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

Added: 
clang/test/SemaCXX/thread-safety-coro.cpp

Modified: 
clang/lib/Analysis/CFG.cpp

Removed: 




diff  --git a/clang/lib/Analysis/CFG.cpp b/clang/lib/Analysis/CFG.cpp
index fd8d1b196f114..1417b95aad931 100644
--- a/clang/lib/Analysis/CFG.cpp
+++ b/clang/lib/Analysis/CFG.cpp
@@ -3137,8 +3137,19 @@ CFGBlock *CFGBuilder::VisitReturnStmt(Stmt *S) {
   return Visit(O, AddStmtChoice::AlwaysAdd, /*ExternallyDestructed=*/true);
 return Block;
   }
-  // co_return
-  return VisitChildren(S);
+
+  CoreturnStmt *CRS = cast(S);
+  auto *B = Block;
+  if (CFGBlock *R = Visit(CRS->getPromiseCall()))
+B = R;
+
+  if (Expr *RV = CRS->getOperand())
+if (RV->getType()->isVoidType() && !isa(RV))
+  // A non-initlist void expression.
+  if (CFGBlock *R = Visit(RV))
+B = R;
+
+  return B;
 }
 
 CFGBlock *CFGBuilder::VisitSEHExceptStmt(SEHExceptStmt *ES) {

diff  --git a/clang/test/SemaCXX/thread-safety-coro.cpp 
b/clang/test/SemaCXX/thread-safety-coro.cpp
new file mode 100644
index 0..a500ad5435e4a
--- /dev/null
+++ b/clang/test/SemaCXX/thread-safety-coro.cpp
@@ -0,0 +1,47 @@
+// RUN: %clang_cc1 -fsyntax-only -verify -Wthread-safety -std=c++17 
-fcoroutines-ts %s
+
+// expected-no-diagnostics
+
+namespace std {
+template 
+struct coroutine_traits {
+  using promise_type = typename _Result::promise_type;
+};
+
+template 
+struct coroutine_handle;
+
+template <>
+struct coroutine_handle {
+  static coroutine_handle from_address(void *__a) noexcept;
+  void resume() const noexcept;
+  void destroy() const noexcept;
+};
+
+template 
+struct coroutine_handle : coroutine_handle<> {};
+
+struct suspend_always {
+  bool await_ready() const noexcept;
+  void await_suspend(coroutine_handle<>) const noexcept;
+  void await_resume() const noexcept;
+};
+} // namespace std
+
+class Task {
+public:
+  struct promise_type {
+  public:
+std::suspend_always initial_suspend() noexcept;
+std::suspend_always final_suspend() noexcept;
+
+Task get_return_object() noexcept;
+void unhandled_exception() noexcept;
+void return_value(int value) noexcept;
+  };
+};
+
+Task Foo() noexcept {
+  // ICE'd
+  co_return({ int frame = 0; 0; });
+}



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


[PATCH] D126399: [clang][PR55406] CFG for coroutine

2022-05-26 Thread Nathan Sidwell via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG6b8c6f15fdd8: [clang][PR55406] CFG for coroutine (authored 
by urnathan).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126399

Files:
  clang/lib/Analysis/CFG.cpp
  clang/test/SemaCXX/thread-safety-coro.cpp


Index: clang/test/SemaCXX/thread-safety-coro.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/thread-safety-coro.cpp
@@ -0,0 +1,47 @@
+// RUN: %clang_cc1 -fsyntax-only -verify -Wthread-safety -std=c++17 
-fcoroutines-ts %s
+
+// expected-no-diagnostics
+
+namespace std {
+template 
+struct coroutine_traits {
+  using promise_type = typename _Result::promise_type;
+};
+
+template 
+struct coroutine_handle;
+
+template <>
+struct coroutine_handle {
+  static coroutine_handle from_address(void *__a) noexcept;
+  void resume() const noexcept;
+  void destroy() const noexcept;
+};
+
+template 
+struct coroutine_handle : coroutine_handle<> {};
+
+struct suspend_always {
+  bool await_ready() const noexcept;
+  void await_suspend(coroutine_handle<>) const noexcept;
+  void await_resume() const noexcept;
+};
+} // namespace std
+
+class Task {
+public:
+  struct promise_type {
+  public:
+std::suspend_always initial_suspend() noexcept;
+std::suspend_always final_suspend() noexcept;
+
+Task get_return_object() noexcept;
+void unhandled_exception() noexcept;
+void return_value(int value) noexcept;
+  };
+};
+
+Task Foo() noexcept {
+  // ICE'd
+  co_return({ int frame = 0; 0; });
+}
Index: clang/lib/Analysis/CFG.cpp
===
--- clang/lib/Analysis/CFG.cpp
+++ clang/lib/Analysis/CFG.cpp
@@ -3137,8 +3137,19 @@
   return Visit(O, AddStmtChoice::AlwaysAdd, /*ExternallyDestructed=*/true);
 return Block;
   }
-  // co_return
-  return VisitChildren(S);
+
+  CoreturnStmt *CRS = cast(S);
+  auto *B = Block;
+  if (CFGBlock *R = Visit(CRS->getPromiseCall()))
+B = R;
+
+  if (Expr *RV = CRS->getOperand())
+if (RV->getType()->isVoidType() && !isa(RV))
+  // A non-initlist void expression.
+  if (CFGBlock *R = Visit(RV))
+B = R;
+
+  return B;
 }
 
 CFGBlock *CFGBuilder::VisitSEHExceptStmt(SEHExceptStmt *ES) {


Index: clang/test/SemaCXX/thread-safety-coro.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/thread-safety-coro.cpp
@@ -0,0 +1,47 @@
+// RUN: %clang_cc1 -fsyntax-only -verify -Wthread-safety -std=c++17 -fcoroutines-ts %s
+
+// expected-no-diagnostics
+
+namespace std {
+template 
+struct coroutine_traits {
+  using promise_type = typename _Result::promise_type;
+};
+
+template 
+struct coroutine_handle;
+
+template <>
+struct coroutine_handle {
+  static coroutine_handle from_address(void *__a) noexcept;
+  void resume() const noexcept;
+  void destroy() const noexcept;
+};
+
+template 
+struct coroutine_handle : coroutine_handle<> {};
+
+struct suspend_always {
+  bool await_ready() const noexcept;
+  void await_suspend(coroutine_handle<>) const noexcept;
+  void await_resume() const noexcept;
+};
+} // namespace std
+
+class Task {
+public:
+  struct promise_type {
+  public:
+std::suspend_always initial_suspend() noexcept;
+std::suspend_always final_suspend() noexcept;
+
+Task get_return_object() noexcept;
+void unhandled_exception() noexcept;
+void return_value(int value) noexcept;
+  };
+};
+
+Task Foo() noexcept {
+  // ICE'd
+  co_return({ int frame = 0; 0; });
+}
Index: clang/lib/Analysis/CFG.cpp
===
--- clang/lib/Analysis/CFG.cpp
+++ clang/lib/Analysis/CFG.cpp
@@ -3137,8 +3137,19 @@
   return Visit(O, AddStmtChoice::AlwaysAdd, /*ExternallyDestructed=*/true);
 return Block;
   }
-  // co_return
-  return VisitChildren(S);
+
+  CoreturnStmt *CRS = cast(S);
+  auto *B = Block;
+  if (CFGBlock *R = Visit(CRS->getPromiseCall()))
+B = R;
+
+  if (Expr *RV = CRS->getOperand())
+if (RV->getType()->isVoidType() && !isa(RV))
+  // A non-initlist void expression.
+  if (CFGBlock *R = Visit(RV))
+B = R;
+
+  return B;
 }
 
 CFGBlock *CFGBuilder::VisitSEHExceptStmt(SEHExceptStmt *ES) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 8f70d16 - [clang-format] Handle attributes in enum declaration.

2022-05-26 Thread Marek Kurdej via cfe-commits

Author: Tyler Chatow
Date: 2022-05-26T15:43:57+02:00
New Revision: 8f70d16c9ab2d7c060f5c92a31a0fc4a82349897

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

LOG: [clang-format] Handle attributes in enum declaration.

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

Ensures that attributes in the enum declaration are interpreted
correctly, for instance:

```
enum class [[nodiscard]] E {
  a,
  b
};
```

Reviewed By: MyDeveloperDay, curdeius

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

Added: 


Modified: 
clang/lib/Format/UnwrappedLineParser.cpp
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index a20562dd77a4..0611e9eace47 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -3419,11 +3419,18 @@ bool UnwrappedLineParser::parseEnum() {
 
   while (FormatTok->Tok.getIdentifierInfo() ||
  FormatTok->isOneOf(tok::colon, tok::coloncolon, tok::less,
-tok::greater, tok::comma, tok::question)) {
+tok::greater, tok::comma, tok::question,
+tok::l_square, tok::r_square)) {
 nextToken();
 // We can have macros or attributes in between 'enum' and the enum name.
 if (FormatTok->is(tok::l_paren))
   parseParens();
+if (FormatTok->is(TT_AttributeSquare)) {
+  parseSquare();
+  // Consume the closing TT_AttributeSquare.
+  if (FormatTok->Next && FormatTok->is(TT_AttributeSquare))
+nextToken();
+}
 if (FormatTok->is(tok::identifier)) {
   nextToken();
   // If there are two identifiers in a row, this is likely an elaborate

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 3621ba667818..44ef882fe7db 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -3573,6 +3573,7 @@ TEST_F(FormatTest, FormatsEnum) {
   verifyFormat("enum X E {} d;");
   verifyFormat("enum __attribute__((...)) E {} d;");
   verifyFormat("enum __declspec__((...)) E {} d;");
+  verifyFormat("enum [[nodiscard]] E {} d;");
   verifyFormat("enum {\n"
"  Bar = Foo::value\n"
"};",
@@ -3619,6 +3620,17 @@ TEST_F(FormatTest, FormatsEnum) {
"};",
EightIndent);
 
+  verifyFormat("enum [[nodiscard]] E {\n"
+   "  ONE,\n"
+   "  TWO,\n"
+   "};");
+  verifyFormat("enum [[nodiscard]] E {\n"
+   "  // Comment 1\n"
+   "  ONE,\n"
+   "  // Comment 2\n"
+   "  TWO,\n"
+   "};");
+
   // Not enums.
   verifyFormat("enum X f() {\n"
"  a();\n"
@@ -3666,7 +3678,19 @@ TEST_F(FormatTest, FormatsEnumStruct) {
   verifyFormat("enum struct X E {} d;");
   verifyFormat("enum struct __attribute__((...)) E {} d;");
   verifyFormat("enum struct __declspec__((...)) E {} d;");
+  verifyFormat("enum struct [[nodiscard]] E {} d;");
   verifyFormat("enum struct X f() {\n  a();\n  return 42;\n}");
+
+  verifyFormat("enum struct [[nodiscard]] E {\n"
+   "  ONE,\n"
+   "  TWO,\n"
+   "};");
+  verifyFormat("enum struct [[nodiscard]] E {\n"
+   "  // Comment 1\n"
+   "  ONE,\n"
+   "  // Comment 2\n"
+   "  TWO,\n"
+   "};");
 }
 
 TEST_F(FormatTest, FormatsEnumClass) {
@@ -3683,7 +3707,19 @@ TEST_F(FormatTest, FormatsEnumClass) {
   verifyFormat("enum class X E {} d;");
   verifyFormat("enum class __attribute__((...)) E {} d;");
   verifyFormat("enum class __declspec__((...)) E {} d;");
+  verifyFormat("enum class [[nodiscard]] E {} d;");
   verifyFormat("enum class X f() {\n  a();\n  return 42;\n}");
+
+  verifyFormat("enum class [[nodiscard]] E {\n"
+   "  ONE,\n"
+   "  TWO,\n"
+   "};");
+  verifyFormat("enum class [[nodiscard]] E {\n"
+   "  // Comment 1\n"
+   "  ONE,\n"
+   "  // Comment 2\n"
+   "  TWO,\n"
+   "};");
 }
 
 TEST_F(FormatTest, FormatsEnumTypes) {



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


[PATCH] D125848: [clang-format] Handle attributes in enum declaration.

2022-05-26 Thread Marek Kurdej via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG8f70d16c9ab2: [clang-format] Handle attributes in enum 
declaration. (authored by tchatow, committed by curdeius).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125848

Files:
  clang/lib/Format/UnwrappedLineParser.cpp
  clang/unittests/Format/FormatTest.cpp


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -3573,6 +3573,7 @@
   verifyFormat("enum X E {} d;");
   verifyFormat("enum __attribute__((...)) E {} d;");
   verifyFormat("enum __declspec__((...)) E {} d;");
+  verifyFormat("enum [[nodiscard]] E {} d;");
   verifyFormat("enum {\n"
"  Bar = Foo::value\n"
"};",
@@ -3619,6 +3620,17 @@
"};",
EightIndent);
 
+  verifyFormat("enum [[nodiscard]] E {\n"
+   "  ONE,\n"
+   "  TWO,\n"
+   "};");
+  verifyFormat("enum [[nodiscard]] E {\n"
+   "  // Comment 1\n"
+   "  ONE,\n"
+   "  // Comment 2\n"
+   "  TWO,\n"
+   "};");
+
   // Not enums.
   verifyFormat("enum X f() {\n"
"  a();\n"
@@ -3666,7 +3678,19 @@
   verifyFormat("enum struct X E {} d;");
   verifyFormat("enum struct __attribute__((...)) E {} d;");
   verifyFormat("enum struct __declspec__((...)) E {} d;");
+  verifyFormat("enum struct [[nodiscard]] E {} d;");
   verifyFormat("enum struct X f() {\n  a();\n  return 42;\n}");
+
+  verifyFormat("enum struct [[nodiscard]] E {\n"
+   "  ONE,\n"
+   "  TWO,\n"
+   "};");
+  verifyFormat("enum struct [[nodiscard]] E {\n"
+   "  // Comment 1\n"
+   "  ONE,\n"
+   "  // Comment 2\n"
+   "  TWO,\n"
+   "};");
 }
 
 TEST_F(FormatTest, FormatsEnumClass) {
@@ -3683,7 +3707,19 @@
   verifyFormat("enum class X E {} d;");
   verifyFormat("enum class __attribute__((...)) E {} d;");
   verifyFormat("enum class __declspec__((...)) E {} d;");
+  verifyFormat("enum class [[nodiscard]] E {} d;");
   verifyFormat("enum class X f() {\n  a();\n  return 42;\n}");
+
+  verifyFormat("enum class [[nodiscard]] E {\n"
+   "  ONE,\n"
+   "  TWO,\n"
+   "};");
+  verifyFormat("enum class [[nodiscard]] E {\n"
+   "  // Comment 1\n"
+   "  ONE,\n"
+   "  // Comment 2\n"
+   "  TWO,\n"
+   "};");
 }
 
 TEST_F(FormatTest, FormatsEnumTypes) {
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -3419,11 +3419,18 @@
 
   while (FormatTok->Tok.getIdentifierInfo() ||
  FormatTok->isOneOf(tok::colon, tok::coloncolon, tok::less,
-tok::greater, tok::comma, tok::question)) {
+tok::greater, tok::comma, tok::question,
+tok::l_square, tok::r_square)) {
 nextToken();
 // We can have macros or attributes in between 'enum' and the enum name.
 if (FormatTok->is(tok::l_paren))
   parseParens();
+if (FormatTok->is(TT_AttributeSquare)) {
+  parseSquare();
+  // Consume the closing TT_AttributeSquare.
+  if (FormatTok->Next && FormatTok->is(TT_AttributeSquare))
+nextToken();
+}
 if (FormatTok->is(tok::identifier)) {
   nextToken();
   // If there are two identifiers in a row, this is likely an elaborate


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -3573,6 +3573,7 @@
   verifyFormat("enum X E {} d;");
   verifyFormat("enum __attribute__((...)) E {} d;");
   verifyFormat("enum __declspec__((...)) E {} d;");
+  verifyFormat("enum [[nodiscard]] E {} d;");
   verifyFormat("enum {\n"
"  Bar = Foo::value\n"
"};",
@@ -3619,6 +3620,17 @@
"};",
EightIndent);
 
+  verifyFormat("enum [[nodiscard]] E {\n"
+   "  ONE,\n"
+   "  TWO,\n"
+   "};");
+  verifyFormat("enum [[nodiscard]] E {\n"
+   "  // Comment 1\n"
+   "  ONE,\n"
+   "  // Comment 2\n"
+   "  TWO,\n"
+   "};");
+
   // Not enums.
   verifyFormat("enum X f() {\n"
"  a();\n"
@@ -3666,7 +3678,19 @@
   verifyFormat("enum struct X E {} d;");
   verifyFormat("enum struct __attribute__((...)) E {} d;");
   verifyFormat("enum struct __declspec__((...)) E {} d;");
+  verifyFormat("enum struct [[nodiscar

[PATCH] D126302: [PowerPC] Diagnose invalid combination with Altivec, VSX and soft-float

2022-05-26 Thread Amy Kwan via Phabricator via cfe-commits
amyk added inline comments.



Comment at: clang/lib/Basic/Targets/PPC.cpp:452
+  if (llvm::is_contained(FeaturesVec, "-hard-float") &&
+  llvm::is_contained(FeaturesVec, "+altivec"))
+Diags.Report(diag::err_opt_not_valid_with_opt) << "-msoft-float"

Do we also need a case to represent `-msoft-float` and `-mvsx`?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126302

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


[PATCH] D126377: [clang][AArch64][SVE] Improve diagnostics for SVE operators

2022-05-26 Thread Cullen Rhodes via Phabricator via cfe-commits
c-rhodes added inline comments.



Comment at: clang/test/Sema/aarch64-sve-vector-arith-ops.c:23
-  (void)(i8 + f64); // expected-error{{invalid operands to binary expression}}
-  (void)(i8 + 0);   // expected-error{{invalid operands to binary expression}}
-  (void)(i8 + 0l);  // expected-error{{invalid operands to binary expression}}

DavidTruby wrote:
> c-rhodes wrote:
> > I think these vector + imm tests should be removed in D126380 but fine to 
> > keep here if it's easier
> Ah yes I missed this, you're correct but I will be pushing the two patches at 
> the same time so I guess it doesn't matter much except for correct history? 
> Happy to change it though.
> Ah yes I missed this, you're correct but I will be pushing the two patches at 
> the same time so I guess it doesn't matter much except for correct history? 
> Happy to change it though.

Yeah no worries keep them in here, thanks for clarifying


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126377

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


[clang] 634c8ef - [PS5] Allow dllimport/dllexport same as PS4

2022-05-26 Thread Paul Robinson via cfe-commits

Author: Paul Robinson
Date: 2022-05-26T07:01:30-07:00
New Revision: 634c8ef69a836f3436d027b03965965bad6f3ff0

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

LOG: [PS5] Allow dllimport/dllexport same as PS4

Added: 


Modified: 
clang/include/clang/Basic/TargetInfo.h
clang/lib/Sema/SemaTemplate.cpp
clang/test/CodeGen/ps4-dllimport-dllexport.c
clang/test/CodeGenCXX/dllexport-vtable-thunks.cpp
clang/test/CodeGenCXX/ps4-dllstorage-vtable-rtti.cpp
clang/test/CodeGenCXX/windows-implicit-dllexport-template-specialization.cpp
clang/test/CodeGenCXX/windows-itanium-dllexport.cpp
clang/test/Sema/dllimport.c
clang/test/SemaCXX/dllexport.cpp
clang/test/SemaCXX/dllimport.cpp
llvm/include/llvm/ADT/Triple.h

Removed: 




diff  --git a/clang/include/clang/Basic/TargetInfo.h 
b/clang/include/clang/Basic/TargetInfo.h
index 470d153d845de..e4b5f0b751c48 100644
--- a/clang/include/clang/Basic/TargetInfo.h
+++ b/clang/include/clang/Basic/TargetInfo.h
@@ -1195,12 +1195,12 @@ class TargetInfo : public virtual 
TransferrableTargetInfo,
   /// Microsoft C++ code using dllimport/export attributes?
   virtual bool shouldDLLImportComdatSymbols() const {
 return getTriple().isWindowsMSVCEnvironment() ||
-   getTriple().isWindowsItaniumEnvironment() || getTriple().isPS4();
+   getTriple().isWindowsItaniumEnvironment() || getTriple().isPS();
   }
 
   // Does this target have PS4 specific dllimport/export handling?
   virtual bool hasPS4DLLImportExport() const {
-return getTriple().isPS4() ||
+return getTriple().isPS() ||
// Windows Itanium support allows for testing the SCEI flavour of
// dllimport/export handling on a Windows system.
(getTriple().isWindowsItaniumEnvironment() &&

diff  --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp
index 4a42969c34d3f..b11b97e12403c 100644
--- a/clang/lib/Sema/SemaTemplate.cpp
+++ b/clang/lib/Sema/SemaTemplate.cpp
@@ -9760,7 +9760,7 @@ DeclResult Sema::ActOnExplicitInstantiation(
 
   if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
   (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
-   !Context.getTargetInfo().getTriple().isPS4())) {
+   !Context.getTargetInfo().getTriple().isPS())) {
 // An explicit instantiation definition can add a dll attribute to a
 // template with a previous instantiation declaration. MinGW doesn't
 // allow this.
@@ -9778,7 +9778,7 @@ DeclResult Sema::ActOnExplicitInstantiation(
 !PreviouslyDLLExported && Specialization->hasAttr();
 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
 (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
- !Context.getTargetInfo().getTriple().isPS4())) {
+ !Context.getTargetInfo().getTriple().isPS())) {
   // An explicit instantiation definition can add a dll attribute to a
   // template with a previous implicit instantiation. MinGW doesn't allow
   // this. We limit clang to only adding dllexport, to avoid potentially

diff  --git a/clang/test/CodeGen/ps4-dllimport-dllexport.c 
b/clang/test/CodeGen/ps4-dllimport-dllexport.c
index a945000e7e323..efcdc4d7a5c48 100644
--- a/clang/test/CodeGen/ps4-dllimport-dllexport.c
+++ b/clang/test/CodeGen/ps4-dllimport-dllexport.c
@@ -1,9 +1,5 @@
-// RUN: %clang_cc1 \
-// RUN: -triple x86_64-scei-ps4 \
-// RUN: -fdeclspec \
-// RUN: -Werror \
-// RUN: -emit-llvm %s -o - | \
-// RUN:   FileCheck %s
+// RUN: %clang_cc1 -triple x86_64-scei-ps4 -fdeclspec -Werror -emit-llvm %s -o 
- | FileCheck %s
+// RUN: %clang_cc1 -triple x86_64-sie-ps5  -fdeclspec -Werror -emit-llvm %s -o 
- | FileCheck %s
 
 __declspec(dllexport) int export_int;
 

diff  --git a/clang/test/CodeGenCXX/dllexport-vtable-thunks.cpp 
b/clang/test/CodeGenCXX/dllexport-vtable-thunks.cpp
index f0327567d5d08..432ef7835ddc5 100644
--- a/clang/test/CodeGenCXX/dllexport-vtable-thunks.cpp
+++ b/clang/test/CodeGenCXX/dllexport-vtable-thunks.cpp
@@ -1,6 +1,7 @@
 // RUN: %clang_cc1 -triple x86_64-windows-gnu -fdeclspec -emit-llvm -o - 
%s | FileCheck %s -DDSO_ATTRS="dso_local dllexport"
 // RUN: %clang_cc1 -triple x86_64-windows-itanium -fdeclspec -emit-llvm -o - 
%s | FileCheck %s -DDSO_ATTRS="dso_local dllexport"
 // RUN: %clang_cc1 -triple x86_64-scei-ps4-fdeclspec -emit-llvm -o - 
%s | FileCheck %s -DDSO_ATTRS=dllexport
+// RUN: %clang_cc1 -triple x86_64-sie-ps5 -fdeclspec -emit-llvm -o - 
%s | FileCheck %s -DDSO_ATTRS=dllexport
 
 struct __declspec(dllexport) A {
   virtual void m();

diff  --git a/clang/test/CodeGenCXX/ps4-dllstorage-vtable-rtti.cpp 
b/clang/test/CodeGenCXX/ps4-dllstorage-vtable-rtti.cpp
index 87d0686d34980.

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

2022-05-26 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/include/clang/Sema/DeclSpec.h:1853-1856
   /// Attrs - Attributes.
   ParsedAttributes Attrs;
 
+  ParsedAttributes DeclarationAttrs;

mboehme wrote:
> aaron.ballman wrote:
> > We should probably rename `Attrs` to be less generic and add some comments 
> > to explain why there are two lists of parsed attributes.
> I've added some comments to clarify the difference. I'm not sure what a good 
> alternative name for `Attrs` would be though. The only obvious candidate that 
> comes to mind is `DeclaratorAttrs`, but that seems pretty redundant given 
> that this is a field of `Declarator`.
> 
> I think there is actually a good case for calling the first list simply 
> `Attrs` because, unlike `DeclarationAttrs`, it applies directly to the 
> `Declarator`. This distinction is amplified by the fact that, since your 
> review, I've changed `DeclarationAttrs` to be a reference, not a by-value 
> field.
The new comment actually makes it less clear for me -- that says the attributes 
are for the `DeclSpec` but they're actually for the `Declatator` (there's no 
relationship between `Attrs` and `DS`).

Given that `DeclSpec` uses `Attrs` for its associated attributes, I think it's 
okay to use `Attrs` here for the ones associated with the `Declarator`, but the 
comment should be updated in that case.



Comment at: clang/include/clang/Sema/ParsedAttr.h:664
+  /// This may only be called if isStandardAttributeSyntax() returns true.
+  bool slidesFromDeclToDeclSpec() const;
+

Because this is now specific to standard attributes, and those don't "slide" 
under normal circumstances, it might be nice to rename this method to make it 
more clear that this should not be called normally. I don't have a strong 
opinion on what a *good* name is, but even something like 
`improperlySlidesFromDeclToDeclSpec()` would make me happy.



Comment at: clang/lib/Parse/ParseDecl.cpp:1854
+ProhibitAttributes(DeclAttrs);
+ProhibitAttributes(OriginalDeclSpecAttrs);
 DeclEnd = Tok.getLocation();

rsmith wrote:
> This looks wrong to me (both before and after this patch; you've faithfully 
> retained an incorrect behavior). If `DeclSpec` attributes aren't allowed, 
> they should be diagnosed by `ParsedFreeStandingDeclSpec`. Before and after 
> this patch, we'll diagnose attributes in a free-standing decl-specifier-seq 
> if we happened to tentatively parse them, not if we happened to parse them in 
> `ParseDeclarationSpecifiers`. For example:
> 
> ```
> __attribute__(()) struct X; // DeclSpecAttrs will be empty, no error
> void f() {
>   __attribute(()) struct X; // DeclSpecAttrs will contain the attribute 
> specifier, error
> }
> ```
> 
> Comparing to GCC's behavior for that example (which GCC silently accepts) and 
> for this one:
> 
> ```
> __attribute__((packed)) struct X; // GCC warns that packed has no meaning 
> here, clang produces a high-quality warning.
> void f() {
>   __attribute((packed)) struct X; // GCC warns that packed has no meaning 
> here, clang produces a bogus error.
> }
> ```
> 
> ... I think the right thing to do is to delete this call (along with 
> `OriginalDeclSpecAttrs`). GNU decl-specifier attributes *are* apparently 
> syntactically permitted here, but most (maybe even all?) GNU attributes don't 
> have any meaning in this position.
Good catch!



Comment at: clang/lib/Parse/ParseDecl.cpp:2188
 // Parse the next declarator.
-D.clear();
+D.clearExceptDeclarationAttrs();
 D.setCommaLoc(CommaLoc);

mboehme wrote:
> aaron.ballman wrote:
> > rsmith wrote:
> > > I wonder if a name like `prepareForNextDeclarator` or `clearForComma` 
> > > would be better here -- something that indicates why we're clearing 
> > > rather than describing how.
> > Personally, I like `prepareForNextDeclarator()` -- that's nice and clear 
> > (to me).
> Now that `Declarator` only holds a reference to the declaration attributes, 
> the additional `clearExceptDeclarationAttrs()` has become unnecessary. With 
> that, I think the original `clear()` name is acceptable?
It's fine by me.



Comment at: clang/lib/Parse/ParseDeclCXX.cpp:2716
 // Otherwise, it must be a using-declaration or an alias-declaration.
 return ParseUsingDeclaration(DeclaratorContext::Member, TemplateInfo,
+ UsingLoc, DeclEnd, DeclAttrs, AS);

mboehme wrote:
> rsmith wrote:
> > Do we need to `ProhibitAttrs(DeclSpecAttrs)` along this code path? For 
> > example:
> > ```
> > struct A { int a; };
> > struct B : A { [uuid("1234")] using A::a; };
> > ```
> > ... currently warns (for `-target x86_64-windows`) but I think with this 
> > patch we'll silently drop the `uuid` attribute on the floor.
> Good point.
> 
> Instead of doing a `ProhibitAttributes()`, I've decided to simply move the 
> `MaybeParseMic

[clang] 3087afb - [OpenCL][Doc] Misc improvements related to SPIR-V support.

2022-05-26 Thread Anastasia Stulova via cfe-commits

Author: Anastasia Stulova
Date: 2022-05-26T15:54:33+01:00
New Revision: 3087afb421bf4ca4450d8981a1410e1a09f3794a

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

LOG: [OpenCL][Doc] Misc improvements related to SPIR-V support.

Added: 


Modified: 
clang/docs/OpenCLSupport.rst
clang/docs/UsersManual.rst

Removed: 




diff  --git a/clang/docs/OpenCLSupport.rst b/clang/docs/OpenCLSupport.rst
index 6b05b5df1d0b..bcd55f6cc841 100644
--- a/clang/docs/OpenCLSupport.rst
+++ b/clang/docs/OpenCLSupport.rst
@@ -25,9 +25,19 @@ Clang also supports :ref:`the C++ for OpenCL kernel language 
`
 available.
 
-For general issues and bugs with OpenCL in clang refer to `the GitHub issue
-list
-`__.
+
+
+Missing features or with limited support
+
+
+- For general issues and bugs with OpenCL in clang refer to `the GitHub issue
+  list
+  
`__.
+
+- Command-line flag :ref:`-cl-ext ` (used to override 
extensions/
+  features supported by a target) is missing support of some functionality 
i.e. that is
+  implemented fully through libraries (see :ref:`library-based features and
+  extensions `).
 
 Internals Manual
 
@@ -213,18 +223,22 @@ indicating the presence of the extension should be added 
to clang.
 
 The default flow for adding a new extension into the frontend is to
 modify `OpenCLExtensions.def
-`_
+`__,
+containing the list of all extensions and optional features supported by
+the frontend.
 
 This will add the macro automatically and also add a field in the target
 options ``clang::TargetOptions::OpenCLFeaturesMap`` to control the exposure
 of the new extension during the compilation.
 
-Note that by default targets like `SPIR` or `X86` expose all the OpenCL
+Note that by default targets like `SPIR-V`, `SPIR` or `X86` expose all the 
OpenCL
 extensions. For all other targets the configuration has to be made explicitly.
 
 Note that the target extension support performed by clang can be overridden
 with :ref:`-cl-ext ` command-line flags.
 
+.. _opencl_ext_libs:
+
 **Library functionality**
 
 If an extension adds functionality that does not modify standard language
@@ -239,7 +253,9 @@ for more details refer to
 :ref:`the section on the OpenCL Header `. The macros indicating
 the presence of such extensions can be added in the standard header files
 conditioned on target specific predefined macros or/and language version
-predefined macros.
+predefined macros (see `feature/extension preprocessor macros defined in
+opencl-c-base.h
+`__).
 
 **Pragmas**
 
@@ -336,8 +352,9 @@ user should specify both (extension and feature) in 
command-line flag:
 
.. code-block:: console
 
- $ clang -cc1 -cl-std=CL3.0 -cl-ext=+cl_khr_fp64,+__opencl_c_fp64 ...
- $ clang -cc1 -cl-std=CL3.0 -cl-ext=-cl_khr_fp64,-__opencl_c_fp64 ...
+ $ clang -cl-std=CL3.0 -cl-ext=+cl_khr_fp64,+__opencl_c_fp64 ...
+ $ clang -cl-std=CL3.0 -cl-ext=-cl_khr_fp64,-__opencl_c_fp64 ...
+
 
 
 OpenCL C 3.0 Implementation Status

diff  --git a/clang/docs/UsersManual.rst b/clang/docs/UsersManual.rst
index 45de85d342c8..b8c468333a67 100644
--- a/clang/docs/UsersManual.rst
+++ b/clang/docs/UsersManual.rst
@@ -3065,7 +3065,7 @@ Compiling to bitcode can be done as follows:
 This will produce a file `test.bc` that can be used in vendor toolchains
 to perform machine code generation.
 
-Note that if compiled to bitcode for generic targets such as SPIR,
+Note that if compiled to bitcode for generic targets such as SPIR/SPIR-V,
 portable IR is produced that can be used with various vendor
 tools as well as open source tools such as `SPIRV-LLVM Translator
 `_
@@ -3073,15 +3073,18 @@ to produce SPIR-V binary. More details are provided in 
`the offline
 compilation from OpenCL kernel sources into SPIR-V using open source
 tools
 
`_.
+From clang 14 onwards SPIR-V can be generated directly as detailed in
+:ref:`the SPIR-V support section `.
 
 Clang currently supports OpenCL C language standards up to v2.0. Clang mainly
 supports full profile. There is only very limited support of the embedded
 profile.
-Starting from clang 9 a C++ mode is available for OpenCL (see
+From clang 9 a C++ mode is available for Ope

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

2022-05-26 Thread Jolanta Jensen via Phabricator via cfe-commits
jolanta.jensen created this revision.
Herald added a project: All.
jolanta.jensen requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

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


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D126479

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

Index: clang/test/Sema/attr-mode.c
===
--- clang/test/Sema/attr-mode.c
+++ clang/test/Sema/attr-mode.c
@@ -37,6 +37,11 @@
 __attribute__((mode(QI))) int invalid_func(void) { return 1; } // expected-error{{'mode' attribute only applies to variables, enums, typedefs, and non-static data members}}
 enum invalid_enum { A1 __attribute__((mode(QI))) }; // expected-error{{'mode' attribute only applies to}}
 
+typedef _Complex float c16a __attribute((mode(HC)));
+int c16a_test[sizeof(c16a) == 4 ? 1 : -1];
+typedef _Complex double c16b __attribute((mode(HC)));
+int c16b_test[sizeof(c16b) == 4 ? 1 : -1];
+
 typedef _Complex double c32 __attribute((mode(SC)));
 int c32_test[sizeof(c32) == 8 ? 1 : -1];
 typedef _Complex float c64 __attribute((mode(DC)));
Index: clang/test/Sema/attr-mode-vector-types.c
===
--- clang/test/Sema/attr-mode-vector-types.c
+++ clang/test/Sema/attr-mode-vector-types.c
@@ -22,8 +22,7 @@
 // expected-error@-1{{unsupported machine mode 'QC'}}
 // expected-error@-2{{type of machine mode does not match type of base type}}
 typedef _Complex float __attribute__((mode(HC))) __attribute__((vector_size(256))) vec_t9;
-// expected-error@-1{{unsupported machine mode 'HC'}}
-// expected-error@-2{{invalid vector element type '_Complex float'}}
+// expected-error@-1{{invalid vector element type '_Complex float'}}
 typedef int __attribute__((mode(SC))) __attribute__((vector_size(256))) vec_t10;
 // expected-error@-1{{type of machine mode does not match type of base type}}
 // expected-error@-2{{type of machine mode does not support base vector types}}
Index: clang/test/CodeGen/aarch64-attr-mode-complex.c
===
--- /dev/null
+++ clang/test/CodeGen/aarch64-attr-mode-complex.c
@@ -0,0 +1,47 @@
+// RUN: %clang_cc1 -triple arm64-none-linux-gnu -emit-llvm -Ofast %s -o - | FileCheck %s
+
+typedef _Complex float c16a __attribute((mode(HC)));
+typedef _Complex double c16b __attribute((mode(HC)));
+typedef _Complex float c32a __attribute((mode(SC)));
+typedef _Complex double c32b __attribute((mode(SC)));
+typedef _Complex float c64a __attribute((mode(DC)));
+typedef _Complex double c64b __attribute((mode(DC)));
+
+// CHECK: define{{.*}} { half, half } @c16_test([2 x half] noundef [[C16A:%.*]])
+// CHECK-NEXT: entry:
+// CHECK-NEXT:   [[C16B:%.*]] = extractvalue [2 x half] [[C16A]], 0
+// CHECK-NEXT:   [[C16C:%.*]] = extractvalue [2 x half] [[C16A]], 1
+// CHECK-NEXT:   [[C16D:%.*]] = fadd half [[C16B]], [[C16B]]
+// CHECK-NEXT:   [[C16E:%.*]] = fadd half [[C16C]], [[C16C]]
+// CHECK-NEXT:   [[C16F:%.*]] = insertvalue { half, half } poison, half [[C16D]], 0
+// CHECK-NEXT:   [[C16G:%.*]] = insertvalue { half, half } [[C16F]], half [[C16E]], 1
+// CHECK-NEXT:   ret { half, half } [[C16G]]
+c16b c16_test(c16a x) {
+  return x + x;
+}
+
+// CHECK: define{{.*}} { float, float } @c32_test([2 x float] noundef [[C32A:%.*]])
+// CHECK-NEXT: entry:
+// CHECK-NEXT:   [[C32B:%.*]] = extractvalue [2 x float] [[C32A]], 0
+// CHECK-NEXT:   [[C32C:%.*]] = extractvalue [2 x float] [[C32A]], 1
+// CHECK-NEXT:   [[C32D:%.*]] = fadd float [[C32B]], [[C32B]]
+// CHECK-NEXT:   [[C32E:%.*]] = fadd float [[C32C]], [[C32C]]
+// CHECK-NEXT:   [[C32F:%.*]] = insertvalue { float, float } poison, float [[C32D]], 0
+// CHECK-NEXT:   [[C32G:%.*]] = insertvalue { float, float } [[C32F]], float [[C32E]], 1
+// CHECK-NEXT:   ret { float, float } [[C32G]]
+c32b c32_test(c32a x) {
+  return x + x;
+}
+
+// CHECK: define{{.*}} { double, double } @c64_test([2 x double] noundef [[C64A:%.*]])
+// CHECK-NEXT: entry:
+// CHECK-NEXT:   [[C64B:%.*]] = extractvalue [2 x double] [[C64A]], 0
+// CHECK-NEXT:   [[C64C:%.*]] = extractvalue [2 x double] [[C64A]], 1
+// CHECK-NEXT:   [[C64D:%.*]] = fadd double [[C64B]], [[C64B]]
+// CHECK-NEXT:   [[C64E:%.*]] = fadd double [[C64C]], [[C64C]]
+// CHECK-NEXT:   [[C64F:%.*]] = insertvalue { double, double } poison, double [[C64D]], 0
+// CHECK-NEXT:   [[C64G:%.*]] = insertvalue { double, double } [[C64F]], double [[C64E]], 1
+// CHECK-NEXT:   ret { double, double } [[C64G]]
+c64b c64_test(c64a x) {
+  return x + x;
+}
Index: clang/lib/Basic/TargetInfo.cpp
===

[PATCH] D107082: [X86][RFC][WIP] Enable `_Float16` type support on X86 following the psABI

2022-05-26 Thread Phoebe Wang via Phabricator via cfe-commits
pengfei updated this revision to Diff 432298.
pengfei marked 2 inline comments as done.
pengfei added a comment.

Address Shengchen's review comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D107082

Files:
  llvm/docs/ReleaseNotes.rst
  llvm/lib/Target/X86/X86FastISel.cpp
  llvm/lib/Target/X86/X86ISelLowering.cpp
  llvm/lib/Target/X86/X86InstrAVX512.td
  llvm/lib/Target/X86/X86InstrCompiler.td
  llvm/lib/Target/X86/X86InstrInfo.cpp
  llvm/lib/Target/X86/X86InstrSSE.td
  llvm/lib/Target/X86/X86InstrVecCompiler.td
  llvm/lib/Target/X86/X86InstructionSelector.cpp
  llvm/lib/Target/X86/X86RegisterInfo.td
  llvm/test/Analysis/CostModel/X86/fptoi_sat.ll
  llvm/test/CodeGen/MIR/X86/inline-asm-registers.mir
  llvm/test/CodeGen/X86/atomic-non-integer.ll
  llvm/test/CodeGen/X86/avx512-insert-extract.ll
  llvm/test/CodeGen/X86/avx512-masked_memop-16-8.ll
  llvm/test/CodeGen/X86/avx512fp16-fp-logic.ll
  llvm/test/CodeGen/X86/callbr-asm-bb-exports.ll
  llvm/test/CodeGen/X86/cvt16-2.ll
  llvm/test/CodeGen/X86/cvt16.ll
  llvm/test/CodeGen/X86/fastmath-float-half-conversion.ll
  llvm/test/CodeGen/X86/fmf-flags.ll
  llvm/test/CodeGen/X86/fp-round.ll
  llvm/test/CodeGen/X86/fp-roundeven.ll
  llvm/test/CodeGen/X86/fp128-cast-strict.ll
  llvm/test/CodeGen/X86/fpclamptosat.ll
  llvm/test/CodeGen/X86/fpclamptosat_vec.ll
  llvm/test/CodeGen/X86/fptosi-sat-scalar.ll
  llvm/test/CodeGen/X86/fptosi-sat-vector-128.ll
  llvm/test/CodeGen/X86/fptoui-sat-scalar.ll
  llvm/test/CodeGen/X86/fptoui-sat-vector-128.ll
  llvm/test/CodeGen/X86/freeze.ll
  llvm/test/CodeGen/X86/half-constrained.ll
  llvm/test/CodeGen/X86/half.ll
  llvm/test/CodeGen/X86/pr31088.ll
  llvm/test/CodeGen/X86/pr38533.ll
  llvm/test/CodeGen/X86/pr47000.ll
  llvm/test/CodeGen/X86/scheduler-asm-moves.mir
  llvm/test/CodeGen/X86/shuffle-extract-subvector.ll
  llvm/test/CodeGen/X86/stack-folding-fp-avx512fp16-fma.ll
  llvm/test/CodeGen/X86/stack-folding-fp-avx512fp16.ll
  llvm/test/CodeGen/X86/statepoint-invoke-ra-enter-at-end.mir
  llvm/test/CodeGen/X86/vec_fp_to_int.ll
  llvm/test/CodeGen/X86/vector-half-conversions.ll
  llvm/test/CodeGen/X86/vector-reduce-fmax-nnan.ll
  llvm/test/CodeGen/X86/vector-reduce-fmin-nnan.ll
  llvm/test/MC/X86/x86_64-asm-match.s

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


[PATCH] D107082: [X86][RFC][WIP] Enable `_Float16` type support on X86 following the psABI

2022-05-26 Thread Phoebe Wang via Phabricator via cfe-commits
pengfei added inline comments.



Comment at: llvm/docs/ReleaseNotes.rst:136
 
-* ...
+* Support ``half`` type on SSE2 and above targets.
 

skan wrote:
> Just for curiosity, why is SSE2?
We are following to GCC. The more background about why chosing SSE2 can be 
found [[ https://www.mail-archive.com/gcc-patches@gcc.gnu.org/msg264242.html | 
here ]]



Comment at: llvm/lib/Target/X86/X86ISelLowering.cpp:593
 
+// Half type will be promoted by default.
+setOperationAction(ISD::FABS, MVT::f16, Promote);

skan wrote:
> Promote to which type?
If we didn't set the promote type, LLVM will automaticly find the next 
available type in the same type class as the order defined in MachineValueType.h



Comment at: llvm/lib/Target/X86/X86ISelLowering.cpp:5714
   return VT == MVT::f32 || VT == MVT::f64 || VT.isVector() ||
- (VT == MVT::f16 && Subtarget.hasFP16());
+ (VT == MVT::f16 && Subtarget.hasBWI());
 }

skan wrote:
> Add comments for `hasBWI`?
Good question! Taking a look at the caller, this is used to combine integer 
logic to FP logic instructions. Since we don't have FP logic instructions on 
f16 type, we don't need set true for it.



Comment at: llvm/lib/Target/X86/X86ISelLowering.cpp:5726
   return (VT == MVT::f64 && Subtarget.hasSSE2()) ||
- (VT == MVT::f32 && Subtarget.hasSSE1()) ||
- (VT == MVT::f16 && Subtarget.hasFP16());
+ (VT == MVT::f32 && Subtarget.hasSSE1()) || VT == MVT::f16;
 }

skan wrote:
> Why is this diffferent from `isScalarFPTypeInSSEReg` in X86FastISel.cpp?
> 
> ``` 
> bool isScalarFPTypeInSSEReg(EVT VT) const {
> return ((VT == MVT::f16 || VT == MVT::f64) && Subtarget->hasSSE2()) ||
>(VT == MVT::f32 && Subtarget->hasSSE1());
>   }
> ```
Good catch! Unlike `f32` and `f64`, we only use SSE register for `f16`. So no 
need to check the condition. I'll update the FastISel part, thanks!



Comment at: llvm/lib/Target/X86/X86InstrAVX512.td:4101
+  X86VectorVTInfo _, Predicate prd = HasAVX512> {
+  let Predicates = !if (!eq (prd, HasFP16), [HasFP16], [prd, OptForSize]) in
   def rr : AVX512PI<0x10, MRMSrcReg, (outs _.RC:$dst),

skan wrote:
> Why do we need compare the `prd` w/ `HasFP16` here?
> Couldn't we just use `[prd, OptForSize]`?
No, we can't. The predicate list AND all its predicates, which means we don't 
have a pattern for non `OptForSize` case.



Comment at: llvm/lib/Target/X86/X86RegisterInfo.td:540
 
+def FR16 : RegisterClass<"X86", [f16], 16, (add FR32)> {let Size = 32;}
+

skan wrote:
> The alignment is not same as the size?
No. This is spill size instead of alignment.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D107082

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


[PATCH] D126481: [analyzer] Handle SymbolCast in SValBuilder

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

Make the SimpleSValBuilder to be able to look up and use a constraint
for an operand of a SymbolCast, when the operand is constrained to a
const value.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D126481

Files:
  clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
  clang/test/Analysis/svalbuilder-casts.cpp


Index: clang/test/Analysis/svalbuilder-casts.cpp
===
--- /dev/null
+++ clang/test/Analysis/svalbuilder-casts.cpp
@@ -0,0 +1,51 @@
+// RUN: %clang_analyze_cc1 %s \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-checker=debug.ExprInspection \
+// RUN:   -analyzer-config support-symbolic-integer-casts=true \
+// RUN:   -analyzer-config eagerly-assume=false \
+// RUN:   -triple x86_64-unknown-linux-gnu \
+// RUN:   -verify
+
+// Test that the SValBuilder is able to look up and use a constraint for an
+// operand of a SymbolCast, when the operand is constrained to a const value.
+
+void clang_analyzer_eval(int);
+void clang_analyzer_warnIfReached();
+
+extern void abort() __attribute__((__noreturn__));
+#define assert(expr) ((expr) ? (void)(0) : abort())
+
+void test(int x) {
+  // Constrain a SymSymExpr to a constant value.
+  assert(x * x == 1);
+  // It is expected to be able to get the constraint for the operand of the
+  // cast.
+  clang_analyzer_eval((char)(x * x) == 1); // expected-warning{{TRUE}}
+  clang_analyzer_eval((long)(x * x) == 1); // expected-warning{{TRUE}}
+}
+
+void test1(int x) {
+  // Even if two lower bytes of `x` equal to zero, it doesn't mean that
+  // the entire `x` is zero. We are not able to know the exact value of x.
+  // It can be one of  65536 possible values like [0, 65536, 131072, ...]
+  // and so on. To avoid huge range sets we still assume `x` in the range
+  // [INT_MIN, INT_MAX].
+  if (!(short)x) {
+if (!x)
+  clang_analyzer_warnIfReached(); // expected-warning {{REACHABLE}}
+else
+  clang_analyzer_warnIfReached(); // expected-warning {{REACHABLE}}
+  }
+}
+
+void test2(int x) {
+  // If two lower bytes of `x` equal to zero, and we know x to be 65537,
+  // which is not truncated to short as zero. Thus the branch is infisible.
+  short s = x;
+  if (!s) {
+if (x == 65537 || x == 131073)
+  clang_analyzer_warnIfReached(); // no-warning
+else
+  clang_analyzer_warnIfReached(); // expected-warning {{REACHABLE}}
+  }
+}
Index: clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
===
--- clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
+++ clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
@@ -1278,8 +1278,6 @@
   return SVB.makeSymbolVal(S);
 }
 
-// TODO: Support SymbolCast.
-
 SVal VisitSymIntExpr(const SymIntExpr *S) {
   auto I = Cached.find(S);
   if (I != Cached.end())
@@ -1349,7 +1347,17 @@
   S, SVB.evalBinOp(State, S->getOpcode(), LHS, RHS, S->getType()));
 }
 
-// FIXME add VisitSymbolCast
+SVal VisitSymbolCast(const SymbolCast *S) {
+  auto I = Cached.find(S);
+  if (I != Cached.end())
+return I->second;
+  SVal Op = getConstOrVisit(S->getOperand());
+  if (isUnchanged(S->getOperand(), Op))
+return skip(S);
+
+  return cache(S,
+   SVB.evalCast(Op, S->getType(), S->getOperand()->getType()));
+}
 
 SVal VisitUnarySymExpr(const UnarySymExpr *S) {
   auto I = Cached.find(S);


Index: clang/test/Analysis/svalbuilder-casts.cpp
===
--- /dev/null
+++ clang/test/Analysis/svalbuilder-casts.cpp
@@ -0,0 +1,51 @@
+// RUN: %clang_analyze_cc1 %s \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-checker=debug.ExprInspection \
+// RUN:   -analyzer-config support-symbolic-integer-casts=true \
+// RUN:   -analyzer-config eagerly-assume=false \
+// RUN:   -triple x86_64-unknown-linux-gnu \
+// RUN:   -verify
+
+// Test that the SValBuilder is able to look up and use a constraint for an
+// operand of a SymbolCast, when the operand is constrained to a const value.
+
+void clang_analyzer_eval(int);
+void clang_analyzer_warnIfReached();
+
+extern void abort() __attribute__((__noreturn__));
+#define assert(expr) ((expr) ? (void)(0) : abort())
+
+void test(int x) {
+  // Constrain a SymSymExpr to a constant value.
+  assert(x * x == 1);
+  // It is expected to be able to get the constraint for the operand of the
+  // cast.
+  clang_analyzer_eval((char)(x * x) == 1); // expected-warning{{TRUE}}
+  cla

[PATCH] D125291: Introduce @llvm.threadlocal.address intrinsic to access TLS variable (1/3)

2022-05-26 Thread Nicolai Hähnle via Phabricator via cfe-commits
nhaehnle added inline comments.



Comment at: llvm/include/llvm/IR/IRBuilder.h:746-747
 
+  /// Create a call to llvm.threadlocal.address intrinsic.
+  CallInst *CreateThreadLocalAddress(Value *Ptr);
+

ChuanqiXu wrote:
> nhaehnle wrote:
> > This could be a `GlobalValue*` operand to reduce the risk of misuse, right?
> We could use `Value*` here to keep consistency with other functions and the 
> uses. We added assertion in implementations to avoid misuses.
Thanks!



Comment at: llvm/include/llvm/IR/Intrinsics.td:1393-1394
 
+def int_threadlocal_address : Intrinsic<[llvm_ptr_ty], [llvm_ptr_ty],
+[IntrNoMem, IntrWillReturn]>;
+

ChuanqiXu wrote:
> nhaehnle wrote:
> > Whether IntrNoMem is truly correct here depends on the overall solution of 
> > the thread identification issue, i.e. it depends on whether readnone 
> > implies "doesn't read thread ID". We'd best discuss that separately.
> Yeah, let's discuss this in discourse thread.
Just to follow up, based on the latest comments including that of @jyknight, 
IntroNoMem is correct.


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

https://reviews.llvm.org/D125291

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


[PATCH] D103096: [analyzer] Implement cast for ranges of symbolic integers

2022-05-26 Thread Gabor Marton via Phabricator via cfe-commits
martong added a comment.

Denys, I've created a very simple patch that makes the SValBuilder to be able 
to look up and use a constraint for an operand of a SymbolCast. That change 
passes 2 of your test cases, thus I made that a parent patch.




Comment at: clang/test/Analysis/symbol-integral-cast.cpp:12-36
+void test1(int x) {
+  // Even if two lower bytes of `x` equal to zero, it doesn't mean that
+  // the entire `x` is zero. We are not able to know the exact value of x.
+  // It can be one of  65536 possible values like [0, 65536, 131072, ...]
+  // and so on. To avoid huge range sets we still assume `x` in the range
+  // [INT_MIN, INT_MAX].
+  if (!(short)x) {

These two tests are redundant because they are handled by the Parent patch I've 
just created. https://reviews.llvm.org/D126481


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

https://reviews.llvm.org/D103096

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


[libunwind] 3d2b5b7 - [libunwind] Factor out sigreturn check condition. NFC

2022-05-26 Thread Shoaib Meenai via cfe-commits

Author: Shoaib Meenai
Date: 2022-05-26T09:12:50-07:00
New Revision: 3d2b5b7b87857b0cc4c322cfc145c46c42fe2bbf

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

LOG: [libunwind] Factor out sigreturn check condition. NFC

Create a macro for this instead of duplicating the architecture checks
everywhere. (It's a little redundant to use it when we're checking for a
specific architecture, but I'm also applying it there for consistency.)

Reviewed By: rprichard, MaskRay, #libunwind

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

Added: 


Modified: 
libunwind/src/UnwindCursor.hpp

Removed: 




diff  --git a/libunwind/src/UnwindCursor.hpp b/libunwind/src/UnwindCursor.hpp
index 7e56eff471596..01f0c404a2ac4 100644
--- a/libunwind/src/UnwindCursor.hpp
+++ b/libunwind/src/UnwindCursor.hpp
@@ -30,6 +30,11 @@
 #include 
 #endif
 
+#if defined(_LIBUNWIND_TARGET_LINUX) &&
\
+(defined(_LIBUNWIND_TARGET_AARCH64) || defined(_LIBUNWIND_TARGET_S390X))
+#define _LIBUNWIND_CHECK_LINUX_SIGRETURN 1
+#endif
+
 #if defined(_LIBUNWIND_SUPPORT_SEH_UNWIND)
 // Provide a definition for the DISPATCHER_CONTEXT struct for old (Win7 and
 // earlier) SDKs.
@@ -953,7 +958,7 @@ class UnwindCursor : public AbstractUnwindCursor{
   }
 #endif
 
-#if defined(_LIBUNWIND_TARGET_LINUX) && (defined(_LIBUNWIND_TARGET_AARCH64) || 
defined(_LIBUNWIND_TARGET_S390X))
+#if defined(_LIBUNWIND_CHECK_LINUX_SIGRETURN)
   bool setInfoForSigReturn() {
 R dummy;
 return setInfoForSigReturn(dummy);
@@ -962,14 +967,14 @@ class UnwindCursor : public AbstractUnwindCursor{
 R dummy;
 return stepThroughSigReturn(dummy);
   }
-  #if defined(_LIBUNWIND_TARGET_AARCH64)
+#if defined(_LIBUNWIND_TARGET_AARCH64)
   bool setInfoForSigReturn(Registers_arm64 &);
   int stepThroughSigReturn(Registers_arm64 &);
-  #endif
-  #if defined(_LIBUNWIND_TARGET_S390X)
+#endif
+#if defined(_LIBUNWIND_TARGET_S390X)
   bool setInfoForSigReturn(Registers_s390x &);
   int stepThroughSigReturn(Registers_s390x &);
-  #endif
+#endif
   template  bool setInfoForSigReturn(Registers &) {
 return false;
   }
@@ -1264,7 +1269,7 @@ class UnwindCursor : public AbstractUnwindCursor{
   unw_proc_info_t  _info;
   bool _unwindInfoMissing;
   bool _isSignalFrame;
-#if defined(_LIBUNWIND_TARGET_LINUX) && (defined(_LIBUNWIND_TARGET_AARCH64) || 
defined(_LIBUNWIND_TARGET_S390X))
+#if defined(_LIBUNWIND_CHECK_LINUX_SIGRETURN)
   bool _isSigReturn = false;
 #endif
 };
@@ -2471,7 +2476,7 @@ int UnwindCursor::stepWithTBTable(pint_t pc, 
tbtable *TBTable,
 
 template 
 void UnwindCursor::setInfoBasedOnIPRegister(bool isReturnAddress) {
-#if defined(_LIBUNWIND_TARGET_LINUX) && (defined(_LIBUNWIND_TARGET_AARCH64) || 
defined(_LIBUNWIND_TARGET_S390X))
+#if defined(_LIBUNWIND_CHECK_LINUX_SIGRETURN)
   _isSigReturn = false;
 #endif
 
@@ -2586,7 +2591,7 @@ void UnwindCursor::setInfoBasedOnIPRegister(bool 
isReturnAddress) {
   }
 #endif // #if defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
 
-#if defined(_LIBUNWIND_TARGET_LINUX) && (defined(_LIBUNWIND_TARGET_AARCH64) || 
defined(_LIBUNWIND_TARGET_S390X))
+#if defined(_LIBUNWIND_CHECK_LINUX_SIGRETURN)
   if (setInfoForSigReturn())
 return;
 #endif
@@ -2595,7 +2600,8 @@ void UnwindCursor::setInfoBasedOnIPRegister(bool 
isReturnAddress) {
   _unwindInfoMissing = true;
 }
 
-#if defined(_LIBUNWIND_TARGET_LINUX) && defined(_LIBUNWIND_TARGET_AARCH64)
+#if defined(_LIBUNWIND_CHECK_LINUX_SIGRETURN) &&   
\
+defined(_LIBUNWIND_TARGET_AARCH64)
 template 
 bool UnwindCursor::setInfoForSigReturn(Registers_arm64 &) {
   // Look for the sigreturn trampoline. The trampoline's body is two
@@ -2657,9 +2663,11 @@ int UnwindCursor::stepThroughSigReturn(Registers_arm64 &) {
   _isSignalFrame = true;
   return UNW_STEP_SUCCESS;
 }
-#endif // defined(_LIBUNWIND_TARGET_LINUX) && 
defined(_LIBUNWIND_TARGET_AARCH64)
+#endif // defined(_LIBUNWIND_CHECK_LINUX_SIGRETURN) &&
+   // defined(_LIBUNWIND_TARGET_AARCH64)
 
-#if defined(_LIBUNWIND_TARGET_LINUX) && defined(_LIBUNWIND_TARGET_S390X)
+#if defined(_LIBUNWIND_CHECK_LINUX_SIGRETURN) &&   
\
+defined(_LIBUNWIND_TARGET_S390X)
 template 
 bool UnwindCursor::setInfoForSigReturn(Registers_s390x &) {
   // Look for the sigreturn trampoline. The trampoline's body is a
@@ -2755,7 +2763,8 @@ int UnwindCursor::stepThroughSigReturn(Registers_s390x &) {
 
   return UNW_STEP_SUCCESS;
 }
-#endif // defined(_LIBUNWIND_TARGET_LINUX) && defined(_LIBUNWIND_TARGET_S390X)
+#endif // defined(_LIBUNWIND_CHECK_LINUX_SIGRETURN) &&
+   // defined(_LIBUNWIND_TARGET_S390X)
 
 template 
 int UnwindCursor::step() {
@@ -2765,7 +2774,7 @@ int UnwindCursor::step() {
 
   

[libunwind] 0be0a53 - [libunwind] Use process_vm_readv to avoid potential segfaults

2022-05-26 Thread Shoaib Meenai via cfe-commits

Author: Shoaib Meenai
Date: 2022-05-26T09:12:51-07:00
New Revision: 0be0a53df65cb402359c257922d80ab93d86fb40

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

LOG: [libunwind] Use process_vm_readv to avoid potential segfaults

We've observed segfaults in libunwind when attempting to check for the
Linux aarch64 sigreturn frame, presumably because of bad unwind info
leading to an incorrect PC that we attempt to read from. Use
process_vm_readv to read the memory safely instead.

The s390x code path should likely follow suit, but I don't have the
hardware to be able to test that, so I didn't modify it here either.

Reviewed By: MaskRay, rprichard, #libunwind

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

Added: 
libunwind/test/bad_unwind_info.pass.cpp

Modified: 
libunwind/src/UnwindCursor.hpp

Removed: 




diff  --git a/libunwind/src/UnwindCursor.hpp b/libunwind/src/UnwindCursor.hpp
index 01f0c404a2ac4..6e8fc45ebfa8f 100644
--- a/libunwind/src/UnwindCursor.hpp
+++ b/libunwind/src/UnwindCursor.hpp
@@ -32,6 +32,9 @@
 
 #if defined(_LIBUNWIND_TARGET_LINUX) &&
\
 (defined(_LIBUNWIND_TARGET_AARCH64) || defined(_LIBUNWIND_TARGET_S390X))
+#include 
+#include 
+#include 
 #define _LIBUNWIND_CHECK_LINUX_SIGRETURN 1
 #endif
 
@@ -2620,16 +2623,28 @@ bool UnwindCursor::setInfoForSigReturn(Registers_arm64 &) {
   //
   // [1] 
https://github.com/torvalds/linux/blob/master/arch/arm64/kernel/vdso/sigreturn.S
   const pint_t pc = static_cast(this->getReg(UNW_REG_IP));
+  // The PC might contain an invalid address if the unwind info is bad, so
+  // directly accessing it could cause a segfault. Use process_vm_readv to read
+  // the memory safely instead. process_vm_readv was added in Linux 3.2, and
+  // AArch64 supported was added in Linux 3.7, so the syscall is guaranteed to
+  // be present. Unfortunately, there are Linux AArch64 environments where the
+  // libc wrapper for the syscall might not be present (e.g. Android 5), so 
call
+  // the syscall directly instead.
+  uint32_t instructions[2];
+  struct iovec local_iov = {&instructions, sizeof instructions};
+  struct iovec remote_iov = {reinterpret_cast(pc), sizeof 
instructions};
+  long bytesRead =
+  syscall(SYS_process_vm_readv, getpid(), &local_iov, 1, &remote_iov, 1, 
0);
   // Look for instructions: mov x8, #0x8b; svc #0x0
-  if (_addressSpace.get32(pc) == 0xd2801168 &&
-  _addressSpace.get32(pc + 4) == 0xd401) {
-_info = {};
-_info.start_ip = pc;
-_info.end_ip = pc + 4;
-_isSigReturn = true;
-return true;
-  }
-  return false;
+  if (bytesRead != sizeof instructions || instructions[0] != 0xd2801168 ||
+  instructions[1] != 0xd401)
+return false;
+
+  _info = {};
+  _info.start_ip = pc;
+  _info.end_ip = pc + 4;
+  _isSigReturn = true;
+  return true;
 }
 
 template 

diff  --git a/libunwind/test/bad_unwind_info.pass.cpp 
b/libunwind/test/bad_unwind_info.pass.cpp
new file mode 100644
index 0..97427ea922737
--- /dev/null
+++ b/libunwind/test/bad_unwind_info.pass.cpp
@@ -0,0 +1,66 @@
+// -*- C++ -*-
+//===--===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+// Ensure that libunwind doesn't crash on invalid info; the Linux aarch64
+// sigreturn frame check would previously attempt to access invalid memory in
+// this scenario.
+// REQUIRES: linux && (target={{aarch64-.+}} || target={{x86_64-.+}})
+
+// GCC doesn't support __attribute__((naked)) on AArch64.
+// UNSUPPORTED: gcc
+
+// Inline assembly is incompatible with MSAN.
+// UNSUPPORTED: msan
+
+#undef NDEBUG
+#include 
+#include 
+#include 
+
+__attribute__((naked)) void bad_unwind_info() {
+#if defined(__aarch64__)
+  __asm__("// not using 0 because unwinder was already resilient to that\n"
+  "mov x8, #4\n"
+  "stp x30, x8, [sp, #-16]!\n"
+  ".cfi_def_cfa_offset 16\n"
+  "// purposely use incorrect offset for x30\n"
+  ".cfi_offset x30, -8\n"
+  "bl  stepper\n"
+  "ldr x30, [sp], #16\n"
+  ".cfi_def_cfa_offset 0\n"
+  ".cfi_restore x30\n"
+  "ret\n");
+#elif defined(__x86_64__)
+  __asm__("pushq   %rbx\n"
+  ".cfi_def_cfa_offset 16\n"
+  "movq8(%rsp), %rbx\n"
+  "# purposely corrupt return value on stack\n"
+  "movq$4, 8(%rsp)\n"
+  "callq   stepper\n"
+  "movq%rbx, 8(%rsp)\n"
+  "popq%r

[clang] 0a5cfbf - [OpenMP] Use the align clause value from 'omp allocate' for globals

2022-05-26 Thread Mike Rice via cfe-commits

Author: Mike Rice
Date: 2022-05-26T09:51:48-07:00
New Revision: 0a5cfbf7b2e82e7980b66428e88b4e28e814d7bb

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

LOG: [OpenMP] Use the align clause value from 'omp allocate' for globals

Refactor the code that handles the align clause of 'omp allocate' so
it can be used with globals as well as local variables.

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

Added: 
clang/test/OpenMP/align_clause_global_codegen.cpp

Modified: 
clang/lib/CodeGen/CGDecl.cpp
clang/lib/CodeGen/CGOpenMPRuntime.cpp
clang/lib/CodeGen/CodeGenModule.cpp
clang/lib/CodeGen/CodeGenModule.h

Removed: 




diff  --git a/clang/lib/CodeGen/CGDecl.cpp b/clang/lib/CodeGen/CGDecl.cpp
index 0f16c7f50a003..a16551e83f93b 100644
--- a/clang/lib/CodeGen/CGDecl.cpp
+++ b/clang/lib/CodeGen/CGDecl.cpp
@@ -2694,3 +2694,22 @@ void CodeGenModule::EmitOMPAllocateDecl(const 
OMPAllocateDecl *D) {
 DummyGV->eraseFromParent();
   }
 }
+
+llvm::Optional
+CodeGenModule::getOMPAllocateAlignment(const VarDecl *VD) {
+  if (const auto *AA = VD->getAttr()) {
+if (Expr *Alignment = AA->getAlignment()) {
+  unsigned UserAlign =
+  Alignment->EvaluateKnownConstInt(getContext()).getExtValue();
+  CharUnits NaturalAlign =
+  getNaturalTypeAlignment(VD->getType().getNonReferenceType());
+
+  // OpenMP5.1 pg 185 lines 7-10
+  //   Each item in the align modifier list must be aligned to the maximum
+  //   of the specified alignment and the type's natural alignment.
+  return CharUnits::fromQuantity(
+  std::max(UserAlign, NaturalAlign.getQuantity()));
+}
+  }
+  return llvm::None;
+}

diff  --git a/clang/lib/CodeGen/CGOpenMPRuntime.cpp 
b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
index 89e26b10dfae5..605d4fe76bc96 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntime.cpp
+++ b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
@@ -12185,25 +12185,15 @@ static llvm::Value *getAllocatorVal(CodeGenFunction 
&CGF,
   return AllocVal;
 }
 
-/// Given the allocate directive list item type and align clause value,
-/// return appropriate alignment.
-static llvm::Value *getAlignmentValue(CodeGenFunction &CGF, QualType 
ListItemTy,
-  const Expr *Alignment) {
-  if (!Alignment)
-return nullptr;
+/// Return the alignment from an allocate directive if present.
+static llvm::Value *getAlignmentValue(CodeGenModule &CGM, const VarDecl *VD) {
+  llvm::Optional AllocateAlignment = 
CGM.getOMPAllocateAlignment(VD);
 
-  unsigned UserAlign =
-  Alignment->EvaluateKnownConstInt(CGF.getContext()).getExtValue();
-  CharUnits NaturalAlign = CGF.CGM.getNaturalTypeAlignment(ListItemTy);
+  if (!AllocateAlignment)
+return nullptr;
 
-  // OpenMP5.1 pg 185 lines 7-10
-  //   Each item in the align modifier list must be aligned to the maximum
-  //   of the specified alignment and the type's natural alignment.
-  //
-  // If no alignment specified then use the natural alignment.
-  return llvm::ConstantInt::get(
-  CGF.CGM.SizeTy,
-  std::max(UserAlign, NaturalAlign.getQuantity()));
+  return llvm::ConstantInt::get(CGM.SizeTy,
+AllocateAlignment.getValue().getQuantity());
 }
 
 Address CGOpenMPRuntime::getAddressOfLocalVariable(CodeGenFunction &CGF,
@@ -12244,8 +12234,7 @@ Address 
CGOpenMPRuntime::getAddressOfLocalVariable(CodeGenFunction &CGF,
 const auto *AA = CVD->getAttr();
 const Expr *Allocator = AA->getAllocator();
 llvm::Value *AllocVal = getAllocatorVal(CGF, Allocator);
-llvm::Value *Alignment = getAlignmentValue(
-CGF, VD->getType().getNonReferenceType(), AA->getAlignment());
+llvm::Value *Alignment = getAlignmentValue(CGM, CVD);
 SmallVector Args;
 Args.push_back(ThreadID);
 if (Alignment)

diff  --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index a035e5ddd9e6d..b4ae266f89881 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -4738,7 +4738,12 @@ void CodeGenModule::EmitGlobalVarDefinition(const 
VarDecl *D,
   GV->setConstant(true);
   }
 
-  GV->setAlignment(getContext().getDeclAlign(D).getAsAlign());
+  CharUnits AlignVal = getContext().getDeclAlign(D);
+  // Check for alignment specifed in an 'omp allocate' directive.
+  if (llvm::Optional AlignValFromAllocate =
+  getOMPAllocateAlignment(D))
+AlignVal = AlignValFromAllocate.getValue();
+  GV->setAlignment(AlignVal.getAsAlign());
 
   // On Darwin, unlike other Itanium C++ ABI platforms, the thread-wrapper
   // function is only defined alongside the variable, not also alongside

diff  --git a/clang/lib/CodeGen/CodeGenModule.h 
b/clang/lib/CodeGen/CodeGenModule.h
index a5ec4c8f988d6..0a

[PATCH] D126426: [OpenMP] Use the align clause value from 'omp allocate' for globals

2022-05-26 Thread Mike Rice via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG0a5cfbf7b2e8: [OpenMP] Use the align clause value from 
'omp allocate' for globals (authored by mikerice).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126426

Files:
  clang/lib/CodeGen/CGDecl.cpp
  clang/lib/CodeGen/CGOpenMPRuntime.cpp
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/lib/CodeGen/CodeGenModule.h
  clang/test/OpenMP/align_clause_global_codegen.cpp

Index: clang/test/OpenMP/align_clause_global_codegen.cpp
===
--- /dev/null
+++ clang/test/OpenMP/align_clause_global_codegen.cpp
@@ -0,0 +1,61 @@
+// RUN: %clang_cc1 -emit-llvm -o - -fopenmp \
+// RUN:  -triple i386-unknown-unknown -fopenmp-version=51 %s \
+// RUN:  | FileCheck %s --check-prefixes=CHECK,CHECK-32
+
+// RUN: %clang_cc1 -emit-llvm -o - -fopenmp \
+// RUN:  -triple x86_64-unknown-linux-gnu -fopenmp-version=51 %s \
+// RUN:  | FileCheck %s --check-prefixes=CHECK,CHECK-64
+
+typedef enum omp_allocator_handle_t {
+  omp_null_allocator = 0,
+  omp_default_mem_alloc = 1,
+  omp_large_cap_mem_alloc = 2,
+  omp_const_mem_alloc = 3,
+  omp_high_bw_mem_alloc = 4,
+  omp_low_lat_mem_alloc = 5,
+  omp_cgroup_mem_alloc = 6,
+  omp_pteam_mem_alloc = 7,
+  omp_thread_mem_alloc = 8,
+  KMP_ALLOCATOR_MAX_HANDLE = __UINTPTR_MAX__
+} omp_allocator_handle_t;
+
+//
+// Should allow larger alignment.
+//
+
+// CHECK: @foo_global1 = global float 0.00e+00, align 16
+float foo_global1;
+#pragma omp allocate(foo_global1) align(16)
+
+// CHECK: @foo_global2 = global float 0.00e+00, align 16
+float foo_global2;
+#pragma omp allocate(foo_global2) allocator(omp_default_mem_alloc) align(16)
+
+// CHECK: @foo_global3 = global float 0.00e+00, align 16
+float foo_global3;
+#pragma omp allocate(foo_global3) allocator(omp_large_cap_mem_alloc) align(16)
+
+// CHECK: @foop_global1 = global ptr null, align 16
+int *foop_global1;
+#pragma omp allocate(foop_global1) align(16)
+
+//
+// Should use natural alignment when alignment specified is too small.
+//
+
+// CHECK: @foo_global4 = global float 0.00e+00, align 4
+float foo_global4;
+#pragma omp allocate(foo_global4) align(2)
+
+// CHECK: @foo_global5 = global float 0.00e+00, align 4
+float foo_global5;
+#pragma omp allocate(foo_global5) allocator(omp_default_mem_alloc) align(2)
+
+// CHECK: @foo_global6 = global float 0.00e+00, align 4
+float foo_global6;
+#pragma omp allocate(foo_global6) allocator(omp_large_cap_mem_alloc) align(2)
+
+// CHECK-32: @foop_global2 = global ptr null, align 4
+// CHECK-64: @foop_global2 = global ptr null, align 8
+int *foop_global2;
+#pragma omp allocate(foop_global2) align(2)
Index: clang/lib/CodeGen/CodeGenModule.h
===
--- clang/lib/CodeGen/CodeGenModule.h
+++ clang/lib/CodeGen/CodeGenModule.h
@@ -1365,6 +1365,9 @@
   /// \param D The allocate declaration
   void EmitOMPAllocateDecl(const OMPAllocateDecl *D);
 
+  /// Return the alignment specified in an allocate directive, if present.
+  llvm::Optional getOMPAllocateAlignment(const VarDecl *VD);
+
   /// Returns whether the given record has hidden LTO visibility and therefore
   /// may participate in (single-module) CFI and whole-program vtable
   /// optimization.
Index: clang/lib/CodeGen/CodeGenModule.cpp
===
--- clang/lib/CodeGen/CodeGenModule.cpp
+++ clang/lib/CodeGen/CodeGenModule.cpp
@@ -4738,7 +4738,12 @@
   GV->setConstant(true);
   }
 
-  GV->setAlignment(getContext().getDeclAlign(D).getAsAlign());
+  CharUnits AlignVal = getContext().getDeclAlign(D);
+  // Check for alignment specifed in an 'omp allocate' directive.
+  if (llvm::Optional AlignValFromAllocate =
+  getOMPAllocateAlignment(D))
+AlignVal = AlignValFromAllocate.getValue();
+  GV->setAlignment(AlignVal.getAsAlign());
 
   // On Darwin, unlike other Itanium C++ ABI platforms, the thread-wrapper
   // function is only defined alongside the variable, not also alongside
Index: clang/lib/CodeGen/CGOpenMPRuntime.cpp
===
--- clang/lib/CodeGen/CGOpenMPRuntime.cpp
+++ clang/lib/CodeGen/CGOpenMPRuntime.cpp
@@ -12185,25 +12185,15 @@
   return AllocVal;
 }
 
-/// Given the allocate directive list item type and align clause value,
-/// return appropriate alignment.
-static llvm::Value *getAlignmentValue(CodeGenFunction &CGF, QualType ListItemTy,
-  const Expr *Alignment) {
-  if (!Alignment)
-return nullptr;
+/// Return the alignment from an allocate directive if present.
+static llvm::Value *getAlignmentValue(CodeGenModule &CGM, const VarDecl *VD) {
+  llvm::Optional AllocateAlignment = CGM.getOMPAllocat

[PATCH] D126481: [analyzer] Handle SymbolCast in SValBuilder

2022-05-26 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added inline comments.



Comment at: clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp:1359
+  return cache(S,
+   SVB.evalCast(Op, S->getType(), S->getOperand()->getType()));
+}

Hoist this common subexpression.



Comment at: clang/test/Analysis/svalbuilder-casts.cpp:9-10
+
+// Test that the SValBuilder is able to look up and use a constraint for an
+// operand of a SymbolCast, when the operand is constrained to a const value.
+

Please ass a test case where these events happen in the execution path:
1) Have an unconstrained variable, such as a fn parameter `x`.
2) Produce a Symbolic cast of `x`, let's call it `s`.
3) Constrain `x` to some value range, let's say it must be positive.
4) Verify that the value of the Symbolic cast `s` is also constrained to be 
positive.



Comment at: clang/test/Analysis/svalbuilder-casts.cpp:30
+  // the entire `x` is zero. We are not able to know the exact value of x.
+  // It can be one of  65536 possible values like [0, 65536, 131072, ...]
+  // and so on. To avoid huge range sets we still assume `x` in the range





Comment at: clang/test/Analysis/svalbuilder-casts.cpp:34-37
+if (!x)
+  clang_analyzer_warnIfReached(); // expected-warning {{REACHABLE}}
+else
+  clang_analyzer_warnIfReached(); // expected-warning {{REACHABLE}}

`clang_analyzer_eval(x == 0); // expected-warning {{UNKNOWN}}`



Comment at: clang/test/Analysis/svalbuilder-casts.cpp:43
+  // If two lower bytes of `x` equal to zero, and we know x to be 65537,
+  // which is not truncated to short as zero. Thus the branch is infisible.
+  short s = x;





Comment at: clang/test/Analysis/svalbuilder-casts.cpp:44-45
+  // which is not truncated to short as zero. Thus the branch is infisible.
+  short s = x;
+  if (!s) {
+if (x == 65537 || x == 131073)

It took me a while to get that the `short` variable has nothing to do with the 
test.
I would recommend extending the previous example with the //short variable// to 
demonstrate that the same thing (narrowing cast) can occur by either an 
explicit cast or some implicit casts like a variable initialization/assignment.



Comment at: clang/test/Analysis/svalbuilder-casts.cpp:46-49
+if (x == 65537 || x == 131073)
+  clang_analyzer_warnIfReached(); // no-warning
+else
+  clang_analyzer_warnIfReached(); // expected-warning {{REACHABLE}}

```lang=C++
clang_analyzer_eval(x == 1);   // expected-warning {{UNKNOWN}}
clang_analyzer_eval(x == -1);  // expected-warning {{UNKNOWN}}
clang_analyzer_eval(x == 0);   // expected-warning {{FALSE}}
clang_analyzer_eval(x == 65537);   // expected-warning {{FALSE}}
clang_analyzer_eval(x == -65537);  // expected-warning {{FALSE}}
clang_analyzer_eval(x == 131073);  // expected-warning {{FALSE}}
clang_analyzer_eval(x == -131073); // expected-warning {{FALSE}}
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126481

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


[PATCH] D120244: [clang][sema] Enable first-class bool support for C2x

2022-05-26 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D120244#3539852 , @ldionne wrote:

> In D120244#3538660 , @aaron.ballman 
> wrote:
>
>> In D120244#3538380 , @ldionne 
>> wrote:
>>
>>> We've started having several internal user complaints because their system 
>>> headers are suddenly triggering a warning for using ``. This 
>>> seems to be caused by the fact that `#warning` is surfaced to users even 
>>> when the `#warning` is present in a system header (which makes sense, 
>>> because otherwise there would be no way to issue a `#warning` from a system 
>>> header). This ends up causing problems because users have no way to 
>>> suppress the warning in the system headers they use without also disabling 
>>> deprecation warnings in their own code. Is this intended? Instead, it seems 
>>> to me like what we'd want is some way to mark the header as deprecated such 
>>> that Clang will not flag uses of `` from within system headers, 
>>> but will flag them from user code. This would be consistent with how the 
>>> deprecated attributes work for classes and functions.
>>>
>>> Thoughts?
>>
>> This is what `_CLANG_DISABLE_CRT_DEPRECATION_WARNINGS` is for. We documented 
>> it here: 
>> https://clang.llvm.org/docs/UsersManual.html#controlling-deprecation-diagnostics-in-clang-provided-c-runtime-headers
>>  but the basic idea is, if that's defined before including the header, we 
>> don't issue those warnings. Does that suffice?
>
> Well, the problem is that a user that is using some system header like 
> `Foundation.h` (which includes ``) will be forced to define 
> `_CLANG_DISABLE_CRT_DEPRECATION_WARNINGS`, which has two drawbacks:
>
> 1. It's annoying to them because they never used `` in their own 
> code
> 2. It turns off deprecation warnings in their own code as well

The system header including a header that's explicitly deprecated is dubious 
practice, but that does still require some amount of timing coordination.

> In other words, the fact that this `#warning` gets out of system headers 
> means that it's going to "spam" users who have no control over what their 
> system headers are doing. So while the long-long term fix is for all system 
> headers (like `Foundation.h`) to be C2x friendly and not include 
> `` in newer standard modes, the current migration path involves a 
> lot of spammy warnings for end users in the meantime. Since such a migration 
> may or may not happen completely everywhere, it also means that this is 
> probably not a "bite the bullet for 3 months" situation.

Okay, that's a fair problem. However, the flip side is: why should C2x users 
not be told about deprecated functionality when they include the header 
directly?

> FWIW, although libc++ is fairly aggressive on marking functions and classes 
> as deprecated, we do not try to warn for *headers* that are deprecated, 
> because there is no satisfying way of doing so right now. Personally, my 
> opinion is that unless we have a way to mark headers as deprecated in a way 
> that the compiler can understand the semantics and have it behave roughly 
> like a "deprecated attribute but on a header" (which means that this warning 
> would behave just like all other compiler warnings w.r.t. system headers), it 
> is not a great idea to do this. I'm very keen on deprecating stuff, however I 
> think this `#warning` is not the right tool for it, because of the downsides 
> I mentioned.

So I take it 
https://github.com/llvm/llvm-project/blob/main/clang/lib/Headers/stdnoreturn.h 
is also an issue?

My feeling is: system headers that spam warnings are a bigger concern than not 
getting a deprecation warning, but we want that deprecation warning eventually 
because we need *some* way to deprecate headers as a whole. Not issuing 
deprecation warnings means standards bodies can't reasonably rely on users 
having been warned, so not diagnosing means "let's stick the *entire ecosystem* 
with this header file forever". So I'm thinking of walking back the `#warning` 
for the headers but with some sort of timeline as to when we can add the 
diagnostics back to the headers. Do you have an idea of what would be 
reasonable for Foundation.h?

We could maybe extend `#pragma clang deprecate` to deprecate inclusion of the 
current file so that it acts sort of like a `[[deprecated]]` attribute that 
triggers on inclusion using typical diagnostics instead of `#warning`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120244

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


[PATCH] D125052: [HLSL] Enable vector types for hlsl.

2022-05-26 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia added inline comments.



Comment at: clang/lib/Driver/ToolChains/Clang.cpp:3490
+  if (!Args.hasArg(options::OPT_dxc_no_stdinc))
+CmdArgs.push_back("-finclude-default-header");
 }

Sharing command line options is great, let's just update the help message 
straight away that this flag now also applies to HLSL: 
https://github.com/llvm/llvm-project/blob/main/clang/include/clang/Driver/Options.td#L6053


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125052

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


[PATCH] D124753: [HLSL] Set main as default entry.

2022-05-26 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia added inline comments.



Comment at: clang/test/CodeGenHLSL/entry_default.hlsl:1
+// RUN: %clang --driver-mode=dxc -Tcs_6_1 -fcgl -Fo - %s | FileCheck %s
+

Would it make sense to test the opposite i.e. if `-E` is passed in the command 
line `main` is not an entry point?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124753

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


[PATCH] D125936: [Sema] Relax an assertion in BuildStmtExpr

2022-05-26 Thread Argyrios Kyrtzidis via Phabricator via cfe-commits
akyrtzi added a comment.

The assertion was assuming "the expression doesn't need cleanups", have you 
considered adding a test that checks that the destructor of the temporary 
inside the asm statement is called, to ensure these temporaries are properly 
handled?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125936

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


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

2022-05-26 Thread Eli Friedman via Phabricator via cfe-commits
efriedma added a comment.

For FENV_ROUND, I think we should try to stick to the standard as closely as 
possible in Sema; since the standard models FENV_ROUND as a separate state, 
Sema should also model it as a separate state.  If CodeGen decides it needs to 
modify the FP environment to actually implement the standard's rules, it can 
change the way it generates code to match.  (The example in 7.6.2p5 is just 
pseudo-code; any internal state changes should be transparent to the user.)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126364

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


[PATCH] D124752: [HLSL] clang codeGen for HLSLShaderAttr.

2022-05-26 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia added inline comments.



Comment at: clang/lib/CodeGen/CGHLSLRuntime.cpp:54
+
+void clang::CodeGen::CGHLSLRuntime::setHLSLFnuctionAttributes(
+llvm::Function *F, const FunctionDecl *FD) {

I don't think you need `clang::CodeGen::`?



Comment at: clang/lib/CodeGen/CGHLSLRuntime.h:39
+
+  void setHLSLFnuctionAttributes(llvm::Function *, const FunctionDecl *);
 };

typo: `setHLSLFnuctionAttributes` -> `setHLSLFunctionAttributes`



Comment at: clang/lib/CodeGen/CodeGenModule.cpp:1654
+  if (getLangOpts().HLSL) {
+if (const FunctionDecl *FD = dyn_cast_or_null(GD.getDecl()))
+  getHLSLRuntime().setHLSLFnuctionAttributes(F, FD);

I think all attributes are expected to be added in `ConstructAttributeList`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124752

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


[clang] ce54b22 - [Clang][CoverageMapping] Fix switch counter codegen compile time explosion

2022-05-26 Thread Bruno Cardoso Lopes via cfe-commits

Author: Bruno Cardoso Lopes
Date: 2022-05-26T11:05:15-07:00
New Revision: ce54b22657f01d1c40de4941ceb6e7119848aecf

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

LOG: [Clang][CoverageMapping] Fix switch counter codegen compile time explosion

C++ generated code with huge amount of switch cases chokes badly while emitting
coverage mapping, in our specific testcase (~72k cases), it won't stop after 
hours.
After this change, the frontend job now finishes in 4.5s and shrinks down 
`@__covrec_`
by 288k when compared to disabling simplification altogether.

There's probably no good way to create a testcase for this, but it's easy to
reproduce, just add thousands of cases in the below switch, and build with
`-fprofile-instr-generate -fcoverage-mapping`.

```
enum type : int {
 FEATURE_INVALID = 0,
 FEATURE_A = 1,
 ...
};

const char *to_string(type e) {
  switch (e) {
  case type::FEATURE_INVALID: return "FEATURE_INVALID";
  case type::FEATURE_A: return "FEATURE_A";}
  ...
  }

```

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

Added: 


Modified: 
clang/lib/CodeGen/CoverageMappingGen.cpp
llvm/include/llvm/ProfileData/Coverage/CoverageMapping.h
llvm/lib/ProfileData/Coverage/CoverageMapping.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CoverageMappingGen.cpp 
b/clang/lib/CodeGen/CoverageMappingGen.cpp
index 9b81c8a670f59..8952125eeefcb 100644
--- a/clang/lib/CodeGen/CoverageMappingGen.cpp
+++ b/clang/lib/CodeGen/CoverageMappingGen.cpp
@@ -550,17 +550,18 @@ struct CounterCoverageMappingBuilder
   Counter GapRegionCounter;
 
   /// Return a counter for the subtraction of \c RHS from \c LHS
-  Counter subtractCounters(Counter LHS, Counter RHS) {
-return Builder.subtract(LHS, RHS);
+  Counter subtractCounters(Counter LHS, Counter RHS, bool Simplify = true) {
+return Builder.subtract(LHS, RHS, Simplify);
   }
 
   /// Return a counter for the sum of \c LHS and \c RHS.
-  Counter addCounters(Counter LHS, Counter RHS) {
-return Builder.add(LHS, RHS);
+  Counter addCounters(Counter LHS, Counter RHS, bool Simplify = true) {
+return Builder.add(LHS, RHS, Simplify);
   }
 
-  Counter addCounters(Counter C1, Counter C2, Counter C3) {
-return addCounters(addCounters(C1, C2), C3);
+  Counter addCounters(Counter C1, Counter C2, Counter C3,
+  bool Simplify = true) {
+return addCounters(addCounters(C1, C2, Simplify), C3, Simplify);
   }
 
   /// Return the region counter for the given statement.
@@ -1317,11 +1318,16 @@ struct CounterCoverageMappingBuilder
 const SwitchCase *Case = S->getSwitchCaseList();
 for (; Case; Case = Case->getNextSwitchCase()) {
   HasDefaultCase = HasDefaultCase || isa(Case);
-  CaseCountSum = addCounters(CaseCountSum, getRegionCounter(Case));
+  CaseCountSum =
+  addCounters(CaseCountSum, getRegionCounter(Case), 
/*Simplify=*/false);
   createSwitchCaseRegion(
   Case, getRegionCounter(Case),
   subtractCounters(ParentCount, getRegionCounter(Case)));
 }
+// Simplify is skipped while building the counters above: it can get really
+// slow on top of switches with thousands of cases. Instead, trigger
+// simplification by adding zero to the last counter.
+CaseCountSum = addCounters(CaseCountSum, Counter::getZero());
 
 // If no explicit default case exists, create a branch region to represent
 // the hidden branch, which will be added later by the CodeGen. This region

diff  --git a/llvm/include/llvm/ProfileData/Coverage/CoverageMapping.h 
b/llvm/include/llvm/ProfileData/Coverage/CoverageMapping.h
index e1f45019b1a92..e35751512245d 100644
--- a/llvm/include/llvm/ProfileData/Coverage/CoverageMapping.h
+++ b/llvm/include/llvm/ProfileData/Coverage/CoverageMapping.h
@@ -195,11 +195,11 @@ class CounterExpressionBuilder {
   ArrayRef getExpressions() const { return Expressions; }
 
   /// Return a counter that represents the expression that adds LHS and RHS.
-  Counter add(Counter LHS, Counter RHS);
+  Counter add(Counter LHS, Counter RHS, bool Simplify = true);
 
   /// Return a counter that represents the expression that subtracts RHS from
   /// LHS.
-  Counter subtract(Counter LHS, Counter RHS);
+  Counter subtract(Counter LHS, Counter RHS, bool Simplify = true);
 };
 
 using LineColPair = std::pair;

diff  --git a/llvm/lib/ProfileData/Coverage/CoverageMapping.cpp 
b/llvm/lib/ProfileData/Coverage/CoverageMapping.cpp
index 94c2bee3590cb..f9e58fd6afa50 100644
--- a/llvm/lib/ProfileData/Coverage/CoverageMapping.cpp
+++ b/llvm/lib/ProfileData/Coverage/CoverageMapping.cpp
@@ -123,13 +123,15 @@ Counter CounterExpressionBuilder::simplify(Counter 
ExpressionTree) {
   return C;
 }
 
-Counter CounterExpressionBuilder::add(Counter LHS, Counter 

[PATCH] D126345: [Clang][CoverageMapping] Fix switch case counter compile time explosion

2022-05-26 Thread Bruno Cardoso Lopes via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGce54b22657f0: [Clang][CoverageMapping] Fix switch counter 
codegen compile time explosion (authored by bruno).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126345

Files:
  clang/lib/CodeGen/CoverageMappingGen.cpp
  llvm/include/llvm/ProfileData/Coverage/CoverageMapping.h
  llvm/lib/ProfileData/Coverage/CoverageMapping.cpp


Index: llvm/lib/ProfileData/Coverage/CoverageMapping.cpp
===
--- llvm/lib/ProfileData/Coverage/CoverageMapping.cpp
+++ llvm/lib/ProfileData/Coverage/CoverageMapping.cpp
@@ -123,13 +123,15 @@
   return C;
 }
 
-Counter CounterExpressionBuilder::add(Counter LHS, Counter RHS) {
-  return simplify(get(CounterExpression(CounterExpression::Add, LHS, RHS)));
+Counter CounterExpressionBuilder::add(Counter LHS, Counter RHS, bool Simplify) 
{
+  auto Cnt = get(CounterExpression(CounterExpression::Add, LHS, RHS));
+  return Simplify ? simplify(Cnt) : Cnt;
 }
 
-Counter CounterExpressionBuilder::subtract(Counter LHS, Counter RHS) {
-  return simplify(
-  get(CounterExpression(CounterExpression::Subtract, LHS, RHS)));
+Counter CounterExpressionBuilder::subtract(Counter LHS, Counter RHS,
+   bool Simplify) {
+  auto Cnt = get(CounterExpression(CounterExpression::Subtract, LHS, RHS));
+  return Simplify ? simplify(Cnt) : Cnt;
 }
 
 void CounterMappingContext::dump(const Counter &C, raw_ostream &OS) const {
Index: llvm/include/llvm/ProfileData/Coverage/CoverageMapping.h
===
--- llvm/include/llvm/ProfileData/Coverage/CoverageMapping.h
+++ llvm/include/llvm/ProfileData/Coverage/CoverageMapping.h
@@ -195,11 +195,11 @@
   ArrayRef getExpressions() const { return Expressions; }
 
   /// Return a counter that represents the expression that adds LHS and RHS.
-  Counter add(Counter LHS, Counter RHS);
+  Counter add(Counter LHS, Counter RHS, bool Simplify = true);
 
   /// Return a counter that represents the expression that subtracts RHS from
   /// LHS.
-  Counter subtract(Counter LHS, Counter RHS);
+  Counter subtract(Counter LHS, Counter RHS, bool Simplify = true);
 };
 
 using LineColPair = std::pair;
Index: clang/lib/CodeGen/CoverageMappingGen.cpp
===
--- clang/lib/CodeGen/CoverageMappingGen.cpp
+++ clang/lib/CodeGen/CoverageMappingGen.cpp
@@ -550,17 +550,18 @@
   Counter GapRegionCounter;
 
   /// Return a counter for the subtraction of \c RHS from \c LHS
-  Counter subtractCounters(Counter LHS, Counter RHS) {
-return Builder.subtract(LHS, RHS);
+  Counter subtractCounters(Counter LHS, Counter RHS, bool Simplify = true) {
+return Builder.subtract(LHS, RHS, Simplify);
   }
 
   /// Return a counter for the sum of \c LHS and \c RHS.
-  Counter addCounters(Counter LHS, Counter RHS) {
-return Builder.add(LHS, RHS);
+  Counter addCounters(Counter LHS, Counter RHS, bool Simplify = true) {
+return Builder.add(LHS, RHS, Simplify);
   }
 
-  Counter addCounters(Counter C1, Counter C2, Counter C3) {
-return addCounters(addCounters(C1, C2), C3);
+  Counter addCounters(Counter C1, Counter C2, Counter C3,
+  bool Simplify = true) {
+return addCounters(addCounters(C1, C2, Simplify), C3, Simplify);
   }
 
   /// Return the region counter for the given statement.
@@ -1317,11 +1318,16 @@
 const SwitchCase *Case = S->getSwitchCaseList();
 for (; Case; Case = Case->getNextSwitchCase()) {
   HasDefaultCase = HasDefaultCase || isa(Case);
-  CaseCountSum = addCounters(CaseCountSum, getRegionCounter(Case));
+  CaseCountSum =
+  addCounters(CaseCountSum, getRegionCounter(Case), 
/*Simplify=*/false);
   createSwitchCaseRegion(
   Case, getRegionCounter(Case),
   subtractCounters(ParentCount, getRegionCounter(Case)));
 }
+// Simplify is skipped while building the counters above: it can get really
+// slow on top of switches with thousands of cases. Instead, trigger
+// simplification by adding zero to the last counter.
+CaseCountSum = addCounters(CaseCountSum, Counter::getZero());
 
 // If no explicit default case exists, create a branch region to represent
 // the hidden branch, which will be added later by the CodeGen. This region


Index: llvm/lib/ProfileData/Coverage/CoverageMapping.cpp
===
--- llvm/lib/ProfileData/Coverage/CoverageMapping.cpp
+++ llvm/lib/ProfileData/Coverage/CoverageMapping.cpp
@@ -123,13 +123,15 @@
   return C;
 }
 
-Counter CounterExpressionBuilder::add(Counter LHS, Counter RHS) {
-  return simplify(get(CounterExpression(CounterExpression::Add, LHS, RHS)));
+C

[PATCH] D120244: [clang][sema] Enable first-class bool support for C2x

2022-05-26 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D120244#3540598 , @aaron.ballman 
wrote:

> We could maybe extend `#pragma clang deprecate` to deprecate inclusion of the 
> current file so that it acts sort of like a `[[deprecated]]` attribute that 
> triggers on inclusion using typical diagnostics instead of `#warning`.

The tricky part to this is the pragma would effectively have to work like 
"diagnose on exit from this file when popping the lexing stack" because the 
header marks itself as being deprecated, so the compiler wouldn't KNOW to warn 
on the inclusion of the file (since it won't have seen the pragma by that 
point). It might be tricky to get the correct location for the diagnostic.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120244

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


[PATCH] D124752: [HLSL] clang codeGen for HLSLShaderAttr.

2022-05-26 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia added inline comments.



Comment at: clang/test/CodeGenHLSL/entry.hlsl:1
+// RUN: %clang --driver-mode=dxc -Tcs_6_1 -Efoo -fcgl -Fo - %s | FileCheck %s
+

Is this test here accidental?



Comment at: clang/test/CodeGenHLSL/shader_type_attr.hlsl:3
+
+// Make sure not mangle entry.
+// CHECK:define void @foo()

I struggle understand the difference in this test? Can it be merged with the 
above?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124752

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


[PATCH] D120244: [clang][sema] Enable first-class bool support for C2x

2022-05-26 Thread Louis Dionne via Phabricator via cfe-commits
ldionne added a comment.

In D120244#3540598 , @aaron.ballman 
wrote:

> The system header including a header that's explicitly deprecated is dubious 
> practice, but that does still require some amount of timing coordination.

I agree, and I'll be filing bug reports against system headers within my 
control that use ``. That is unfortunately not the majority of 
headers, though.

>> In other words, the fact that this `#warning` gets out of system headers 
>> means that it's going to "spam" users who have no control over what their 
>> system headers are doing. So while the long-long term fix is for all system 
>> headers (like `Foundation.h`) to be C2x friendly and not include 
>> `` in newer standard modes, the current migration path involves a 
>> lot of spammy warnings for end users in the meantime. Since such a migration 
>> may or may not happen completely everywhere, it also means that this is 
>> probably not a "bite the bullet for 3 months" situation.
>
> Okay, that's a fair problem. However, the flip side is: why should C2x users 
> not be told about deprecated functionality when they include the header 
> directly?

I agree -- they should be told about the deprecated functionality. The problem 
is that with the currently available technology, we have to choose between 
telling them about their use of deprecated `` AND spamming them for 
system headers' use of it, or not telling them at all. Both options have 
downsides, I think it's a matter of what we value the most.

> So I take it 
> https://github.com/llvm/llvm-project/blob/main/clang/lib/Headers/stdnoreturn.h
>  is also an issue?

I think so. I suspect it may be much less widely used, so that might be why it 
wasn't brought up.

> My feeling is: system headers that spam warnings are a bigger concern than 
> not getting a deprecation warning, but we want that deprecation warning 
> eventually because we need *some* way to deprecate headers as a whole. Not 
> issuing deprecation warnings means standards bodies can't reasonably rely on 
> users having been warned, so not diagnosing means "let's stick the *entire 
> ecosystem* with this header file forever". So I'm thinking of walking back 
> the `#warning` for the headers but with some sort of timeline as to when we 
> can add the diagnostics back to the headers. Do you have an idea of what 
> would be reasonable for Foundation.h?

I fully agree -- we need a way to deprecate headers (just like we do for 
classes and functions). My intent is really not to impair your efforts at doing 
that -- I'm just trying to point out the unfortunate tradeoff we are making. 
Regarding `Foundation.h` -- I am using this as an example, but it's really just 
the tip of the iceberg. We can probably get this one fixed within a reasonable 
time frame, however that won't change the fundamental issue.

> We could maybe extend `#pragma clang deprecate` to deprecate inclusion of the 
> current file so that it acts sort of like a `[[deprecated]]` attribute that 
> triggers on inclusion using typical diagnostics instead of `#warning`.

Yes, if that is feasible, I think something like that is exactly what we would 
need. If we had a tool like this, by the way, I would be very keen on 
deprecating some libc++ headers that we keep around like `` & friends.

So, in summary, my opinion is that we should wait until we have the appropriate 
technology (something like proposed above) before deprecating these headers. 
And once we do, then I'll be 100% supportive of efforts in that direction. But 
I'm mostly relaying user feedback here, I don't own the Clang headers so I must 
defer to your judgement.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120244

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


[PATCH] D124690: [clangd] add inlay hints for std::forward-ed parameter packs

2022-05-26 Thread Tobias Ribizel via Phabricator via cfe-commits
upsj added a comment.

I've hit a roadblock I'm not sure how to proceed with. It seems that in some 
cases, a `ParmVarDecl` of an instantiated function template indeed doesn't 
preserve the `SubstTemplateTypeParmType` type sugar allowing me to check which 
template parameter it was instantiated from. This might be related to reference 
collapsing on type deduction, since `Args...` preserves the sugar, but 
`Args&&...` doesn't. Without this ability to distinguish between expanded packs 
and normal parameters, I risk recursing into other functions and pulling up 
unrelated type names. Any ideas how to proceed here? Essentially, it's the same 
issue that @nridge already provided a partial solution for by not using 
`getNonReferenceType()`, but more complex. I would really like to avoid having 
to reconstruct parameter indices from arbitrarily many levels of template 
parameters packs from surrounding scopes.

Example where this pops up:

  cpp
  namespace std { template  T&& forward(T&); }
  struct S { S(int a); };
  template 
  T bar(Args&&... args) { return T{std::forward($fwd[[args]])...}; }
  void baz() {
int b;
bar($param[[b]]);
  }


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124690

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


[PATCH] D126137: [X86] Add support for `-mharden-sls=all`

2022-05-26 Thread Nick Desaulniers via Phabricator via cfe-commits
nickdesaulniers accepted this revision.
nickdesaulniers added a comment.
This revision is now accepted and ready to land.

Nice work Phoebe; thank you very much for this patch!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126137

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


[PATCH] D111283: [clang] template / auto deduction deduces common sugar

2022-05-26 Thread Matheus Izvekov via Phabricator via cfe-commits
mizvekov updated this revision to Diff 432339.
mizvekov added a comment.

- Just rebase, no review comments addressed yet.
- One small churn in test/SemaCXX/deduced-return-void.cpp, which is new since 
last rebase. As this patch uses the template deduction machinery to also handle 
the mutiple return statements, we detect the inconsistent deduction before 
substitution, so we don't error out trying to form the reference to void.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111283

Files:
  clang/include/clang/AST/ASTContext.h
  clang/include/clang/AST/Type.h
  clang/include/clang/Sema/Sema.h
  clang/lib/AST/ASTContext.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaExprCXX.cpp
  clang/lib/Sema/SemaOverload.cpp
  clang/lib/Sema/SemaStmt.cpp
  clang/lib/Sema/SemaTemplate.cpp
  clang/lib/Sema/SemaTemplateDeduction.cpp
  clang/test/SemaCXX/deduced-return-void.cpp
  clang/test/SemaCXX/sugared-auto.cpp
  clang/test/SemaTemplate/deduction.cpp
  libcxx/DELETE.ME

Index: libcxx/DELETE.ME
===
--- /dev/null
+++ libcxx/DELETE.ME
@@ -0,0 +1 @@
+D111283
Index: clang/test/SemaTemplate/deduction.cpp
===
--- clang/test/SemaTemplate/deduction.cpp
+++ clang/test/SemaTemplate/deduction.cpp
@@ -162,6 +162,15 @@
 
 } // namespace test4
 
+namespace test5 {
+
+template  class a {};
+template  void c(b, b);
+template  void c(a, a);
+void d() { c(a(), a()); }
+
+} // namespace test5
+
 // Verify that we can deduce enum-typed arguments correctly.
 namespace test14 {
   enum E { E0, E1 };
Index: clang/test/SemaCXX/sugared-auto.cpp
===
--- clang/test/SemaCXX/sugared-auto.cpp
+++ clang/test/SemaCXX/sugared-auto.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -fsyntax-only -verify %s -std=c++20
+// RUN: %clang_cc1 -fsyntax-only -verify %s -std=c++20 -fblocks -fenable-matrix -Wno-dynamic-exception-spec
 
 enum class N {};
 
@@ -9,6 +9,26 @@
 using Man = Animal;
 using Dog = Animal;
 
+using ManPtr = Man *;
+using DogPtr = Dog *;
+
+using SocratesPtr = ManPtr;
+
+using ConstMan = const Man;
+using ConstDog = const Dog;
+
+using Virus = void;
+using SARS = Virus;
+using Ebola = Virus;
+
+using Bacteria = float;
+using Bacilli = Bacteria;
+using Vibrio = Bacteria;
+
+struct Plant;
+using Gymnosperm = Plant;
+using Angiosperm = Plant;
+
 namespace variable {
 
 auto x1 = Animal();
@@ -41,3 +61,115 @@
 N t3 = x3; // expected-error {{lvalue of type 'Animal' (aka 'int')}}
 
 } // namespace function_basic
+
+namespace function_multiple_basic {
+
+N t1 = [] { // expected-error {{rvalue of type 'Animal' (aka 'int')}}
+  if (true)
+return Man();
+  return Dog();
+}();
+
+N t2 = []() -> decltype(auto) { // expected-error {{rvalue of type 'Animal' (aka 'int')}}
+  if (true)
+return Man();
+  return Dog();
+}();
+
+N t3 = [] { // expected-error {{rvalue of type 'Animal' (aka 'int')}}
+  if (true)
+return Dog();
+  auto x = Man();
+  return x;
+}();
+
+N t4 = [] { // expected-error {{rvalue of type 'int'}}
+  if (true)
+return Dog();
+  return 1;
+}();
+
+N t5 = [] { // expected-error {{rvalue of type 'Virus' (aka 'void')}}
+  if (true)
+return Ebola();
+  return SARS();
+}();
+
+N t6 = [] { // expected-error {{rvalue of type 'void'}}
+  if (true)
+return SARS();
+  return;
+}();
+
+} // namespace function_multiple_basic
+
+#define TEST_AUTO(X, A, B) \
+  auto X(A a, B b) {   \
+if (0) \
+  return a;\
+if (0) \
+  return b;\
+return N();\
+  }
+#define TEST_DAUTO(X, A, B) \
+  decltype(auto) X(A a, B b) {  \
+if (0)  \
+  return static_cast(a); \
+if (0)  \
+  return static_cast(b); \
+return N(); \
+  }
+
+namespace misc {
+
+TEST_AUTO(t1, ManPtr, DogPtr)  // expected-error {{but deduced as 'Animal *' (aka 'int *')}}
+TEST_AUTO(t2, ManPtr, int *)   // expected-error {{but deduced as 'int *'}}
+TEST_AUTO(t3, SocratesPtr, ManPtr) // expected-error {{but deduced as 'ManPtr' (aka 'int *')}}
+
+TEST_AUTO(t4, _Atomic(Man), _Atomic(Dog)) // expected-error {{but deduced as '_Atomic(Animal)'}}
+
+using block_man = void (^)(Man);
+using block_dog = void (^)(Dog);
+TEST_AUTO(t5, block_man, block_dog) // expected-error {{but deduced as 'void (^)(Animal)'}}
+
+using fp1 = SARS (*)(Man, DogPtr) throw(Vibrio);
+using fp2 = Ebola (*)(Dog, ManPtr) throw(Bacilli);
+TEST_AUTO(t6, fp1, fp2); // expected-error {{but deduced as 'Virus (*)(Animal, Animal *) throw(Bacteria)' (aka 'void (*)(int, int *) throw(Bacteria)')}}
+
+using fp3 = SARS (*)() throw(Man);
+using fp4 = Ebola (*)() throw(Vibrio);
+auto t7(fp3 a, fp4 b) {
+  if (false)
+return true ? a : b;
+  if (false)
+return a;
+  return

[PATCH] D120244: [clang][sema] Enable first-class bool support for C2x

2022-05-26 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D120244#3540703 , @ldionne wrote:

> In D120244#3540598 , @aaron.ballman 
> wrote:
>
>> The system header including a header that's explicitly deprecated is dubious 
>> practice, but that does still require some amount of timing coordination.
>
> I agree, and I'll be filing bug reports against system headers within my 
> control that use ``. That is unfortunately not the majority of 
> headers, though.

Thanks!

>> My feeling is: system headers that spam warnings are a bigger concern than 
>> not getting a deprecation warning, but we want that deprecation warning 
>> eventually because we need *some* way to deprecate headers as a whole. Not 
>> issuing deprecation warnings means standards bodies can't reasonably rely on 
>> users having been warned, so not diagnosing means "let's stick the *entire 
>> ecosystem* with this header file forever". So I'm thinking of walking back 
>> the `#warning` for the headers but with some sort of timeline as to when we 
>> can add the diagnostics back to the headers. Do you have an idea of what 
>> would be reasonable for Foundation.h?
>
> I fully agree -- we need a way to deprecate headers (just like we do for 
> classes and functions). My intent is really not to impair your efforts at 
> doing that -- I'm just trying to point out the unfortunate tradeoff we are 
> making. Regarding `Foundation.h` -- I am using this as an example, but it's 
> really just the tip of the iceberg. We can probably get this one fixed within 
> a reasonable time frame, however that won't change the fundamental issue.

Agreed, the issue is that `#warning` is effectively useless in system headers.  
:-(

>> We could maybe extend `#pragma clang deprecate` to deprecate inclusion of 
>> the current file so that it acts sort of like a `[[deprecated]]` attribute 
>> that triggers on inclusion using typical diagnostics instead of `#warning`.
>
> Yes, if that is feasible, I think something like that is exactly what we 
> would need. If we had a tool like this, by the way, I would be very keen on 
> deprecating some libc++ headers that we keep around like `` & 
> friends.

I'll explore just how possible this is. There's all sorts of neat problems with 
it, like header guards/`#pragma once` meaning the header file's contents aren't 
scanned on a second inclusion (so we need to keep a list of already-included 
files that are deprecated), and truly awful things like:

  // Foo.h, which has no header guard because it's like assert.h
  #if WHATEVER
  ...
  #else
  #pragma clang deprecate_header
  #endif
  
  // main.c
  #define WHATEVER
  #include "Foo.h"
  #undef WHATEVER
  #include "Foo.h"
  #define WHATEVER
  #include "Foo.h"
  #endif

and so on.

> So, in summary, my opinion is that we should wait until we have the 
> appropriate technology (something like proposed above) before deprecating 
> these headers. And once we do, then I'll be 100% supportive of efforts in 
> that direction. But I'm mostly relaying user feedback here, I don't own the 
> Clang headers so I must defer to your judgement.

The feedback from your users (and you) is very much appreciated; this is 
exactly the kind of feedback I hoped to get by doing those changes early in the 
release (so I still have time to address issues like this before it's too 
late). So thank you for bringing this up and the discussion around it!

I'll roll back the `#warning` use and report back when that's done.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120244

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


[clang] 6273b5c - Roll back use of #warning for header deprecations

2022-05-26 Thread Aaron Ballman via cfe-commits

Author: Aaron Ballman
Date: 2022-05-26T14:51:39-04:00
New Revision: 6273b5cbcdd346a833120c55061ab56f61827068

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

LOG: Roll back use of #warning for header deprecations

e5ccd668019888de2704ae670da88a7be8cf7e0f and
5029dce492b3cf3ac191eda0b5bf268c3acac2e0 added deprecation warnings to
the  and  headers, respectively, because the
headers are deprecated in C2x.

However, there are system headers that include these headers
unconditionally, and #warning diagnostics within system headers are
shown to users instead of suppressed, which means these deprecation
warnings are being triggered in circumstances that users have no
control over except to disable all the warnings through the
_CLANG_DISABLE_CRT_DEPRECATION_WARNINGS macro or other means.

This removes the problematic #warning uses until we find a more
palatable solution.

Added: 


Modified: 
clang/lib/Headers/stdbool.h
clang/lib/Headers/stdnoreturn.h
clang/test/Headers/stdbool.c
clang/test/Sema/c2x-noreturn.c

Removed: 




diff  --git a/clang/lib/Headers/stdbool.h b/clang/lib/Headers/stdbool.h
index ecf560218c3b5..f0e588532e166 100644
--- a/clang/lib/Headers/stdbool.h
+++ b/clang/lib/Headers/stdbool.h
@@ -13,9 +13,9 @@
 #define __bool_true_false_are_defined 1
 
 #if __STDC_VERSION__ > 201710L
-#if !defined(_CLANG_DISABLE_CRT_DEPRECATION_WARNINGS)
-#warning "the  header is deprecated in C2x"
-#endif /* !defined(_CLANG_DISABLE_CRT_DEPRECATION_WARNINGS) */
+/* FIXME: We should be issuing a deprecation warning here, but cannot yet due
+ * to system headers which include this header file unconditionally.
+ */
 #elif !defined(__cplusplus)
 #define bool _Bool
 #define true 1

diff  --git a/clang/lib/Headers/stdnoreturn.h b/clang/lib/Headers/stdnoreturn.h
index 944e6904c7df6..7d19fa7b2f2b9 100644
--- a/clang/lib/Headers/stdnoreturn.h
+++ b/clang/lib/Headers/stdnoreturn.h
@@ -21,7 +21,9 @@
followed by code that writes [[noreturn]]. The issue with such code is not
with the attribute, or the use of 'noreturn', but the inclusion of the
header. */
-#warning "the '' header is deprecated in C2x; either use the 
'_Noreturn' keyword or the '[[noreturn]]' attribute"
+/* FIXME: We should be issuing a deprecation warning here, but cannot yet due
+ * to system headers which include this header file unconditionally.
+ */
 #endif
 
 #endif /* __STDNORETURN_H */

diff  --git a/clang/test/Headers/stdbool.c b/clang/test/Headers/stdbool.c
index 1ac94dc67a28f..a5189633c3596 100644
--- a/clang/test/Headers/stdbool.c
+++ b/clang/test/Headers/stdbool.c
@@ -1,6 +1,5 @@
 // RUN: %clang_cc1 -fgnuc-version=4.2.1 -std=c11 -E -dM %s 2>&1 | FileCheck 
--check-prefix=CHECK-C11 %s
 // RUN: %clang_cc1 -fgnuc-version=4.2.1 -std=c2x -E -dM %s 2>&1 | FileCheck 
--check-prefix=CHECK-C2X %s
-// RUN: %clang_cc1 -fgnuc-version=4.2.1 -std=c2x -E -dM 
-D_CLANG_DISABLE_CRT_DEPRECATION_WARNINGS %s 2>&1 | FileCheck 
--check-prefix=CHECK-C2X-CRT %s
 
 #include 
 
@@ -8,12 +7,6 @@
 // CHECK-C11: #define false 0
 // CHECK-C11: #define true 1
 
-// CHECK-C2X: warning "the  header is deprecated
 // CHECK-C2X-NOT: #define bool
 // CHECK-C2X-NOT: #define true
-// CHECK-C2X-NOT: #define falsea
-
-// CHECK-C2X-CRT-NOT: warning "the  header is deprecated
-// CHECK-C2X-CRT-NOT: #define bool
-// CHECK-C2X-CRT-NOT: #define true
-// CHECK-C2X-CRT-NOT: #define false
+// CHECK-C2X-NOT: #define false

diff  --git a/clang/test/Sema/c2x-noreturn.c b/clang/test/Sema/c2x-noreturn.c
index 6c119736f6454..cc276877c2860 100644
--- a/clang/test/Sema/c2x-noreturn.c
+++ b/clang/test/Sema/c2x-noreturn.c
@@ -36,7 +36,7 @@ _Noreturn void func1(void); // ok, using the function 
specifier
 [[_Noreturn]] void func3(void); // all-warning {{the '[[_Noreturn]]' attribute 
spelling is deprecated in C2x; use '[[noreturn]]' instead}}
 
 // Test the behavior of including 
-#include  // c2x-warning@stdnoreturn.h:* {{the 
'' header is deprecated in C2x; either use the '_Noreturn' 
keyword or the '[[noreturn]]' attribute}}
+#include 
 
 [[noreturn]] void func6(void);
 



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


[PATCH] D126100: Add sanitizer-specific GlobalValue attributes.

2022-05-26 Thread Mitch Phillips via Phabricator via cfe-commits
hctim added a comment.

(friendly ping)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126100

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


[PATCH] D120244: [clang][sema] Enable first-class bool support for C2x

2022-05-26 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D120244#3540746 , @aaron.ballman 
wrote:

> I'll roll back the `#warning` use and report back when that's done.

I've rolled it back in 6273b5cbcdd346a833120c55061ab56f61827068 
.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120244

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


[clang] 48ca3a5 - [OpenMP] Extend omp teams to permit nested omp atomic

2022-05-26 Thread Joel E. Denny via cfe-commits

Author: Joel E. Denny
Date: 2022-05-26T14:59:16-04:00
New Revision: 48ca3a5ebb156ccb776eea399138b7cda4d13395

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

LOG: [OpenMP] Extend omp teams to permit nested omp atomic

OpenMP 5.2, sec. 10.2 "teams Construct", p. 232, L9-12 restricts what
regions can be strictly nested within a `teams` construct.  This patch
relaxes Clang's enforcement of this restriction in the case of nested
`atomic` constructs unless `-fno-openmp-extensions` is specified.
Cases like the following then seem to work fine with no additional
implementation changes:

```
 #pragma omp target teams map(tofrom:x)
 #pragma omp atomic update
 x++;
```

Reviewed By: ABataev

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

Added: 
openmp/libomptarget/test/offloading/target-teams-atomic.c
openmp/runtime/test/teams/teams-atomic.c

Modified: 
clang/lib/Sema/SemaOpenMP.cpp
clang/test/OpenMP/nesting_of_regions.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaOpenMP.cpp b/clang/lib/Sema/SemaOpenMP.cpp
index 09c187f24a802..753decfb167cd 100644
--- a/clang/lib/Sema/SemaOpenMP.cpp
+++ b/clang/lib/Sema/SemaOpenMP.cpp
@@ -4975,9 +4975,13 @@ static bool checkNestingOfRegions(Sema &SemaRef, const 
DSAStackTy *Stack,
   // omp_get_num_teams() regions, and omp_get_team_num() regions are the
   // only OpenMP regions that may be strictly nested inside the teams
   // region.
+  //
+  // As an extension, we permit atomic within teams as well.
   NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
   !isOpenMPDistributeDirective(CurrentRegion) &&
-  CurrentRegion != OMPD_loop;
+  CurrentRegion != OMPD_loop &&
+  !(SemaRef.getLangOpts().OpenMPExtensions &&
+CurrentRegion == OMPD_atomic);
   Recommend = ShouldBeInParallelRegion;
 }
 if (!NestingProhibited && CurrentRegion == OMPD_loop) {

diff  --git a/clang/test/OpenMP/nesting_of_regions.cpp 
b/clang/test/OpenMP/nesting_of_regions.cpp
index 7e23e00548197..3581b05e3a043 100644
--- a/clang/test/OpenMP/nesting_of_regions.cpp
+++ b/clang/test/OpenMP/nesting_of_regions.cpp
@@ -1,10 +1,11 @@
-// RUN: %clang_cc1 -fsyntax-only -fopenmp -fopenmp-version=45 
-verify=expected,omp45,omp45warn %s
-// RUN: %clang_cc1 -fsyntax-only -fopenmp -verify=expected,omp50 %s
-// RUN: %clang_cc1 -fsyntax-only -fopenmp -fopenmp-version=45 
-verify=expected,omp45 -Wno-openmp %s
-// RUN: %clang_cc1 -fsyntax-only -fopenmp -fopenmp-version=45 
-verify=expected,omp45 -Wno-source-uses-openmp %s
+// RUN: %clang_cc1 -fsyntax-only -fopenmp -fopenmp-version=45 
-fno-openmp-extensions -verify=expected,omp45,omp45warn,omp %s
+// RUN: %clang_cc1 -fsyntax-only -fopenmp -fno-openmp-extensions 
-verify=expected,omp50,omp %s
+// RUN: %clang_cc1 -fsyntax-only -fopenmp -fopenmp-extensions 
-verify=expected,omp50 %s
+// RUN: %clang_cc1 -fsyntax-only -fopenmp -fopenmp-version=45 
-verify=expected,omp45,omp -fno-openmp-extensions -Wno-openmp %s
+// RUN: %clang_cc1 -fsyntax-only -fopenmp -fopenmp-version=45 
-verify=expected,omp45,omp -fno-openmp-extensions -Wno-source-uses-openmp %s
 
-// RUN: %clang_cc1 -fsyntax-only -fopenmp-simd -fopenmp-version=45 
-verify=expected,omp45,omp45warn %s
-// RUN: %clang_cc1 -fsyntax-only -fopenmp-simd -verify=expected,omp50 %s
+// RUN: %clang_cc1 -fsyntax-only -fopenmp-simd -fopenmp-version=45 
-fno-openmp-extensions -verify=expected,omp45,omp45warn,omp %s
+// RUN: %clang_cc1 -fsyntax-only -fopenmp-simd -verify=expected,omp50,omp 
-fno-openmp-extensions %s
 // SIMD-ONLY0-NOT: {{__kmpc|__tgt}}
 
 void bar();
@@ -5264,7 +5265,7 @@ void foo() {
 #pragma omp target
 #pragma omp teams
   {
-#pragma omp atomic // expected-error {{region cannot be closely nested inside 
'teams' region; perhaps you forget to enclose 'omp atomic' directive into a 
parallel region?}}
+#pragma omp atomic // omp-error {{region cannot be closely nested inside 
'teams' region; perhaps you forget to enclose 'omp atomic' directive into a 
parallel region?}}
 ++a;
   }
 #pragma omp target
@@ -8422,7 +8423,7 @@ void foo() {
   }
 #pragma omp target teams
   {
-#pragma omp atomic // expected-error {{region cannot be closely nested inside 
'target teams' region; perhaps you forget to enclose 'omp atomic' directive 
into a parallel region?}}
+#pragma omp atomic // omp-error {{region cannot be closely nested inside 
'target teams' region; perhaps you forget to enclose 'omp atomic' directive 
into a parallel region?}}
 ++a;
   }
 #pragma omp target teams
@@ -14096,7 +14097,7 @@ void foo() {
 #pragma omp target
 #pragma omp teams
   {
-#pragma omp atomic // expected-error {{region cannot be close

[PATCH] D126323: [OpenMP] Extend omp teams to permit nested omp atomic

2022-05-26 Thread Joel E. Denny via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG48ca3a5ebb15: [OpenMP] Extend omp teams to permit nested omp 
atomic (authored by jdenny).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126323

Files:
  clang/lib/Sema/SemaOpenMP.cpp
  clang/test/OpenMP/nesting_of_regions.cpp
  openmp/libomptarget/test/offloading/target-teams-atomic.c
  openmp/runtime/test/teams/teams-atomic.c

Index: openmp/runtime/test/teams/teams-atomic.c
===
--- /dev/null
+++ openmp/runtime/test/teams/teams-atomic.c
@@ -0,0 +1,49 @@
+// Check that omp atomic is permitted and behaves when strictly nested within
+// omp teams.  This is an extension to OpenMP 5.2 and is enabled by default.
+
+// RUN: %libomp-compile-and-run | FileCheck %s
+
+#include 
+#include 
+#include 
+#include 
+
+// High parallelism increases our chances of detecting a lack of atomicity.
+#define NUM_TEAMS_TRY 256
+
+int main() {
+  //  CHECK: update: num_teams=[[#NUM_TEAMS:]]{{$}}
+  // CHECK-NEXT: update: x=[[#NUM_TEAMS]]{{$}}
+  int x = 0;
+  int numTeams;
+  #pragma omp teams num_teams(NUM_TEAMS_TRY)
+  {
+#pragma omp atomic update
+++x;
+if (omp_get_team_num() == 0)
+  numTeams = omp_get_num_teams();
+  }
+  printf("update: num_teams=%d\n", numTeams);
+  printf("update: x=%d\n", x);
+
+  // CHECK-NEXT: capture: x=[[#NUM_TEAMS]]{{$}}
+  // CHECK-NEXT: capture: xCapturedCount=[[#NUM_TEAMS]]{{$}}
+  bool xCaptured[numTeams];
+  memset(xCaptured, 0, sizeof xCaptured);
+  x = 0;
+  #pragma omp teams num_teams(NUM_TEAMS_TRY)
+  {
+int v;
+#pragma omp atomic capture
+v = x++;
+xCaptured[v] = true;
+  }
+  printf("capture: x=%d\n", x);
+  int xCapturedCount = 0;
+  for (int i = 0; i < numTeams; ++i) {
+if (xCaptured[i])
+  ++xCapturedCount;
+  }
+  printf("capture: xCapturedCount=%d\n", xCapturedCount);
+  return 0;
+}
Index: openmp/libomptarget/test/offloading/target-teams-atomic.c
===
--- /dev/null
+++ openmp/libomptarget/test/offloading/target-teams-atomic.c
@@ -0,0 +1,50 @@
+// Check that omp atomic is permitted and behaves when strictly nested within
+// omp target teams.  This is an extension to OpenMP 5.2 and is enabled by
+// default.
+
+// RUN: %libomptarget-compile-run-and-check-generic
+
+#include 
+#include 
+#include 
+#include 
+
+// High parallelism increases our chances of detecting a lack of atomicity.
+#define NUM_TEAMS_TRY 256
+
+int main() {
+  //  CHECK: update: num_teams=[[#NUM_TEAMS:]]{{$}}
+  // CHECK-NEXT: update: x=[[#NUM_TEAMS]]{{$}}
+  int x = 0;
+  int numTeams;
+  #pragma omp target teams num_teams(NUM_TEAMS_TRY) map(tofrom:x, numTeams)
+  {
+#pragma omp atomic update
+++x;
+if (omp_get_team_num() == 0)
+  numTeams = omp_get_num_teams();
+  }
+  printf("update: num_teams=%d\n", numTeams);
+  printf("update: x=%d\n", x);
+
+  // CHECK-NEXT: capture: x=[[#NUM_TEAMS]]{{$}}
+  // CHECK-NEXT: capture: xCapturedCount=[[#NUM_TEAMS]]{{$}}
+  bool xCaptured[numTeams];
+  memset(xCaptured, 0, sizeof xCaptured);
+  x = 0;
+  #pragma omp target teams num_teams(NUM_TEAMS_TRY) map(tofrom:x, numTeams)
+  {
+int v;
+#pragma omp atomic capture
+v = x++;
+xCaptured[v] = true;
+  }
+  printf("capture: x=%d\n", x);
+  int xCapturedCount = 0;
+  for (int i = 0; i < numTeams; ++i) {
+if (xCaptured[i])
+  ++xCapturedCount;
+  }
+  printf("capture: xCapturedCount=%d\n", xCapturedCount);
+  return 0;
+}
Index: clang/test/OpenMP/nesting_of_regions.cpp
===
--- clang/test/OpenMP/nesting_of_regions.cpp
+++ clang/test/OpenMP/nesting_of_regions.cpp
@@ -1,10 +1,11 @@
-// RUN: %clang_cc1 -fsyntax-only -fopenmp -fopenmp-version=45 -verify=expected,omp45,omp45warn %s
-// RUN: %clang_cc1 -fsyntax-only -fopenmp -verify=expected,omp50 %s
-// RUN: %clang_cc1 -fsyntax-only -fopenmp -fopenmp-version=45 -verify=expected,omp45 -Wno-openmp %s
-// RUN: %clang_cc1 -fsyntax-only -fopenmp -fopenmp-version=45 -verify=expected,omp45 -Wno-source-uses-openmp %s
+// RUN: %clang_cc1 -fsyntax-only -fopenmp -fopenmp-version=45 -fno-openmp-extensions -verify=expected,omp45,omp45warn,omp %s
+// RUN: %clang_cc1 -fsyntax-only -fopenmp -fno-openmp-extensions -verify=expected,omp50,omp %s
+// RUN: %clang_cc1 -fsyntax-only -fopenmp -fopenmp-extensions -verify=expected,omp50 %s
+// RUN: %clang_cc1 -fsyntax-only -fopenmp -fopenmp-version=45 -verify=expected,omp45,omp -fno-openmp-extensions -Wno-openmp %s
+// RUN: %clang_cc1 -fsyntax-only -fopenmp -fopenmp-version=45 -verify=expected,omp45,omp -fno-openmp-extensions -Wno-source-uses-openmp %s
 
-// RUN: %clang_cc1 -fsyntax-only -fopenmp-simd -fopenmp-version=45 -verify=expected,omp45,omp45warn %s

[PATCH] D119051: Extend the C++03 definition of POD to include defaulted functions

2022-05-26 Thread David Blaikie via Phabricator via cfe-commits
dblaikie added inline comments.



Comment at: clang/lib/Driver/ToolChains/Clang.cpp:5596
+  DefaultedSMFArePOD = false;
+  }
+

probinson wrote:
> dblaikie wrote:
> > probinson wrote:
> > > Does this mean `-fclang-abi-compat` will override the PS4/Darwin special 
> > > case?  I think we don't want to do that.
> > I don't think so - this expression will make `DefaultedSMFArePOD` false 
> > when it's already false due to the target not being PS4 or Darwin, yeah? So 
> > it'll redundantly/harmlessly set it to false.
> No, I mean if it *is* PS4, it will turn true into false, and that's bad.  If 
> I'm reading this correctly.
Right - let's see if I can explain how I'm understanding it at least - maybe 
I've got some code blindness from staring at it too long.

If it /is/ PS4, then this code:
```
bool DefaultedSMFArePOD = !RawTriple.isPS4() && !RawTriple.isOSDarwin();
```
Will amount to this:
```
bool DefaultedSMFArePOD = !true && !RawTriple.isOSDarwin();
```
```
bool DefaultedSMFArePOD = false && !RawTriple.isOSDarwin();
```
```
bool DefaultedSMFArePOD = false;
```
So then then the code at 5595 can only reinforce that, not change it - since it 
only sets the value to false. So my understanding is that the 
`-fclang-abi-compat` flag can not have any effect on the `DefaultedSMFArePOD` 
behavior of PS4. And it sounds like that's what you want? So I think we're good 
here?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119051

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


[PATCH] D125052: [HLSL] Enable vector types for hlsl.

2022-05-26 Thread Xiang Li via Phabricator via cfe-commits
python3kgae updated this revision to Diff 432346.
python3kgae added a comment.

Update comment for finclude_default_header.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125052

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Basic/LangOptions.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/lib/Frontend/InitPreprocessor.cpp
  clang/lib/Headers/CMakeLists.txt
  clang/lib/Headers/hlsl.h
  clang/lib/Headers/hlsl/hlsl_basic_types.h
  clang/test/CodeGenHLSL/basic_types.hlsl
  clang/test/Driver/hlsl_no_stdinc.hlsl

Index: clang/test/Driver/hlsl_no_stdinc.hlsl
===
--- /dev/null
+++ clang/test/Driver/hlsl_no_stdinc.hlsl
@@ -0,0 +1,12 @@
+// RUN: %clang_dxc  -Tlib_6_7 -fcgl -Fo - %s -### 2>&1 | FileCheck %s --check-prefix=STDINC
+// RUN: %clang_dxc  -Tlib_6_7 -hlsl-no-stdinc -fcgl -Fo - %s -### 2>&1 | FileCheck %s --check-prefix=NOSTDINC
+
+// RUN: %clang -cc1 -triple dxil-pc-shadermodel6.3-library -x hlsl -ast-dump -o - %s -verify
+
+// Make sure hlsl-no-stdinc is translated into finclude-default-header.
+// STDINC:"-finclude-default-header"
+// NOSTDINC-NOT:"-finclude-default-header"
+
+// Make sure uint not work when finclude-default-header is off.
+// expected-error@+1 {{unknown type name 'uint'}}
+uint a;
\ No newline at end of file
Index: clang/test/CodeGenHLSL/basic_types.hlsl
===
--- /dev/null
+++ clang/test/CodeGenHLSL/basic_types.hlsl
@@ -0,0 +1,76 @@
+// RUN: %clang_dxc  -Tlib_6_7 -fcgl -Fo - %s | FileCheck %s
+
+// FIXME: check 16bit types once enable-16bit-types is ready.
+
+// CHECK:@uint_Val = global i32 0, align 4
+// CHECK:@uint64_t_Val = global i64 0, align 8
+// CHECK:@int64_t_Val = global i64 0, align 8
+// CHECK:@int2_Val = global <2 x i32> zeroinitializer, align 8
+// CHECK:@int3_Val = global <3 x i32> zeroinitializer, align 16
+// CHECK:@int4_Val = global <4 x i32> zeroinitializer, align 16
+// CHECK:@uint2_Val = global <2 x i32> zeroinitializer, align 8
+// CHECK:@uint3_Val = global <3 x i32> zeroinitializer, align 16
+// CHECK:@uint4_Val = global <4 x i32> zeroinitializer, align 16
+// CHECK:@int64_t2_Val = global <2 x i64> zeroinitializer, align 16
+// CHECK:@int64_t3_Val = global <3 x i64> zeroinitializer, align 32
+// CHECK:@int64_t4_Val = global <4 x i64> zeroinitializer, align 32
+// CHECK:@uint64_t2_Val = global <2 x i64> zeroinitializer, align 16
+// CHECK:@uint64_t3_Val = global <3 x i64> zeroinitializer, align 32
+// CHECK:@uint64_t4_Val = global <4 x i64> zeroinitializer, align 32
+// CHECK:@float2_Val = global <2 x float> zeroinitializer, align 8
+// CHECK:@float3_Val = global <3 x float> zeroinitializer, align 16
+// CHECK:@float4_Val = global <4 x float> zeroinitializer, align 16
+// CHECK:@double2_Val = global <2 x double> zeroinitializer, align 16
+// CHECK:@double3_Val = global <3 x double> zeroinitializer, align 32
+// CHECK:@double4_Val = global <4 x double> zeroinitializer, align 32
+
+#define TYPE_DECL(T)  T T##_Val
+
+#ifdef __HLSL_ENABLE_16_BIT
+TYPE_DECL(uint16_t);
+TYPE_DECL(int16_t);
+#endif
+
+// unsigned 32-bit integer.
+TYPE_DECL(uint);
+
+// 64-bit integer.
+TYPE_DECL(uint64_t);
+TYPE_DECL(int64_t);
+
+// built-in vector data types:
+
+#ifdef __HLSL_ENABLE_16_BIT
+TYPE_DECL(int16_t2   );
+TYPE_DECL(int16_t3   );
+TYPE_DECL(int16_t4   );
+TYPE_DECL( uint16_t2 );
+TYPE_DECL( uint16_t3 );
+TYPE_DECL( uint16_t4 );
+#endif
+
+TYPE_DECL( int2  );
+TYPE_DECL( int3  );
+TYPE_DECL( int4  );
+TYPE_DECL( uint2 );
+TYPE_DECL( uint3 );
+TYPE_DECL( uint4 );
+TYPE_DECL( int64_t2  );
+TYPE_DECL( int64_t3  );
+TYPE_DECL( int64_t4  );
+TYPE_DECL( uint64_t2 );
+TYPE_DECL( uint64_t3 );
+TYPE_DECL( uint64_t4 );
+
+#ifdef __HLSL_ENABLE_16_BIT
+TYPE_DECL(half2 );
+TYPE_DECL(half3 );
+TYPE_DECL(half4 );
+#endif
+
+TYPE_DECL( float2  );
+TYPE_DECL( float3  );
+TYPE_DECL( float4  );
+TYPE_DECL( double2 );
+TYPE_DECL( double3 );
+TYPE_DECL( double4 );
Index: clang/lib/Headers/hlsl/hlsl_basic_types.h
===
--- /dev/null
+++ clang/lib/Headers/hlsl/hlsl_basic_types.h
@@ -0,0 +1,64 @@
+//===- hlsl_basic_types.h - HLSL definitions for basic types --===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#ifndef _HLSL_HLSL_BASIC_TYPES_H_
+#define _HLSL_HLSL_BASIC_TYPES_H_
+
+// built-in scalar data types:
+
+#ifdef __HLSL_ENABLE_16_BIT
+// 16-bit integer.
+typedef unsigned short uint16_t;
+typedef short int16_t;
+#endif
+
+// unsigned 32-bit integer.
+typedef unsigned int uint;
+
+// 64-bit integer.
+typed

[PATCH] D125847: LTO: Decide upfront whether to use opaque/non-opaque pointer types

2022-05-26 Thread Matthias Braun via Phabricator via cfe-commits
MatzeB updated this revision to Diff 432347.
MatzeB marked an inline comment as done.
MatzeB added a comment.

Address review feedback.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125847

Files:
  clang/lib/Driver/ToolChains/CommonArgs.cpp
  clang/test/CodeGen/thinlto-inline-asm2.c
  clang/test/Driver/arm-float-abi-lto.c
  clang/test/Driver/lto-no-opaque-pointers.c
  clang/test/Driver/lto-opaque-pointers.c
  clang/test/Driver/memtag_lto.c
  lld/ELF/Config.h
  lld/ELF/Driver.cpp
  lld/ELF/LTO.cpp
  lld/ELF/Options.td
  lld/test/ELF/lto/discard-value-names.ll
  lld/test/ELF/lto/ltopasses-basic.ll
  lld/test/ELF/lto/type-merge.ll
  lld/test/ELF/lto/type-merge2.ll
  lld/test/ELF/lto/wrap-unreferenced-before-codegen.test
  llvm/docs/OpaquePointers.rst
  llvm/include/llvm/LTO/Config.h
  llvm/test/Analysis/StackSafetyAnalysis/ipa-alias.ll
  llvm/test/Analysis/StackSafetyAnalysis/ipa.ll
  llvm/test/LTO/Resolution/X86/alias-alias.ll
  llvm/test/LTO/Resolution/X86/comdat.ll
  llvm/test/LTO/Resolution/X86/ifunc2.ll
  llvm/test/LTO/Resolution/X86/local-def-dllimport.ll
  llvm/test/LTO/X86/Inputs/opaque-pointers.ll
  llvm/test/LTO/X86/cfi_jt_aliases.ll
  llvm/test/LTO/X86/mix-opaque-typed.ll
  llvm/test/LTO/X86/type-mapping-bug4.ll
  llvm/test/ThinLTO/X86/Inputs/import-constant.ll
  llvm/test/ThinLTO/X86/cfi-devirt.ll
  llvm/test/ThinLTO/X86/cfi-unsat.ll
  llvm/test/ThinLTO/X86/devirt-after-icp.ll
  llvm/test/ThinLTO/X86/devirt2.ll
  llvm/test/ThinLTO/X86/devirt_check.ll
  llvm/test/ThinLTO/X86/devirt_promote.ll
  llvm/test/ThinLTO/X86/devirt_single_hybrid.ll
  llvm/test/ThinLTO/X86/funcattrs-prop-unknown.ll
  llvm/test/ThinLTO/X86/globals-import-blockaddr.ll
  llvm/test/ThinLTO/X86/import-constant.ll
  llvm/test/ThinLTO/X86/import-dsolocal.ll
  llvm/test/ThinLTO/X86/index-const-prop-gvref-pie.ll
  llvm/test/ThinLTO/X86/index-const-prop-gvref.ll
  llvm/test/ThinLTO/X86/index-const-prop-linkage.ll
  llvm/test/ThinLTO/X86/reference_non_importable.ll
  llvm/test/ThinLTO/X86/weak_externals.ll
  llvm/tools/gold/gold-plugin.cpp
  llvm/tools/llvm-lto2/llvm-lto2.cpp

Index: llvm/tools/llvm-lto2/llvm-lto2.cpp
===
--- llvm/tools/llvm-lto2/llvm-lto2.cpp
+++ llvm/tools/llvm-lto2/llvm-lto2.cpp
@@ -143,6 +143,10 @@
  cl::desc("Run PGO context sensitive IR instrumentation"),
  cl::init(false), cl::Hidden);
 
+static cl::opt LtoOpaquePointers("lto-opaque-pointers",
+   cl::desc("Enable opaque pointer types"),
+   cl::init(true), cl::Hidden);
+
 static cl::opt
 DebugPassManager("debug-pass-manager", cl::init(false), cl::Hidden,
  cl::desc("Print pass management debugging information"));
@@ -291,6 +295,7 @@
   Conf.StatsFile = StatsFile;
   Conf.PTO.LoopVectorization = Conf.OptLevel > 1;
   Conf.PTO.SLPVectorization = Conf.OptLevel > 1;
+  Conf.OpaquePointers = LtoOpaquePointers;
 
   ThinBackend Backend;
   if (ThinLTODistributedIndexes)
Index: llvm/tools/gold/gold-plugin.cpp
===
--- llvm/tools/gold/gold-plugin.cpp
+++ llvm/tools/gold/gold-plugin.cpp
@@ -208,6 +208,8 @@
   static std::string stats_file;
   // Asserts that LTO link has whole program visibility
   static bool whole_program_visibility = false;
+  // Use opaque pointer types.
+  static bool opaque_pointers = true;
 
   // Optimization remarks filename, accepted passes and hotness options
   static std::string RemarksFilename;
@@ -308,6 +310,10 @@
   RemarksFormat = std::string(opt);
 } else if (opt.consume_front("stats-file=")) {
   stats_file = std::string(opt);
+} else if (opt == "opaque-pointers") {
+  opaque_pointers = true;
+} else if (opt == "no-opaque-pointers") {
+  opaque_pointers = false;
 } else {
   // Save this option to pass to the code generator.
   // ParseCommandLineOptions() expects argv[0] to be program name. Lazily
@@ -957,6 +963,8 @@
 
   Conf.HasWholeProgramVisibility = options::whole_program_visibility;
 
+  Config.OpaquePointers = options.opaque_pointers;
+
   Conf.StatsFile = options::stats_file;
   return std::make_unique(std::move(Conf), Backend,
 options::ParallelCodeGenParallelismLevel);
Index: llvm/test/ThinLTO/X86/weak_externals.ll
===
--- llvm/test/ThinLTO/X86/weak_externals.ll
+++ llvm/test/ThinLTO/X86/weak_externals.ll
@@ -10,9 +10,9 @@
 ; RUN: llvm-dis %t.out.1.2.internalize.bc -o - | FileCheck %s --check-prefix=INTERNALIZE
 
 ; CHECK: @_ZZN9SingletonI1SE11getInstanceEvE8instance = available_externally dso_local global %struct.S zeroinitializer
-; CHECK: @_ZZN9SingletonI1SE11getInstanceEvE13instance_weak = available_externally dso_local global %struct.S* null, align

[PATCH] D125847: LTO: Decide upfront whether to use opaque/non-opaque pointer types

2022-05-26 Thread Matthias Braun via Phabricator via cfe-commits
MatzeB marked an inline comment as done.
MatzeB added inline comments.



Comment at: lld/ELF/Options.td:311
+  "Use opaque pointers in IR used during LTO",
+  "Use typed pointers in IR used during LTO (default)">;
+

nikic wrote:
> `(default)` here is outdated.
> 
> Possibly this option should be `lto_opaque_pointers`? That seems to be the 
> convention for other related options.
👍


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125847

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


[PATCH] D126494: [clang] avoid assert due to device treated long double as double

2022-05-26 Thread Chi Chun Chen via Phabricator via cfe-commits
cchen created this revision.
Herald added a project: All.
cchen requested review of this revision.
Herald added a reviewer: jdoerfert.
Herald added subscribers: cfe-commits, sstefan1.
Herald added a project: clang.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D126494

Files:
  clang/lib/CodeGen/CodeGenModule.cpp


Index: clang/lib/CodeGen/CodeGenModule.cpp
===
--- clang/lib/CodeGen/CodeGenModule.cpp
+++ clang/lib/CodeGen/CodeGenModule.cpp
@@ -4648,7 +4648,13 @@
   InitDecl->getFlexibleArrayInitChars(getContext());
   CharUnits CstSize = CharUnits::fromQuantity(
   getDataLayout().getTypeAllocSize(Init->getType()));
-  assert(VarSize == CstSize && "Emitted constant has unexpected size");
+  // 'long double' is treated as 'double' in device code
+  const BuiltinType *BType = D->getType()->getAs();
+  bool IsLongDouble = BType && BType->getKind() == BuiltinType::LongDouble;
+  bool IsDevice = getLangOpts().HIP || getLangOpts().CUDA ||
+  getLangOpts().OpenMPIsDevice;
+  assert((VarSize == CstSize || (IsDevice && IsLongDouble)) &&
+ "Emitted constant has unexpected size");
 #endif
 }
   }


Index: clang/lib/CodeGen/CodeGenModule.cpp
===
--- clang/lib/CodeGen/CodeGenModule.cpp
+++ clang/lib/CodeGen/CodeGenModule.cpp
@@ -4648,7 +4648,13 @@
   InitDecl->getFlexibleArrayInitChars(getContext());
   CharUnits CstSize = CharUnits::fromQuantity(
   getDataLayout().getTypeAllocSize(Init->getType()));
-  assert(VarSize == CstSize && "Emitted constant has unexpected size");
+  // 'long double' is treated as 'double' in device code
+  const BuiltinType *BType = D->getType()->getAs();
+  bool IsLongDouble = BType && BType->getKind() == BuiltinType::LongDouble;
+  bool IsDevice = getLangOpts().HIP || getLangOpts().CUDA ||
+  getLangOpts().OpenMPIsDevice;
+  assert((VarSize == CstSize || (IsDevice && IsLongDouble)) &&
+ "Emitted constant has unexpected size");
 #endif
 }
   }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D125847: LTO: Decide upfront whether to use opaque/non-opaque pointer types

2022-05-26 Thread Matthias Braun via Phabricator via cfe-commits
MatzeB updated this revision to Diff 432350.
MatzeB marked an inline comment as done.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125847

Files:
  clang/lib/Driver/ToolChains/CommonArgs.cpp
  clang/test/CodeGen/thinlto-inline-asm2.c
  clang/test/Driver/arm-float-abi-lto.c
  clang/test/Driver/lto-no-opaque-pointers.c
  clang/test/Driver/lto-opaque-pointers.c
  clang/test/Driver/memtag_lto.c
  lld/ELF/Config.h
  lld/ELF/Driver.cpp
  lld/ELF/LTO.cpp
  lld/ELF/Options.td
  lld/test/ELF/lto/discard-value-names.ll
  lld/test/ELF/lto/ltopasses-basic.ll
  lld/test/ELF/lto/type-merge.ll
  lld/test/ELF/lto/type-merge2.ll
  lld/test/ELF/lto/wrap-unreferenced-before-codegen.test
  llvm/docs/OpaquePointers.rst
  llvm/include/llvm/LTO/Config.h
  llvm/test/Analysis/StackSafetyAnalysis/ipa-alias.ll
  llvm/test/Analysis/StackSafetyAnalysis/ipa.ll
  llvm/test/LTO/Resolution/X86/alias-alias.ll
  llvm/test/LTO/Resolution/X86/comdat.ll
  llvm/test/LTO/Resolution/X86/ifunc2.ll
  llvm/test/LTO/Resolution/X86/local-def-dllimport.ll
  llvm/test/LTO/X86/Inputs/opaque-pointers.ll
  llvm/test/LTO/X86/cfi_jt_aliases.ll
  llvm/test/LTO/X86/mix-opaque-typed.ll
  llvm/test/LTO/X86/type-mapping-bug4.ll
  llvm/test/ThinLTO/X86/Inputs/import-constant.ll
  llvm/test/ThinLTO/X86/cfi-devirt.ll
  llvm/test/ThinLTO/X86/cfi-unsat.ll
  llvm/test/ThinLTO/X86/devirt-after-icp.ll
  llvm/test/ThinLTO/X86/devirt2.ll
  llvm/test/ThinLTO/X86/devirt_check.ll
  llvm/test/ThinLTO/X86/devirt_promote.ll
  llvm/test/ThinLTO/X86/devirt_single_hybrid.ll
  llvm/test/ThinLTO/X86/funcattrs-prop-unknown.ll
  llvm/test/ThinLTO/X86/globals-import-blockaddr.ll
  llvm/test/ThinLTO/X86/import-constant.ll
  llvm/test/ThinLTO/X86/import-dsolocal.ll
  llvm/test/ThinLTO/X86/index-const-prop-gvref-pie.ll
  llvm/test/ThinLTO/X86/index-const-prop-gvref.ll
  llvm/test/ThinLTO/X86/index-const-prop-linkage.ll
  llvm/test/ThinLTO/X86/reference_non_importable.ll
  llvm/test/ThinLTO/X86/weak_externals.ll
  llvm/tools/gold/gold-plugin.cpp
  llvm/tools/llvm-lto2/llvm-lto2.cpp

Index: llvm/tools/llvm-lto2/llvm-lto2.cpp
===
--- llvm/tools/llvm-lto2/llvm-lto2.cpp
+++ llvm/tools/llvm-lto2/llvm-lto2.cpp
@@ -143,6 +143,10 @@
  cl::desc("Run PGO context sensitive IR instrumentation"),
  cl::init(false), cl::Hidden);
 
+static cl::opt LtoOpaquePointers("lto-opaque-pointers",
+   cl::desc("Enable opaque pointer types"),
+   cl::init(true), cl::Hidden);
+
 static cl::opt
 DebugPassManager("debug-pass-manager", cl::init(false), cl::Hidden,
  cl::desc("Print pass management debugging information"));
@@ -291,6 +295,7 @@
   Conf.StatsFile = StatsFile;
   Conf.PTO.LoopVectorization = Conf.OptLevel > 1;
   Conf.PTO.SLPVectorization = Conf.OptLevel > 1;
+  Conf.OpaquePointers = LtoOpaquePointers;
 
   ThinBackend Backend;
   if (ThinLTODistributedIndexes)
Index: llvm/tools/gold/gold-plugin.cpp
===
--- llvm/tools/gold/gold-plugin.cpp
+++ llvm/tools/gold/gold-plugin.cpp
@@ -208,6 +208,8 @@
   static std::string stats_file;
   // Asserts that LTO link has whole program visibility
   static bool whole_program_visibility = false;
+  // Use opaque pointer types.
+  static bool opaque_pointers = true;
 
   // Optimization remarks filename, accepted passes and hotness options
   static std::string RemarksFilename;
@@ -308,6 +310,10 @@
   RemarksFormat = std::string(opt);
 } else if (opt.consume_front("stats-file=")) {
   stats_file = std::string(opt);
+} else if (opt == "opaque-pointers") {
+  opaque_pointers = true;
+} else if (opt == "no-opaque-pointers") {
+  opaque_pointers = false;
 } else {
   // Save this option to pass to the code generator.
   // ParseCommandLineOptions() expects argv[0] to be program name. Lazily
@@ -957,6 +963,8 @@
 
   Conf.HasWholeProgramVisibility = options::whole_program_visibility;
 
+  Config.OpaquePointers = options.opaque_pointers;
+
   Conf.StatsFile = options::stats_file;
   return std::make_unique(std::move(Conf), Backend,
 options::ParallelCodeGenParallelismLevel);
Index: llvm/test/ThinLTO/X86/weak_externals.ll
===
--- llvm/test/ThinLTO/X86/weak_externals.ll
+++ llvm/test/ThinLTO/X86/weak_externals.ll
@@ -10,9 +10,9 @@
 ; RUN: llvm-dis %t.out.1.2.internalize.bc -o - | FileCheck %s --check-prefix=INTERNALIZE
 
 ; CHECK: @_ZZN9SingletonI1SE11getInstanceEvE8instance = available_externally dso_local global %struct.S zeroinitializer
-; CHECK: @_ZZN9SingletonI1SE11getInstanceEvE13instance_weak = available_externally dso_local global %struct.S* null, align 8
-; CHECK: define linkonce_odr dso_local derefere

[PATCH] D124525: [OpenMP][ClangLinkerWrapper] Extending linker wrapper to embed metadata for multi-arch fat binaries

2022-05-26 Thread Saiyedul Islam via Phabricator via cfe-commits
saiislam updated this revision to Diff 432352.
saiislam marked 8 inline comments as done.
saiislam added a comment.

Addressed some simple review changes. Will update remaining in the next 
iteration.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124525

Files:
  clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
  clang/tools/clang-linker-wrapper/OffloadWrapper.cpp
  clang/tools/clang-linker-wrapper/OffloadWrapper.h
  openmp/libomptarget/include/omptarget.h
  openmp/libomptarget/src/rtl.cpp

Index: openmp/libomptarget/src/rtl.cpp
===
--- openmp/libomptarget/src/rtl.cpp
+++ openmp/libomptarget/src/rtl.cpp
@@ -13,6 +13,7 @@
 #include "rtl.h"
 #include "device.h"
 #include "private.h"
+//#include "llvm/OffloadArch/OffloadArch.h"
 
 #include 
 #include 
@@ -20,6 +21,8 @@
 #include 
 #include 
 #include 
+// It's strange we do not have llvm tools for openmp runtime, so we use stat
+#include 
 
 // List of all plugins that can support offloading.
 static const char *RTLNames[] = {
@@ -351,18 +354,108 @@
 initRTLonce(R);
 }
 
+/// Query runtime capabilities of this system by calling offload-arch -c
+/// offload_arch_output_buffer is persistant storage returned by this
+/// __tgt_get_active_offload_env.
+static void
+__tgt_get_active_offload_env(__tgt_active_offload_env *active_env,
+ char *offload_arch_output_buffer,
+ size_t offload_arch_output_buffer_size) {
+
+  // If OFFLOAD_ARCH_OVERRIDE env varible is present then use its value instead
+  // of querying it using LLVMOffloadArch library.
+  if (char *OffloadArchEnvVar = getenv("OFFLOAD_ARCH_OVERRIDE")) {
+if (OffloadArchEnvVar) {
+  active_env->capabilities = OffloadArchEnvVar;
+  return;
+}
+  }
+  // Qget runtime capabilities of this system with libLLVMOffloadArch.a
+  // if (int rc = getRuntimeCapabilities(offload_arch_output_buffer,
+  // offload_arch_output_buffer_size))
+  //   return;
+  // active_env->capabilities = offload_arch_output_buffer;
+  // return;
+}
+
+std::vector _splitstrings(char *input, const char *sep) {
+  std::vector split_strings;
+  std::string s(input);
+  std::string delimiter(sep);
+  size_t pos = 0;
+  while ((pos = s.find(delimiter)) != std::string::npos) {
+if (pos != 0)
+  split_strings.push_back(s.substr(0, pos));
+s.erase(0, pos + delimiter.length());
+  }
+  if (s.length() > 1)
+split_strings.push_back(s.substr(0, s.length()));
+  return split_strings;
+}
+
+static bool _ImageIsCompatibleWithEnv(__tgt_image_info *image_info,
+  __tgt_active_offload_env *active_env) {
+  // get_image_info will return null if no image information was registered.
+  // If no image information, assume application built with old compiler and
+  // check each image.
+  if (!image_info)
+return true;
+
+  if (!active_env->capabilities)
+return false;
+
+  // Each runtime requirement for the compiled image is stored in
+  // the image_info->offload_arch (TargetID) string.
+  // Each runtime capability obtained from "offload-arch -c" is stored in
+  // actvie_env->capabilities (TargetID) string.
+  // If every requirement has a matching capability, then the image
+  // is compatible with active environment
+
+  std::vector reqs = _splitstrings(image_info->offload_arch, ":");
+  std::vector caps = _splitstrings(active_env->capabilities, ":");
+
+  bool is_compatible = true;
+  for (auto req : reqs) {
+bool missing_capability = true;
+for (auto capability : caps)
+  if (capability == req)
+missing_capability = false;
+if (missing_capability) {
+  DP("Image requires %s but runtime capability %s is missing.\n",
+ image_info->offload_arch, req.c_str());
+  is_compatible = false;
+}
+  }
+  return is_compatible;
+}
+
+#define MAX_CAPS_STR_SIZE 1024
 void RTLsTy::RegisterLib(__tgt_bin_desc *desc) {
+
+  // Get the current active offload environment
+  __tgt_active_offload_env offload_env = {nullptr};
+  // Need a buffer to hold results of offload-arch -c command
+  size_t offload_arch_output_buffer_size = MAX_CAPS_STR_SIZE;
+  std::vector offload_arch_output_buffer;
+  offload_arch_output_buffer.resize(offload_arch_output_buffer_size);
+  __tgt_get_active_offload_env(&offload_env, offload_arch_output_buffer.data(),
+   offload_arch_output_buffer_size);
+
+  RTLInfoTy *FoundRTL = NULL;
   PM->RTLsMtx.lock();
   // Register the images with the RTLs that understand them, if any.
   for (int32_t i = 0; i < desc->NumDeviceImages; ++i) {
 // Obtain the image.
 __tgt_device_image *img = &desc->DeviceImages[i];
 
-RTLInfoTy *FoundRTL = nullptr;
-
+// Get corresponding image info offload_arch and check with runtime
+if (!_ImageIsCompatibleWithEnv(i

[PATCH] D124525: [OpenMP][ClangLinkerWrapper] Extending linker wrapper to embed metadata for multi-arch fat binaries

2022-05-26 Thread Saiyedul Islam via Phabricator via cfe-commits
saiislam added a comment.

Thanks for the detailed review. I will update rest of the patch soon.




Comment at: clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp:613-614
   CmdArgs.push_back("-shared");
+  std::string ArchArg = std::string("-plugin-opt=mcpu=").append(Arch.str());
+  CmdArgs.push_back(ArchArg);
   CmdArgs.push_back("-o");

jhuber6 wrote:
> Does this just pass the architecture to the AMD link? Is this related? If not 
> move it to a separate patch and I'll review it.
Yes, it passes the architecture to AMD link.



Comment at: clang/tools/clang-linker-wrapper/OffloadWrapper.cpp:229-232
+// store value of these variables (i.e. offload archs) into a custom
+// section which will be used by "offload-arch -f". It won't be
+// removed during binary stripping.
+GV->setSection(".offload_arch_list");

jhuber6 wrote:
> Why does this need a custom section? We should just use it like this, not 
> sure why we need these to  be anything but some internal struct.
> ```
> for (auto *Image : BinDesc->Images) {
>   if (Image->Info)
>// Use Info
> }
> ```
Custom section is required so that it survives binary stripping done by various 
OSes. `Offload-arch` tool will look into this section of the binary to print 
list of supported architectures.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124525

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


  1   2   >