[clang] afcb77c - [Analyzer] Fix for incorrect use of container and iterator checkers

2020-03-30 Thread Adam Balogh via cfe-commits

Author: Adam Balogh
Date: 2020-03-30T09:14:45+02:00
New Revision: afcb77cc88a2ed489bbd383774c54daa82340761

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

LOG: [Analyzer] Fix for incorrect use of container and iterator checkers

Iterator checkers (and planned container checkers) need the option
aggressive-binary-operation-simplification to be enabled. Without this
option they may cause assertions. To prevent such misuse, this patch adds
a preventive check which issues a warning and denies the registartion of
the checker if this option is disabled.

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

Added: 

clang/test/Analysis/container-modeling-no-aggressive-binary-operation-simplification-warn.cpp

clang/test/Analysis/iterator-modeling-no-aggressive-binary-operation-simplification-no-crash.cpp

Modified: 
clang/include/clang/Basic/DiagnosticDriverKinds.td
clang/lib/StaticAnalyzer/Checkers/ContainerModeling.cpp
clang/test/Analysis/loop-widening-notes.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/DiagnosticDriverKinds.td 
b/clang/include/clang/Basic/DiagnosticDriverKinds.td
index 5a3249215189..27ffd562c6de 100644
--- a/clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ b/clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -344,6 +344,8 @@ def err_analyzer_checker_option_unknown : Error<
   "checker '%0' has no option called '%1'">;
 def err_analyzer_checker_option_invalid_input : Error<
   "invalid input for checker option '%0', that expects %1">;
+def err_analyzer_checker_incompatible_analyzer_option : Error<
+  "checker cannot be enabled with analyzer option '%0' == %1">;
 
 def err_drv_invalid_hvx_length : Error<
   "-mhvx-length is not supported without a -mhvx/-mhvx= flag">;

diff  --git a/clang/lib/StaticAnalyzer/Checkers/ContainerModeling.cpp 
b/clang/lib/StaticAnalyzer/Checkers/ContainerModeling.cpp
index 0af10cec9378..73c6517fd0eb 100644
--- a/clang/lib/StaticAnalyzer/Checkers/ContainerModeling.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/ContainerModeling.cpp
@@ -12,6 +12,7 @@
 
 #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
 #include "clang/AST/DeclTemplate.h"
+#include "clang/Driver/DriverDiagnostic.h"
 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
 #include "clang/StaticAnalyzer/Core/Checker.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
@@ -1068,5 +1069,15 @@ void ento::registerContainerModeling(CheckerManager 
&mgr) {
 }
 
 bool ento::shouldRegisterContainerModeling(const CheckerManager &mgr) {
+  if (!mgr.getLangOpts().CPlusPlus)
+return false;
+
+  if (!mgr.getAnalyzerOptions().ShouldAggressivelySimplifyBinaryOperation) {
+mgr.getASTContext().getDiagnostics().Report(
+diag::err_analyzer_checker_incompatible_analyzer_option)
+  << "aggressive-binary-operation-simplification" << "false";
+return false;
+  }
+
   return true;
 }

diff  --git 
a/clang/test/Analysis/container-modeling-no-aggressive-binary-operation-simplification-warn.cpp
 
b/clang/test/Analysis/container-modeling-no-aggressive-binary-operation-simplification-warn.cpp
new file mode 100644
index ..1a55e878f9ef
--- /dev/null
+++ 
b/clang/test/Analysis/container-modeling-no-aggressive-binary-operation-simplification-warn.cpp
@@ -0,0 +1,7 @@
+// RUN: %clang_analyze_cc1 -std=c++11\
+// RUN: -analyzer-checker=core,cplusplus,alpha.cplusplus.ContainerModeling\
+// RUN: %s 2>&1 | FileCheck %s
+
+// XFAIL: *
+
+// CHECK: checker cannot be enabled with analyzer option 
'aggressive-binary-operation-simplification' == false

diff  --git 
a/clang/test/Analysis/iterator-modeling-no-aggressive-binary-operation-simplification-no-crash.cpp
 
b/clang/test/Analysis/iterator-modeling-no-aggressive-binary-operation-simplification-no-crash.cpp
new file mode 100644
index ..4b7c52db5462
--- /dev/null
+++ 
b/clang/test/Analysis/iterator-modeling-no-aggressive-binary-operation-simplification-no-crash.cpp
@@ -0,0 +1,15 @@
+// RUN: %clang_analyze_cc1 -std=c++11\
+// RUN: 
-analyzer-checker=core,cplusplus,debug.DebugIteratorModeling,debug.ExprInspection\
+// RUN: %s 2>&1 | FileCheck %s
+
+// XFAIL: *
+
+// CHECK: checker cannot be enabled with analyzer option 
'aggressive-binary-operation-simplification' == false
+
+#include "Inputs/system-header-simulator-cxx.h"
+
+void clang_analyzer_eval(bool);
+
+void comparison(std::vector &V) {
+  clang_analyzer_eval(V.begin() == V.end()); // no-crash
+}

diff  --git a/clang/test/Analysis/loop-widening-notes.cpp 
b/clang/test/Analysis/loop-widening-notes.cpp
index 2c26a1490e5c..0ba71d030d05 100644
--- a/clang/test/Analysis/loop-widening-notes.cpp
+++ b/clang/test/Analysis/loop-widening-notes.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_analyze_cc1 -analyzer-c

[clang] eb90692 - [Analyzer] Rename test `iterator-modelling.cpp` to `iterator-modeling.cpp`

2020-03-30 Thread Adam Balogh via cfe-commits

Author: Adam Balogh
Date: 2020-03-30T09:23:35+02:00
New Revision: eb90692d8a660bb3172c9c2cc5adb3864c626d96

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

LOG: [Analyzer] Rename test `iterator-modelling.cpp` to `iterator-modeling.cpp`

Typo fix.

Added: 
clang/test/Analysis/iterator-modeling.cpp

Modified: 


Removed: 
clang/test/Analysis/iterator-modelling.cpp



diff  --git a/clang/test/Analysis/iterator-modelling.cpp 
b/clang/test/Analysis/iterator-modeling.cpp
similarity index 100%
rename from clang/test/Analysis/iterator-modelling.cpp
rename to clang/test/Analysis/iterator-modeling.cpp



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


[PATCH] D75171: [Analyzer] Fix for incorrect use of container and iterator checkers

2020-03-30 Thread Balogh, Ádám via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGafcb77cc88a2: [Analyzer] Fix for incorrect use of container 
and iterator checkers (authored by baloghadamsoftware).
Herald added a subscriber: ASDenysPetrov.

Changed prior to commit:
  https://reviews.llvm.org/D75171?vs=249352&id=253506#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D75171

Files:
  clang/include/clang/Basic/DiagnosticDriverKinds.td
  clang/lib/StaticAnalyzer/Checkers/ContainerModeling.cpp
  
clang/test/Analysis/container-modeling-no-aggressive-binary-operation-simplification-warn.cpp
  
clang/test/Analysis/iterator-modeling-no-aggressive-binary-operation-simplification-no-crash.cpp
  clang/test/Analysis/loop-widening-notes.cpp


Index: clang/test/Analysis/loop-widening-notes.cpp
===
--- clang/test/Analysis/loop-widening-notes.cpp
+++ clang/test/Analysis/loop-widening-notes.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_analyze_cc1 -analyzer-checker=core,alpha -analyzer-max-loop 2 
-analyzer-config widen-loops=true -analyzer-output=text -verify 
-analyzer-config eagerly-assume=false %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,alpha.core 
-analyzer-max-loop 2 -analyzer-config widen-loops=true -analyzer-output=text 
-verify -analyzer-config eagerly-assume=false %s
 
 int *p_a;
 int bar();
Index: 
clang/test/Analysis/iterator-modeling-no-aggressive-binary-operation-simplification-no-crash.cpp
===
--- /dev/null
+++ 
clang/test/Analysis/iterator-modeling-no-aggressive-binary-operation-simplification-no-crash.cpp
@@ -0,0 +1,15 @@
+// RUN: %clang_analyze_cc1 -std=c++11\
+// RUN: 
-analyzer-checker=core,cplusplus,debug.DebugIteratorModeling,debug.ExprInspection\
+// RUN: %s 2>&1 | FileCheck %s
+
+// XFAIL: *
+
+// CHECK: checker cannot be enabled with analyzer option 
'aggressive-binary-operation-simplification' == false
+
+#include "Inputs/system-header-simulator-cxx.h"
+
+void clang_analyzer_eval(bool);
+
+void comparison(std::vector &V) {
+  clang_analyzer_eval(V.begin() == V.end()); // no-crash
+}
Index: 
clang/test/Analysis/container-modeling-no-aggressive-binary-operation-simplification-warn.cpp
===
--- /dev/null
+++ 
clang/test/Analysis/container-modeling-no-aggressive-binary-operation-simplification-warn.cpp
@@ -0,0 +1,7 @@
+// RUN: %clang_analyze_cc1 -std=c++11\
+// RUN: -analyzer-checker=core,cplusplus,alpha.cplusplus.ContainerModeling\
+// RUN: %s 2>&1 | FileCheck %s
+
+// XFAIL: *
+
+// CHECK: checker cannot be enabled with analyzer option 
'aggressive-binary-operation-simplification' == false
Index: clang/lib/StaticAnalyzer/Checkers/ContainerModeling.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/ContainerModeling.cpp
+++ clang/lib/StaticAnalyzer/Checkers/ContainerModeling.cpp
@@ -12,6 +12,7 @@
 
 #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
 #include "clang/AST/DeclTemplate.h"
+#include "clang/Driver/DriverDiagnostic.h"
 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
 #include "clang/StaticAnalyzer/Core/Checker.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
@@ -1068,5 +1069,15 @@
 }
 
 bool ento::shouldRegisterContainerModeling(const CheckerManager &mgr) {
+  if (!mgr.getLangOpts().CPlusPlus)
+return false;
+
+  if (!mgr.getAnalyzerOptions().ShouldAggressivelySimplifyBinaryOperation) {
+mgr.getASTContext().getDiagnostics().Report(
+diag::err_analyzer_checker_incompatible_analyzer_option)
+  << "aggressive-binary-operation-simplification" << "false";
+return false;
+  }
+
   return true;
 }
Index: clang/include/clang/Basic/DiagnosticDriverKinds.td
===
--- clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -344,6 +344,8 @@
   "checker '%0' has no option called '%1'">;
 def err_analyzer_checker_option_invalid_input : Error<
   "invalid input for checker option '%0', that expects %1">;
+def err_analyzer_checker_incompatible_analyzer_option : Error<
+  "checker cannot be enabled with analyzer option '%0' == %1">;
 
 def err_drv_invalid_hvx_length : Error<
   "-mhvx-length is not supported without a -mhvx/-mhvx= flag">;


Index: clang/test/Analysis/loop-widening-notes.cpp
===
--- clang/test/Analysis/loop-widening-notes.cpp
+++ clang/test/Analysis/loop-widening-notes.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_analyze_cc1 -analyzer-checker=core,alpha -analyzer-max-loop 2 -analyzer-config widen-loops=true -analyzer-output=text -verify -analyzer-config eagerly-assume=false %s
+// RUN: %clang_analyze_cc1 -analy

[PATCH] D77037: [AST] Fix crashes on decltype(recovery-expr).

2020-03-30 Thread Haojian Wu via Phabricator via cfe-commits
hokein created this revision.
hokein added a reviewer: sammccall.
Herald added a project: clang.

We mark these decls as invalid.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D77037

Files:
  clang/include/clang/AST/DependenceFlags.h
  clang/include/clang/AST/Type.h
  clang/lib/Parse/ParseExprCXX.cpp
  clang/lib/Sema/SemaType.cpp
  clang/test/AST/ast-dump-expr-errors.cpp
  clang/test/Sema/invalid-member.cpp

Index: clang/test/Sema/invalid-member.cpp
===
--- clang/test/Sema/invalid-member.cpp
+++ clang/test/Sema/invalid-member.cpp
@@ -1,7 +1,15 @@
 // RUN: %clang_cc1 -verify -fsyntax-only %s
-void foo(); // expected-note {{requires 0 arguments}}
+// RUN: %clang_cc1 -verify -fsyntax-only -frecovery-ast %s
+
+void foo(); // expected-note 2{{requires 0 arguments}}
 class X {
   decltype(foo(42)) invalid; // expected-error {{no matching function}}
 };
 // Should be able to evaluate sizeof without crashing.
 static_assert(sizeof(X) == 1, "No valid members");
+
+class Y {
+  typeof(foo(42)) invalid; // expected-error {{no matching function}}
+};
+// Should be able to evaluate sizeof without crashing.
+static_assert(sizeof(Y) == 1, "No valid members");
Index: clang/test/AST/ast-dump-expr-errors.cpp
===
--- clang/test/AST/ast-dump-expr-errors.cpp
+++ clang/test/AST/ast-dump-expr-errors.cpp
@@ -42,5 +42,9 @@
 
 // FIXME: store initializer even when 'auto' could not be deduced.
 // Expressions with errors currently do not keep initializers around.
-// CHECK: `-VarDecl {{.*}} invalid e 'auto'
+// CHECK: -VarDecl {{.*}} invalid e 'auto'
 auto e = bar();
+
+// Error type should result in an invalid decl.
+// CHECK: -VarDecl {{.*}} invalid f
+decltype(bar()) f;
\ No newline at end of file
Index: clang/lib/Sema/SemaType.cpp
===
--- clang/lib/Sema/SemaType.cpp
+++ clang/lib/Sema/SemaType.cpp
@@ -1587,7 +1587,7 @@
 assert(E && "Didn't get an expression for typeof?");
 // TypeQuals handled by caller.
 Result = S.BuildTypeofExprType(E, DS.getTypeSpecTypeLoc());
-if (Result.isNull()) {
+if (Result.isNull() || Result->isErrorType()) {
   Result = Context.IntTy;
   declarator.setInvalidType(true);
 }
@@ -1598,7 +1598,7 @@
 assert(E && "Didn't get an expression for decltype?");
 // TypeQuals handled by caller.
 Result = S.BuildDecltypeType(E, DS.getTypeSpecTypeLoc());
-if (Result.isNull()) {
+if (Result.isNull() || Result->isErrorType()) {
   Result = Context.IntTy;
   declarator.setInvalidType(true);
 }
Index: clang/lib/Parse/ParseExprCXX.cpp
===
--- clang/lib/Parse/ParseExprCXX.cpp
+++ clang/lib/Parse/ParseExprCXX.cpp
@@ -3105,10 +3105,11 @@
   auto RunSignatureHelp = [&]() {
 ParsedType TypeRep =
 Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
-assert(TypeRep && "invalid types should be handled before");
-QualType PreferredType = Actions.ProduceConstructorSignatureHelp(
-getCurScope(), TypeRep.get()->getCanonicalTypeInternal(),
-DeclaratorInfo.getEndLoc(), ConstructorArgs, ConstructorLParen);
+QualType PreferredType;
+if (TypeRep)
+  PreferredType = Actions.ProduceConstructorSignatureHelp(
+  getCurScope(), TypeRep.get()->getCanonicalTypeInternal(),
+  DeclaratorInfo.getEndLoc(), ConstructorArgs, ConstructorLParen);
 CalledSignatureHelp = true;
 return PreferredType;
   };
Index: clang/include/clang/AST/Type.h
===
--- clang/include/clang/AST/Type.h
+++ clang/include/clang/AST/Type.h
@@ -2139,6 +2139,11 @@
 return static_cast(TypeBits.Dependence);
   }
 
+  /// Whether this type is an error type.
+  bool isErrorType() const {
+return getDependence() & TypeDependence::Error;
+  }
+
   /// Whether this type is a dependent type, meaning that its definition
   /// somehow depends on a template parameter (C++ [temp.dep.type]).
   bool isDependentType() const {
Index: clang/include/clang/AST/DependenceFlags.h
===
--- clang/include/clang/AST/DependenceFlags.h
+++ clang/include/clang/AST/DependenceFlags.h
@@ -50,14 +50,16 @@
 /// Whether this type is a variably-modified type (C99 6.7.5).
 VariablyModified = 8,
 
-// FIXME: add Error bit.
+/// Whether this type references an error, e.g. decltype(err-expression)
+/// yields an error type.
+Error = 16,
 
 None = 0,
-All = 15,
+All = 31,
 
 DependentInstantiation = Dependent | Instantiation,
 
-LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/VariablyModified)
+LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/Error)
   };
 };
 using TypeDep

[PATCH] D77039: [clang-format] Don't break multi block parameters on ObjCBreakBeforeNestedBlockParam

2020-03-30 Thread Kanglei Fang via Phabricator via cfe-commits
ghvg1313 created this revision.
ghvg1313 added reviewers: jolesiak, benhamilton.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

While the original diff  makes a lot of sense, 
and multiple inline block parameter/trailing paramemter after inline block 
paramemter should be discouraged, the formatting result is different than what 
xcode does by default
For the exact same example provided in the original diff:

  [object
blockArgument:^{
  a = 42;
}
   anotherArg:42];

The code is hard to read and not very visually pleasing

This diff uses `ObjCBreakBeforeNestedBlockParam` to shield from the formatting
When it's set to false, don't allign the inline block paramemters.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D77039

Files:
  clang/lib/Format/ContinuationIndenter.cpp
  clang/unittests/Format/FormatTestObjC.cpp


Index: clang/unittests/Format/FormatTestObjC.cpp
===
--- clang/unittests/Format/FormatTestObjC.cpp
+++ clang/unittests/Format/FormatTestObjC.cpp
@@ -1420,6 +1420,10 @@
"*b, NSNumber *c) {\n"
"  b = c;\n"
"}]");
+  verifyFormat("[self.test1 t:self w:self callback:^(typeof(self) self, "
+   "NSNumber *u, NSNumber *v) {\n"
+   "  u = v;\n"
+   "} z:self]");
 
   Style.ColumnLimit = 80;
   verifyFormat(
Index: clang/lib/Format/ContinuationIndenter.cpp
===
--- clang/lib/Format/ContinuationIndenter.cpp
+++ clang/lib/Format/ContinuationIndenter.cpp
@@ -342,6 +342,7 @@
   if (Previous.is(tok::semi) && State.LineContainsContinuedForLoopSection)
 return true;
   if (Style.Language == FormatStyle::LK_ObjC &&
+  Style.ObjCBreakBeforeNestedBlockParam &&
   Current.ObjCSelectorNameParts > 1 &&
   Current.startsSequence(TT_SelectorName, tok::colon, tok::caret)) {
 return true;


Index: clang/unittests/Format/FormatTestObjC.cpp
===
--- clang/unittests/Format/FormatTestObjC.cpp
+++ clang/unittests/Format/FormatTestObjC.cpp
@@ -1420,6 +1420,10 @@
"*b, NSNumber *c) {\n"
"  b = c;\n"
"}]");
+  verifyFormat("[self.test1 t:self w:self callback:^(typeof(self) self, "
+   "NSNumber *u, NSNumber *v) {\n"
+   "  u = v;\n"
+   "} z:self]");
 
   Style.ColumnLimit = 80;
   verifyFormat(
Index: clang/lib/Format/ContinuationIndenter.cpp
===
--- clang/lib/Format/ContinuationIndenter.cpp
+++ clang/lib/Format/ContinuationIndenter.cpp
@@ -342,6 +342,7 @@
   if (Previous.is(tok::semi) && State.LineContainsContinuedForLoopSection)
 return true;
   if (Style.Language == FormatStyle::LK_ObjC &&
+  Style.ObjCBreakBeforeNestedBlockParam &&
   Current.ObjCSelectorNameParts > 1 &&
   Current.startsSequence(TT_SelectorName, tok::colon, tok::caret)) {
 return true;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D76922: [Syntax] Remove delayed folding from tree building.

2020-03-30 Thread Marcel Hlopko via Phabricator via cfe-commits
hlopko updated this revision to Diff 253517.
hlopko added a comment.

Rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76922

Files:
  clang/lib/Tooling/Syntax/BuildTree.cpp
  clang/lib/Tooling/Syntax/Tokens.cpp
  clang/unittests/Tooling/Syntax/TreeTest.cpp

Index: clang/unittests/Tooling/Syntax/TreeTest.cpp
===
--- clang/unittests/Tooling/Syntax/TreeTest.cpp
+++ clang/unittests/Tooling/Syntax/TreeTest.cpp
@@ -224,6 +224,59 @@
 )txt");
 }
 
+TEST_F(SyntaxTreeTest, SimpleVariable) {
+  expectTreeDumpEqual(
+  R"cpp(
+int a;
+int b = 42;
+)cpp",
+  R"txt(
+*: TranslationUnit
+|-SimpleDeclaration
+| |-int
+| |-SimpleDeclarator
+| | `-a
+| `-;
+`-SimpleDeclaration
+  |-int
+  |-SimpleDeclarator
+  | |-b
+  | |-=
+  | `-UnknownExpression
+  |   `-42
+  `-;
+)txt");
+}
+
+TEST_F(SyntaxTreeTest, SimpleFunction) {
+  expectTreeDumpEqual(
+  R"cpp(
+void foo(int a, int b) {}
+)cpp",
+  R"txt(
+*: TranslationUnit
+`-SimpleDeclaration
+  |-void
+  |-SimpleDeclarator
+  | |-foo
+  | `-ParametersAndQualifiers
+  |   |-(
+  |   |-SimpleDeclaration
+  |   | |-int
+  |   | `-SimpleDeclarator
+  |   |   `-a
+  |   |-,
+  |   |-SimpleDeclaration
+  |   | |-int
+  |   | `-SimpleDeclarator
+  |   |   `-b
+  |   `-)
+  `-CompoundStatement
+|-{
+`-}
+)txt");
+}
+
 TEST_F(SyntaxTreeTest, If) {
   expectTreeDumpEqual(
   R"cpp(
@@ -541,20 +594,32 @@
 TEST_F(SyntaxTreeTest, MultipleDeclaratorsGrouping) {
   expectTreeDumpEqual(
   R"cpp(
-  int *a, b;
+  int *a, b; int *c, d;
   )cpp",
   R"txt(
 *: TranslationUnit
+|-SimpleDeclaration
+| |-int
+| |-SimpleDeclarator
+| | |-*
+| | `-a
+| |-,
+| |-SimpleDeclarator
+| | `-b
+| `-;
 `-SimpleDeclaration
   |-int
   |-SimpleDeclarator
   | |-*
-  | `-a
+  | `-c
   |-,
   |-SimpleDeclarator
-  | `-b
+  | `-d
   `-;
   )txt");
+}
+
+TEST_F(SyntaxTreeTest, MultipleDeclaratorsGroupingTypedef) {
   expectTreeDumpEqual(
   R"cpp(
 typedef int *a, b;
Index: clang/lib/Tooling/Syntax/Tokens.cpp
===
--- clang/lib/Tooling/Syntax/Tokens.cpp
+++ clang/lib/Tooling/Syntax/Tokens.cpp
@@ -710,8 +710,8 @@
 }
 
 std::string syntax::Token::dumpForTests(const SourceManager &SM) const {
-  return std::string(
-  llvm::formatv("{0}   {1}", tok::getTokenName(kind()), text(SM)));
+  return std::string(llvm::formatv("Token(`{0}`, {1}, length = {2})", text(SM),
+   tok::getTokenName(kind()), length()));
 }
 
 std::string TokenBuffer::dumpForTests() const {
Index: clang/lib/Tooling/Syntax/BuildTree.cpp
===
--- clang/lib/Tooling/Syntax/BuildTree.cpp
+++ clang/lib/Tooling/Syntax/BuildTree.cpp
@@ -44,15 +44,6 @@
 LLVM_ATTRIBUTE_UNUSED
 static bool isImplicitExpr(clang::Expr *E) { return E->IgnoreImplicit() != E; }
 
-static SourceLocation getQualifiedNameStart(DeclaratorDecl *D) {
-  auto DN = D->getDeclName();
-  bool IsAnonymous = DN.isIdentifier() && !DN.getAsIdentifierInfo();
-  if (IsAnonymous)
-return SourceLocation();
-  return D->getQualifierLoc() ? D->getQualifierLoc().getBeginLoc()
-  : D->getLocation();
-}
-
 namespace {
 /// Get start location of the Declarator from the TypeLoc.
 /// E.g.:
@@ -212,10 +203,6 @@
 foldNode(Range, New, nullptr);
   }
 
-  /// Must be called with the range of each `DeclaratorDecl`. Ensures the
-  /// corresponding declarator nodes are covered by `SimpleDeclaration`.
-  void noticeDeclRange(llvm::ArrayRef Range);
-
   /// Notifies that we should not consume trailing semicolon when computing
   /// token range of \p D.
   void noticeDeclWithoutSemicolon(Decl *D);
@@ -237,11 +224,6 @@
   void markChild(syntax::Node *N, NodeRole R);
   /// Set role for the syntax node matching \p N.
   void markChild(ASTPtr N, NodeRole R);
-  /// Set role for the delayed node that spans exactly \p Range.
-  void markDelayedChild(llvm::ArrayRef Range, NodeRole R);
-  /// Set role for the node that may or may not be delayed. Node must span
-  /// exactly \p Range.
-  void markMaybeDelayedChild(llvm::ArrayRef Range, NodeRole R);
 
   /// Finish building the tree and consume the root node.
   syntax::TranslationUnit *finalize() && {
@@ -285,7 +267,43 @@
 return maybeAppendSemicolon(Tokens, D);
   }
 
-  llvm::ArrayRef getDeclRange(const Decl *D) const {
+  /// Returns true if \p D is the last declarator in a chain and is thus
+  /// reponsible for creating SimpleDeclaration for the whole chain.
+  template 
+  bool isResponsibleForCreatingDeclaration(const T *D) const {
+static_assert((std::is_base_of::value ||
+   std::is_base_of::value),
+  "only DeclaratorDecl and TypedefNameDecl are supported.");
+
+const auto *TD = llvm::dyn_cast(D);
+if (TD 

[PATCH] D77041: [AST] Fix a crash on invalid constexpr Ctorinitializer when building RecoveryExpr.

2020-03-30 Thread Haojian Wu via Phabricator via cfe-commits
hokein created this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.
hokein edited the summary of this revision.
hokein added inline comments.
hokein added a reviewer: sammccall.



Comment at: clang/lib/Sema/SemaDecl.cpp:14359
+!ErrorsInCtorInitializer &&
 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
   FD->setInvalidDecl();

The crash is in `CheckConstexprFunctionDefinition`, I tried different ways to 
fixing it:

1) mark `FD` invalid when there are any errors in CtorInitailizer -- clang 
deliberately treats CtorDecl as valid even there are some errors in the 
initializer to prevent spurious diagnostics (see the cycle delegation in the 
test as an example), so marking them invalid may affect the quality of 
diagnostics;

2) Fixing it inside `CheckConstexprFunctionDefinition` or 
`isPotentialConstantExpr`, but it doesn't seem to be a right layer, these 
functions are expected to be called on a validDecl (or at least after a few 
sanity checks), and emit diagnostics.


crash stack:

  lang:  workspace/llvm-project/clang/lib/AST/ExprConstant.cpp:13704: bool 
EvaluateInPlace(clang::APValue &, (anonymous namespace)::EvalInfo &, const 
(anonymous namespace)::LValue &, const clang::Expr *, bool): Assertion 
`!E->isValueDependent()' failed.
   #8  EvaluateInPlace(clang::APValue&, (anonymous namespace)::EvalInfo&, 
(anonymous namespace)::LValue const&, clang::Expr const*, bool)  
workspace/llvm-project/clang/lib/AST/ExprConstant.cpp:0:0
   #9  HandleConstructorCall(clang::Expr const*, (anonymous namespace)::LValue 
const&, clang::APValue*, clang::CXXConstructorDecl const*, (anonymous 
namespace)::EvalInfo&, clang::APValue&)  
workspace/llvm-project/clang/lib/AST/ExprConstant.cpp:5779:57
  #10  HandleConstructorCall(clang::Expr const*, (anonymous namespace)::LValue 
const&, llvm::ArrayRef, clang::CXXConstructorDecl const*, 
(anonymous namespace)::EvalInfo&, clang::APValue&)  
workspace/llvm-project/clang/lib/AST/ExprConstant.cpp:5819:10
  #11  clang::Expr::isPotentialConstantExpr(clang::FunctionDecl const*, 
llvm::SmallVectorImpl >&) 
workspace/llvm-project/clang/lib/AST/ExprConstant.cpp:14746:5
  #12  CheckConstexprFunctionBody(clang::Sema&, clang::FunctionDecl const*, 
clang::Stmt*, clang::Sema::CheckConstexprKind)  
workspace/llvm-project/clang/lib/Sema/SemaDeclCXX.cpp:2306:7
  #13  clang::Sema::CheckConstexprFunctionDefinition(clang::FunctionDecl 
const*, clang::Sema::CheckConstexprKind)  
workspace/llvm-project/clang/lib/Sema/SemaDeclCXX.cpp:1766:0
  #14  clang::Sema::ActOnFinishFunctionBody(clang::Decl*, clang::Stmt*, bool)  
workspace/llvm-project/clang/lib/Sema/SemaDecl.cpp:14357:9
  #15  clang::Parser::ParseFunctionStatementBody(clang::Decl*, 
clang::Parser::ParseScope&)  
workspace/llvm-project/clang/lib/Parse/ParseStmt.cpp:2213:18


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D77041

Files:
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/test/SemaCXX/invalid-constructor-init.cpp


Index: clang/test/SemaCXX/invalid-constructor-init.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/invalid-constructor-init.cpp
@@ -0,0 +1,19 @@
+// RUN: %clang_cc1 -frecovery-ast -verify %s
+
+struct X {
+  int Y;
+  constexpr X() : Y(foo()) {} // expected-error {{use of undeclared identifier 
'foo'}}
+};
+
+struct X2 {
+  int Y = foo(); // expected-error {{use of undeclared identifier 'foo'}} \
+ // expected-note {{subexpression not valid in a constant 
expression}}
+  constexpr X2() {} // expected-error {{constexpr constructor never produces a 
constant expression}}
+};
+
+struct CycleDelegate {
+  int Y;
+  CycleDelegate(int) : Y(foo()) {} // expected-error {{use of undeclared 
identifier 'foo'}}
+  // no "delegation cycle" diagnostic emitted!
+  CycleDelegate(float) : CycleDelegate(1) {}
+};
Index: clang/lib/Sema/SemaDeclCXX.cpp
===
--- clang/lib/Sema/SemaDeclCXX.cpp
+++ clang/lib/Sema/SemaDeclCXX.cpp
@@ -1685,6 +1685,7 @@
 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
 bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD,
 CheckConstexprKind Kind) {
+  assert(!NewFD->isInvalidDecl());
   const CXXMethodDecl *MD = dyn_cast(NewFD);
   if (MD && MD->isInstance()) {
 // C++11 [dcl.constexpr]p4:
Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -45,6 +45,7 @@
 #include "clang/Sema/Template.h"
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/Triple.h"
+#include "llvm/Support/Casting.h"
 #include 
 #include 
 #include 
@@ -14345,7 +14346,16 @@
   ActivePolicy = &WP;
 }
 
+bool ErrorsInCtorInitializer =
+llvm::isa

[PATCH] D76953: [AST] Fix a crash on invalid bitwidth exprs when preserving the recoveryexprs.

2020-03-30 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 253523.
hokein marked 2 inline comments as done.
hokein added a comment.

address comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76953

Files:
  clang/lib/AST/ASTContext.cpp
  clang/lib/AST/RecordLayoutBuilder.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/test/Sema/invalid-bitwidth-expr.mm


Index: clang/test/Sema/invalid-bitwidth-expr.mm
===
--- /dev/null
+++ clang/test/Sema/invalid-bitwidth-expr.mm
@@ -0,0 +1,13 @@
+// RUN: %clang_cc1 -fobjc-runtime=gcc -frecovery-ast -verify %s
+// RUN: %clang_cc1 -fobjc-runtime=gcc -fno-recovery-ast -verify %s
+
+@interface Ivar
+{
+  int Foo : foo(); // expected-error {{use of undeclared identifier}}
+};
+@end
+
+struct X { int Y: foo(); }; // expected-error {{use of undeclared identifier}}
+
+constexpr int s = sizeof(Ivar);
+constexpr int ss = sizeof(X);
Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -16172,6 +16172,10 @@
 IdentifierInfo *FieldName,
 QualType FieldTy, bool IsMsStruct,
 Expr *BitWidth, bool *ZeroWidth) {
+  assert(BitWidth);
+  if (BitWidth->containsErrors())
+return ExprError();
+
   // Default to true; that shouldn't confuse checks for emptiness
   if (ZeroWidth)
 *ZeroWidth = true;
Index: clang/lib/AST/RecordLayoutBuilder.cpp
===
--- clang/lib/AST/RecordLayoutBuilder.cpp
+++ clang/lib/AST/RecordLayoutBuilder.cpp
@@ -3222,7 +3222,8 @@
   if (D->hasExternalLexicalStorage() && !D->getDefinition())
 getExternalSource()->CompleteType(const_cast(D));
   D = D->getDefinition();
-  assert(D && D->isThisDeclarationADefinition() && "Invalid interface decl!");
+  assert(D && !D->isInvalidDecl() && D->isThisDeclarationADefinition() &&
+ "Invalid interface decl!");
 
   // Look up this layout, if already laid out, return what we have.
   const ObjCContainerDecl *Key =
Index: clang/lib/AST/ASTContext.cpp
===
--- clang/lib/AST/ASTContext.cpp
+++ clang/lib/AST/ASTContext.cpp
@@ -2161,6 +2161,11 @@
 return getTypeInfo(cast(T)->getAdjustedType().getTypePtr());
   case Type::ObjCInterface: {
 const auto *ObjCI = cast(T);
+if (ObjCI->getDecl()->isInvalidDecl()) {
+  Width = 8;
+  Align = 8;
+  break;
+}
 const ASTRecordLayout &Layout = 
getASTObjCInterfaceLayout(ObjCI->getDecl());
 Width = toBits(Layout.getSize());
 Align = toBits(Layout.getAlignment());


Index: clang/test/Sema/invalid-bitwidth-expr.mm
===
--- /dev/null
+++ clang/test/Sema/invalid-bitwidth-expr.mm
@@ -0,0 +1,13 @@
+// RUN: %clang_cc1 -fobjc-runtime=gcc -frecovery-ast -verify %s
+// RUN: %clang_cc1 -fobjc-runtime=gcc -fno-recovery-ast -verify %s
+
+@interface Ivar
+{
+  int Foo : foo(); // expected-error {{use of undeclared identifier}}
+};
+@end
+
+struct X { int Y: foo(); }; // expected-error {{use of undeclared identifier}}
+
+constexpr int s = sizeof(Ivar);
+constexpr int ss = sizeof(X);
Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -16172,6 +16172,10 @@
 IdentifierInfo *FieldName,
 QualType FieldTy, bool IsMsStruct,
 Expr *BitWidth, bool *ZeroWidth) {
+  assert(BitWidth);
+  if (BitWidth->containsErrors())
+return ExprError();
+
   // Default to true; that shouldn't confuse checks for emptiness
   if (ZeroWidth)
 *ZeroWidth = true;
Index: clang/lib/AST/RecordLayoutBuilder.cpp
===
--- clang/lib/AST/RecordLayoutBuilder.cpp
+++ clang/lib/AST/RecordLayoutBuilder.cpp
@@ -3222,7 +3222,8 @@
   if (D->hasExternalLexicalStorage() && !D->getDefinition())
 getExternalSource()->CompleteType(const_cast(D));
   D = D->getDefinition();
-  assert(D && D->isThisDeclarationADefinition() && "Invalid interface decl!");
+  assert(D && !D->isInvalidDecl() && D->isThisDeclarationADefinition() &&
+ "Invalid interface decl!");
 
   // Look up this layout, if already laid out, return what we have.
   const ObjCContainerDecl *Key =
Index: clang/lib/AST/ASTContext.cpp
===
--- clang/lib/AST/ASTContext.cpp
+++ clang/lib/AST/ASTContext.cpp
@@ -2161,6 +2161,11 @@
 return getTypeInfo(cast(T)->getAdjustedType().getTypePtr());
   case Type::ObjCInterface: {
 const auto *ObjCI = cast(T);
+if (ObjCI->getDecl(

[PATCH] D77041: [AST] Fix a crash on invalid constexpr Ctorinitializer when building RecoveryExpr.

2020-03-30 Thread Haojian Wu via Phabricator via cfe-commits
hokein added inline comments.



Comment at: clang/lib/Sema/SemaDecl.cpp:14359
+!ErrorsInCtorInitializer &&
 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
   FD->setInvalidDecl();

The crash is in `CheckConstexprFunctionDefinition`, I tried different ways to 
fixing it:

1) mark `FD` invalid when there are any errors in CtorInitailizer -- clang 
deliberately treats CtorDecl as valid even there are some errors in the 
initializer to prevent spurious diagnostics (see the cycle delegation in the 
test as an example), so marking them invalid may affect the quality of 
diagnostics;

2) Fixing it inside `CheckConstexprFunctionDefinition` or 
`isPotentialConstantExpr`, but it doesn't seem to be a right layer, these 
functions are expected to be called on a validDecl (or at least after a few 
sanity checks), and emit diagnostics.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D77041



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


[clang] dcc04e0 - [Analyzer][MallocChecker] No warning for kfree of ZERO_SIZE_PTR.

2020-03-30 Thread Balázs Kéri via cfe-commits

Author: Balázs Kéri
Date: 2020-03-30T10:33:14+02:00
New Revision: dcc04e09cf6e36c6d2c47057a8f201f2c0784c69

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

LOG: [Analyzer][MallocChecker] No warning for kfree of ZERO_SIZE_PTR.

Summary:
The kernel kmalloc function may return a constant value ZERO_SIZE_PTR
if a zero-sized block is allocated. This special value is allowed to
be passed to kfree and should produce no warning.

This is a simple version but should be no problem. The macro is always
detected independent of if this is a kernel source code or any other
code.

Reviewers: Szelethus, martong

Reviewed By: Szelethus, martong

Subscribers: rnkovacs, xazax.hun, baloghadamsoftware, szepet, a.sidorin, 
mikhail.ramalho, Szelethus, donat.nagy, dkrupp, gamesh411, Charusso, martong, 
ASDenysPetrov, cfe-commits

Tags: #clang

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

Added: 


Modified: 
clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
clang/lib/StaticAnalyzer/Core/CheckerHelpers.cpp
clang/test/Analysis/kmalloc-linux.c
clang/test/Analysis/malloc.cpp

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
index baf2c48de3b2..32a500ffd102 100644
--- a/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
@@ -58,6 +58,7 @@
 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerHelpers.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/DynamicSize.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
@@ -389,6 +390,13 @@ class MallocChecker
   // TODO: Remove mutable by moving the initializtaion to the registry 
function.
   mutable Optional KernelZeroFlagVal;
 
+  using KernelZeroSizePtrValueTy = Optional;
+  /// Store the value of macro called `ZERO_SIZE_PTR`.
+  /// The value is initialized at first use, before first use the outer
+  /// Optional is empty, afterwards it contains another Optional that indicates
+  /// if the macro value could be determined, and if yes the value itself.
+  mutable Optional KernelZeroSizePtrValue;
+
   /// Process C++ operator new()'s allocation, which is the part of C++
   /// new-expression that goes before the constructor.
   void processNewAllocation(const CXXNewExpr *NE, CheckerContext &C,
@@ -658,6 +666,10 @@ class MallocChecker
 CheckerContext &C);
 
   void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
+
+  /// Test if value in ArgVal equals to value in macro `ZERO_SIZE_PTR`.
+  bool isArgZERO_SIZE_PTR(ProgramStateRef State, CheckerContext &C,
+  SVal ArgVal) const;
 };
 
 
//===--===//
@@ -1677,7 +1689,13 @@ ProgramStateRef MallocChecker::FreeMemAux(
   // Nonlocs can't be freed, of course.
   // Non-region locations (labels and fixed addresses) also shouldn't be freed.
   if (!R) {
-ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr, Family);
+// Exception:
+// If the macro ZERO_SIZE_PTR is defined, this could be a kernel source
+// code. In that case, the ZERO_SIZE_PTR defines a special value used for a
+// zero-sized memory block which is allowed to be freed, despite not being 
a
+// null pointer.
+if (Family != AF_Malloc || !isArgZERO_SIZE_PTR(State, C, ArgVal))
+  ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr, Family);
 return nullptr;
   }
 
@@ -3023,6 +3041,18 @@ ProgramStateRef MallocChecker::checkPointerEscapeAux(
   return State;
 }
 
+bool MallocChecker::isArgZERO_SIZE_PTR(ProgramStateRef State, CheckerContext 
&C,
+   SVal ArgVal) const {
+  if (!KernelZeroSizePtrValue)
+KernelZeroSizePtrValue =
+tryExpandAsInteger("ZERO_SIZE_PTR", C.getPreprocessor());
+
+  const llvm::APSInt *ArgValKnown =
+  C.getSValBuilder().getKnownValue(State, ArgVal);
+  return ArgValKnown && *KernelZeroSizePtrValue &&
+ ArgValKnown->getSExtValue() == **KernelZeroSizePtrValue;
+}
+
 static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
  ProgramStateRef prevState) {
   ReallocPairsTy currMap = currState->get();

diff  --git a/clang/lib/StaticAnalyzer/Core/CheckerHelpers.cpp 
b/clang/lib/StaticAnalyzer/Core/CheckerHelpers.cpp
index e43b172d018d..4b63ebc40ede 100644
--- a/clang/lib/StaticAnalyzer/C

[clang] f757ecb - [AST] Fix a crash on invalid bitwidth exprs when preserving the recoveryexprs.

2020-03-30 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2020-03-30T10:52:00+02:00
New Revision: f757ecbf85605735195441abefd9c291f5e317cc

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

LOG: [AST] Fix a crash on invalid bitwidth exprs when preserving the 
recoveryexprs.

Summary:
If the bitwith expr contains errors, we mark the field decl invalid.

This patch also tweaks the behavior of ObjCInterfaceDecl to be consistent with
existing RecordDecl -- getObjCLayout method is only called with valid decls.

Reviewers: sammccall

Subscribers: cfe-commits

Tags: #clang

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

Added: 
clang/test/Sema/invalid-bitwidth-expr.mm

Modified: 
clang/lib/AST/ASTContext.cpp
clang/lib/AST/RecordLayoutBuilder.cpp
clang/lib/Sema/SemaDecl.cpp

Removed: 




diff  --git a/clang/lib/AST/ASTContext.cpp b/clang/lib/AST/ASTContext.cpp
index 19f67fc2bb3f..461b155df7bf 100644
--- a/clang/lib/AST/ASTContext.cpp
+++ b/clang/lib/AST/ASTContext.cpp
@@ -2161,6 +2161,11 @@ TypeInfo ASTContext::getTypeInfoImpl(const Type *T) 
const {
 return getTypeInfo(cast(T)->getAdjustedType().getTypePtr());
   case Type::ObjCInterface: {
 const auto *ObjCI = cast(T);
+if (ObjCI->getDecl()->isInvalidDecl()) {
+  Width = 8;
+  Align = 8;
+  break;
+}
 const ASTRecordLayout &Layout = 
getASTObjCInterfaceLayout(ObjCI->getDecl());
 Width = toBits(Layout.getSize());
 Align = toBits(Layout.getAlignment());

diff  --git a/clang/lib/AST/RecordLayoutBuilder.cpp 
b/clang/lib/AST/RecordLayoutBuilder.cpp
index 9a21732b63e3..028e82a5df4d 100644
--- a/clang/lib/AST/RecordLayoutBuilder.cpp
+++ b/clang/lib/AST/RecordLayoutBuilder.cpp
@@ -3222,7 +3222,8 @@ ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
   if (D->hasExternalLexicalStorage() && !D->getDefinition())
 getExternalSource()->CompleteType(const_cast(D));
   D = D->getDefinition();
-  assert(D && D->isThisDeclarationADefinition() && "Invalid interface decl!");
+  assert(D && !D->isInvalidDecl() && D->isThisDeclarationADefinition() &&
+ "Invalid interface decl!");
 
   // Look up this layout, if already laid out, return what we have.
   const ObjCContainerDecl *Key =

diff  --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 9319f4eff919..ea3a0c22c401 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -16172,6 +16172,10 @@ ExprResult Sema::VerifyBitField(SourceLocation 
FieldLoc,
 IdentifierInfo *FieldName,
 QualType FieldTy, bool IsMsStruct,
 Expr *BitWidth, bool *ZeroWidth) {
+  assert(BitWidth);
+  if (BitWidth->containsErrors())
+return ExprError();
+
   // Default to true; that shouldn't confuse checks for emptiness
   if (ZeroWidth)
 *ZeroWidth = true;

diff  --git a/clang/test/Sema/invalid-bitwidth-expr.mm 
b/clang/test/Sema/invalid-bitwidth-expr.mm
new file mode 100644
index ..fe93cac683ae
--- /dev/null
+++ b/clang/test/Sema/invalid-bitwidth-expr.mm
@@ -0,0 +1,13 @@
+// RUN: %clang_cc1 -fobjc-runtime=gcc -frecovery-ast -verify %s
+// RUN: %clang_cc1 -fobjc-runtime=gcc -fno-recovery-ast -verify %s
+
+@interface Ivar
+{
+  int Foo : foo(); // expected-error {{use of undeclared identifier}}
+};
+@end
+
+struct X { int Y: foo(); }; // expected-error {{use of undeclared identifier}}
+
+constexpr int s = sizeof(Ivar);
+constexpr int ss = sizeof(X);



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


[PATCH] D76830: [Analyzer][MallocChecker] No warning for kfree of ZERO_SIZE_PTR.

2020-03-30 Thread Balázs Kéri via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGdcc04e09cf6e: [Analyzer][MallocChecker] No warning for kfree 
of ZERO_SIZE_PTR. (authored by balazske).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76830

Files:
  clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
  clang/lib/StaticAnalyzer/Core/CheckerHelpers.cpp
  clang/test/Analysis/kmalloc-linux.c
  clang/test/Analysis/malloc.cpp

Index: clang/test/Analysis/malloc.cpp
===
--- clang/test/Analysis/malloc.cpp
+++ clang/test/Analysis/malloc.cpp
@@ -164,3 +164,11 @@
   (void)a.getName();
 }
 } // namespace argument_leak
+
+#define ZERO_SIZE_PTR ((void *)16)
+
+void test_delete_ZERO_SIZE_PTR() {
+  int *Ptr = (int *)ZERO_SIZE_PTR;
+  // ZERO_SIZE_PTR is specially handled but only for malloc family
+  delete Ptr; // expected-warning{{Argument to 'delete' is a constant address (16)}}
+}
Index: clang/test/Analysis/kmalloc-linux.c
===
--- clang/test/Analysis/kmalloc-linux.c
+++ clang/test/Analysis/kmalloc-linux.c
@@ -121,3 +121,17 @@
   if (list == NULL)
 return;
 } // expected-warning{{Potential leak of memory pointed to by 'list'}}
+
+// kmalloc can return a constant value defined in ZERO_SIZE_PTR
+// if a block of size 0 is requested
+#define ZERO_SIZE_PTR ((void *)16)
+
+void test_kfree_ZERO_SIZE_PTR() {
+  void *ptr = ZERO_SIZE_PTR;
+  kfree(ptr); // no warning about freeing this value
+}
+
+void test_kfree_other_constant_value() {
+  void *ptr = (void *)1;
+  kfree(ptr); // expected-warning{{Argument to kfree() is a constant address (1)}}
+}
Index: clang/lib/StaticAnalyzer/Core/CheckerHelpers.cpp
===
--- clang/lib/StaticAnalyzer/Core/CheckerHelpers.cpp
+++ clang/lib/StaticAnalyzer/Core/CheckerHelpers.cpp
@@ -126,9 +126,6 @@
 if (!T.isOneOf(tok::l_paren, tok::r_paren))
   FilteredTokens.push_back(T);
 
-  if (FilteredTokens.size() > 2)
-return llvm::None;
-
   // Parse an integer at the end of the macro definition.
   const Token &T = FilteredTokens.back();
   if (!T.isLiteral())
@@ -140,11 +137,10 @@
 return llvm::None;
 
   // Parse an optional minus sign.
-  if (FilteredTokens.size() == 2) {
-if (FilteredTokens.front().is(tok::minus))
+  size_t Size = FilteredTokens.size();
+  if (Size >= 2) {
+if (FilteredTokens[Size - 2].is(tok::minus))
   IntValue = -IntValue;
-else
-  return llvm::None;
   }
 
   return IntValue.getSExtValue();
Index: clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
@@ -58,6 +58,7 @@
 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerHelpers.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/DynamicSize.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
@@ -389,6 +390,13 @@
   // TODO: Remove mutable by moving the initializtaion to the registry function.
   mutable Optional KernelZeroFlagVal;
 
+  using KernelZeroSizePtrValueTy = Optional;
+  /// Store the value of macro called `ZERO_SIZE_PTR`.
+  /// The value is initialized at first use, before first use the outer
+  /// Optional is empty, afterwards it contains another Optional that indicates
+  /// if the macro value could be determined, and if yes the value itself.
+  mutable Optional KernelZeroSizePtrValue;
+
   /// Process C++ operator new()'s allocation, which is the part of C++
   /// new-expression that goes before the constructor.
   void processNewAllocation(const CXXNewExpr *NE, CheckerContext &C,
@@ -658,6 +666,10 @@
 CheckerContext &C);
 
   void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
+
+  /// Test if value in ArgVal equals to value in macro `ZERO_SIZE_PTR`.
+  bool isArgZERO_SIZE_PTR(ProgramStateRef State, CheckerContext &C,
+  SVal ArgVal) const;
 };
 
 //===--===//
@@ -1677,7 +1689,13 @@
   // Nonlocs can't be freed, of course.
   // Non-region locations (labels and fixed addresses) also shouldn't be freed.
   if (!R) {
-ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr, Family);
+// Exception:
+// If the macro ZERO_SIZE_PTR is defined, this could be a kernel source
+// code. In that case, the ZERO_SIZE_PTR defines a special value used for a
+// zero-sized me

[PATCH] D76953: [AST] Fix a crash on invalid bitwidth exprs when preserving the recoveryexprs.

2020-03-30 Thread Haojian Wu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGf757ecbf8560: [AST] Fix a crash on invalid bitwidth exprs 
when preserving the recoveryexprs. (authored by hokein).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76953

Files:
  clang/lib/AST/ASTContext.cpp
  clang/lib/AST/RecordLayoutBuilder.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/test/Sema/invalid-bitwidth-expr.mm


Index: clang/test/Sema/invalid-bitwidth-expr.mm
===
--- /dev/null
+++ clang/test/Sema/invalid-bitwidth-expr.mm
@@ -0,0 +1,13 @@
+// RUN: %clang_cc1 -fobjc-runtime=gcc -frecovery-ast -verify %s
+// RUN: %clang_cc1 -fobjc-runtime=gcc -fno-recovery-ast -verify %s
+
+@interface Ivar
+{
+  int Foo : foo(); // expected-error {{use of undeclared identifier}}
+};
+@end
+
+struct X { int Y: foo(); }; // expected-error {{use of undeclared identifier}}
+
+constexpr int s = sizeof(Ivar);
+constexpr int ss = sizeof(X);
Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -16172,6 +16172,10 @@
 IdentifierInfo *FieldName,
 QualType FieldTy, bool IsMsStruct,
 Expr *BitWidth, bool *ZeroWidth) {
+  assert(BitWidth);
+  if (BitWidth->containsErrors())
+return ExprError();
+
   // Default to true; that shouldn't confuse checks for emptiness
   if (ZeroWidth)
 *ZeroWidth = true;
Index: clang/lib/AST/RecordLayoutBuilder.cpp
===
--- clang/lib/AST/RecordLayoutBuilder.cpp
+++ clang/lib/AST/RecordLayoutBuilder.cpp
@@ -3222,7 +3222,8 @@
   if (D->hasExternalLexicalStorage() && !D->getDefinition())
 getExternalSource()->CompleteType(const_cast(D));
   D = D->getDefinition();
-  assert(D && D->isThisDeclarationADefinition() && "Invalid interface decl!");
+  assert(D && !D->isInvalidDecl() && D->isThisDeclarationADefinition() &&
+ "Invalid interface decl!");
 
   // Look up this layout, if already laid out, return what we have.
   const ObjCContainerDecl *Key =
Index: clang/lib/AST/ASTContext.cpp
===
--- clang/lib/AST/ASTContext.cpp
+++ clang/lib/AST/ASTContext.cpp
@@ -2161,6 +2161,11 @@
 return getTypeInfo(cast(T)->getAdjustedType().getTypePtr());
   case Type::ObjCInterface: {
 const auto *ObjCI = cast(T);
+if (ObjCI->getDecl()->isInvalidDecl()) {
+  Width = 8;
+  Align = 8;
+  break;
+}
 const ASTRecordLayout &Layout = 
getASTObjCInterfaceLayout(ObjCI->getDecl());
 Width = toBits(Layout.getSize());
 Align = toBits(Layout.getAlignment());


Index: clang/test/Sema/invalid-bitwidth-expr.mm
===
--- /dev/null
+++ clang/test/Sema/invalid-bitwidth-expr.mm
@@ -0,0 +1,13 @@
+// RUN: %clang_cc1 -fobjc-runtime=gcc -frecovery-ast -verify %s
+// RUN: %clang_cc1 -fobjc-runtime=gcc -fno-recovery-ast -verify %s
+
+@interface Ivar
+{
+  int Foo : foo(); // expected-error {{use of undeclared identifier}}
+};
+@end
+
+struct X { int Y: foo(); }; // expected-error {{use of undeclared identifier}}
+
+constexpr int s = sizeof(Ivar);
+constexpr int ss = sizeof(X);
Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -16172,6 +16172,10 @@
 IdentifierInfo *FieldName,
 QualType FieldTy, bool IsMsStruct,
 Expr *BitWidth, bool *ZeroWidth) {
+  assert(BitWidth);
+  if (BitWidth->containsErrors())
+return ExprError();
+
   // Default to true; that shouldn't confuse checks for emptiness
   if (ZeroWidth)
 *ZeroWidth = true;
Index: clang/lib/AST/RecordLayoutBuilder.cpp
===
--- clang/lib/AST/RecordLayoutBuilder.cpp
+++ clang/lib/AST/RecordLayoutBuilder.cpp
@@ -3222,7 +3222,8 @@
   if (D->hasExternalLexicalStorage() && !D->getDefinition())
 getExternalSource()->CompleteType(const_cast(D));
   D = D->getDefinition();
-  assert(D && D->isThisDeclarationADefinition() && "Invalid interface decl!");
+  assert(D && !D->isInvalidDecl() && D->isThisDeclarationADefinition() &&
+ "Invalid interface decl!");
 
   // Look up this layout, if already laid out, return what we have.
   const ObjCContainerDecl *Key =
Index: clang/lib/AST/ASTContext.cpp
===
--- clang/lib/AST/ASTContext.cpp
+++ clang/lib/AST/ASTContext.cpp
@@ -2161,6 +2161,11 @@
 return getTypeInfo(cast(T)->getAdjustedType().getTypePtr());
   case Ty

[PATCH] D77037: [AST] Fix crashes on decltype(recovery-expr).

2020-03-30 Thread Sam McCall via Phabricator via cfe-commits
sammccall added inline comments.



Comment at: clang/include/clang/AST/Type.h:2144
+  bool isErrorType() const {
+return getDependence() & TypeDependence::Error;
+  }

Why is this  called `isErrorType` when the expr version is `containsErrors`?



Comment at: clang/lib/Parse/ParseExprCXX.cpp:3109
+QualType PreferredType;
+if (TypeRep)
+  PreferredType = Actions.ProduceConstructorSignatureHelp(

Add a comment for what the null case means? (When do we actually hit this?)



Comment at: clang/lib/Sema/SemaType.cpp:1591
+if (Result.isNull() || Result->isErrorType()) {
   Result = Context.IntTy;
   declarator.setInvalidType(true);

we've added the ability to represent types containing errors, but now we're 
dropping the type.
Is marking the declarator as invalid sufficient?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D77037



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


[PATCH] D77012: [analyzer] Fix StdLibraryFunctionsChecker NotNull Constraint Check

2020-03-30 Thread Gabor Marton via Phabricator via cfe-commits
martong accepted this revision.
martong added a comment.

LGTM and thanks!

In D77012#1948550 , @NoQ wrote:

> Thanks!
>
> @Szelethus can we make this checker depend on undefined value checker 
> (probably CallAndMessage) so that uninitialized arguments were handled first? 
> In fact, can we make a silent assumption that everything depends on `core`? 
> If so we could eliminate all checks for undefined values in PreStmt and 
> PreCall.


+1, we should really do that.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D77012



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


[PATCH] D75068: libclang: Add static build support for Windows

2020-03-30 Thread Cristian Adam via Phabricator via cfe-commits
cristian.adam added a comment.

Ping


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D75068



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


[PATCH] D77037: [AST] Fix crashes on decltype(recovery-expr).

2020-03-30 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 253537.
hokein marked 3 inline comments as done.
hokein added a comment.

address review comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D77037

Files:
  clang/include/clang/AST/DependenceFlags.h
  clang/include/clang/AST/Type.h
  clang/lib/Parse/ParseExprCXX.cpp
  clang/lib/Sema/SemaType.cpp
  clang/test/AST/ast-dump-expr-errors.cpp
  clang/test/Sema/invalid-member.cpp

Index: clang/test/Sema/invalid-member.cpp
===
--- clang/test/Sema/invalid-member.cpp
+++ clang/test/Sema/invalid-member.cpp
@@ -1,7 +1,15 @@
 // RUN: %clang_cc1 -verify -fsyntax-only %s
-void foo(); // expected-note {{requires 0 arguments}}
+// RUN: %clang_cc1 -verify -fsyntax-only -frecovery-ast %s
+
+void foo(); // expected-note 2{{requires 0 arguments}}
 class X {
   decltype(foo(42)) invalid; // expected-error {{no matching function}}
 };
 // Should be able to evaluate sizeof without crashing.
 static_assert(sizeof(X) == 1, "No valid members");
+
+class Y {
+  typeof(foo(42)) invalid; // expected-error {{no matching function}}
+};
+// Should be able to evaluate sizeof without crashing.
+static_assert(sizeof(Y) == 1, "No valid members");
Index: clang/test/AST/ast-dump-expr-errors.cpp
===
--- clang/test/AST/ast-dump-expr-errors.cpp
+++ clang/test/AST/ast-dump-expr-errors.cpp
@@ -42,5 +42,9 @@
 
 // FIXME: store initializer even when 'auto' could not be deduced.
 // Expressions with errors currently do not keep initializers around.
-// CHECK: `-VarDecl {{.*}} invalid e 'auto'
+// CHECK: -VarDecl {{.*}} invalid e 'auto'
 auto e = bar();
+
+// Error type should result in an invalid decl.
+// CHECK: -VarDecl {{.*}} invalid f 'decltype((bar))'
+decltype(bar()) f;
Index: clang/lib/Sema/SemaType.cpp
===
--- clang/lib/Sema/SemaType.cpp
+++ clang/lib/Sema/SemaType.cpp
@@ -1591,6 +1591,8 @@
   Result = Context.IntTy;
   declarator.setInvalidType(true);
 }
+if (Result->containsErrors())
+  declarator.setInvalidType(true);
 break;
   }
   case DeclSpec::TST_decltype: {
@@ -1602,6 +1604,8 @@
   Result = Context.IntTy;
   declarator.setInvalidType(true);
 }
+if (Result->containsErrors())
+  declarator.setInvalidType(true);
 break;
   }
   case DeclSpec::TST_underlyingType:
Index: clang/lib/Parse/ParseExprCXX.cpp
===
--- clang/lib/Parse/ParseExprCXX.cpp
+++ clang/lib/Parse/ParseExprCXX.cpp
@@ -3105,10 +3105,14 @@
   auto RunSignatureHelp = [&]() {
 ParsedType TypeRep =
 Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
-assert(TypeRep && "invalid types should be handled before");
-QualType PreferredType = Actions.ProduceConstructorSignatureHelp(
-getCurScope(), TypeRep.get()->getCanonicalTypeInternal(),
-DeclaratorInfo.getEndLoc(), ConstructorArgs, ConstructorLParen);
+QualType PreferredType;
+// ActOnTypeName might adjust DeclaratorInfo and return a null type even
+// the passing DeclaratorInfo is valid, e.g. running SignatureHelp on
+// `new decltype(invalid) (^)`.
+if (TypeRep)
+  PreferredType = Actions.ProduceConstructorSignatureHelp(
+  getCurScope(), TypeRep.get()->getCanonicalTypeInternal(),
+  DeclaratorInfo.getEndLoc(), ConstructorArgs, ConstructorLParen);
 CalledSignatureHelp = true;
 return PreferredType;
   };
Index: clang/include/clang/AST/Type.h
===
--- clang/include/clang/AST/Type.h
+++ clang/include/clang/AST/Type.h
@@ -2139,6 +2139,11 @@
 return static_cast(TypeBits.Dependence);
   }
 
+  /// Whether this type is an error type.
+  bool containsErrors() const {
+return getDependence() & TypeDependence::Error;
+  }
+
   /// Whether this type is a dependent type, meaning that its definition
   /// somehow depends on a template parameter (C++ [temp.dep.type]).
   bool isDependentType() const {
Index: clang/include/clang/AST/DependenceFlags.h
===
--- clang/include/clang/AST/DependenceFlags.h
+++ clang/include/clang/AST/DependenceFlags.h
@@ -50,14 +50,16 @@
 /// Whether this type is a variably-modified type (C99 6.7.5).
 VariablyModified = 8,
 
-// FIXME: add Error bit.
+/// Whether this type references an error, e.g. decltype(err-expression)
+/// yields an error type.
+Error = 16,
 
 None = 0,
-All = 15,
+All = 31,
 
 DependentInstantiation = Dependent | Instantiation,
 
-LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/VariablyModified)
+LLVM_MARK_AS_BITMASK_ENUM(/*Large

[PATCH] D77037: [AST] Fix crashes on decltype(recovery-expr).

2020-03-30 Thread Haojian Wu via Phabricator via cfe-commits
hokein added inline comments.



Comment at: clang/lib/Parse/ParseExprCXX.cpp:3109
+QualType PreferredType;
+if (TypeRep)
+  PreferredType = Actions.ProduceConstructorSignatureHelp(

sammccall wrote:
> Add a comment for what the null case means? (When do we actually hit this?)
yeah, the 
[`CompleteTest`](https://github.com/llvm/llvm-project/blob/master/clang/unittests/Sema/CodeCompleteTest.cpp#L490)
 hits the assertion after this patch. 

the assertion seems incorrect  -- IIUC, the assertion is for the 
`isInvalidType()` sanity check on Line 3090, however
In `ActOnTypeName`,  `DeclaratorInfo` could be modified (by 
`GetTypeForDeclarator`) before calling `isInvalidType`.


btw, I think for the CodeCompleteTest, would be nicer to make `ActOnTypeName` 
return `decltype((bar))`, rather than the null type, but I'm not 
sure changing the `ActOnTypeName` behavior has any side effect.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D77037



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


[PATCH] D77041: [AST] Fix a crash on invalid constexpr Ctorinitializer when building RecoveryExpr.

2020-03-30 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

This makes me nervous, marking the constructor as invalid seems much safer. Can 
you show tests it regresses?




Comment at: clang/lib/Sema/SemaDecl.cpp:14359
+!ErrorsInCtorInitializer &&
 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
   FD->setInvalidDecl();

hokein wrote:
> The crash is in `CheckConstexprFunctionDefinition`, I tried different ways to 
> fixing it:
> 
> 1) mark `FD` invalid when there are any errors in CtorInitailizer -- clang 
> deliberately treats CtorDecl as valid even there are some errors in the 
> initializer to prevent spurious diagnostics (see the cycle delegation in the 
> test as an example), so marking them invalid may affect the quality of 
> diagnostics;
> 
> 2) Fixing it inside `CheckConstexprFunctionDefinition` or 
> `isPotentialConstantExpr`, but it doesn't seem to be a right layer, these 
> functions are expected to be called on a validDecl (or at least after a few 
> sanity checks), and emit diagnostics.
> clang deliberately treats CtorDecl as valid even there are some errors in the 
> initializer
Do you mean currently? (when such errors result in destroying the whole init 
expr)
If so, it would be nice to preserve this indeed.

I'm worried that we're going to decide that a constexpr constructor is valid 
and then actually try to evaluate it at compile time.
What happens if we try to evaluate `constexpr int Z = X().Y` in your testcase?

> Fixing it inside CheckConstexprFunctionDefinition

I have a couple of concerns with where it's currently implemented:
 - aren't there lots of other paths we're going to call isPotentialConstantExpr 
and crash? CheckConstexprFunctionDefinition is large and complicated, 
init-lists are only a small part.
 - if we treat anything with errors in the ctor as valid (am I reading that 
right?!) then won't that mask *other* problems where the non-error parts of the 
definition should cause it to be treated as invalid? e.g. `Foo() : 
m1(broken_but_maybe_constexpr()), m2(exists_and_not_constexpr()) {}`

Wherever this goes, if we're going to do something subtle like marking 
diagnostics as valid based on errors in them, it deserves a comment laying out 
the cases.



Comment at: clang/test/SemaCXX/invalid-constructor-init.cpp:17
+  CycleDelegate(int) : Y(foo()) {} // expected-error {{use of undeclared 
identifier 'foo'}}
+  // no "delegation cycle" diagnostic emitted!
+  CycleDelegate(float) : CycleDelegate(1) {}

what's the behavior with -fno-recovery-ast?
(It'd be nice to improve it, failing to improve it is OK. regressing is 
probably bad...)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D77041



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


[PATCH] D77048: [Clang][CodeGen] Fixing mismatch between memory layout and const expressions for oversized bitfields

2020-03-30 Thread Lucas Prates via Phabricator via cfe-commits
pratlucas created this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

The construction of constants for structs/unions was conflicting the
expected memory layout for over-sized bit-fields. When building the
necessary bits for those fields, clang was ignoring the size information
computed for the struct/union memory layout and using the original data
from the AST's FieldDecl information. This caused an issue in big-endian
targets, where the field's contant was incorrectly misplaced due to
endian calculations.

This patch aims to separate the constant value from the necessary
padding bits, using the proper size information for each one of them.
With this, the layout of constants for over-sized bit-fields matches the
ABI requirements.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D77048

Files:
  clang/lib/CodeGen/CGExprConstant.cpp
  clang/test/CodeGenCXX/bitfield-layout.cpp

Index: clang/test/CodeGenCXX/bitfield-layout.cpp
===
--- clang/test/CodeGenCXX/bitfield-layout.cpp
+++ clang/test/CodeGenCXX/bitfield-layout.cpp
@@ -1,11 +1,14 @@
-// RUN: %clang_cc1 %s -triple=x86_64-apple-darwin10 -emit-llvm -o - -O3 | FileCheck -check-prefix CHECK-LP64 %s
-// RUN: %clang_cc1 %s -triple=i386-apple-darwin10 -emit-llvm -o - -O3 | FileCheck -check-prefix CHECK-LP32 %s
+// RUN: %clang_cc1 %s -triple=x86_64-apple-darwin10 -emit-llvm -o - -O3 | FileCheck -check-prefix=CHECK-LP64 -check-prefix=CHECK %s
+// RUN: %clang_cc1 %s -triple=i386-apple-darwin10 -emit-llvm -o - -O3 | FileCheck -check-prefix CHECK-LP32 -check-prefix=CHECK %s
+// RUN: %clang_cc1 %s -triple=aarch64_be-none-eabi -emit-llvm -o - -O3 | FileCheck -check-prefix CHECK-A64BE -check-prefix=CHECK %s
+// RUN: %clang_cc1 %s -triple=thumbv7_be-none-eabi -emit-llvm -o - -O3 | FileCheck -check-prefix CHECK-A32BE -check-prefix=CHECK %s
 
 // CHECK-LP64: %union.Test1 = type { i32, [4 x i8] }
 union Test1 {
   int a;
   int b: 39;
-} t1;
+};
+Test1 t1;
 
 // CHECK-LP64: %union.Test2 = type { i8 }
 union Test2 {
@@ -17,10 +20,16 @@
   int : 9;
 } t3;
 
+// CHECK: %union.Test4 = type { i8, i8 }
+union Test4 {
+  char val : 16;
+};
+Test4 t4;
 
 #define CHECK(x) if (!(x)) return __LINE__
 
-int f() {
+// CHECK: define i32 @_Z11test_assignv()
+int test_assign() {
   struct {
 int a;
 
@@ -37,7 +46,42 @@
   CHECK(c.b == (unsigned long long)-1);
   CHECK(c.c == 0);
 
-// CHECK-LP64: ret i32 0
-// CHECK-LP32: ret i32 0
+  Test1 u1;
+  Test4 u2;
+
+  u1.b = 1;
+  u2.val = 42;
+
+  CHECK(u1.b == 1);
+  CHECK(u2.val == 42);
+
+// CHECK: ret i32 0
+  return 0;
+}
+
+// CHECK: define i32 @_Z9test_initv()
+int test_init() {
+  struct S {
+int a;
+
+unsigned long long b : 65;
+
+int c;
+  };
+  S s1 = {1, 42, 0};
+
+  CHECK(s1.a == 1);
+  CHECK(s1.b == (unsigned long long)42);
+  CHECK(s1.c == 0);
+
+  Test1 u1 = {1};
+  Test4 u2 = {42};
+
+  CHECK(u1.a == 1);
+  CHECK(u1.b == 1);
+  CHECK(u2.val == 42);
+
+// CHECK: ret i32 0
   return 0;
 }
+
Index: clang/lib/CodeGen/CGExprConstant.cpp
===
--- clang/lib/CodeGen/CGExprConstant.cpp
+++ clang/lib/CodeGen/CGExprConstant.cpp
@@ -589,23 +589,37 @@
 bool ConstStructBuilder::AppendBitField(
 const FieldDecl *Field, uint64_t FieldOffset, llvm::ConstantInt *CI,
 bool AllowOverwrite) {
-  uint64_t FieldSize = Field->getBitWidthValue(CGM.getContext());
+  const CGRecordLayout &RL =
+CGM.getTypes().getCGRecordLayout(Field->getParent());
+  const CGBitFieldInfo &Info = RL.getBitFieldInfo(Field);
   llvm::APInt FieldValue = CI->getValue();
 
   // Promote the size of FieldValue if necessary
   // FIXME: This should never occur, but currently it can because initializer
   // constants are cast to bool, and because clang is not enforcing bitfield
   // width limits.
-  if (FieldSize > FieldValue.getBitWidth())
-FieldValue = FieldValue.zext(FieldSize);
+  if (Info.Size > FieldValue.getBitWidth())
+FieldValue = FieldValue.zext(Info.Size);
 
   // Truncate the size of FieldValue to the bit field size.
-  if (FieldSize < FieldValue.getBitWidth())
-FieldValue = FieldValue.trunc(FieldSize);
+  if (Info.Size < FieldValue.getBitWidth())
+FieldValue = FieldValue.trunc(Info.Size);
 
-  return Builder.addBits(FieldValue,
- CGM.getContext().toBits(StartOffset) + FieldOffset,
- AllowOverwrite);
+  // Add field value bits
+  uint64_t AdjustedOffset = CGM.getContext().toBits(StartOffset) + FieldOffset;
+  if (!Builder.addBits(FieldValue, AdjustedOffset, AllowOverwrite))
+return false;
+  
+  // Add padding bits in case of over-sized bit-field.
+  //   "The first sizeof(T)*8 bits are used to hold the value of the bit-field,
+  //   followed by n - sizeof(T)*8 bits of padding."
+  uint64_t FieldWidth = Field->getBitWidthValue(CGM.getContext());
+  if (FieldWidth > Info.Size) {
+llvm::APIn

[PATCH] D77037: [AST] Fix crashes on decltype(recovery-expr).

2020-03-30 Thread Sam McCall via Phabricator via cfe-commits
sammccall accepted this revision.
sammccall added inline comments.
This revision is now accepted and ready to land.



Comment at: clang/lib/Parse/ParseExprCXX.cpp:3109
+QualType PreferredType;
+if (TypeRep)
+  PreferredType = Actions.ProduceConstructorSignatureHelp(

hokein wrote:
> sammccall wrote:
> > Add a comment for what the null case means? (When do we actually hit this?)
> yeah, the 
> [`CompleteTest`](https://github.com/llvm/llvm-project/blob/master/clang/unittests/Sema/CodeCompleteTest.cpp#L490)
>  hits the assertion after this patch. 
> 
> the assertion seems incorrect  -- IIUC, the assertion is for the 
> `isInvalidType()` sanity check on Line 3090, however
> In `ActOnTypeName`,  `DeclaratorInfo` could be modified (by 
> `GetTypeForDeclarator`) before calling `isInvalidType`.
> 
> 
> btw, I think for the CodeCompleteTest, would be nicer to make `ActOnTypeName` 
> return `decltype((bar))`, rather than the null type, but I'm 
> not sure changing the `ActOnTypeName` behavior has any side effect.
> the assertion seems incorrect -- IIUC, the assertion is for the 
> isInvalidType() sanity check on Line 3090, however

What you say makes sense, but I think it's worth probing why it's not currently 
hit (e.g. by `int x(auto);`, where `GetDeclSpecTypeForDeclarator` marks the 
decl as invalid because auto isn't allowed in a prototype).

> btw, I think for the CodeCompleteTest, would be nicer to make ActOnTypeName 
> return decltype((bar)), rather than the null type

Definitely. I think "invalid" on a type-concept is stronger than what we're 
looking for - since we're not tracking errors in decls, we'd want to use 
"haserrors" on type-concepts and then promote to "invalid" on decl-concepts.

Ugh, the design of "Declarator" makes this difficult, because there's no 
distinction between "type of this declarator is invalid" and "type of this 
declarator makes the declarator invalid".

I'd suggest leaving a FIXME on the changes in SemaType, saying something like 
"we want resulting declarations to be marked invalid, but claiming the type is 
invalid is too strong - e.g. it causes ActOnTypeName to return a null type."



Comment at: clang/lib/Sema/SemaType.cpp:1594
 }
+if (Result->containsErrors())
+  declarator.setInvalidType(true);

are you sure you want this in the individual cases, rather than once at the end 
of this function?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D77037



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


[clang] 0574030 - [clang-format] only parse C# generic type constraints in C#

2020-03-30 Thread Krasimir Georgiev via cfe-commits

Author: Krasimir Georgiev
Date: 2020-03-30T13:13:07+02:00
New Revision: 0574030c01615d4ce26de0d9b0d64292ab3eac9b

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

LOG: [clang-format] only parse C# generic type constraints in C#

Commit "[clang-format] Handle C# generic type constraints",
https://github.com/llvm/llvm-project/commit/dcbcec4822f47ec5b638dd9c20dcebd464569dae
regressed the formatting of code containing `where` as an identifier in other
languages.

Added: 


Modified: 
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTestCSharp.cpp

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 8a1e247463d5..8f40fc7bdcb6 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -1047,7 +1047,7 @@ class AnnotatingParser {
Keywords.kw___has_include_next)) {
 parseHasInclude();
   }
-  if (Tok->is(Keywords.kw_where) && Tok->Next &&
+  if (Style.isCSharp() && Tok->is(Keywords.kw_where) && Tok->Next &&
   Tok->Next->isNot(tok::l_paren)) {
 Tok->Type = TT_CSharpGenericTypeConstraint;
 parseCSharpGenericTypeConstraint();

diff  --git a/clang/unittests/Format/FormatTestCSharp.cpp 
b/clang/unittests/Format/FormatTestCSharp.cpp
index 17b8e070c36a..f5e0bab1cb31 100644
--- a/clang/unittests/Format/FormatTestCSharp.cpp
+++ b/clang/unittests/Format/FormatTestCSharp.cpp
@@ -709,6 +709,14 @@ class ItemFactory
   IAnotherInterface,
   IAnotherInterfaceStill {})",
Style);
+
+  // In other languages `where` can be used as a normal identifier.
+  // This example is in C++!
+  verifyFormat(R"(//
+class A {
+  int f(int where) {}
+};)",
+   getGoogleStyle(FormatStyle::LK_Cpp));
 }
 
 } // namespace format



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


[PATCH] D76725: [clangd] Build ASTs only with fresh preambles or after building a new preamble

2020-03-30 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet updated this revision to Diff 253552.
kadircet added a comment.

- Make use of a separate queue for golden ASTs to prevent any races that might

occur due PreambleThread finishing multiple preambles before ASTWorker gets to
process others.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76725

Files:
  clang-tools-extra/clangd/Preamble.cpp
  clang-tools-extra/clangd/Preamble.h
  clang-tools-extra/clangd/TUScheduler.cpp
  clang-tools-extra/clangd/unittests/FileIndexTests.cpp
  clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
  clang-tools-extra/clangd/unittests/TestTU.cpp

Index: clang-tools-extra/clangd/unittests/TestTU.cpp
===
--- clang-tools-extra/clangd/unittests/TestTU.cpp
+++ clang-tools-extra/clangd/unittests/TestTU.cpp
@@ -66,8 +66,7 @@
   auto CI = buildCompilerInvocation(Inputs, Diags);
   assert(CI && "Failed to build compilation invocation.");
   auto Preamble =
-  buildPreamble(FullFilename, *CI,
-/*OldPreamble=*/nullptr, Inputs,
+  buildPreamble(FullFilename, *CI, Inputs,
 /*StoreInMemory=*/true, /*PreambleCallback=*/nullptr);
   auto AST =
   buildAST(FullFilename, std::move(CI), Diags.take(), Inputs, Preamble);
Index: clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
===
--- clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
+++ clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
@@ -283,6 +283,7 @@
 S.runWithPreamble("StaleRead", Path, TUScheduler::Stale,
   [&](Expected Pre) {
 ASSERT_TRUE(bool(Pre));
+ASSERT_TRUE(Pre->Preamble);
 EXPECT_EQ(Pre->Preamble->Version, "A");
 EXPECT_THAT(includes(Pre->Preamble),
 ElementsAre(""));
@@ -292,11 +293,13 @@
 S.runWithPreamble("ConsistentRead", Path, TUScheduler::Consistent,
   [&](Expected Pre) {
 ASSERT_TRUE(bool(Pre));
+ASSERT_TRUE(Pre->Preamble);
 EXPECT_EQ(Pre->Preamble->Version, "B");
 EXPECT_THAT(includes(Pre->Preamble),
 ElementsAre(""));
 ++CallbackCount;
   });
+S.blockUntilIdle(timeoutSeconds(10));
   }
   EXPECT_EQ(2, CallbackCount);
 }
@@ -853,15 +856,19 @@
   TUState(PreambleAction::Idle, ASTAction::RunningAction),
   // We build the preamble
   TUState(PreambleAction::Building, ASTAction::RunningAction),
-  // Preamble worker goes idle
+  // We built the preamble, and issued ast built on ASTWorker
+  // thread. Preambleworker goes idle afterwards.
   TUState(PreambleAction::Idle, ASTAction::RunningAction),
-  // We start building the ast
+  // Start task for building the ast, as a result of building
+  // preamble, on astworker thread.
+  TUState(PreambleAction::Idle, ASTAction::RunningAction),
+  // AST build starts.
   TUState(PreambleAction::Idle, ASTAction::Building),
-  // Built finished succesffully
+  // AST built finished successfully
   TUState(PreambleAction::Idle, ASTAction::Building),
-  // Rnning go to def
+  // Running go to def
   TUState(PreambleAction::Idle, ASTAction::RunningAction),
-  // both workers go idle
+  // ASTWorker goes idle.
   TUState(PreambleAction::Idle, ASTAction::Idle)));
 }
 
Index: clang-tools-extra/clangd/unittests/FileIndexTests.cpp
===
--- clang-tools-extra/clangd/unittests/FileIndexTests.cpp
+++ clang-tools-extra/clangd/unittests/FileIndexTests.cpp
@@ -286,7 +286,7 @@
 
   FileIndex Index;
   bool IndexUpdated = false;
-  buildPreamble(FooCpp, *CI, /*OldPreamble=*/nullptr, PI,
+  buildPreamble(FooCpp, *CI, PI,
 /*StoreInMemory=*/true,
 [&](ASTContext &Ctx, std::shared_ptr PP,
 const CanonicalIncludes &CanonIncludes) {
@@ -424,7 +424,7 @@
 }
 
 TEST(FileIndexTest, MergeMainFileSymbols) {
-  const char* CommonHeader = "void foo();";
+  const char *CommonHeader = "void foo();";
   TestTU Header = TestTU::withCode(CommonHeader);
   TestTU Cpp = TestTU::withCode("void foo() {}");
   Cpp.Filename = "foo.cpp";
Index: clang-tools-extra/clangd/TUScheduler.cpp
===
--- clang-tools-extra/clangd/TUScheduler.cpp
+++ clang-tools-extra/clangd/TUS

[PATCH] D76594: [clang][AST] Support AST files larger than 512M

2020-03-30 Thread Sam McCall via Phabricator via cfe-commits
sammccall added inline comments.



Comment at: clang/include/clang/Serialization/ASTBitCodes.h:220
 /// Source range/offset of a preprocessed entity.
 struct DeclOffset {
+  /// Raw source location. The unsigned i.e. 32-bit integer is enough for

Is there one of these for every decl in the module? It seems like we're 
probably giving up a good fraction of the 4% increase for just using absolute 
64 bit offsets everywhere :-( Is there still a significant gain from using 
section-relative elsewhere?

If there are indeed lots of these, giving up 4 bytes to padding (in addition to 
the wide offset) seems unfortunate and because we memcpy the structs into the 
AST file seems like a sad reason :-)
Can we align this to 4 bytes instead?
(e.g. by splitting into two fields and encapsulating the few direct accesses, 
though there's probably a neater way)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76594



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


[PATCH] D76725: [clangd] Build ASTs only with fresh preambles or after building a new preamble

2020-03-30 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet updated this revision to Diff 253556.
kadircet added a comment.

- Add assertion to explicitly spell out scheduling for golden ASTs.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76725

Files:
  clang-tools-extra/clangd/Preamble.cpp
  clang-tools-extra/clangd/Preamble.h
  clang-tools-extra/clangd/TUScheduler.cpp
  clang-tools-extra/clangd/unittests/FileIndexTests.cpp
  clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
  clang-tools-extra/clangd/unittests/TestTU.cpp

Index: clang-tools-extra/clangd/unittests/TestTU.cpp
===
--- clang-tools-extra/clangd/unittests/TestTU.cpp
+++ clang-tools-extra/clangd/unittests/TestTU.cpp
@@ -66,8 +66,7 @@
   auto CI = buildCompilerInvocation(Inputs, Diags);
   assert(CI && "Failed to build compilation invocation.");
   auto Preamble =
-  buildPreamble(FullFilename, *CI,
-/*OldPreamble=*/nullptr, Inputs,
+  buildPreamble(FullFilename, *CI, Inputs,
 /*StoreInMemory=*/true, /*PreambleCallback=*/nullptr);
   auto AST =
   buildAST(FullFilename, std::move(CI), Diags.take(), Inputs, Preamble);
Index: clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
===
--- clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
+++ clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
@@ -283,6 +283,7 @@
 S.runWithPreamble("StaleRead", Path, TUScheduler::Stale,
   [&](Expected Pre) {
 ASSERT_TRUE(bool(Pre));
+ASSERT_TRUE(Pre->Preamble);
 EXPECT_EQ(Pre->Preamble->Version, "A");
 EXPECT_THAT(includes(Pre->Preamble),
 ElementsAre(""));
@@ -292,11 +293,13 @@
 S.runWithPreamble("ConsistentRead", Path, TUScheduler::Consistent,
   [&](Expected Pre) {
 ASSERT_TRUE(bool(Pre));
+ASSERT_TRUE(Pre->Preamble);
 EXPECT_EQ(Pre->Preamble->Version, "B");
 EXPECT_THAT(includes(Pre->Preamble),
 ElementsAre(""));
 ++CallbackCount;
   });
+S.blockUntilIdle(timeoutSeconds(10));
   }
   EXPECT_EQ(2, CallbackCount);
 }
@@ -853,15 +856,19 @@
   TUState(PreambleAction::Idle, ASTAction::RunningAction),
   // We build the preamble
   TUState(PreambleAction::Building, ASTAction::RunningAction),
-  // Preamble worker goes idle
+  // We built the preamble, and issued ast built on ASTWorker
+  // thread. Preambleworker goes idle afterwards.
   TUState(PreambleAction::Idle, ASTAction::RunningAction),
-  // We start building the ast
+  // Start task for building the ast, as a result of building
+  // preamble, on astworker thread.
+  TUState(PreambleAction::Idle, ASTAction::RunningAction),
+  // AST build starts.
   TUState(PreambleAction::Idle, ASTAction::Building),
-  // Built finished succesffully
+  // AST built finished successfully
   TUState(PreambleAction::Idle, ASTAction::Building),
-  // Rnning go to def
+  // Running go to def
   TUState(PreambleAction::Idle, ASTAction::RunningAction),
-  // both workers go idle
+  // ASTWorker goes idle.
   TUState(PreambleAction::Idle, ASTAction::Idle)));
 }
 
Index: clang-tools-extra/clangd/unittests/FileIndexTests.cpp
===
--- clang-tools-extra/clangd/unittests/FileIndexTests.cpp
+++ clang-tools-extra/clangd/unittests/FileIndexTests.cpp
@@ -286,7 +286,7 @@
 
   FileIndex Index;
   bool IndexUpdated = false;
-  buildPreamble(FooCpp, *CI, /*OldPreamble=*/nullptr, PI,
+  buildPreamble(FooCpp, *CI, PI,
 /*StoreInMemory=*/true,
 [&](ASTContext &Ctx, std::shared_ptr PP,
 const CanonicalIncludes &CanonIncludes) {
@@ -424,7 +424,7 @@
 }
 
 TEST(FileIndexTest, MergeMainFileSymbols) {
-  const char* CommonHeader = "void foo();";
+  const char *CommonHeader = "void foo();";
   TestTU Header = TestTU::withCode(CommonHeader);
   TestTU Cpp = TestTU::withCode("void foo() {}");
   Cpp.Filename = "foo.cpp";
Index: clang-tools-extra/clangd/TUScheduler.cpp
===
--- clang-tools-extra/clangd/TUScheduler.cpp
+++ clang-tools-extra/clangd/TUScheduler.cpp
@@ -5,41 +5,55 @@
 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
 //
 //===--

[PATCH] D75364: [clang-format] Handle macros in function params and return value

2020-03-30 Thread Tamas Petz via Phabricator via cfe-commits
tamas.petz added a comment.

Friendly ping.


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

https://reviews.llvm.org/D75364



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


[PATCH] D75914: systemz: allow configuring default CLANG_SYSTEMZ_ARCH

2020-03-30 Thread Ulrich Weigand via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG9c9d88d8b1bb: [SystemZ] Allow configuring default 
CLANG_SYSTEMZ_ARCH (authored by uweigand).
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D75914

Files:
  clang/CMakeLists.txt
  clang/lib/Driver/ToolChains/Arch/SystemZ.cpp


Index: clang/lib/Driver/ToolChains/Arch/SystemZ.cpp
===
--- clang/lib/Driver/ToolChains/Arch/SystemZ.cpp
+++ clang/lib/Driver/ToolChains/Arch/SystemZ.cpp
@@ -47,7 +47,7 @@
 
 return std::string(CPUName);
   }
-  return "z10";
+  return CLANG_SYSTEMZ_DEFAULT_ARCH;
 }
 
 void systemz::getSystemZTargetFeatures(const Driver &D, const ArgList &Args,
Index: clang/CMakeLists.txt
===
--- clang/CMakeLists.txt
+++ clang/CMakeLists.txt
@@ -306,6 +306,10 @@
 "Default architecture for OpenMP offloading to Nvidia GPUs." FORCE)
 endif()
 
+set(CLANG_SYSTEMZ_DEFAULT_ARCH "z10" CACHE STRING
+  "SystemZ Default Arch")
+add_definitions( -DCLANG_SYSTEMZ_DEFAULT_ARCH="${CLANG_SYSTEMZ_DEFAULT_ARCH}")
+
 set(CLANG_VENDOR ${PACKAGE_VENDOR} CACHE STRING
   "Vendor-specific text for showing with version information.")
 


Index: clang/lib/Driver/ToolChains/Arch/SystemZ.cpp
===
--- clang/lib/Driver/ToolChains/Arch/SystemZ.cpp
+++ clang/lib/Driver/ToolChains/Arch/SystemZ.cpp
@@ -47,7 +47,7 @@
 
 return std::string(CPUName);
   }
-  return "z10";
+  return CLANG_SYSTEMZ_DEFAULT_ARCH;
 }
 
 void systemz::getSystemZTargetFeatures(const Driver &D, const ArgList &Args,
Index: clang/CMakeLists.txt
===
--- clang/CMakeLists.txt
+++ clang/CMakeLists.txt
@@ -306,6 +306,10 @@
 "Default architecture for OpenMP offloading to Nvidia GPUs." FORCE)
 endif()
 
+set(CLANG_SYSTEMZ_DEFAULT_ARCH "z10" CACHE STRING
+  "SystemZ Default Arch")
+add_definitions( -DCLANG_SYSTEMZ_DEFAULT_ARCH="${CLANG_SYSTEMZ_DEFAULT_ARCH}")
+
 set(CLANG_VENDOR ${PACKAGE_VENDOR} CACHE STRING
   "Vendor-specific text for showing with version information.")
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 9c9d88d - [SystemZ] Allow configuring default CLANG_SYSTEMZ_ARCH

2020-03-30 Thread Ulrich Weigand via cfe-commits

Author: Ulrich Weigand
Date: 2020-03-30T14:20:48+02:00
New Revision: 9c9d88d8b1bb6468f6c4258fe41bbcd01f742801

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

LOG: [SystemZ] Allow configuring default CLANG_SYSTEMZ_ARCH

On Ubuntu, we want to raise default CLANG_SYSTEMZ_ARCH to z13,
thus allow configuring this via CMake.
On Debian, we want to raise it to z196.

Author: Dimitri John Ledkov
Differential Revision: https://reviews.llvm.org/D75914

Added: 


Modified: 
clang/CMakeLists.txt
clang/lib/Driver/ToolChains/Arch/SystemZ.cpp

Removed: 




diff  --git a/clang/CMakeLists.txt b/clang/CMakeLists.txt
index 7809d6529195..c9e76c5e4518 100644
--- a/clang/CMakeLists.txt
+++ b/clang/CMakeLists.txt
@@ -306,6 +306,10 @@ if (NOT DEFINED MATCHED_ARCH OR "${CMAKE_MATCH_1}" LESS 35)
 "Default architecture for OpenMP offloading to Nvidia GPUs." FORCE)
 endif()
 
+set(CLANG_SYSTEMZ_DEFAULT_ARCH "z10" CACHE STRING
+  "SystemZ Default Arch")
+add_definitions( -DCLANG_SYSTEMZ_DEFAULT_ARCH="${CLANG_SYSTEMZ_DEFAULT_ARCH}")
+
 set(CLANG_VENDOR ${PACKAGE_VENDOR} CACHE STRING
   "Vendor-specific text for showing with version information.")
 

diff  --git a/clang/lib/Driver/ToolChains/Arch/SystemZ.cpp 
b/clang/lib/Driver/ToolChains/Arch/SystemZ.cpp
index 4d871104c95a..b263fb7df09e 100644
--- a/clang/lib/Driver/ToolChains/Arch/SystemZ.cpp
+++ b/clang/lib/Driver/ToolChains/Arch/SystemZ.cpp
@@ -47,7 +47,7 @@ std::string systemz::getSystemZTargetCPU(const ArgList &Args) 
{
 
 return std::string(CPUName);
   }
-  return "z10";
+  return CLANG_SYSTEMZ_DEFAULT_ARCH;
 }
 
 void systemz::getSystemZTargetFeatures(const Driver &D, const ArgList &Args,



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


[PATCH] D77053: [Syntax] A tool to dump syntax tree and token buffer

2020-03-30 Thread Marcel Hlopko via Phabricator via cfe-commits
hlopko created this revision.
Herald added subscribers: cfe-commits, mgorny.
Herald added a project: clang.
hlopko updated this revision to Diff 253561.
hlopko added a comment.
hlopko updated this revision to Diff 253562.
hlopko added a reviewer: gribozavr2.
hlopko edited the summary of this revision.

Cleanup


hlopko added a comment.

Cleanup


Taking over of https://reviews.llvm.org/D70788.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D77053

Files:
  clang/test/CMakeLists.txt
  clang/test/clang-syntax/no_args.cpp
  clang/test/clang-syntax/syntax_hello_world.cpp
  clang/test/clang-syntax/syntax_no_file_arg.cpp
  clang/test/clang-syntax/tokens_hello_world.cpp
  clang/test/clang-syntax/tokens_no_file_arg.cpp
  clang/tools/CMakeLists.txt
  clang/tools/clang-syntax/CMakeLists.txt
  clang/tools/clang-syntax/SyntaxMain.cpp

Index: clang/tools/clang-syntax/SyntaxMain.cpp
===
--- /dev/null
+++ clang/tools/clang-syntax/SyntaxMain.cpp
@@ -0,0 +1,88 @@
+//===- SyntaxMain.cpp -*- 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
+//
+//===--===//
+#include "clang/Frontend/CompilerInstance.h"
+#include "clang/Tooling/Execution.h"
+#include "clang/Tooling/Syntax/BuildTree.h"
+#include "clang/Tooling/Syntax/Tokens.h"
+#include "clang/Tooling/Syntax/Tree.h"
+#include "clang/Tooling/Tooling.h"
+#include "llvm/ADT/STLExtras.h"
+#include "llvm/Support/Signals.h"
+#include "llvm/Support/raw_ostream.h"
+#include 
+
+using namespace clang;
+
+namespace {
+
+llvm::cl::OptionCategory ClangSyntaxOptions("clang-syntax common options");
+
+llvm::cl::opt DumpTokens("dump-tokens",
+   llvm::cl::desc("dump the preprocessed tokens"),
+   llvm::cl::init(false),
+   llvm::cl::cat(ClangSyntaxOptions));
+llvm::cl::opt DumpSyntax("dump-syntax",
+   llvm::cl::desc("dump the syntax tree"),
+   llvm::cl::init(false),
+   llvm::cl::cat(ClangSyntaxOptions));
+
+class BuildSyntaxTree : public ASTFrontendAction {
+public:
+  std::unique_ptr CreateASTConsumer(CompilerInstance &CI,
+ StringRef InFile) override {
+class Consumer : public ASTConsumer {
+public:
+  Consumer(CompilerInstance &CI) : Collector(CI.getPreprocessor()) {}
+
+  void HandleTranslationUnit(ASTContext &AST) override {
+syntax::Arena A(AST.getSourceManager(), AST.getLangOpts(),
+std::move(Collector).consume());
+auto *TU = syntax::buildSyntaxTree(A, *AST.getTranslationUnitDecl());
+if (DumpTokens)
+  llvm::outs() << A.tokenBuffer().dumpForTests();
+if (DumpSyntax)
+  llvm::outs() << TU->dump(A);
+  }
+
+private:
+  syntax::TokenCollector Collector;
+};
+return std::make_unique(CI);
+  }
+};
+
+class Factory : public tooling::FrontendActionFactory {
+  std::unique_ptr create() override {
+return std::make_unique();
+  }
+};
+
+} // namespace
+
+int main(int argc, const char **argv) {
+  llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
+
+  auto Executor = clang::tooling::createExecutorFromCommandLineArgs(
+  argc, argv, ClangSyntaxOptions,
+  "Build syntax trees for the specified files");
+  if (!Executor) {
+llvm::errs() << llvm::toString(Executor.takeError()) << "\n";
+return 1;
+  }
+
+  if (!DumpTokens && !DumpSyntax) {
+llvm::errs()
+<< "Please specify at least one of -dump-tree or -dump-tokens\n";
+return 1;
+  }
+  // Collect symbols found in each translation unit, merging as we go.
+  auto Err = Executor->get()->execute(std::make_unique());
+  if (Err)
+llvm::errs() << llvm::toString(std::move(Err)) << "\n";
+  return 0;
+}
Index: clang/tools/clang-syntax/CMakeLists.txt
===
--- /dev/null
+++ clang/tools/clang-syntax/CMakeLists.txt
@@ -0,0 +1,16 @@
+set(LLVM_LINK_COMPONENTS Support)
+
+add_clang_tool(clang-syntax
+  SyntaxMain.cpp
+  )
+
+target_link_libraries(clang-syntax
+  PRIVATE
+  clangAST
+  clangBasic
+  clangFrontend
+  clangLex
+  clangTooling
+  clangToolingCore
+  clangToolingSyntax
+)
Index: clang/tools/CMakeLists.txt
===
--- clang/tools/CMakeLists.txt
+++ clang/tools/CMakeLists.txt
@@ -18,6 +18,7 @@
 if(UNIX)
   add_clang_subdirectory(clang-shlib)
 endif()
+add_clang_subdirectory(clang-syntax)
 
 if(CLANG_ENABLE_ARCMT)
   add_clang_subdirectory(arcmt-test)
Index: clang/test/clang-syntax/tokens_no_file_arg.cpp
===

[PATCH] D77053: [Syntax] A tool to dump syntax tree and token buffer

2020-03-30 Thread Marcel Hlopko via Phabricator via cfe-commits
hlopko updated this revision to Diff 253562.
hlopko added a comment.

Cleanup


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D77053

Files:
  clang/test/CMakeLists.txt
  clang/test/clang-syntax/no_args.cpp
  clang/test/clang-syntax/syntax_hello_world.cpp
  clang/test/clang-syntax/syntax_no_file_arg.cpp
  clang/test/clang-syntax/tokens_hello_world.cpp
  clang/test/clang-syntax/tokens_no_file_arg.cpp
  clang/tools/CMakeLists.txt
  clang/tools/clang-syntax/CMakeLists.txt
  clang/tools/clang-syntax/SyntaxMain.cpp

Index: clang/tools/clang-syntax/SyntaxMain.cpp
===
--- /dev/null
+++ clang/tools/clang-syntax/SyntaxMain.cpp
@@ -0,0 +1,88 @@
+//===- SyntaxMain.cpp -*- 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
+//
+//===--===//
+#include "clang/Frontend/CompilerInstance.h"
+#include "clang/Tooling/Execution.h"
+#include "clang/Tooling/Syntax/BuildTree.h"
+#include "clang/Tooling/Syntax/Tokens.h"
+#include "clang/Tooling/Syntax/Tree.h"
+#include "clang/Tooling/Tooling.h"
+#include "llvm/ADT/STLExtras.h"
+#include "llvm/Support/Signals.h"
+#include "llvm/Support/raw_ostream.h"
+#include 
+
+using namespace clang;
+
+namespace {
+
+llvm::cl::OptionCategory ClangSyntaxOptions("clang-syntax common options");
+
+llvm::cl::opt DumpTokens("dump-tokens",
+   llvm::cl::desc("dump the preprocessed tokens"),
+   llvm::cl::init(false),
+   llvm::cl::cat(ClangSyntaxOptions));
+llvm::cl::opt DumpSyntax("dump-syntax",
+   llvm::cl::desc("dump the syntax tree"),
+   llvm::cl::init(false),
+   llvm::cl::cat(ClangSyntaxOptions));
+
+class BuildSyntaxTree : public ASTFrontendAction {
+public:
+  std::unique_ptr CreateASTConsumer(CompilerInstance &CI,
+ StringRef InFile) override {
+class Consumer : public ASTConsumer {
+public:
+  Consumer(CompilerInstance &CI) : Collector(CI.getPreprocessor()) {}
+
+  void HandleTranslationUnit(ASTContext &AST) override {
+syntax::Arena A(AST.getSourceManager(), AST.getLangOpts(),
+std::move(Collector).consume());
+auto *TU = syntax::buildSyntaxTree(A, *AST.getTranslationUnitDecl());
+if (DumpTokens)
+  llvm::outs() << A.tokenBuffer().dumpForTests();
+if (DumpSyntax)
+  llvm::outs() << TU->dump(A);
+  }
+
+private:
+  syntax::TokenCollector Collector;
+};
+return std::make_unique(CI);
+  }
+};
+
+class Factory : public tooling::FrontendActionFactory {
+  std::unique_ptr create() override {
+return std::make_unique();
+  }
+};
+
+} // namespace
+
+int main(int argc, const char **argv) {
+  llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
+
+  auto Executor = clang::tooling::createExecutorFromCommandLineArgs(
+  argc, argv, ClangSyntaxOptions,
+  "Build syntax trees for the specified files");
+  if (!Executor) {
+llvm::errs() << llvm::toString(Executor.takeError()) << "\n";
+return 1;
+  }
+
+  if (!DumpTokens && !DumpSyntax) {
+llvm::errs()
+<< "Please specify at least one of -dump-tree or -dump-tokens\n";
+return 1;
+  }
+  // Collect symbols found in each translation unit, merging as we go.
+  auto Err = Executor->get()->execute(std::make_unique());
+  if (Err)
+llvm::errs() << llvm::toString(std::move(Err)) << "\n";
+  return 0;
+}
Index: clang/tools/clang-syntax/CMakeLists.txt
===
--- /dev/null
+++ clang/tools/clang-syntax/CMakeLists.txt
@@ -0,0 +1,16 @@
+set(LLVM_LINK_COMPONENTS Support)
+
+add_clang_tool(clang-syntax
+  SyntaxMain.cpp
+  )
+
+target_link_libraries(clang-syntax
+  PRIVATE
+  clangAST
+  clangBasic
+  clangFrontend
+  clangLex
+  clangTooling
+  clangToolingCore
+  clangToolingSyntax
+)
Index: clang/tools/CMakeLists.txt
===
--- clang/tools/CMakeLists.txt
+++ clang/tools/CMakeLists.txt
@@ -18,6 +18,7 @@
 if(UNIX)
   add_clang_subdirectory(clang-shlib)
 endif()
+add_clang_subdirectory(clang-syntax)
 
 if(CLANG_ENABLE_ARCMT)
   add_clang_subdirectory(arcmt-test)
Index: clang/test/clang-syntax/tokens_no_file_arg.cpp
===
--- /dev/null
+++ clang/test/clang-syntax/tokens_no_file_arg.cpp
@@ -0,0 +1,10 @@
+// RUN: rm -rf %t.dir
+// RUN: mkdir -p %t.dir
+//
+// RUN: clang-syntax -dump-tokens 2> %t.dir/tokens_no_fil

[PATCH] D75181: [AArch64] Handle BTI/PAC in case of generated functions.

2020-03-30 Thread Daniel Kiss via Phabricator via cfe-commits
danielkiss added a comment.

ping


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

https://reviews.llvm.org/D75181



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


[PATCH] D77053: [Syntax] A tool to dump syntax tree and token buffer

2020-03-30 Thread Marcel Hlopko via Phabricator via cfe-commits
hlopko updated this revision to Diff 253561.
hlopko added a comment.

Cleanup


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D77053

Files:
  clang/test/CMakeLists.txt
  clang/test/clang-syntax/no_args.cpp
  clang/test/clang-syntax/syntax_hello_world.cpp
  clang/test/clang-syntax/syntax_no_file_arg.cpp
  clang/test/clang-syntax/tokens_hello_world.cpp
  clang/test/clang-syntax/tokens_no_file_arg.cpp
  clang/tools/CMakeLists.txt
  clang/tools/clang-syntax/CMakeLists.txt
  clang/tools/clang-syntax/SyntaxMain.cpp

Index: clang/tools/clang-syntax/SyntaxMain.cpp
===
--- /dev/null
+++ clang/tools/clang-syntax/SyntaxMain.cpp
@@ -0,0 +1,88 @@
+//===- SyntaxMain.cpp -*- 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
+//
+//===--===//
+#include "clang/Frontend/CompilerInstance.h"
+#include "clang/Tooling/Execution.h"
+#include "clang/Tooling/Syntax/BuildTree.h"
+#include "clang/Tooling/Syntax/Tokens.h"
+#include "clang/Tooling/Syntax/Tree.h"
+#include "clang/Tooling/Tooling.h"
+#include "llvm/ADT/STLExtras.h"
+#include "llvm/Support/Signals.h"
+#include "llvm/Support/raw_ostream.h"
+#include 
+
+using namespace clang;
+
+namespace {
+
+llvm::cl::OptionCategory ClangSyntaxOptions("clang-syntax common options");
+
+llvm::cl::opt DumpTokens("dump-tokens",
+   llvm::cl::desc("dump the preprocessed tokens"),
+   llvm::cl::init(false),
+   llvm::cl::cat(ClangSyntaxOptions));
+llvm::cl::opt DumpSyntax("dump-syntax",
+   llvm::cl::desc("dump the syntax tree"),
+   llvm::cl::init(false),
+   llvm::cl::cat(ClangSyntaxOptions));
+
+class BuildSyntaxTree : public ASTFrontendAction {
+public:
+  std::unique_ptr CreateASTConsumer(CompilerInstance &CI,
+ StringRef InFile) override {
+class Consumer : public ASTConsumer {
+public:
+  Consumer(CompilerInstance &CI) : Collector(CI.getPreprocessor()) {}
+
+  void HandleTranslationUnit(ASTContext &AST) override {
+syntax::Arena A(AST.getSourceManager(), AST.getLangOpts(),
+std::move(Collector).consume());
+auto *TU = syntax::buildSyntaxTree(A, *AST.getTranslationUnitDecl());
+if (DumpTokens)
+  llvm::outs() << A.tokenBuffer().dumpForTests();
+if (DumpSyntax)
+  llvm::outs() << TU->dump(A);
+  }
+
+private:
+  syntax::TokenCollector Collector;
+};
+return std::make_unique(CI);
+  }
+};
+
+class Factory : public tooling::FrontendActionFactory {
+  std::unique_ptr create() override {
+return std::make_unique();
+  }
+};
+
+} // namespace
+
+int main(int argc, const char **argv) {
+  llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
+
+  auto Executor = clang::tooling::createExecutorFromCommandLineArgs(
+  argc, argv, ClangSyntaxOptions,
+  "Build syntax trees for the specified files");
+  if (!Executor) {
+llvm::errs() << llvm::toString(Executor.takeError()) << "\n";
+return 1;
+  }
+
+  if (!DumpTokens && !DumpSyntax) {
+llvm::errs()
+<< "Please specify at least one of -dump-tree or -dump-tokens\n";
+return 1;
+  }
+  // Collect symbols found in each translation unit, merging as we go.
+  auto Err = Executor->get()->execute(std::make_unique());
+  if (Err)
+llvm::errs() << llvm::toString(std::move(Err)) << "\n";
+  return 0;
+}
Index: clang/tools/clang-syntax/CMakeLists.txt
===
--- /dev/null
+++ clang/tools/clang-syntax/CMakeLists.txt
@@ -0,0 +1,16 @@
+set(LLVM_LINK_COMPONENTS Support)
+
+add_clang_tool(clang-syntax
+  SyntaxMain.cpp
+  )
+
+target_link_libraries(clang-syntax
+  PRIVATE
+  clangAST
+  clangBasic
+  clangFrontend
+  clangLex
+  clangTooling
+  clangToolingCore
+  clangToolingSyntax
+)
Index: clang/tools/CMakeLists.txt
===
--- clang/tools/CMakeLists.txt
+++ clang/tools/CMakeLists.txt
@@ -18,6 +18,7 @@
 if(UNIX)
   add_clang_subdirectory(clang-shlib)
 endif()
+add_clang_subdirectory(clang-syntax)
 
 if(CLANG_ENABLE_ARCMT)
   add_clang_subdirectory(arcmt-test)
Index: clang/test/clang-syntax/tokens_no_file_arg.cpp
===
--- /dev/null
+++ clang/test/clang-syntax/tokens_no_file_arg.cpp
@@ -0,0 +1,10 @@
+// RUN: rm -rf %t.dir
+// RUN: mkdir -p %t.dir
+//
+// RUN: clang-syntax -dump-tokens 2> %t.dir/tokens_no_fil

[PATCH] D77037: [AST] Fix crashes on decltype(recovery-expr).

2020-03-30 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 253567.
hokein marked 4 inline comments as done.
hokein added a comment.

address comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D77037

Files:
  clang/include/clang/AST/DependenceFlags.h
  clang/include/clang/AST/Type.h
  clang/lib/Parse/ParseExprCXX.cpp
  clang/lib/Sema/SemaType.cpp
  clang/test/AST/ast-dump-expr-errors.cpp
  clang/test/Sema/invalid-member.cpp
  clang/unittests/Sema/CodeCompleteTest.cpp

Index: clang/unittests/Sema/CodeCompleteTest.cpp
===
--- clang/unittests/Sema/CodeCompleteTest.cpp
+++ clang/unittests/Sema/CodeCompleteTest.cpp
@@ -486,7 +486,10 @@
   StringRef Code = R"cpp(
 auto x = decltype(&1)(^);
 auto y = new decltype(&1)(^);
+// GNU decimal type extension is not supported in clang.
+auto z = new _Decimal128(^);
   )cpp";
   EXPECT_THAT(collectPreferredTypes(Code), Each("NULL TYPE"));
 }
+
 } // namespace
Index: clang/test/Sema/invalid-member.cpp
===
--- clang/test/Sema/invalid-member.cpp
+++ clang/test/Sema/invalid-member.cpp
@@ -1,7 +1,15 @@
 // RUN: %clang_cc1 -verify -fsyntax-only %s
-void foo(); // expected-note {{requires 0 arguments}}
+// RUN: %clang_cc1 -verify -fsyntax-only -frecovery-ast %s
+
+void foo(); // expected-note 2{{requires 0 arguments}}
 class X {
   decltype(foo(42)) invalid; // expected-error {{no matching function}}
 };
 // Should be able to evaluate sizeof without crashing.
 static_assert(sizeof(X) == 1, "No valid members");
+
+class Y {
+  typeof(foo(42)) invalid; // expected-error {{no matching function}}
+};
+// Should be able to evaluate sizeof without crashing.
+static_assert(sizeof(Y) == 1, "No valid members");
Index: clang/test/AST/ast-dump-expr-errors.cpp
===
--- clang/test/AST/ast-dump-expr-errors.cpp
+++ clang/test/AST/ast-dump-expr-errors.cpp
@@ -42,5 +42,9 @@
 
 // FIXME: store initializer even when 'auto' could not be deduced.
 // Expressions with errors currently do not keep initializers around.
-// CHECK: `-VarDecl {{.*}} invalid e 'auto'
+// CHECK: -VarDecl {{.*}} invalid e 'auto'
 auto e = bar();
+
+// Error type should result in an invalid decl.
+// CHECK: -VarDecl {{.*}} invalid f 'decltype((bar))'
+decltype(bar()) f;
Index: clang/lib/Sema/SemaType.cpp
===
--- clang/lib/Sema/SemaType.cpp
+++ clang/lib/Sema/SemaType.cpp
@@ -1678,6 +1678,12 @@
 break;
   }
 
+  // FIXME: we want resulting declarations to be marked invalid, but claiming
+  // the type is invalid is too strong - e.g. it causes ActOnTypeName to return
+  // a null type.
+  if (Result->containsErrors())
+declarator.setInvalidType();
+
   if (S.getLangOpts().OpenCL &&
   S.checkOpenCLDisabledTypeDeclSpec(DS, Result))
 declarator.setInvalidType(true);
Index: clang/lib/Parse/ParseExprCXX.cpp
===
--- clang/lib/Parse/ParseExprCXX.cpp
+++ clang/lib/Parse/ParseExprCXX.cpp
@@ -3105,10 +3105,14 @@
   auto RunSignatureHelp = [&]() {
 ParsedType TypeRep =
 Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
-assert(TypeRep && "invalid types should be handled before");
-QualType PreferredType = Actions.ProduceConstructorSignatureHelp(
-getCurScope(), TypeRep.get()->getCanonicalTypeInternal(),
-DeclaratorInfo.getEndLoc(), ConstructorArgs, ConstructorLParen);
+QualType PreferredType;
+// ActOnTypeName might adjust DeclaratorInfo and return a null type even
+// the passing DeclaratorInfo is valid, e.g. running SignatureHelp on
+// `new decltype(invalid) (^)`.
+if (TypeRep)
+  PreferredType = Actions.ProduceConstructorSignatureHelp(
+  getCurScope(), TypeRep.get()->getCanonicalTypeInternal(),
+  DeclaratorInfo.getEndLoc(), ConstructorArgs, ConstructorLParen);
 CalledSignatureHelp = true;
 return PreferredType;
   };
Index: clang/include/clang/AST/Type.h
===
--- clang/include/clang/AST/Type.h
+++ clang/include/clang/AST/Type.h
@@ -2139,6 +2139,11 @@
 return static_cast(TypeBits.Dependence);
   }
 
+  /// Whether this type is an error type.
+  bool containsErrors() const {
+return getDependence() & TypeDependence::Error;
+  }
+
   /// Whether this type is a dependent type, meaning that its definition
   /// somehow depends on a template parameter (C++ [temp.dep.type]).
   bool isDependentType() const {
Index: clang/include/clang/AST/DependenceFlags.h
===
--- clang/include/clang/AST/DependenceFlags.h
+++ clang/include/cla

[PATCH] D75914: systemz: allow configuring default CLANG_SYSTEMZ_ARCH

2020-03-30 Thread Jonas Hahnfeld via Phabricator via cfe-commits
Hahnfeld added inline comments.



Comment at: clang/CMakeLists.txt:311
+  "SystemZ Default Arch")
+add_definitions( -DCLANG_SYSTEMZ_DEFAULT_ARCH="${CLANG_SYSTEMZ_DEFAULT_ARCH}")
+

Passing values like this is unusual for CMake and causes all source files to be 
recompiled if the value is changed. Instead could we add this to 
`include/clang/Config/config.h.cmake` like other `CLANG_DEFAULT_*` options?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D75914



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


[PATCH] D77048: [Clang][CodeGen] Fixing mismatch between memory layout and const expressions for oversized bitfields

2020-03-30 Thread Lucas Prates via Phabricator via cfe-commits
pratlucas updated this revision to Diff 253568.
pratlucas added a comment.

Formatting.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D77048

Files:
  clang/lib/CodeGen/CGExprConstant.cpp
  clang/test/CodeGenCXX/bitfield-layout.cpp

Index: clang/test/CodeGenCXX/bitfield-layout.cpp
===
--- clang/test/CodeGenCXX/bitfield-layout.cpp
+++ clang/test/CodeGenCXX/bitfield-layout.cpp
@@ -1,11 +1,14 @@
-// RUN: %clang_cc1 %s -triple=x86_64-apple-darwin10 -emit-llvm -o - -O3 | FileCheck -check-prefix CHECK-LP64 %s
-// RUN: %clang_cc1 %s -triple=i386-apple-darwin10 -emit-llvm -o - -O3 | FileCheck -check-prefix CHECK-LP32 %s
+// RUN: %clang_cc1 %s -triple=x86_64-apple-darwin10 -emit-llvm -o - -O3 | FileCheck -check-prefix=CHECK-LP64 -check-prefix=CHECK %s
+// RUN: %clang_cc1 %s -triple=i386-apple-darwin10 -emit-llvm -o - -O3 | FileCheck -check-prefix CHECK-LP32 -check-prefix=CHECK %s
+// RUN: %clang_cc1 %s -triple=aarch64_be-none-eabi -emit-llvm -o - -O3 | FileCheck -check-prefix CHECK-A64BE -check-prefix=CHECK %s
+// RUN: %clang_cc1 %s -triple=thumbv7_be-none-eabi -emit-llvm -o - -O3 | FileCheck -check-prefix CHECK-A32BE -check-prefix=CHECK %s
 
 // CHECK-LP64: %union.Test1 = type { i32, [4 x i8] }
 union Test1 {
   int a;
   int b: 39;
-} t1;
+};
+Test1 t1;
 
 // CHECK-LP64: %union.Test2 = type { i8 }
 union Test2 {
@@ -17,10 +20,16 @@
   int : 9;
 } t3;
 
+// CHECK: %union.Test4 = type { i8, i8 }
+union Test4 {
+  char val : 16;
+};
+Test4 t4;
 
 #define CHECK(x) if (!(x)) return __LINE__
 
-int f() {
+// CHECK: define i32 @_Z11test_assignv()
+int test_assign() {
   struct {
 int a;
 
@@ -37,7 +46,41 @@
   CHECK(c.b == (unsigned long long)-1);
   CHECK(c.c == 0);
 
-// CHECK-LP64: ret i32 0
-// CHECK-LP32: ret i32 0
+  Test1 u1;
+  Test4 u2;
+
+  u1.b = 1;
+  u2.val = 42;
+
+  CHECK(u1.b == 1);
+  CHECK(u2.val == 42);
+
+  // CHECK: ret i32 0
+  return 0;
+}
+
+// CHECK: define i32 @_Z9test_initv()
+int test_init() {
+  struct S {
+int a;
+
+unsigned long long b : 65;
+
+int c;
+  };
+  S s1 = {1, 42, 0};
+
+  CHECK(s1.a == 1);
+  CHECK(s1.b == (unsigned long long)42);
+  CHECK(s1.c == 0);
+
+  Test1 u1 = {1};
+  Test4 u2 = {42};
+
+  CHECK(u1.a == 1);
+  CHECK(u1.b == 1);
+  CHECK(u2.val == 42);
+
+  // CHECK: ret i32 0
   return 0;
 }
Index: clang/lib/CodeGen/CGExprConstant.cpp
===
--- clang/lib/CodeGen/CGExprConstant.cpp
+++ clang/lib/CodeGen/CGExprConstant.cpp
@@ -589,23 +589,37 @@
 bool ConstStructBuilder::AppendBitField(
 const FieldDecl *Field, uint64_t FieldOffset, llvm::ConstantInt *CI,
 bool AllowOverwrite) {
-  uint64_t FieldSize = Field->getBitWidthValue(CGM.getContext());
+  const CGRecordLayout &RL =
+  CGM.getTypes().getCGRecordLayout(Field->getParent());
+  const CGBitFieldInfo &Info = RL.getBitFieldInfo(Field);
   llvm::APInt FieldValue = CI->getValue();
 
   // Promote the size of FieldValue if necessary
   // FIXME: This should never occur, but currently it can because initializer
   // constants are cast to bool, and because clang is not enforcing bitfield
   // width limits.
-  if (FieldSize > FieldValue.getBitWidth())
-FieldValue = FieldValue.zext(FieldSize);
+  if (Info.Size > FieldValue.getBitWidth())
+FieldValue = FieldValue.zext(Info.Size);
 
   // Truncate the size of FieldValue to the bit field size.
-  if (FieldSize < FieldValue.getBitWidth())
-FieldValue = FieldValue.trunc(FieldSize);
+  if (Info.Size < FieldValue.getBitWidth())
+FieldValue = FieldValue.trunc(Info.Size);
 
-  return Builder.addBits(FieldValue,
- CGM.getContext().toBits(StartOffset) + FieldOffset,
- AllowOverwrite);
+  // Add field value bits
+  uint64_t AdjustedOffset = CGM.getContext().toBits(StartOffset) + FieldOffset;
+  if (!Builder.addBits(FieldValue, AdjustedOffset, AllowOverwrite))
+return false;
+  
+  // Add padding bits in case of over-sized bit-field.
+  //   "The first sizeof(T)*8 bits are used to hold the value of the bit-field,
+  //   followed by n - sizeof(T)*8 bits of padding."
+  uint64_t FieldWidth = Field->getBitWidthValue(CGM.getContext());
+  if (FieldWidth > Info.Size) {
+llvm::APInt PaddingValue((FieldWidth - Info.Size), /*val=*/0);
+return Builder.addBits(PaddingValue, (AdjustedOffset + Info.Size),
+   AllowOverwrite);
+  }
+  return true;
 }
 
 static bool EmitDesignatedInitUpdater(ConstantEmitter &Emitter,
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D77037: [AST] Fix crashes on decltype(recovery-expr).

2020-03-30 Thread Haojian Wu via Phabricator via cfe-commits
hokein added inline comments.



Comment at: clang/lib/Parse/ParseExprCXX.cpp:3109
+QualType PreferredType;
+if (TypeRep)
+  PreferredType = Actions.ProduceConstructorSignatureHelp(

sammccall wrote:
> hokein wrote:
> > sammccall wrote:
> > > Add a comment for what the null case means? (When do we actually hit 
> > > this?)
> > yeah, the 
> > [`CompleteTest`](https://github.com/llvm/llvm-project/blob/master/clang/unittests/Sema/CodeCompleteTest.cpp#L490)
> >  hits the assertion after this patch. 
> > 
> > the assertion seems incorrect  -- IIUC, the assertion is for the 
> > `isInvalidType()` sanity check on Line 3090, however
> > In `ActOnTypeName`,  `DeclaratorInfo` could be modified (by 
> > `GetTypeForDeclarator`) before calling `isInvalidType`.
> > 
> > 
> > btw, I think for the CodeCompleteTest, would be nicer to make 
> > `ActOnTypeName` return `decltype((bar))`, rather than the 
> > null type, but I'm not sure changing the `ActOnTypeName` behavior has any 
> > side effect.
> > the assertion seems incorrect -- IIUC, the assertion is for the 
> > isInvalidType() sanity check on Line 3090, however
> 
> What you say makes sense, but I think it's worth probing why it's not 
> currently hit (e.g. by `int x(auto);`, where `GetDeclSpecTypeForDeclarator` 
> marks the decl as invalid because auto isn't allowed in a prototype).
> 
> > btw, I think for the CodeCompleteTest, would be nicer to make ActOnTypeName 
> > return decltype((bar)), rather than the null type
> 
> Definitely. I think "invalid" on a type-concept is stronger than what we're 
> looking for - since we're not tracking errors in decls, we'd want to use 
> "haserrors" on type-concepts and then promote to "invalid" on decl-concepts.
> 
> Ugh, the design of "Declarator" makes this difficult, because there's no 
> distinction between "type of this declarator is invalid" and "type of this 
> declarator makes the declarator invalid".
> 
> I'd suggest leaving a FIXME on the changes in SemaType, saying something like 
> "we want resulting declarations to be marked invalid, but claiming the type 
> is invalid is too strong - e.g. it causes ActOnTypeName to return a null 
> type."
> What you say makes sense, but I think it's worth probing why it's not 
> currently hit (e.g. by int x(auto);, where GetDeclSpecTypeForDeclarator marks 
> the decl as invalid because auto isn't allowed in a prototype).

I believe the issue exists even before this patch, it was just not caught by 
tests. Added one.



Comment at: clang/lib/Sema/SemaType.cpp:1594
 }
+if (Result->containsErrors())
+  declarator.setInvalidType(true);

sammccall wrote:
> are you sure you want this in the individual cases, rather than once at the 
> end of this function?
ah, good point, moved the end of the `switch` statement.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D77037



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


[clang] 6f428e0 - [AST] Fix crashes on decltype(recovery-expr).

2020-03-30 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2020-03-30T14:56:33+02:00
New Revision: 6f428e09fbe8ce7e3510ae024031a5fc19653483

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

LOG: [AST] Fix crashes on decltype(recovery-expr).

Summary: We mark these decls as invalid.

Reviewers: sammccall

Subscribers: cfe-commits

Tags: #clang

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

Added: 


Modified: 
clang/include/clang/AST/DependenceFlags.h
clang/include/clang/AST/Type.h
clang/lib/Parse/ParseExprCXX.cpp
clang/lib/Sema/SemaType.cpp
clang/test/AST/ast-dump-expr-errors.cpp
clang/test/Sema/invalid-member.cpp
clang/unittests/Sema/CodeCompleteTest.cpp

Removed: 




diff  --git a/clang/include/clang/AST/DependenceFlags.h 
b/clang/include/clang/AST/DependenceFlags.h
index 75c9aa1656b8..0b24bae6df9b 100644
--- a/clang/include/clang/AST/DependenceFlags.h
+++ b/clang/include/clang/AST/DependenceFlags.h
@@ -50,14 +50,16 @@ struct TypeDependenceScope {
 /// Whether this type is a variably-modified type (C99 6.7.5).
 VariablyModified = 8,
 
-// FIXME: add Error bit.
+/// Whether this type references an error, e.g. decltype(err-expression)
+/// yields an error type.
+Error = 16,
 
 None = 0,
-All = 15,
+All = 31,
 
 DependentInstantiation = Dependent | Instantiation,
 
-LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/VariablyModified)
+LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/Error)
   };
 };
 using TypeDependence = TypeDependenceScope::TypeDependence;
@@ -147,6 +149,7 @@ class Dependence {
 return translate(V, UnexpandedPack, TypeDependence::UnexpandedPack) |
translate(V, Instantiation, TypeDependence::Instantiation) |
translate(V, Dependent, TypeDependence::Dependent) |
+   translate(V, Error, TypeDependence::Error) |
translate(V, VariablyModified, TypeDependence::VariablyModified);
   }
 

diff  --git a/clang/include/clang/AST/Type.h b/clang/include/clang/AST/Type.h
index 248fbcfba98e..5d2c035ea0fe 100644
--- a/clang/include/clang/AST/Type.h
+++ b/clang/include/clang/AST/Type.h
@@ -2139,6 +2139,11 @@ class alignas(8) Type : public ExtQualsTypeCommonBase {
 return static_cast(TypeBits.Dependence);
   }
 
+  /// Whether this type is an error type.
+  bool containsErrors() const {
+return getDependence() & TypeDependence::Error;
+  }
+
   /// Whether this type is a dependent type, meaning that its definition
   /// somehow depends on a template parameter (C++ [temp.dep.type]).
   bool isDependentType() const {

diff  --git a/clang/lib/Parse/ParseExprCXX.cpp 
b/clang/lib/Parse/ParseExprCXX.cpp
index 761fad9456be..4389c8777c6d 100644
--- a/clang/lib/Parse/ParseExprCXX.cpp
+++ b/clang/lib/Parse/ParseExprCXX.cpp
@@ -3105,10 +3105,14 @@ Parser::ParseCXXNewExpression(bool UseGlobal, 
SourceLocation Start) {
   auto RunSignatureHelp = [&]() {
 ParsedType TypeRep =
 Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
-assert(TypeRep && "invalid types should be handled before");
-QualType PreferredType = Actions.ProduceConstructorSignatureHelp(
-getCurScope(), TypeRep.get()->getCanonicalTypeInternal(),
-DeclaratorInfo.getEndLoc(), ConstructorArgs, ConstructorLParen);
+QualType PreferredType;
+// ActOnTypeName might adjust DeclaratorInfo and return a null type 
even
+// the passing DeclaratorInfo is valid, e.g. running SignatureHelp on
+// `new decltype(invalid) (^)`.
+if (TypeRep)
+  PreferredType = Actions.ProduceConstructorSignatureHelp(
+  getCurScope(), TypeRep.get()->getCanonicalTypeInternal(),
+  DeclaratorInfo.getEndLoc(), ConstructorArgs, ConstructorLParen);
 CalledSignatureHelp = true;
 return PreferredType;
   };

diff  --git a/clang/lib/Sema/SemaType.cpp b/clang/lib/Sema/SemaType.cpp
index 55ce028fb8c2..e128ebf31270 100644
--- a/clang/lib/Sema/SemaType.cpp
+++ b/clang/lib/Sema/SemaType.cpp
@@ -1678,6 +1678,12 @@ static QualType 
ConvertDeclSpecToType(TypeProcessingState &state) {
 break;
   }
 
+  // FIXME: we want resulting declarations to be marked invalid, but claiming
+  // the type is invalid is too strong - e.g. it causes ActOnTypeName to return
+  // a null type.
+  if (Result->containsErrors())
+declarator.setInvalidType();
+
   if (S.getLangOpts().OpenCL &&
   S.checkOpenCLDisabledTypeDeclSpec(DS, Result))
 declarator.setInvalidType(true);

diff  --git a/clang/test/AST/ast-dump-expr-errors.cpp 
b/clang/test/AST/ast-dump-expr-errors.cpp
index e623fad04f4c..9334b73a4354 100644
--- a/clang/test/AST/ast-dump-expr-errors.cpp
+++ b/clang/test/AST/ast-dump-expr-errors.cpp
@@ -42,5 +42,9 @@ int d = stat

[PATCH] D77037: [AST] Fix crashes on decltype(recovery-expr).

2020-03-30 Thread Haojian Wu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG6f428e09fbe8: [AST] Fix crashes on decltype(recovery-expr). 
(authored by hokein).

Changed prior to commit:
  https://reviews.llvm.org/D77037?vs=253567&id=253581#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D77037

Files:
  clang/include/clang/AST/DependenceFlags.h
  clang/include/clang/AST/Type.h
  clang/lib/Parse/ParseExprCXX.cpp
  clang/lib/Sema/SemaType.cpp
  clang/test/AST/ast-dump-expr-errors.cpp
  clang/test/Sema/invalid-member.cpp
  clang/unittests/Sema/CodeCompleteTest.cpp

Index: clang/unittests/Sema/CodeCompleteTest.cpp
===
--- clang/unittests/Sema/CodeCompleteTest.cpp
+++ clang/unittests/Sema/CodeCompleteTest.cpp
@@ -486,7 +486,10 @@
   StringRef Code = R"cpp(
 auto x = decltype(&1)(^);
 auto y = new decltype(&1)(^);
+// GNU decimal type extension is not supported in clang.
+auto z = new _Decimal128(^);
   )cpp";
   EXPECT_THAT(collectPreferredTypes(Code), Each("NULL TYPE"));
 }
+
 } // namespace
Index: clang/test/Sema/invalid-member.cpp
===
--- clang/test/Sema/invalid-member.cpp
+++ clang/test/Sema/invalid-member.cpp
@@ -1,7 +1,15 @@
-// RUN: %clang_cc1 -verify -fsyntax-only %s
-void foo(); // expected-note {{requires 0 arguments}}
+// RUN: %clang_cc1 -verify -fsyntax-only -fno-recovery-ast %s
+// RUN: %clang_cc1 -verify -fsyntax-only -frecovery-ast %s
+
+void foo(); // expected-note 2{{requires 0 arguments}}
 class X {
   decltype(foo(42)) invalid; // expected-error {{no matching function}}
 };
 // Should be able to evaluate sizeof without crashing.
 static_assert(sizeof(X) == 1, "No valid members");
+
+class Y {
+  typeof(foo(42)) invalid; // expected-error {{no matching function}}
+};
+// Should be able to evaluate sizeof without crashing.
+static_assert(sizeof(Y) == 1, "No valid members");
Index: clang/test/AST/ast-dump-expr-errors.cpp
===
--- clang/test/AST/ast-dump-expr-errors.cpp
+++ clang/test/AST/ast-dump-expr-errors.cpp
@@ -42,5 +42,9 @@
 
 // FIXME: store initializer even when 'auto' could not be deduced.
 // Expressions with errors currently do not keep initializers around.
-// CHECK: `-VarDecl {{.*}} invalid e 'auto'
+// CHECK: -VarDecl {{.*}} invalid e 'auto'
 auto e = bar();
+
+// Error type should result in an invalid decl.
+// CHECK: -VarDecl {{.*}} invalid f 'decltype((bar))'
+decltype(bar()) f;
Index: clang/lib/Sema/SemaType.cpp
===
--- clang/lib/Sema/SemaType.cpp
+++ clang/lib/Sema/SemaType.cpp
@@ -1678,6 +1678,12 @@
 break;
   }
 
+  // FIXME: we want resulting declarations to be marked invalid, but claiming
+  // the type is invalid is too strong - e.g. it causes ActOnTypeName to return
+  // a null type.
+  if (Result->containsErrors())
+declarator.setInvalidType();
+
   if (S.getLangOpts().OpenCL &&
   S.checkOpenCLDisabledTypeDeclSpec(DS, Result))
 declarator.setInvalidType(true);
Index: clang/lib/Parse/ParseExprCXX.cpp
===
--- clang/lib/Parse/ParseExprCXX.cpp
+++ clang/lib/Parse/ParseExprCXX.cpp
@@ -3105,10 +3105,14 @@
   auto RunSignatureHelp = [&]() {
 ParsedType TypeRep =
 Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
-assert(TypeRep && "invalid types should be handled before");
-QualType PreferredType = Actions.ProduceConstructorSignatureHelp(
-getCurScope(), TypeRep.get()->getCanonicalTypeInternal(),
-DeclaratorInfo.getEndLoc(), ConstructorArgs, ConstructorLParen);
+QualType PreferredType;
+// ActOnTypeName might adjust DeclaratorInfo and return a null type even
+// the passing DeclaratorInfo is valid, e.g. running SignatureHelp on
+// `new decltype(invalid) (^)`.
+if (TypeRep)
+  PreferredType = Actions.ProduceConstructorSignatureHelp(
+  getCurScope(), TypeRep.get()->getCanonicalTypeInternal(),
+  DeclaratorInfo.getEndLoc(), ConstructorArgs, ConstructorLParen);
 CalledSignatureHelp = true;
 return PreferredType;
   };
Index: clang/include/clang/AST/Type.h
===
--- clang/include/clang/AST/Type.h
+++ clang/include/clang/AST/Type.h
@@ -2139,6 +2139,11 @@
 return static_cast(TypeBits.Dependence);
   }
 
+  /// Whether this type is an error type.
+  bool containsErrors() const {
+return getDependence() & TypeDependence::Error;
+  }
+
   /// Whether this type is a dependent type, meaning that its definition
   /// somehow depends on a template parameter (C++ [temp.dep.type]).
   bool isDependentType()

[PATCH] D76932: [AIX] emit .extern and .weak directive linkage

2020-03-30 Thread Digger via Phabricator via cfe-commits
DiggerLin updated this revision to Diff 253579.
DiggerLin added a comment.

delete -u from clang test case aix-as.c


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76932

Files:
  clang/lib/Driver/ToolChains/AIX.cpp
  clang/test/Driver/aix-as.c
  llvm/include/llvm/CodeGen/AsmPrinter.h
  llvm/include/llvm/MC/MCAsmInfo.h
  llvm/include/llvm/MC/MCDirectives.h
  llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp
  llvm/lib/CodeGen/TargetLoweringObjectFileImpl.cpp
  llvm/lib/MC/MCAsmInfoXCOFF.cpp
  llvm/lib/MC/MCAsmStreamer.cpp
  llvm/lib/MC/MCXCOFFStreamer.cpp
  llvm/lib/MC/XCOFFObjectWriter.cpp
  llvm/lib/Target/PowerPC/PPCAsmPrinter.cpp
  llvm/test/CodeGen/PowerPC/aix-extern-weak.ll
  llvm/test/CodeGen/PowerPC/aix-reference-func-addr-const.ll

Index: llvm/test/CodeGen/PowerPC/aix-reference-func-addr-const.ll
===
--- llvm/test/CodeGen/PowerPC/aix-reference-func-addr-const.ll
+++ llvm/test/CodeGen/PowerPC/aix-reference-func-addr-const.ll
@@ -15,6 +15,7 @@
 ;CHECK-NEXT: .globl  foo_ptr
 ;CHECK-NEXT: .align  2
 ;CHECK-NEXT: foo_ptr:
+;CHECK-NEXT: .extern foo[DS]
 ;CHECK-NEXT: .long   foo[DS]
 ;CHECK-NEXT: .globl  bar_ptr1
 ;CHECK-NEXT: .align  2
@@ -25,6 +26,7 @@
 ;CHECK64-NEXT: .globl  foo_ptr
 ;CHECK64-NEXT: .align  3
 ;CHECK64-NEXT:foo_ptr:
+;CHECK64-NEXT:  .extern foo[DS]
 ;CHECK64-NEXT: .llong  foo[DS]
 ;CHECK64-NEXT: .globl  bar_ptr1
 ;CHECK64-NEXT: .align  3
Index: llvm/test/CodeGen/PowerPC/aix-extern-weak.ll
===
--- /dev/null
+++ llvm/test/CodeGen/PowerPC/aix-extern-weak.ll
@@ -0,0 +1,628 @@
+; RUN: llc -verify-machineinstrs -mtriple powerpc-ibm-aix-xcoff -mcpu=pwr4 \
+; RUN: -mattr=-altivec < %s | FileCheck --check-prefixes=COMMON,BIT32 %s
+
+; RUN: llc -verify-machineinstrs -mtriple powerpc64-ibm-aix-xcoff -mcpu=pwr4 \
+; RUN: -mattr=-altivec < %s | FileCheck --check-prefixes=COMMON,BIT64 %s
+
+; RUN: llc -verify-machineinstrs -mtriple powerpc-ibm-aix-xcoff -mcpu=pwr4 \
+; RUN: -mattr=-altivec -filetype=obj -o %t.o < %s
+; RUN: llvm-readobj  --symbols %t.o | FileCheck --check-prefix=CHECKSYM %s
+
+@bar_p = global i32 (...)* @bar_ref, align 4
+@foo_weak_p = global void (...)* bitcast (void ()* @foo_ref_weak to void (...)*), align 4
+@foo_ext_weak_p = global void (...)* bitcast (void ()* @foo_ext_weak to void (...)*), align 4
+@b = weak global i32 0, align 4
+@b_e = external global i32, align 4
+
+define weak void @foo_weak() #0 {
+entry:
+  ret void
+}
+
+define weak void @foo_ref_weak() #0 {
+entry:
+  ret void
+}
+
+define void @foo() #0 {
+entry:
+  ret void
+}
+
+declare i32 @bar_ref(...) #1
+
+declare extern_weak void @foo_ext_weak() #1
+
+define i32 @main() #0 {
+entry:
+  %call = call i32 @bar_extern(i32* @b)
+  call void @foo()
+  %0 = load i32 (...)*, i32 (...)** @bar_p, align 4
+  %callee.knr.cast = bitcast i32 (...)* %0 to i32 (i32*)*
+  %call1 = call i32 %callee.knr.cast(i32* @b_e)
+  %1 = load void (...)*, void (...)** @foo_weak_p, align 4
+  %callee.knr.cast2 = bitcast void (...)* %1 to void ()*
+  call void %callee.knr.cast2()
+  %2 = load void (...)*, void (...)** @foo_ext_weak_p, align 4
+  %callee.knr.cast3 = bitcast void (...)* %2 to void ()*
+  call void %callee.knr.cast3()
+  call void @foo_weak()
+  ret i32 0
+}
+
+declare i32 @bar_extern(i32*) #1
+
+; COMMON:  	.weak	foo_weak[DS]# -- Begin function foo_weak
+; COMMON-NEXT:	.weak	.foo_weak
+; COMMON-NEXT:	.align	4
+; COMMON-NEXT:	.csect foo_weak[DS]
+; BIT32-NEXT:	.long	.foo_weak   # @foo_weak
+; BIT32-NEXT:	.long	TOC[TC0]
+; BIT32-NEXT:	.long	0
+; BIT64-NEXT:	.llong	.foo_weak   # @foo_weak
+; BIT64-NEXT:	.llong	TOC[TC0]
+; BIT64-NEXT:	.llong	0
+; COMMON-NEXT:	.csect .text[PR]
+; COMMON-NEXT:.foo_weak:
+
+; COMMON:	.weak	foo_ref_weak[DS]# -- Begin function foo_ref_weak
+; COMMON-NEXT:	.weak	.foo_ref_weak
+; COMMON-NEXT:	.align	4
+; COMMON-NEXT:	.csect foo_ref_weak[DS]
+; BIT32-NEXT:	.long	.foo_ref_weak   # @foo_ref_weak
+; BIT32-NEXT:	.long	TOC[TC0]
+; BIT32-NEXT:	.long	0
+; BIT64-NEXT:	.llong	.foo_ref_weak   # @foo_ref_weak
+; BIT64-NEXT:	.llong	TOC[TC0]
+; BIT64-NEXT:	.llong	0
+; COMMON-NEXT:	.csect .text[PR]
+; COMMON-NEXT:.foo_ref_weak:
+
+; COMMON:  	.globl	foo[DS] # -- Begin function foo
+; COMMON-NEXT:	.globl	.foo
+; COMMON-NEXT:	.align	4
+; COMMON-NEXT:	.csect foo[DS]
+; BIT32-NEXT:	.long	.foo# @foo
+; BIT32-NEXT:	.long	TOC[TC0]
+; BIT32-NEXT:	.long	0
+; BIT64-NEXT:	.llong	.foo# @foo
+; BIT64-NEXT:	.llong	TOC[TC0]
+; BIT64-NEXT:	.llong	0
+; COMMON-NEXT:	.csect .text[PR]
+; COMMON-NEXT:.foo:
+
+; COMMON:  	.globl	main[DS]# -- Begin function main
+; COMMON-NEXT:	.globl	.main
+; COMMON-NEXT:	.align	4
+; COMMON

[PATCH] D75914: systemz: allow configuring default CLANG_SYSTEMZ_ARCH

2020-03-30 Thread Ulrich Weigand via Phabricator via cfe-commits
uweigand added a comment.

Ah, good point.  Dimitry, can you prepare an updated patch to implement Jonas' 
suggestion?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D75914



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


[PATCH] D77054: [AArch64][SVE] Add SVE intrinsics for saturating add & subtract

2020-03-30 Thread Kerry McLaughlin via Phabricator via cfe-commits
kmclaughlin created this revision.
kmclaughlin added reviewers: sdesmalen, c-rhodes, dancgr, efriedma, 
cameron.mcinally.
Herald added subscribers: danielkiss, psnobl, rkruppe, hiraditya, 
kristof.beyls, tschuett.
Herald added a reviewer: rengolin.
Herald added a project: LLVM.

Adds the following intrinsics:

- @llvm.aarch64.sve.[s|u]qadd.x
- @llvm.aarch64.sve.[s|u]qsub.x


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D77054

Files:
  llvm/include/llvm/IR/IntrinsicsAArch64.td
  llvm/lib/Target/AArch64/AArch64ISelLowering.cpp
  llvm/lib/Target/AArch64/AArch64SVEInstrInfo.td
  llvm/test/CodeGen/AArch64/sve-int-arith.ll
  llvm/test/CodeGen/AArch64/sve-int-imm.ll
  llvm/test/CodeGen/AArch64/sve-intrinsics-int-arith.ll

Index: llvm/test/CodeGen/AArch64/sve-intrinsics-int-arith.ll
===
--- llvm/test/CodeGen/AArch64/sve-intrinsics-int-arith.ll
+++ llvm/test/CodeGen/AArch64/sve-intrinsics-int-arith.ll
@@ -134,6 +134,82 @@
   ret  %out
 }
 
+; SQADD
+
+define  @sqadd_i8( %a,  %b) {
+; CHECK-LABEL: sqadd_i8:
+; CHECK: sqadd z0.b, z0.b, z1.b
+; CHECK-NEXT: ret
+  %out = call  @llvm.aarch64.sve.sqadd.x.nxv16i8( %a,
+%b)
+  ret  %out
+}
+
+define  @sqadd_i16( %a,  %b) {
+; CHECK-LABEL: sqadd_i16:
+; CHECK: sqadd z0.h, z0.h, z1.h
+; CHECK-NEXT: ret
+  %out = call  @llvm.aarch64.sve.sqadd.x.nxv8i16( %a,
+%b)
+  ret  %out
+}
+
+define  @sqadd_i32( %a,  %b) {
+; CHECK-LABEL: sqadd_i32:
+; CHECK: sqadd z0.s, z0.s, z1.s
+; CHECK-NEXT: ret
+  %out = call  @llvm.aarch64.sve.sqadd.x.nxv4i32( %a,
+%b)
+  ret  %out
+}
+
+define  @sqadd_i64( %a,  %b) {
+; CHECK-LABEL: sqadd_i64:
+; CHECK: sqadd z0.d, z0.d, z1.d
+; CHECK-NEXT: ret
+  %out = call  @llvm.aarch64.sve.sqadd.x.nxv2i64( %a,
+%b)
+  ret  %out
+}
+
+; SQSUB
+
+define  @sqsub_i8( %a,  %b) {
+; CHECK-LABEL: sqsub_i8:
+; CHECK: sqsub z0.b, z0.b, z1.b
+; CHECK-NEXT: ret
+  %out = call  @llvm.aarch64.sve.sqsub.x.nxv16i8( %a,
+%b)
+  ret  %out
+}
+
+define  @sqsub_i16( %a,  %b) {
+; CHECK-LABEL: sqsub_i16:
+; CHECK: sqsub z0.h, z0.h, z1.h
+; CHECK-NEXT: ret
+  %out = call  @llvm.aarch64.sve.sqsub.x.nxv8i16( %a,
+%b)
+  ret  %out
+}
+
+define  @sqsub_i32( %a,  %b) {
+; CHECK-LABEL: sqsub_i32:
+; CHECK: sqsub z0.s, z0.s, z1.s
+; CHECK-NEXT: ret
+  %out = call  @llvm.aarch64.sve.sqsub.x.nxv4i32( %a,
+%b)
+  ret  %out
+}
+
+define  @sqsub_i64( %a,  %b) {
+; CHECK-LABEL: sqsub_i64:
+; CHECK: sqsub z0.d, z0.d, z1.d
+; CHECK-NEXT: ret
+  %out = call  @llvm.aarch64.sve.sqsub.x.nxv2i64( %a,
+%b)
+  ret  %out
+}
+
 ; UDOT
 
 define  @udot_i32( %a,  %b,  %c) {
@@ -169,6 +245,82 @@
   ret  %out
 }
 
+; UQADD
+
+define  @uqadd_i8( %a,  %b) {
+; CHECK-LABEL: uqadd_i8:
+; CHECK: uqadd z0.b, z0.b, z1.b
+; CHECK-NEXT: ret
+  %out = call  @llvm.aarch64.sve.uqadd.x.nxv16i8( %a,
+%b)
+  ret  %out
+}
+
+define  @uqadd_i16( %a,  %b) {
+; CHECK-LABEL: uqadd_i16:
+; CHECK: uqadd z0.h, z0.h, z1.h
+; CHECK-NEXT: ret
+  %out = call  @llvm.aarch64.sve.uqadd.x.nxv8i16( %a,
+%b)
+  ret  %out
+}
+
+define  @uqadd_i32( %a,  %b) {
+; CHECK-LABEL: uqadd_i32:
+; CHECK: uqadd z0.s, z0.s, z1.s
+; CHECK-NEXT: ret
+  %out = call  @llvm.aarch64.sve.uqadd.x.nxv4i32( %a,
+%b)
+  ret  %out
+}
+
+define  @uqadd_i64( %a,  %b) {
+; CHECK-LABEL: uqadd_i64:
+; CHECK: uqadd z0.d, z0.d, z1.d
+; CHECK-NEXT: ret
+  %out = call  @llvm.aarch64.sve.uqadd.x.nxv2i64( %a,
+%b)
+  ret  %out
+}
+
+; UQSUB
+
+define  @uqsub_i8( %a,  %b) {
+; CHECK-LABEL: uqsub_i8:
+; CHECK: uqsub z0.b, z0.b, z1.b
+; CHECK-NEXT: ret
+  %out = call  @llvm.aarch64.sve.uqsub.x.nxv16i8( %a,
+%b)
+  ret  %out
+}
+
+define  @uqsub_i16( %a,  %b) {
+; CHECK-LABEL: uqsub_i16:
+; CHECK: uqsub z0.h, z0.h, z1.h
+; CHECK-NEXT: ret
+  %out = call  @llvm.aarch64.sve.uqsub.x.nxv8i16( %a,
+%b)
+  ret  %out
+}
+
+define  @uqsub_i32( %a,  %b) {
+; CHECK-LABEL: uqsub_i32:
+; CHECK: uqsub z0.s, z0.s, z1.s
+; CHECK-NEXT: ret
+  %out = call  @llvm.aarch64.sve.uqsub.x.nxv4i32( %a,
+%b)
+  ret  %out

[clang] 7ac9efb - [OPENMP50]Add basic support for array-shaping operation.

2020-03-30 Thread Alexey Bataev via cfe-commits

Author: Alexey Bataev
Date: 2020-03-30T09:18:24-04:00
New Revision: 7ac9efb0c322bacd4f09e6aed82466116b685892

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

LOG: [OPENMP50]Add basic support for array-shaping operation.

Summary:
Added basic representation and parsing/sema handling of array-shaping
operations. Array shaping expression is an expression of form ([s0]..[sn])base,
where s0, ..., sn must be a positive integer, base - a pointer. This
expression is a kind of cast operation that converts pointer expression
into an array-like kind of expression.

Reviewers: rjmccall, rsmith, jdoerfert

Subscribers: guansong, arphaman, cfe-commits, caomhin, kkwli0

Tags: #clang

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

Added: 


Modified: 
clang/include/clang-c/Index.h
clang/include/clang/AST/ASTContext.h
clang/include/clang/AST/BuiltinTypes.def
clang/include/clang/AST/ComputeDependence.h
clang/include/clang/AST/ExprOpenMP.h
clang/include/clang/AST/RecursiveASTVisitor.h
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/include/clang/Basic/StmtNodes.td
clang/include/clang/Parse/Parser.h
clang/include/clang/Sema/Sema.h
clang/include/clang/Serialization/ASTBitCodes.h
clang/lib/AST/ASTContext.cpp
clang/lib/AST/ComputeDependence.cpp
clang/lib/AST/Expr.cpp
clang/lib/AST/ExprClassification.cpp
clang/lib/AST/ExprConstant.cpp
clang/lib/AST/ItaniumMangle.cpp
clang/lib/AST/NSAPI.cpp
clang/lib/AST/StmtPrinter.cpp
clang/lib/AST/StmtProfile.cpp
clang/lib/AST/Type.cpp
clang/lib/AST/TypeLoc.cpp
clang/lib/Parse/ParseExpr.cpp
clang/lib/Sema/SemaExceptionSpec.cpp
clang/lib/Sema/SemaExpr.cpp
clang/lib/Sema/SemaOpenMP.cpp
clang/lib/Sema/TreeTransform.h
clang/lib/Serialization/ASTCommon.cpp
clang/lib/Serialization/ASTReader.cpp
clang/lib/Serialization/ASTReaderStmt.cpp
clang/lib/Serialization/ASTWriterStmt.cpp
clang/lib/StaticAnalyzer/Checkers/IdenticalExprChecker.cpp
clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
clang/test/OpenMP/depobj_messages.cpp
clang/test/OpenMP/parallel_reduction_messages.c
clang/test/OpenMP/task_ast_print.cpp
clang/test/OpenMP/task_depend_messages.cpp
clang/tools/libclang/CIndex.cpp
clang/tools/libclang/CXCursor.cpp

Removed: 




diff  --git a/clang/include/clang-c/Index.h b/clang/include/clang-c/Index.h
index cca7198d2f9f..641f058dafaa 100644
--- a/clang/include/clang-c/Index.h
+++ b/clang/include/clang-c/Index.h
@@ -2176,7 +2176,11 @@ enum CXCursorKind {
*/
   CXCursor_FixedPointLiteral = 149,
 
-  CXCursor_LastExpr = CXCursor_FixedPointLiteral,
+  /** OpenMP 5.0 [2.1.4, Array Shaping].
+   */
+  CXCursor_OMPArrayShapingExpr = 150,
+
+  CXCursor_LastExpr = CXCursor_OMPArrayShapingExpr,
 
   /* Statements */
   CXCursor_FirstStmt = 200,

diff  --git a/clang/include/clang/AST/ASTContext.h 
b/clang/include/clang/AST/ASTContext.h
index ca0f991c24e3..ebb5ca593843 100644
--- a/clang/include/clang/AST/ASTContext.h
+++ b/clang/include/clang/AST/ASTContext.h
@@ -970,7 +970,7 @@ class ASTContext : public RefCountedBase {
 #include "clang/Basic/OpenCLImageTypes.def"
   CanQualType OCLSamplerTy, OCLEventTy, OCLClkEventTy;
   CanQualType OCLQueueTy, OCLReserveIDTy;
-  CanQualType OMPArraySectionTy;
+  CanQualType OMPArraySectionTy, OMPArrayShapingTy;
 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
   CanQualType Id##Ty;
 #include "clang/Basic/OpenCLExtensionTypes.def"

diff  --git a/clang/include/clang/AST/BuiltinTypes.def 
b/clang/include/clang/AST/BuiltinTypes.def
index 74a45ee4ccc0..f42503773945 100644
--- a/clang/include/clang/AST/BuiltinTypes.def
+++ b/clang/include/clang/AST/BuiltinTypes.def
@@ -313,8 +313,11 @@ PLACEHOLDER_TYPE(ARCUnbridgedCast, ARCUnbridgedCastTy)
 // A placeholder type for OpenMP array sections.
 PLACEHOLDER_TYPE(OMPArraySection, OMPArraySectionTy)
 
+// A placeholder type for OpenMP array shaping operation.
+PLACEHOLDER_TYPE(OMPArrayShaping, OMPArrayShapingTy)
+
 #ifdef LAST_BUILTIN_TYPE
-LAST_BUILTIN_TYPE(OMPArraySection)
+LAST_BUILTIN_TYPE(OMPArrayShaping)
 #undef LAST_BUILTIN_TYPE
 #endif
 

diff  --git a/clang/include/clang/AST/ComputeDependence.h 
b/clang/include/clang/AST/ComputeDependence.h
index 02f826438d4d..63947eaff73b 100644
--- a/clang/include/clang/AST/ComputeDependence.h
+++ b/clang/include/clang/AST/ComputeDependence.h
@@ -87,6 +87,7 @@ class ParenListExpr;
 class PseudoObjectExpr;
 class AtomicExpr;
 class OMPArraySectionExpr;
+class OMPArrayShapingExpr;
 class ObjCArrayLiteral;
 class ObjCDictionaryLiteral;
 class ObjCBoxedExpr;
@@ -172,6 +173,7 @@ ExprDependence computeDependence(PseudoObjectExpr *E);
 ExprDependence computeDependence(AtomicExpr *E);
 
 ExprDependence computeDepe

[PATCH] D76432: [clangd] Add a tweak for adding "using" statement.

2020-03-30 Thread Adam Czachorowski via Phabricator via cfe-commits
adamcz updated this revision to Diff 253583.
adamcz marked 10 inline comments as done.
adamcz added a comment.

review round 2


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76432

Files:
  clang-tools-extra/clangd/refactor/tweaks/AddUsing.cpp
  clang-tools-extra/clangd/refactor/tweaks/CMakeLists.txt
  clang-tools-extra/clangd/unittests/TweakTests.cpp

Index: clang-tools-extra/clangd/unittests/TweakTests.cpp
===
--- clang-tools-extra/clangd/unittests/TweakTests.cpp
+++ clang-tools-extra/clangd/unittests/TweakTests.cpp
@@ -2390,6 +2390,250 @@
 EXPECT_EQ(apply(Case.first), Case.second);
   }
 }
+
+TWEAK_TEST(AddUsing);
+TEST_F(AddUsingTest, Prepare) {
+  const std::string Header = R"cpp(
+#define NS(name) one::two::name
+namespace one {
+void oo() {}
+namespace two {
+enum ee {};
+void ff() {}
+class cc {
+public:
+  struct st {};
+  static void mm() {}
+};
+}
+})cpp";
+
+  EXPECT_AVAILABLE(Header + "void fun() { o^n^e^:^:^t^w^o^:^:^f^f(); }");
+  EXPECT_AVAILABLE(Header + "void fun() { o^n^e^::^o^o(); }");
+  EXPECT_AVAILABLE(Header + "void fun() { o^n^e^:^:^t^w^o^:^:^e^e E; }");
+  EXPECT_AVAILABLE(Header + "void fun() { o^n^e^:^:^t^w^o:^:^c^c C; }");
+  EXPECT_UNAVAILABLE(Header +
+ "void fun() { o^n^e^:^:^t^w^o^:^:^c^c^:^:^m^m(); }");
+  EXPECT_UNAVAILABLE(Header +
+ "void fun() { o^n^e^:^:^t^w^o^:^:^c^c^:^:^s^t inst; }");
+  EXPECT_UNAVAILABLE(Header +
+ "void fun() { o^n^e^:^:^t^w^o^:^:^c^c^:^:^s^t inst; }");
+  EXPECT_UNAVAILABLE(Header + "void fun() { N^S(c^c) inst; }");
+}
+
+TEST_F(AddUsingTest, Apply) {
+  FileName = "test.cpp";
+  struct {
+llvm::StringRef TestSource;
+llvm::StringRef ExpectedSource;
+  } Cases[]{{
+// Function, no other using, namespace.
+R"cpp(
+#include "test.hpp"
+namespace {
+void fun() {
+  ^o^n^e^:^:^t^w^o^:^:^f^f();
+}
+})cpp",
+R"cpp(
+#include "test.hpp"
+namespace {using one::two::ff;
+
+void fun() {
+  ff();
+}
+})cpp",
+},
+// Type, no other using, namespace.
+{
+R"cpp(
+#include "test.hpp"
+namespace {
+void fun() {
+  ::on^e::t^wo::c^c inst;
+}
+})cpp",
+R"cpp(
+#include "test.hpp"
+namespace {using ::one::two::cc;
+
+void fun() {
+  cc inst;
+}
+})cpp",
+},
+// Type, no other using, no namespace.
+{
+R"cpp(
+#include "test.hpp"
+
+void fun() {
+  on^e::t^wo::e^e inst;
+})cpp",
+R"cpp(
+#include "test.hpp"
+
+using one::two::ee;
+
+void fun() {
+  ee inst;
+})cpp"},
+// Function, other usings.
+{
+R"cpp(
+#include "test.hpp"
+
+using one::two::cc;
+using one::two::ee;
+
+namespace {
+void fun() {
+  one::two::f^f();
+}
+})cpp",
+R"cpp(
+#include "test.hpp"
+
+using one::two::cc;
+using one::two::ff;using one::two::ee;
+
+namespace {
+void fun() {
+  ff();
+}
+})cpp",
+},
+// Function, other usings inside namespace.
+{
+R"cpp(
+#include "test.hpp"
+
+using one::two::cc;
+
+namespace {
+
+using one::two::ff;
+
+void fun() {
+  o^ne::o^o();
+}
+})cpp",
+R"cpp(
+#include "test.hpp"
+
+using one::two::cc;
+
+namespace {
+
+using one::oo;using one::two::ff;
+
+void fun() {
+  oo();
+}
+})cpp"},
+// Using comes after cursor.
+{
+R"cpp(
+#include "test.hpp"
+
+namespace {
+
+void fun() {
+  one::t^wo::ff();
+}
+
+using one::two::cc;
+
+})cpp",
+R"cpp(
+#include "test.hpp"
+
+namespace {using one::two::ff;
+
+
+void fun() {
+  ff();
+}
+
+using one::two::cc;
+
+})cpp"},
+// Pointer type.
+{R"cpp(
+#include "test.hpp"
+
+void fun() {
+  one::two::c^c *p;
+})cpp",
+ R"cpp(
+#include "test.hpp"
+
+using one::two::cc;
+
+void fun() {
+  cc *p;
+})cpp"},
+// Namespace declared via macro.
+{R"cpp(
+#include "test.hpp"
+#define NS_BEGIN(name) namespace name {
+
+NS_BEGIN(foo)
+
+void fun() {
+  one::two::f^f();
+}
+})cpp",
+ R"cpp(
+#include "test.hpp"
+#define NS_BEGIN(name) namespace name {
+
+using one::two::ff;
+
+NS_BEGIN(foo)
+
+void fun() {
+  ff();
+}
+})cpp"},
+// Inside macro argument.
+{R"cpp(
+#include "test.hpp"
+#define CALL(name) name()
+
+void fun() {
+  CALL(one::t^wo::ff);
+})cpp",
+ R"cpp(
+#include "test.hpp"
+#define CALL(name) name()
+
+using one::two::ff;
+
+void fun() {
+  CALL(ff);
+})cpp"}};
+  llvm::StringMap EditedFiles;
+  for (const auto &Case : Cases) {
+for (const auto &SubCase : expandCases(Case.TestSource)) {
+  ExtraFiles["test.hpp"] = R"cpp(
+namespace one {
+void oo() {}
+namespace two {
+enum ee {};
+void ff() {}
+class cc {
+public:
+  struct st { struct

[PATCH] D76932: [AIX] emit .extern and .weak directive linkage

2020-03-30 Thread Digger via Phabricator via cfe-commits
DiggerLin marked an inline comment as done.
DiggerLin added inline comments.



Comment at: llvm/include/llvm/MC/MCDirectives.h:47
+  MCSA_WeakReference,   ///< .weak_reference (MachO)
+  MCSA_WeakDefAutoPrivate   ///< .weak_def_can_be_hidden (MachO)
 };

@hubert.reinterpretcast , @jasonliu , do we need to create a NFC patch for the 
clang format problem of the above first ?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76932



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


[PATCH] D74144: [OPENMP50]Add basic support for array-shaping operation.

2020-03-30 Thread Alexey Bataev via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG7ac9efb0c322: [OPENMP50]Add basic support for array-shaping 
operation. (authored by ABataev).

Changed prior to commit:
  https://reviews.llvm.org/D74144?vs=252859&id=253584#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D74144

Files:
  clang/include/clang-c/Index.h
  clang/include/clang/AST/ASTContext.h
  clang/include/clang/AST/BuiltinTypes.def
  clang/include/clang/AST/ComputeDependence.h
  clang/include/clang/AST/ExprOpenMP.h
  clang/include/clang/AST/RecursiveASTVisitor.h
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Basic/StmtNodes.td
  clang/include/clang/Parse/Parser.h
  clang/include/clang/Sema/Sema.h
  clang/include/clang/Serialization/ASTBitCodes.h
  clang/lib/AST/ASTContext.cpp
  clang/lib/AST/ComputeDependence.cpp
  clang/lib/AST/Expr.cpp
  clang/lib/AST/ExprClassification.cpp
  clang/lib/AST/ExprConstant.cpp
  clang/lib/AST/ItaniumMangle.cpp
  clang/lib/AST/NSAPI.cpp
  clang/lib/AST/StmtPrinter.cpp
  clang/lib/AST/StmtProfile.cpp
  clang/lib/AST/Type.cpp
  clang/lib/AST/TypeLoc.cpp
  clang/lib/Parse/ParseExpr.cpp
  clang/lib/Sema/SemaExceptionSpec.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaOpenMP.cpp
  clang/lib/Sema/TreeTransform.h
  clang/lib/Serialization/ASTCommon.cpp
  clang/lib/Serialization/ASTReader.cpp
  clang/lib/Serialization/ASTReaderStmt.cpp
  clang/lib/Serialization/ASTWriterStmt.cpp
  clang/lib/StaticAnalyzer/Checkers/IdenticalExprChecker.cpp
  clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
  clang/test/OpenMP/depobj_messages.cpp
  clang/test/OpenMP/parallel_reduction_messages.c
  clang/test/OpenMP/task_ast_print.cpp
  clang/test/OpenMP/task_depend_messages.cpp
  clang/tools/libclang/CIndex.cpp
  clang/tools/libclang/CXCursor.cpp

Index: clang/tools/libclang/CXCursor.cpp
===
--- clang/tools/libclang/CXCursor.cpp
+++ clang/tools/libclang/CXCursor.cpp
@@ -423,6 +423,10 @@
 K = CXCursor_OMPArraySectionExpr;
 break;
 
+  case Stmt::OMPArrayShapingExprClass:
+K = CXCursor_OMPArrayShapingExpr;
+break;
+
   case Stmt::BinaryOperatorClass:
 K = CXCursor_BinaryOperator;
 break;
Index: clang/tools/libclang/CIndex.cpp
===
--- clang/tools/libclang/CIndex.cpp
+++ clang/tools/libclang/CIndex.cpp
@@ -5183,6 +5183,8 @@
 return cxstring::createRef("ArraySubscriptExpr");
   case CXCursor_OMPArraySectionExpr:
 return cxstring::createRef("OMPArraySectionExpr");
+  case CXCursor_OMPArrayShapingExpr:
+return cxstring::createRef("OMPArrayShapingExpr");
   case CXCursor_BinaryOperator:
 return cxstring::createRef("BinaryOperator");
   case CXCursor_CompoundAssignOperator:
Index: clang/test/OpenMP/task_depend_messages.cpp
===
--- clang/test/OpenMP/task_depend_messages.cpp
+++ clang/test/OpenMP/task_depend_messages.cpp
@@ -35,14 +35,14 @@
   #pragma omp task depend (source) // expected-error {{expected expression}} expected-warning {{missing ':' after dependency type - ignoring}} omp45-error {{expected 'in', 'out', 'inout' or 'mutexinoutset' in OpenMP clause 'depend'}} omp50-error {{expected 'in', 'out', 'inout', 'mutexinoutset' or 'depobj' in OpenMP clause 'depend'}}
   #pragma omp task depend (in : argc)) // expected-warning {{extra tokens at the end of '#pragma omp task' are ignored}}
   #pragma omp task depend (out: ) // expected-error {{expected expression}}
-  #pragma omp task depend (inout : foobool(argc)), depend (in, argc) // expected-error {{expected addressable lvalue expression, array element or array section}} expected-warning {{missing ':' after dependency type - ignoring}} expected-error {{expected expression}}
+  #pragma omp task depend (inout : foobool(argc)), depend (in, argc) // omp50-error {{expected addressable lvalue expression, array element, array section or array shaping expression}} omp45-error {{expected addressable lvalue expression, array element or array section}} expected-warning {{missing ':' after dependency type - ignoring}} expected-error {{expected expression}}
   #pragma omp task depend (out :S1) // expected-error {{'S1' does not refer to a value}}
   #pragma omp task depend(in : argv[1][1] = '2')
-  #pragma omp task depend (in : vec[1]) // expected-error {{expected addressable lvalue expression, array element or array section}}
+  #pragma omp task depend (in : vec[1]) // omp50-error {{expected addressable lvalue expression, array element, array section or array shaping expression}} omp45-error {{expected addressable lvalue expression, array element or array section}}
   #pragma omp task depend (in : argv[0])
   #pragma omp task depend (in : ) // expected-error {{expected expression}}
   #pragma omp task depend (in : main)

[PATCH] D76996: [analyzer] Improve PlacementNewChecker

2020-03-30 Thread Gabor Marton via Phabricator via cfe-commits
martong added a comment.

Wohoow! I am impressed, this is really nice work, I like it! :) Could not find 
any glitch, looks good from my side once you address NoQ's concerns.




Comment at: clang/lib/StaticAnalyzer/Checkers/CheckPlacementNew.cpp:125
+Msg = std::string(llvm::formatv(
+"Possibly not enough {0} bytes for array allocation which "
+"requires "

Maybe the below could be a wording that's more easy to follow?
`{0} bytes is possibly not enough for array allocation which ...`


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76996



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


[PATCH] D77053: [Syntax] A tool to dump syntax tree and token buffer

2020-03-30 Thread Marcel Hlopko via Phabricator via cfe-commits
hlopko abandoned this revision.
hlopko added a comment.

Talked to gribozavr2 offline and decided to abandon this patch. If in the 
future we'll have a need for a tool to dump syntax trees, we'll probably 
implement it in clang behind hidden options, and we'll provide a json output 
format as well.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D77053



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


[PATCH] D76432: [clangd] Add a tweak for adding "using" statement.

2020-03-30 Thread Adam Czachorowski via Phabricator via cfe-commits
adamcz added inline comments.



Comment at: clang-tools-extra/clangd/refactor/tweaks/AddUsing.cpp:89
+
+  // If we're looking at a type or NestedNameSpecifier, walk up the tree until
+  // we find the "main" node we care about, which would be ElaboratedTypeLoc or

sammccall wrote:
> adamcz wrote:
> > sammccall wrote:
> > > I like the idea here, but I'm not sure it quite works. e.g. any typeloc 
> > > has a directly enclosing typeloc, the inner one can't be targeted. So 
> > > what about `x::S*`? (pointertypeloc > elaboratedtypeloc > recordtypeloc)?
> > > 
> > > - looping up from NNS until you get to something else makes sense
> > > - unwrapping typeloc -> elaboratedtypeloc makes sense, but I don't think 
> > > you ever want to unwrap multiple levels?
> > > - i don't think these cases overlap at all, you want one or the other
> > > 
> > > Am I missing something?
> > If you have a class foo::bar::cc and a struct st inside it, and then do:
> > foo::bar::c^c::st *p;
> > you end up with:
> > PointerTypeLoc -> ElaboratedTypeLoc ->NestedNameSpecifierLoc -> 
> > RecordTypeLoc
> > in which case you need to go up from type to NNSL and then up again, from 
> > NNSL to something that's not NNSL.
> > 
> > You have a good point with the PointerTypeLoc, that's a bug. We should stop 
> > going up the tree as soon as we find ElaboratedTypeLoc. I added a test for 
> > that.
> > foo::bar::c^c::st *p;
> 
> But this isn't a case we support, right? We only support extraction when the 
> NNS consists entirely of namespaces, and such NNSes don't have any children 
> apart from the qualifier NNS.
Not right now, but I left a comment that we should improve that. The way it is 
now, code is correct, always, and improving it is just a matter or removing the 
"no record types" check and replacing with a bit more code. Seems better to me.



Comment at: clang-tools-extra/clangd/refactor/tweaks/AddUsing.cpp:206
+  tooling::Replacements R;
+  if (auto Err = R.add(tooling::Replacement(
+  SM, CharSourceRange::getTokenRange(NNSL.getSourceRange()), "",

kadircet wrote:
> sammccall wrote:
> > adamcz wrote:
> > > sammccall wrote:
> > > > (Sorry if some of this is obvious: TL;DR: we should use TokenBuffer to 
> > > > handle macros in this case)
> > > > 
> > > > Whenever we try to use SourceLocations to reason about written source 
> > > > code, we have to think about macros. Some libraries try to encapsulate 
> > > > this, but the road to confusion is paved with good intentions, and it's 
> > > > often best to decide on the policy and be explicit about it.
> > > > 
> > > > For example, when provided a macro location, the tooling::Replacement 
> > > > constructor uses its spelling location. 
> > > > Given: 
> > > > ```
> > > > // imagine we're trying to abstract away namespaces for C or something
> > > > #define NS(X) foo::X
> > > > NS(Bar) boo;
> > > > ```
> > > > Running this action on `N` would result in changing the definition of 
> > > > the `NS` macro to delete the "foo::", as that's where the qualifier was 
> > > > spelled!
> > > > 
> > > > It would be reasonable (but actually not trivial!) to try to detect any 
> > > > macro usage and bail out. The general case of "is there some sequence 
> > > > of source-code tokens that correspond to this range of preprocessed 
> > > > tokens and nothing else" is pretty hard.
> > > > 
> > > > However TokenBuffer does have APIs for this exact question, as it was 
> > > > designed for writing refactorings that replace nodes. I think you want:
> > > >  - `expandedTokens(NNSL.getSourceRange())`
> > > >  - `spelledForExpanded(ExpandedTokens)`
> > > >  - `Token::range(SM, Spelled.front(), Spelled.back())`
> > > >  - `Replacement("fname", Range.Offset, Range.Length, "")`
> > > > 
> > > > (ugh, that's really awkward. Maybe we should have a helper in 
> > > > TokenBuffer that combines 1-3)
> > > > 
> > > You have a good point that this doesn't work well with macros, but I'm 
> > > not entirely sure how you think this should work.
> > > 
> > > I'd argue that code actions should refer to the thing under the cursor, 
> > > not it's expansion. That would be confusing to the user, as they would 
> > > not be able to understand what the action offered is, nor how it would 
> > > affect other places. So in your example of 
> > > #define NS(X) foo::X
> > > I'd argue that we should not offer the action. 
> > > We should, however, support something like:
> > > EXPECT_TRUE(fo^o::bar());
> > > In this case, the qualifier is spelled under the cursor and the fact that 
> > > EXPECT_TRUE is a macro and not a function should not matter to the user.
> > > 
> > > I updated the code to support that and added tests.
> > > We can use isMacroID() and isMacroArgExpansion() to filter out macros, 
> > > except for macro arguments. Note that we can't use spelledForExpanded(), 
> > > since the qualifier might not be the entire expansion of the macro, thus 
> > > sp

[clang] 703a1b8 - [analyzer][MallocChecker][NFC] Split checkPostCall up, deploy CallDescriptionMap

2020-03-30 Thread Kirstóf Umann via cfe-commits

Author: Louis Dionne
Date: 2020-03-30T16:01:58+02:00
New Revision: 703a1b8caf09a5262a45c2179b8131922f71cf25

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

LOG: [analyzer][MallocChecker][NFC] Split checkPostCall up, deploy 
CallDescriptionMap

Since its important to know whether a function frees memory (even if its a
reallocating function!), I used two CallDescriptionMaps to merge all
CallDescriptions into it. MemFunctionInfoTy no longer makes sense, it may never
have, but for now, it would be more of a distraction then anything else.

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

Added: 


Modified: 
clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
index 32a500ffd102..52786bcaf072 100644
--- a/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
@@ -62,16 +62,19 @@
 #include "clang/StaticAnalyzer/Core/PathSensitive/DynamicSize.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/Support/ErrorHandling.h"
 #include 
+#include 
 #include 
 
 using namespace clang;
 using namespace ento;
+using namespace std::placeholders;
 
 
//===--===//
 // The types of allocation we're modeling. This is used to check whether a
@@ -93,8 +96,6 @@ enum AllocationFamily {
   AF_InnerBuffer
 };
 
-struct MemFunctionInfoTy;
-
 } // end of anonymous namespace
 
 /// Print names of allocators and deallocators.
@@ -263,47 +264,6 @@ struct ReallocPair {
 
 REGISTER_MAP_WITH_PROGRAMSTATE(ReallocPairs, SymbolRef, ReallocPair)
 
-//===--===//
-// Kinds of memory operations, information about resource managing functions.
-//===--===//
-
-namespace {
-
-struct MemFunctionInfoTy {
-  /// The value of the MallocChecker:Optimistic is stored in this variable.
-  ///
-  /// In pessimistic mode, the checker assumes that it does not know which
-  /// functions might free the memory.
-  /// In optimistic mode, the checker assumes that all user-defined functions
-  /// which might free a pointer are annotated.
-  DefaultBool ShouldIncludeOwnershipAnnotatedFunctions;
-
-  CallDescription CD_alloca{{"alloca"}, 1}, CD_win_alloca{{"_alloca"}, 1},
-  CD_malloc{{"malloc"}, 1}, CD_BSD_malloc{{"malloc"}, 3},
-  CD_free{{"free"}, 1}, CD_realloc{{"realloc"}, 2},
-  CD_calloc{{"calloc"}, 2}, CD_valloc{{"valloc"}, 1},
-  CD_reallocf{{"reallocf"}, 2}, CD_strndup{{"strndup"}, 2},
-  CD_strdup{{"strdup"}, 1}, CD_win_strdup{{"_strdup"}, 1},
-  CD_kmalloc{{"kmalloc"}, 2}, CD_if_nameindex{{"if_nameindex"}, 1},
-  CD_if_freenameindex{{"if_freenameindex"}, 1}, CD_wcsdup{{"wcsdup"}, 1},
-  CD_win_wcsdup{{"_wcsdup"}, 1}, CD_kfree{{"kfree"}, 1},
-  CD_g_malloc{{"g_malloc"}, 1}, CD_g_malloc0{{"g_malloc0"}, 1},
-  CD_g_realloc{{"g_realloc"}, 2}, CD_g_try_malloc{{"g_try_malloc"}, 1},
-  CD_g_try_malloc0{{"g_try_malloc0"}, 1},
-  CD_g_try_realloc{{"g_try_realloc"}, 2}, CD_g_free{{"g_free"}, 1},
-  CD_g_memdup{{"g_memdup"}, 2}, CD_g_malloc_n{{"g_malloc_n"}, 2},
-  CD_g_malloc0_n{{"g_malloc0_n"}, 2}, CD_g_realloc_n{{"g_realloc_n"}, 3},
-  CD_g_try_malloc_n{{"g_try_malloc_n"}, 2},
-  CD_g_try_malloc0_n{{"g_try_malloc0_n"}, 2},
-  CD_g_try_realloc_n{{"g_try_realloc_n"}, 3};
-
-  bool isMemFunction(const CallEvent &Call) const;
-  bool isCMemFunction(const CallEvent &Call) const;
-  bool isCMemFreeFunction(const CallEvent &Call) const;
-  bool isCMemAllocFunction(const CallEvent &Call) const;
-};
-} // end of anonymous namespace
-
 /// Tells if the callee is one of the builtin new/delete operators, including
 /// placement operators and other standard overloads.
 static bool isStandardNewDelete(const FunctionDecl *FD);
@@ -327,7 +287,11 @@ class MallocChecker
  check::PreStmt, check::PostStmt,
  check::PostObjCMessage, check::Location, eval::Assume> {
 public:
-  MemFunctionInfoTy MemFunctionInfo;
+  /// In pessimistic mode, the checker assumes that it does not know which
+  /// functions might free the memory.
+  /// In optimistic mode, the checker assumes that all user-defined functions
+  /// w

[PATCH] D77056: RFC: [Sema][SVE] Allow non-member operators for SVE types

2020-03-30 Thread Richard Sandiford via Phabricator via cfe-commits
rsandifo-arm created this revision.
rsandifo-arm added reviewers: sdesmalen, efriedma, rovka, rjmccall.
Herald added subscribers: cfe-commits, danielkiss, psnobl, rkruppe, 
kristof.beyls, tschuett.
Herald added a reviewer: rengolin.
Herald added a project: clang.
rsandifo-arm edited the summary of this revision.

SVE types are defined to be opaque built-in types that by default
can only be used via intrinsics.  One consequence of this is that
the types provide no built-in versions of the unary and binary
arithmetic operators.

Instead, we'd like to allow users to define non-member operators
for SVE types, in much the same way as for enumeration types.
This specifically means:

- replacing "enumeration" in sections [over.match.oper] and [over.oper] of the 
C++ standard with wording that includes both enumerations and SVE types.

- extending the enumeration handling of operator= in [over.built] to include 
SVE types.

This feature is defined by a to-be-published update to the SVE ACLE spec.
The feature is optional and its availability can be tested by the
preprocessor condition:

  __ARM_FEATURE_SVE_NONMEMBER_OPERATORS==1

An alternative would be to build the operators into the compiler.
However, we didn't want to do that for several reasons:

- Some of the operators would not be performance-portable. (E.g. %, and the 
8-bit and 16-bit integer versions of /.) The SVE ACLE is supposed to be a 
low-level, almost asm-level interface to the architecture, so synthesising this 
kind of operation seems out-of-place.

- SVE types cannot be used in structures, so unlike with normal vector types, 
the user doesn't have the option of using a wrapper class to opt out of the 
standard handling.

- If in future we do want to provide a core group of operators in a standard 
header file/module, we could use this extension to write it.

The patch triggers a duplicate warning for:

  ref_int8 = ref_int8;

but it seemed better to fix that separately.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D77056

Files:
  clang/include/clang/AST/Type.h
  clang/lib/Basic/Targets/AArch64.cpp
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/lib/Sema/SemaOverload.cpp
  clang/test/SemaCXX/sizeless-1.cpp

Index: clang/test/SemaCXX/sizeless-1.cpp
===
--- clang/test/SemaCXX/sizeless-1.cpp
+++ clang/test/SemaCXX/sizeless-1.cpp
@@ -3,6 +3,10 @@
 // RUN: %clang_cc1 -fcxx-exceptions -fsyntax-only -verify -W -Wall -Wrange-loop-analysis -triple arm64-linux-gnu -target-feature +sve -std=c++17 %s
 // RUN: %clang_cc1 -fcxx-exceptions -fsyntax-only -verify -W -Wall -Wrange-loop-analysis -triple arm64-linux-gnu -target-feature +sve -std=gnu++17 %s
 
+#if __ARM_FEATURE_SVE_NONMEMBER_OPERATORS != 1
+#error "__ARM_FEATURE_SVE_NONMEMBER_OPERATORS should be defined"
+#endif
+
 namespace std {
 struct type_info;
 }
@@ -450,7 +454,7 @@
   local_int16 = wrapper(); // expected-error {{assigning to 'svint16_t' (aka '__SVInt16_t') from incompatible type 'wrapper'}}
 
   svint8_t &ref_int8 = local_int8;
-  ref_int8 = ref_int8; // expected-warning {{explicitly assigning value of variable of type 'svint8_t' (aka '__SVInt8_t') to itself}}
+  ref_int8 = ref_int8; // expected-warning + {{explicitly assigning value of variable of type 'svint8_t' (aka '__SVInt8_t') to itself}}
   ref_int8 = local_int8;
   local_int8 = ref_int8;
 
@@ -602,3 +606,160 @@
 #if __cplusplus >= 201103L
 svint8_t ret_bad_conv() { return explicit_conv(); } // expected-error {{no viable conversion from returned value of type 'explicit_conv' to function return type 'svint8_t'}}
 #endif
+
+svint8_t operator()(svint8_t);// expected-error {{must be a non-static member function}}
+svint8_t operator()(svint8_t, int, int, int); // expected-error {{must be a non-static member function}}
+svint8_t operator[](svint8_t, int);   // expected-error {{must be a non-static member function}}
+svint8_t operator->(svint8_t);// expected-error {{must be a non-static member function}}
+svint8_t operator~(svint8_t);
+svint8_t operator!(svint8_t);
+svint8_t operator+(svint8_t); // expected-note + {{not viable}}
+svint8_t operator-(svint8_t); // expected-note + {{not viable}}
+svint8_t operator&(svint8_t &);
+svint8_t operator+(svint8_t, svint8_t);  // expected-note + {{not viable}}
+svint8_t operator-(svint8_t, int);   // expected-note + {{not viable}}
+svint8_t operator-(int, svint8_t);   // expected-note + {{not viable}}
+svint8_t operator*(svint8_t, int);   // expected-note + {{not viable}}
+svint8_t operator*(svint8_t, svint16_t); // expected-note + {{not viable}}
+svint8_t operator/(svint8_t, svint8_t);
+svint8_t operator/(svint8_t, svint16_t); // expected-note + {{not viable}}
+svint8_t operator/(svint16_t, svint8_t); // expected-note + {{not viable}}
+svint8_t operator%(svint8_t, svint8_t);
+svint8_t operator%(svint8_t, svint16_t);
+svint8_t operator%(svint16_t, svint8_t);
+svint8_t operator

[PATCH] D76496: [clang-tidy] StringFindStartswith should ignore 3-arg find()

2020-03-30 Thread Niko Weh via Phabricator via cfe-commits
niko added a comment.

In D76496#1947127 , @njames93 wrote:

> In D76496#1947059 , @niko wrote:
>
> > In D76496#1935127 , @njames93 
> > wrote:
> >
> > > I'm not hugely familiar with the abseil library, but from what I can see 
> > > `absl::StartsWith` takes `absl::string_view` as args. Therefore surely it 
> > > makes sense to handle the 3rd arg for `str::find` by explicitly 
> > > constructing the `absl::string_view` from the pointer and size.
> >
> >
> > I am mainly worried that the 3-arg find is rarely used, and using 
> > absl::string_view requires another option to be specified for the header 
> > file. If you think that's still a good tradeoff i'll change it to construct 
> > a string_view.
>
>
> The `absl/strings/match` header includes the `absl/strings/string_view` 
> header so you wouldn't need to include another header file. Well that's as 
> long as the user hasn't done something funky with header files, but arguably 
> the shouldn't be using Fix-Its if they have done something like that.


Correct me if I'm wrong, but that seems to be in violation of IWYU? Maybe I'm 
misreading this, or is the idea that higher-lever tooling (e.g. IWYU fixer) is 
supposed to address that?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76496



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


[PATCH] D75682: [Analyzer][StreamChecker] Introduction of stream error handling.

2020-03-30 Thread Balázs Kéri via Phabricator via cfe-commits
balazske updated this revision to Diff 253587.
balazske added a comment.

Added test checker.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D75682

Files:
  clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
  clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
  clang/test/Analysis/stream-error.c

Index: clang/test/Analysis/stream-error.c
===
--- clang/test/Analysis/stream-error.c
+++ clang/test/Analysis/stream-error.c
@@ -1,8 +1,10 @@
-// RUN: %clang_analyze_cc1 -analyzer-checker=alpha.unix.Stream -analyzer-checker=debug.ExprInspection -analyzer-store region -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=alpha.unix.StreamTester -analyzer-checker=debug.ExprInspection -analyzer-store region -verify %s
 
 #include "Inputs/system-header-simulator.h"
 
 void clang_analyzer_eval(int);
+void StreamTesterChecker_make_feof_stream(FILE *);
+void StreamTesterChecker_make_ferror_stream(FILE *);
 
 void error_fopen() {
   FILE *F = fopen("file", "r");
@@ -25,16 +27,28 @@
   fclose(F);
 }
 
-void error_clearerr() {
+void stream_error_feof() {
   FILE *F = fopen("file", "r");
   if (!F)
 return;
-  int ch = fputc('a', F);
-  if (ch == EOF) {
-// FIXME: fputc not handled by checker yet, should expect TRUE
-clang_analyzer_eval(feof(F) || ferror(F)); // expected-warning {{FALSE}}
-clearerr(F);
-clang_analyzer_eval(feof(F) || ferror(F)); // expected-warning {{FALSE}}
-  }
+  StreamTesterChecker_make_feof_stream(F);
+  clang_analyzer_eval(feof(F));   // expected-warning {{TRUE}}
+  clang_analyzer_eval(ferror(F)); // expected-warning {{FALSE}}
+  clearerr(F);
+  clang_analyzer_eval(feof(F));   // expected-warning {{FALSE}}
+  clang_analyzer_eval(ferror(F)); // expected-warning {{FALSE}}
+  fclose(F);
+}
+
+void stream_error_ferror() {
+  FILE *F = fopen("file", "r");
+  if (!F)
+return;
+  StreamTesterChecker_make_ferror_stream(F);
+  clang_analyzer_eval(feof(F));   // expected-warning {{FALSE}}
+  clang_analyzer_eval(ferror(F)); // expected-warning {{TRUE}}
+  clearerr(F);
+  clang_analyzer_eval(feof(F));   // expected-warning {{FALSE}}
+  clang_analyzer_eval(ferror(F)); // expected-warning {{FALSE}}
   fclose(F);
 }
Index: clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
@@ -19,17 +19,20 @@
 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
-#include 
 
 using namespace clang;
 using namespace ento;
-using namespace std::placeholders;
+
+#define ASSERT_STREAMSTATE_OPENED  \
+  assert(SS->isOpened() && \
+ "Create of error node failed (only way to get this state)?");
 
 namespace {
 
 /// Full state information about a stream pointer.
 struct StreamState {
   /// State of a stream symbol.
+  /// FIXME: We need maybe an "escaped" state later.
   enum KindTy {
 Opened, /// Stream is opened.
 Closed, /// Closed stream (an invalid stream pointer after it was closed).
@@ -37,37 +40,44 @@
   } State;
 
   /// The error state of a stream.
+  /// Valid only if the stream is opened.
   enum ErrorKindTy {
-NoError,/// No error flag is set or stream is not open.
-EofError,   /// EOF condition (`feof` is true).
-OtherError, /// Other (non-EOF) error (`ferror` is true).
-AnyError/// EofError or OtherError, used if exact error is unknown.
+/// No error flag is set (or stream is not open).
+NoError,
+/// EOF condition (`feof` is true).
+FEof,
+/// Other generic (non-EOF) error (`ferror` is true).
+FError,
   } ErrorState = NoError;
 
   bool isOpened() const { return State == Opened; }
   bool isClosed() const { return State == Closed; }
   bool isOpenFailed() const { return State == OpenFailed; }
 
-  bool isNoError() const { return ErrorState == NoError; }
-  bool isEofError() const { return ErrorState == EofError; }
-  bool isOtherError() const { return ErrorState == OtherError; }
-  bool isAnyError() const { return ErrorState == AnyError; }
+  bool isNoError() const {
+assert(State == Opened && "Error undefined for closed stream.");
+return ErrorState == NoError;
+  }
+  bool isFEof() const {
+assert(State == Opened && "Error undefined for closed stream.");
+return ErrorState == FEof;
+  }
+  bool isFError() const {
+assert(State == Opened && "Error undefined for closed stream.");
+return ErrorState == FError;
+  }
 
   bool operator==(const StreamState &X) const {
+// In not opened state error should always NoError.
 return Sta

[PATCH] D76922: [Syntax] Remove delayed folding from tree building.

2020-03-30 Thread Dmitri Gribenko via Phabricator via cfe-commits
gribozavr2 accepted this revision.
gribozavr2 added a comment.
This revision is now accepted and ready to land.

Could you add the following tests?

  struct Point { int x, y; } point, *pointPtr;
  typedef struct Point { int x, y; } PointTy, *PointPtr;
  typedef struct { int x, y; } PointTy, *PointPtr;




Comment at: clang/lib/Tooling/Syntax/BuildTree.cpp:278
+
+const auto *TD = llvm::dyn_cast(D);
+if (TD == nullptr) {

I think this cast should not be necessary -- `D` is already a `const T*`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76922



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


[PATCH] D77058: [Clang] Add llvm.loop.unroll.disable to loops with -fno-unroll-loops.

2020-03-30 Thread Florian Hahn via Phabricator via cfe-commits
fhahn created this revision.
fhahn added reviewers: Meinersbur, hfinkel, dexonsmith, tejohnson.
Herald added a subscriber: zzheng.
Herald added a project: clang.

Currently Clang does not respect -fno-unroll-loops during LTO. During
D76916  it was suggested to respect 
-fno-unroll-loops on a TU basis.

This patch uses the existing llvm.loop.unroll.disable metadata to
disable loop unrolling explicitly for each loop in the TU if
unrolling is disabled. This should ensure that loops from TUs compiled
with -fno-unroll-loops are skipped by the unroller during LTO.

This also means that if a loop from a TU with -fno-unroll-loops
gets inlined into a TU without this option, the loop won't be
unrolled.

Due to the fact that some transforms might drop loop metadata, there
potentially are cases in which we still unroll loops from TUs with
-fno-unroll-loops. I think we should fix those issues rather than
introducing a function attribute to disable loop unrolling during LTO.
Improving the metadata handling will benefit other use cases, like
various loop pragmas, too. And it is an improvement to clang completely
ignoring -fno-unroll-loops during LTO.

If that direction looks good, we can use a similar approach to also
respect -fno-vectorize during LTO, at least for LoopVectorize.

In the future, this might also allow us to remove the UnrollLoops option
LLVM's PassManagerBuilder.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D77058

Files:
  clang/lib/CodeGen/CGLoopInfo.cpp
  clang/lib/CodeGen/CGLoopInfo.h
  clang/lib/CodeGen/CGStmt.cpp
  clang/test/CodeGenCXX/fno-unroll-loops-metadata.cpp
  clang/test/CodeGenCXX/pragma-unroll.cpp

Index: clang/test/CodeGenCXX/pragma-unroll.cpp
===
--- clang/test/CodeGenCXX/pragma-unroll.cpp
+++ clang/test/CodeGenCXX/pragma-unroll.cpp
@@ -1,5 +1,8 @@
 // RUN: %clang_cc1 -triple x86_64-apple-darwin -std=c++11 -emit-llvm -o - %s | FileCheck %s
 
+// Check that passing -fno-unroll-loops does not impact the decision made using pragmas.
+// RUN: %clang_cc1 -triple x86_64-apple-darwin -std=c++11 -emit-llvm -o - -O1 -disable-llvm-optzns -fno-unroll-loops %s | FileCheck %s
+
 // Verify while loop is recognized after unroll pragma.
 void while_test(int *List, int Length) {
   // CHECK: define {{.*}} @_Z10while_test
Index: clang/test/CodeGenCXX/fno-unroll-loops-metadata.cpp
===
--- /dev/null
+++ clang/test/CodeGenCXX/fno-unroll-loops-metadata.cpp
@@ -0,0 +1,48 @@
+// RUN: %clang_cc1 -triple x86_64-apple-darwin -std=c++11 -emit-llvm -o - %s -O0 -disable-llvm-optzns -fno-unroll-loops | FileCheck --check-prefix=NO_UNROLL_MD %s
+// RUN: %clang_cc1 -triple x86_64-apple-darwin -std=c++11 -emit-llvm -o - %s -O1 -disable-llvm-optzns -fno-unroll-loops | FileCheck --check-prefix=UNROLL_DISABLED_MD %s
+// RUN: %clang_cc1 -triple x86_64-apple-darwin -std=c++11 -emit-llvm -o - %s -O2 -disable-llvm-optzns -fno-unroll-loops | FileCheck --check-prefix=UNROLL_DISABLED_MD %s
+// RUN: %clang_cc1 -triple x86_64-apple-darwin -std=c++11 -emit-llvm -o - %s -O3 -disable-llvm-optzns -fno-unroll-loops | FileCheck --check-prefix=UNROLL_DISABLED_MD %s
+// RUN: %clang_cc1 -triple x86_64-apple-darwin -std=c++11 -emit-llvm -o - %s -O3 -disable-llvm-optzns | FileCheck --check-prefix=NO_UNROLL_MD %s
+
+// NO_UNROLL_MD-NOT: llvm.loop
+
+// Verify unroll.disable metadata is added to while loop with -fno-unroll-loops
+// and optlevel > 0.
+void while_test(int *List, int Length) {
+  // UNROLL_DISABLED_MD: define {{.*}} @_Z10while_test
+  int i = 0;
+
+  while (i < Length) {
+// UNROLL_DISABLED_MD: br label {{.*}}, !llvm.loop ![[LOOP_1:.*]]
+List[i] = i * 2;
+i++;
+  }
+}
+
+// Verify unroll.disable metadata is added to do-while loop with
+// -fno-unroll-loops and optlevel > 0.
+void do_test(int *List, int Length) {
+  // UNROLL_DISABLED_MD: define {{.*}} @_Z7do_test
+  int i = 0;
+
+  do {
+// UNROLL_DISABLED_MD: br i1 {{.*}}, label {{.*}}, label {{.*}}, !llvm.loop ![[LOOP_2:.*]]
+List[i] = i * 2;
+i++;
+  } while (i < Length);
+}
+
+// Verify unroll.disable metadata is added to while loop with -fno-unroll-loops
+// and optlevel > 0.
+void for_test(int *List, int Length) {
+  // UNROLL_DISABLED_MD: define {{.*}} @_Z8for_test
+  for (int i = 0; i < Length; i++) {
+// UNROLL_DISABLED_MD: br label {{.*}}, !llvm.loop ![[LOOP_3:.*]]
+List[i] = i * 2;
+  }
+}
+
+// UNROLL_DISABLED_MD: ![[LOOP_1]] = distinct !{![[LOOP_1]], ![[UNROLL_DISABLE:.*]]}
+// UNROLL_DISABLED_MD: ![[UNROLL_DISABLE]] = !{!"llvm.loop.unroll.disable"}
+// UNROLL_DISABLED_MD: ![[LOOP_2]] = distinct !{![[LOOP_2:.*]], ![[UNROLL_DISABLE:.*]]}
+// UNROLL_DISABLED_MD: ![[LOOP_3]] = distinct !{![[LOOP_3]], ![[UNROLL_DISABLE:.*]]}
Index: clang/lib/CodeGen/CGStmt.cpp
===
--- clang/lib/CodeGen/CGStmt.cpp
+++

[PATCH] D77012: [analyzer] Fix StdLibraryFunctionsChecker NotNull Constraint Check

2020-03-30 Thread Kristóf Umann via Phabricator via cfe-commits
Szelethus added a comment.



In D77012#1948550 , @NoQ wrote:

> @Szelethus can we make this checker depend on undefined value checker 
> (probably CallAndMessage) so that uninitialized arguments were handled first?


I'll drop some pointers to previous discussions: D67336#1928925 
, D69662#1891124 
. I took a look, the evaluation order 
indeed depends on the order of registration, and the order of registration can 
be controlled with checker dependencies.

> In fact, can we make a silent assumption that everything depends on `core`? 
> If so we could eliminate all checks for undefined values in PreStmt and 
> PreCall.

I wouldn't be comfortable doing that before we can separate the modeling 
portions from the diagnostics.

[cfe-dev] [analyzer][RFC] Our stance on checker dependencies and disabling core 
checkers: http://lists.llvm.org/pipermail/cfe-dev/2019-August/063070.html


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D77012



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


[PATCH] D77012: [analyzer] Fix StdLibraryFunctionsChecker NotNull Constraint Check

2020-03-30 Thread Kristóf Umann via Phabricator via cfe-commits
Szelethus accepted this revision.
Szelethus added a comment.

Oh, yea, LGTM! Thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D77012



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


[PATCH] D68165: [analyzer][MallocChecker][NFC] Split checkPostCall up, deploy CallDescriptionMap

2020-03-30 Thread Kristóf Umann via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Szelethus marked 5 inline comments as done.
Closed by commit rG703a1b8caf09: [analyzer][MallocChecker][NFC] Split 
checkPostCall up, deploy CallDescriptionMap (authored by ldionne, committed by 
Szelethus).
Herald added a subscriber: ASDenysPetrov.

Changed prior to commit:
  https://reviews.llvm.org/D68165?vs=247512&id=253593#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68165

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

Index: clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
@@ -62,16 +62,19 @@
 #include "clang/StaticAnalyzer/Core/PathSensitive/DynamicSize.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/Support/ErrorHandling.h"
 #include 
+#include 
 #include 
 
 using namespace clang;
 using namespace ento;
+using namespace std::placeholders;
 
 //===--===//
 // The types of allocation we're modeling. This is used to check whether a
@@ -93,8 +96,6 @@
   AF_InnerBuffer
 };
 
-struct MemFunctionInfoTy;
-
 } // end of anonymous namespace
 
 /// Print names of allocators and deallocators.
@@ -263,47 +264,6 @@
 
 REGISTER_MAP_WITH_PROGRAMSTATE(ReallocPairs, SymbolRef, ReallocPair)
 
-//===--===//
-// Kinds of memory operations, information about resource managing functions.
-//===--===//
-
-namespace {
-
-struct MemFunctionInfoTy {
-  /// The value of the MallocChecker:Optimistic is stored in this variable.
-  ///
-  /// In pessimistic mode, the checker assumes that it does not know which
-  /// functions might free the memory.
-  /// In optimistic mode, the checker assumes that all user-defined functions
-  /// which might free a pointer are annotated.
-  DefaultBool ShouldIncludeOwnershipAnnotatedFunctions;
-
-  CallDescription CD_alloca{{"alloca"}, 1}, CD_win_alloca{{"_alloca"}, 1},
-  CD_malloc{{"malloc"}, 1}, CD_BSD_malloc{{"malloc"}, 3},
-  CD_free{{"free"}, 1}, CD_realloc{{"realloc"}, 2},
-  CD_calloc{{"calloc"}, 2}, CD_valloc{{"valloc"}, 1},
-  CD_reallocf{{"reallocf"}, 2}, CD_strndup{{"strndup"}, 2},
-  CD_strdup{{"strdup"}, 1}, CD_win_strdup{{"_strdup"}, 1},
-  CD_kmalloc{{"kmalloc"}, 2}, CD_if_nameindex{{"if_nameindex"}, 1},
-  CD_if_freenameindex{{"if_freenameindex"}, 1}, CD_wcsdup{{"wcsdup"}, 1},
-  CD_win_wcsdup{{"_wcsdup"}, 1}, CD_kfree{{"kfree"}, 1},
-  CD_g_malloc{{"g_malloc"}, 1}, CD_g_malloc0{{"g_malloc0"}, 1},
-  CD_g_realloc{{"g_realloc"}, 2}, CD_g_try_malloc{{"g_try_malloc"}, 1},
-  CD_g_try_malloc0{{"g_try_malloc0"}, 1},
-  CD_g_try_realloc{{"g_try_realloc"}, 2}, CD_g_free{{"g_free"}, 1},
-  CD_g_memdup{{"g_memdup"}, 2}, CD_g_malloc_n{{"g_malloc_n"}, 2},
-  CD_g_malloc0_n{{"g_malloc0_n"}, 2}, CD_g_realloc_n{{"g_realloc_n"}, 3},
-  CD_g_try_malloc_n{{"g_try_malloc_n"}, 2},
-  CD_g_try_malloc0_n{{"g_try_malloc0_n"}, 2},
-  CD_g_try_realloc_n{{"g_try_realloc_n"}, 3};
-
-  bool isMemFunction(const CallEvent &Call) const;
-  bool isCMemFunction(const CallEvent &Call) const;
-  bool isCMemFreeFunction(const CallEvent &Call) const;
-  bool isCMemAllocFunction(const CallEvent &Call) const;
-};
-} // end of anonymous namespace
-
 /// Tells if the callee is one of the builtin new/delete operators, including
 /// placement operators and other standard overloads.
 static bool isStandardNewDelete(const FunctionDecl *FD);
@@ -327,7 +287,11 @@
  check::PreStmt, check::PostStmt,
  check::PostObjCMessage, check::Location, eval::Assume> {
 public:
-  MemFunctionInfoTy MemFunctionInfo;
+  /// In pessimistic mode, the checker assumes that it does not know which
+  /// functions might free the memory.
+  /// In optimistic mode, the checker assumes that all user-defined functions
+  /// which might free a pointer are annotated.
+  DefaultBool ShouldIncludeOwnershipAnnotatedFunctions;
 
   /// Many checkers are essentially built into this one, so enabling them will
   /// make MallocChecker perform additional modeling and reporting.
@@ -387,6 +351,81 @@
   mutable std::unique_ptr BT_OffsetFree[CK_NumCheckKinds];
   mutable std::unique_ptr BT_UseZerroAllocated[CK_NumCheckKinds];
 
+#define CHECK_FN(

[clang] 7899a11 - Revert "[Darwin] Respect -fno-unroll-loops during LTO."

2020-03-30 Thread Florian Hahn via cfe-commits

Author: Florian Hahn
Date: 2020-03-30T15:20:30+01:00
New Revision: 7899a111ea1160e2ae0aae42de37b14a0b75d71b

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

LOG: Revert "[Darwin] Respect -fno-unroll-loops during LTO."

As per post-commit comment at https://reviews.llvm.org/D76916, this
should better be done at the TU level.

This reverts commit 9ce198d6ed371399e9bd9ba8b48fbab0f4e60240.

Added: 


Modified: 
clang/lib/Driver/ToolChains/Darwin.cpp
llvm/lib/LTO/LTOCodeGenerator.cpp

Removed: 
clang/test/Driver/darwin-ld-lto-fno-unroll-loops.c
llvm/test/tools/llvm-lto/fno-unroll-loops-option.ll



diff  --git a/clang/lib/Driver/ToolChains/Darwin.cpp 
b/clang/lib/Driver/ToolChains/Darwin.cpp
index 951c71bff00e..451d0d206d07 100644
--- a/clang/lib/Driver/ToolChains/Darwin.cpp
+++ b/clang/lib/Driver/ToolChains/Darwin.cpp
@@ -543,12 +543,6 @@ void darwin::Linker::ConstructJob(Compilation &C, const 
JobAction &JA,
 CmdArgs.push_back(Args.MakeArgString("-lto-stats-file=" + 
StatsFile.str()));
   }
 
-  // Forward -fno-unroll-loops to the linker in LTO.
-  if (Args.hasArg(options::OPT_fno_unroll_loops)) {
-CmdArgs.push_back("-mllvm");
-CmdArgs.push_back(Args.MakeArgString("-lto-no-unroll-loops"));
-  }
-
   // It seems that the 'e' option is completely ignored for dynamic executables
   // (the default), and with static executables, the last one wins, as 
expected.
   Args.AddAllArgs(CmdArgs, {options::OPT_d_Flag, options::OPT_s, 
options::OPT_t,

diff  --git a/clang/test/Driver/darwin-ld-lto-fno-unroll-loops.c 
b/clang/test/Driver/darwin-ld-lto-fno-unroll-loops.c
deleted file mode 100644
index b248898a89f5..
--- a/clang/test/Driver/darwin-ld-lto-fno-unroll-loops.c
+++ /dev/null
@@ -1,17 +0,0 @@
-// REQUIRES: system-darwin
-
-// RUN: mkdir -p %t/bin
-// RUN: mkdir -p %t/lib
-// RUN: touch %t/lib/libLTO.dylib
-
-// Check that ld gets "-lto-no-unroll-loops" when -fno-unroll-loops is passed.
-//
-// RUN: %clang -target x86_64-apple-darwin10 %s -fno-unroll-loops -flto=full 
-### 2>&1 | \
-// RUN:   FileCheck --check-prefix=NOUNROLL %s
-
-// NOUNROLL:  "-mllvm" "-lto-no-unroll-loops"
-//
-// RUN: %clang -target x86_64-apple-darwin10 %s -flto=full -### 2>&1 | \
-// RUN:   FileCheck --check-prefix=UNROLL %s
-
-// UNROLL-NOT:  -lto-no-unroll-loops

diff  --git a/llvm/lib/LTO/LTOCodeGenerator.cpp 
b/llvm/lib/LTO/LTOCodeGenerator.cpp
index d2ae956b7823..a8a7877f66da 100644
--- a/llvm/lib/LTO/LTOCodeGenerator.cpp
+++ b/llvm/lib/LTO/LTOCodeGenerator.cpp
@@ -109,10 +109,6 @@ cl::opt LTOStatsFile(
 cl::Hidden);
 }
 
-cl::opt LTONoUnrollLoops("lto-no-unroll-loops",
-   cl::desc("Disable unrolling during LTO."),
-   cl::Hidden, cl::init(false));
-
 LTOCodeGenerator::LTOCodeGenerator(LLVMContext &Context)
 : Context(Context), MergedModule(new Module("ld-temp.o", Context)),
   TheLinker(new Linker(*MergedModule)) {
@@ -574,7 +570,6 @@ bool LTOCodeGenerator::optimize(bool DisableVerify, bool 
DisableInline,
 
   Triple TargetTriple(TargetMach->getTargetTriple());
   PassManagerBuilder PMB;
-  PMB.DisableUnrollLoops = LTONoUnrollLoops;
   PMB.DisableGVNLoadPRE = DisableGVNLoadPRE;
   PMB.LoopVectorize = !DisableVectorization;
   PMB.SLPVectorize = !DisableVectorization;

diff  --git a/llvm/test/tools/llvm-lto/fno-unroll-loops-option.ll 
b/llvm/test/tools/llvm-lto/fno-unroll-loops-option.ll
deleted file mode 100644
index 3ac4c285ffe7..
--- a/llvm/test/tools/llvm-lto/fno-unroll-loops-option.ll
+++ /dev/null
@@ -1,34 +0,0 @@
-; REQUIRES: asserts
-
-; RUN: llvm-as < %s > %t1.bc
-
-; Build with unrolling disabled (-lto-no-unroll-loops).
-; RUN: llvm-lto %t1.bc -o %t.nounroll.o -lto-no-unroll-loops 
--exported-symbol=foo -save-merged-module
-; RUN: llvm-dis  -o - %t.nounroll.o.merged.bc | FileCheck 
--check-prefix=NOUNROLL %s
-
-; NOUNROLL: br label %loop
-; NOUNROLL: br i1 %ec, label %exit, label %loop
-
-; Build with unrolling enabled (by not passing -lto-no-unroll-loops). All
-; branches should be gone.
-; RUN: llvm-lto %t1.bc -o %t.nounroll.o --exported-symbol=foo 
-save-merged-module
-; RUN: llvm-dis  -o - %t.nounroll.o.merged.bc | FileCheck 
--check-prefix=UNROLL %s
-
-; UNROLL-NOT: br
-
-define void @foo(i32* %ptr) {
-
-entry:
-  br label %loop
-
-loop:
-  %iv = phi i32 [ 0, %entry], [ %iv.next, %loop ]
-  %iv.ptr = getelementptr i32, i32* %ptr, i32 %iv
-  store i32 %iv, i32* %iv.ptr
-  %iv.next = add i32 %iv, 1
-  %ec = icmp eq i32 %iv.next, 10
-  br i1 %ec, label %exit, label %loop
-
-exit:
-  ret void
-}



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


[PATCH] D76790: [analyzer] StdLibraryFunctionsChecker: fix bug with arg constraints

2020-03-30 Thread Gabor Marton via Phabricator via cfe-commits
martong updated this revision to Diff 253595.
martong added a comment.

- Test multiple constraints on the same arg


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76790

Files:
  clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
  clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
  clang/test/Analysis/std-c-library-functions-arg-constraints.c

Index: clang/test/Analysis/std-c-library-functions-arg-constraints.c
===
--- clang/test/Analysis/std-c-library-functions-arg-constraints.c
+++ clang/test/Analysis/std-c-library-functions-arg-constraints.c
@@ -3,6 +3,7 @@
 // RUN:   -analyzer-checker=core \
 // RUN:   -analyzer-checker=apiModeling.StdCLibraryFunctions \
 // RUN:   -analyzer-checker=apiModeling.StdCLibraryFunctionArgs \
+// RUN:   -analyzer-checker=debug.StdCLibraryFunctionsTester \
 // RUN:   -analyzer-checker=debug.ExprInspection \
 // RUN:   -triple x86_64-unknown-linux-gnu \
 // RUN:   -verify=report
@@ -12,6 +13,7 @@
 // RUN:   -analyzer-checker=core \
 // RUN:   -analyzer-checker=apiModeling.StdCLibraryFunctions \
 // RUN:   -analyzer-checker=apiModeling.StdCLibraryFunctionArgs \
+// RUN:   -analyzer-checker=debug.StdCLibraryFunctionsTester \
 // RUN:   -analyzer-checker=debug.ExprInspection \
 // RUN:   -triple x86_64-unknown-linux-gnu \
 // RUN:   -analyzer-output=text \
@@ -85,3 +87,30 @@
 // bugpath-warning{{Function argument constraint is not satisfied}} \
 // bugpath-note{{Function argument constraint is not satisfied}}
 }
+
+int __two_constrained_args(int, int);
+void test_constraints_on_multiple_args(int x, int y) {
+  // State split should not happen here. I.e. x == 1 should not be evaluated
+  // FALSE.
+  __two_constrained_args(x, y);
+  clang_analyzer_eval(x == 1); // \
+  // report-warning{{TRUE}} \
+  // bugpath-warning{{TRUE}} \
+  // bugpath-note{{TRUE}}
+  clang_analyzer_eval(y == 1); // \
+  // report-warning{{TRUE}} \
+  // bugpath-warning{{TRUE}} \
+  // bugpath-note{{TRUE}}
+}
+
+int __arg_constrained_twice(int);
+void test_multiple_constraints_on_same_arg(int x) {
+  __arg_constrained_twice(x);
+  // Check that both constraints are applied and only one branch is there.
+  clang_analyzer_eval(x < 1 || x > 2); // \
+  // report-warning{{TRUE}} \
+  // bugpath-warning{{TRUE}} \
+  // bugpath-note{{TRUE}} \
+  // bugpath-note{{Assuming 'x' is < 1}} \
+  // bugpath-note{{Left side of '||' is true}}
+}
Index: clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
@@ -303,7 +303,11 @@
   void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
   bool evalCall(const CallEvent &Call, CheckerContext &C) const;
 
-  enum CheckKind { CK_StdCLibraryFunctionArgsChecker, CK_NumCheckKinds };
+  enum CheckKind {
+CK_StdCLibraryFunctionArgsChecker,
+CK_StdCLibraryFunctionsTesterChecker,
+CK_NumCheckKinds
+  };
   DefaultBool ChecksEnabled[CK_NumCheckKinds];
   CheckerNameRef CheckNames[CK_NumCheckKinds];
 
@@ -452,23 +456,26 @@
   const Summary &Summary = *FoundSummary;
   ProgramStateRef State = C.getState();
 
+  ProgramStateRef NewState = State;
   for (const ValueConstraintPtr& VC : Summary.ArgConstraints) {
-ProgramStateRef SuccessSt = VC->apply(State, Call, Summary);
-ProgramStateRef FailureSt = VC->negate()->apply(State, Call, Summary);
+ProgramStateRef SuccessSt = VC->apply(NewState, Call, Summary);
+ProgramStateRef FailureSt = VC->negate()->apply(NewState, Call, Summary);
 // The argument constraint is not satisfied.
 if (FailureSt && !SuccessSt) {
-  if (ExplodedNode *N = C.generateErrorNode(State))
+  if (ExplodedNode *N = C.generateErrorNode(NewState))
 reportBug(Call, N, C);
   break;
 } else {
-  // Apply the constraint even if we cannot reason about the argument. This
-  // means both SuccessSt and FailureSt can be true. If we weren't applying
-  // the constraint that would mean that symbolic execution continues on a
-  // code whose behaviour is undefined.
+  // We will apply the constraint even if we cannot reason about the
+  // argument. This means both SuccessSt and FailureSt can be true. If we
+  // weren't applying the constraint that would mean that symbolic
+  // execution continues on a code whose behaviour is undefined.
   assert(SuccessSt);
-  C.addTransition(SuccessSt);
+  NewState = SuccessSt;
 }
   }
+  if (NewState && NewState != State)
+C.addTransition(NewState);
 }
 
 void StdLibraryFunctionsChecker::checkPostCall(const CallEvent &Call,
@@ -933,6 +940,32 @@
   {"getdelim", Summaries{Getline(IntTy, IntMax), Getline(LongTy, LongMax),
  

[PATCH] D76916: [Darwin] Respect -fno-unroll-loops during LTO.

2020-03-30 Thread Florian Hahn via Phabricator via cfe-commits
fhahn marked an inline comment as done.
fhahn added a comment.

Thanks for taking a look @dexonsmith!

In D76916#1947324 , @dexonsmith wrote:

> @fhahn, please revert, this isn't how we usually pass options in LTO.


Reverted in 7899a111ea1160e2ae0aae42de37b14a0b75d71b 
.

It looks like there are similar options exposed by libLTO (-disable-inlining, 
-disable-gvn-loadpre, -disable-lto-vectorization). However those are not hooked 
up in the driver, presumably expecting the user to pass them to the linker 
through clang.

It seems like currently clang is not too consistent when it comes to handling 
arguments for LTO. Is there some documentation describing how various options 
should interact with LTO?

> If this is something we expect developers to use, it should be specifiable on 
> a per-TU basis.  The way we do this is by specifying it during compilation, 
> attaching string-based function attributes, and checking that attribute at 
> the beginning of the "unroll loop" pass to see whether to skip it for that 
> function.

Agreed, I think we should respect -fno-unroll-loops on a TU basis. I've put up 
D77058  to use the existing 
llvm.loop.unroll.disable metadata.

Is there any documentation on how TU level flags should interact with inlining 
across TU without those options? D77058  means 
that the loops in TUs compiled with -fno-unroll-loops won't be unrolled if they 
are inlined in functions in TUs without -fno-unroll-loops and loops from 
functions without -fno-unrolled-loops inlined into functions in TUs with 
-fno-unroll-loops will get unrolled. That is, -fno-unroll-loops will get 
applied exactly to the loops in the original TU, regardless where they are 
inlined. It is not applied to functions that get inlined from TUs without 
-fno-unroll-loops.




Comment at: clang/lib/Driver/ToolChains/Darwin.cpp:546-551
+  // Forward -fno-unroll-loops to the linker in LTO.
+  if (Args.hasArg(options::OPT_fno_unroll_loops)) {
+CmdArgs.push_back("-mllvm");
+CmdArgs.push_back(Args.MakeArgString("-lto-no-unroll-loops"));
+  }
+

dexonsmith wrote:
> I don't understand why we need driver support for this... is this something 
> we expect users to do?
Clang provides a -fno-unroll-loops option and allows users to specify it 
together with LTO. I think it is desirable for users to respect the option 
during LTO. For example, projects might have to disable unrolling, because 
their code is only correct assuming unrolling does not happen.

I think for the user it would be most convenient to disable unrolling during 
the clang linker invocation with LTO, together with an option to disable it per 
TU. I think that is similarly to how the mcpu option is handled during LTO with 
the gold plugin for example.

 Only providing a way to disable it per TU should also be fine as well I think, 
but then Clang should at least warn if -fno-unroll-loops is passed for linking 
with LTO (and ignored).

Does that seem reasonable?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76916



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


[PATCH] D76360: [PPC][AIX] Emit correct Vaarg for 32BIT-AIX in clang

2020-03-30 Thread Jason Liu via Phabricator via cfe-commits
jasonliu added inline comments.



Comment at: clang/lib/CodeGen/TargetInfo.cpp:10019
+  return SetCGInfo(
+  new PPCAIX32TargetCodeGenInfo(Types, CodeGenOpts.FloatABI == 
"soft"));
 return SetCGInfo(

Does AIX have soft Float? If not, do we want to always pass in 'false'? 



Comment at: clang/test/CodeGen/aix-vararg.c:4
+// RUN: %clang_cc1 -triple powerpc-ibm-aix-xcoff -emit-llvm -o - %s | 
FileCheck %s --check-prefix=32BIT
+#include 
+

Any reason we don't use __builtin_va... any more?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76360



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


[PATCH] D76211: OpenMP Metadirective with user defined condition

2020-03-30 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert added inline comments.



Comment at: clang/lib/Sema/SemaOpenMP.cpp:5801
+Expr *expr = whenClause->getExpr();
+Stmt *stmt = NULL;
+

Style: start names with upper case letter.



Comment at: clang/lib/Sema/SemaOpenMP.cpp:5817
+llvm::errs() << "Misplaced default clause! Only one default clause is";
+llvm::errs() << " allowed in metadirective in the end\n";
+return StmtError();

You need to use `Diag` here. See other uses in this file.



Comment at: clang/lib/Sema/SemaOpenMP.cpp:5834
+ stmt, SourceLocation(), ElseStmt);
+  }
+

Doesn't this produce:
```
if (when1) case1;
if (when2) case2;
...
```
while we need:
```
if (when1) case1;
else if (when2) case2;
...
```




Comment at: clang/lib/Sema/SemaOpenMP.cpp:11987
+}
+break;
   }

I think a simple `if (DKind == ...)` makes more sense here.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76211



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


[PATCH] D68165: [analyzer][MallocChecker][NFC] Split checkPostCall up, deploy CallDescriptionMap

2020-03-30 Thread Louis Dionne via Phabricator via cfe-commits
ldionne added a comment.

> Closed by commit rG703a1b8caf09 
> : 
> [analyzer][MallocChecker][NFC] Split checkPostCall up, deploy 
> CallDescriptionMap (authored by ldionne, committed by Szelethus). · Explain 
> Why

This is really strange -- it looks like 703a1b8caf09 
 was 
attributed to me in git, but I have nothing to do with this change. How did you 
commit the patch? Is that some Phabricator bug?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68165



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


[PATCH] D77061: [analyzer] Add core.CallAndMessage to StdCLibraryFunctionArgsChecker's dependency

2020-03-30 Thread Gabor Marton via Phabricator via cfe-commits
martong created this revision.
martong added reviewers: Szelethus, NoQ.
Herald added subscribers: cfe-commits, ASDenysPetrov, steakhal, Charusso, 
gamesh411, dkrupp, donat.nagy, mikhail.ramalho, a.sidorin, rnkovacs, szepet, 
baloghadamsoftware, xazax.hun, whisperity.
Herald added a project: clang.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D77061

Files:
  clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
  clang/test/Analysis/analyzer-enabled-checkers.c


Index: clang/test/Analysis/analyzer-enabled-checkers.c
===
--- clang/test/Analysis/analyzer-enabled-checkers.c
+++ clang/test/Analysis/analyzer-enabled-checkers.c
@@ -7,11 +7,11 @@
 // CHECK:  OVERVIEW: Clang Static Analyzer Enabled Checkers List
 // CHECK-EMPTY:
 // CHECK-NEXT: apiModeling.StdCLibraryFunctions
+// CHECK-NEXT: core.CallAndMessage
 // CHECK-NEXT: apiModeling.StdCLibraryFunctionArgs
 // CHECK-NEXT: apiModeling.TrustNonnull
 // CHECK-NEXT: apiModeling.llvm.CastValue
 // CHECK-NEXT: apiModeling.llvm.ReturnValue
-// CHECK-NEXT: core.CallAndMessage
 // CHECK-NEXT: core.DivideZero
 // CHECK-NEXT: core.DynamicTypePropagation
 // CHECK-NEXT: core.NonNullParamChecker
Index: clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
===
--- clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
+++ clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
@@ -299,7 +299,7 @@
   HelpText<"Check constraints of arguments of C standard library functions, "
"such as whether the parameter of isalpha is in the range [0, 255] "
"or is EOF.">,
-  Dependencies<[StdCLibraryFunctionsChecker]>,
+  Dependencies<[StdCLibraryFunctionsChecker, CallAndMessageChecker]>,
   Documentation;
 
 def TrustNonnullChecker : Checker<"TrustNonnull">,


Index: clang/test/Analysis/analyzer-enabled-checkers.c
===
--- clang/test/Analysis/analyzer-enabled-checkers.c
+++ clang/test/Analysis/analyzer-enabled-checkers.c
@@ -7,11 +7,11 @@
 // CHECK:  OVERVIEW: Clang Static Analyzer Enabled Checkers List
 // CHECK-EMPTY:
 // CHECK-NEXT: apiModeling.StdCLibraryFunctions
+// CHECK-NEXT: core.CallAndMessage
 // CHECK-NEXT: apiModeling.StdCLibraryFunctionArgs
 // CHECK-NEXT: apiModeling.TrustNonnull
 // CHECK-NEXT: apiModeling.llvm.CastValue
 // CHECK-NEXT: apiModeling.llvm.ReturnValue
-// CHECK-NEXT: core.CallAndMessage
 // CHECK-NEXT: core.DivideZero
 // CHECK-NEXT: core.DynamicTypePropagation
 // CHECK-NEXT: core.NonNullParamChecker
Index: clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
===
--- clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
+++ clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
@@ -299,7 +299,7 @@
   HelpText<"Check constraints of arguments of C standard library functions, "
"such as whether the parameter of isalpha is in the range [0, 255] "
"or is EOF.">,
-  Dependencies<[StdCLibraryFunctionsChecker]>,
+  Dependencies<[StdCLibraryFunctionsChecker, CallAndMessageChecker]>,
   Documentation;
 
 def TrustNonnullChecker : Checker<"TrustNonnull">,
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D77061: [analyzer] Add core.CallAndMessage to StdCLibraryFunctionArgsChecker's dependency

2020-03-30 Thread Kristóf Umann via Phabricator via cfe-commits
Szelethus accepted this revision.
Szelethus added a comment.
This revision is now accepted and ready to land.

LGTM! It would be great if we could separate the modeling portions of the 
`CallAndMessage` checker out, but hey, there are only so many hours in each day 
:^)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D77061



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


[PATCH] D77058: [Clang] Add llvm.loop.unroll.disable to loops with -fno-unroll-loops.

2020-03-30 Thread Teresa Johnson via Phabricator via cfe-commits
tejohnson added a comment.

I think this is a good approach, rather than a per-function attribute, since as 
mentioned this will be preserved through inlining.
@dexonsmith, does that seem reasonable to you? I missed the original patch and 
agree with you that we don't want to fix this in LTO by passing the option 
through to LTO.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D77058



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


[PATCH] D77063: [WIP][clangd] Dont block for preamble builds

2020-03-30 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet created this revision.
Herald added subscribers: cfe-commits, usaxena95, jfb, arphaman, jkorous, 
MaskRay, javed.absar, ilya-biryukov.
Herald added a project: clang.
kadircet added a parent revision: D76725: [clangd] Build ASTs only with fresh 
preambles or after building a new preamble.
kadircet added a comment.

This requires patched-up ASTs and getting rid of consistent preamble needs 
first.


Build preambles fully asynchronously.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D77063

Files:
  clang-tools-extra/clangd/TUScheduler.cpp
  clang-tools-extra/clangd/unittests/ClangdTests.cpp
  clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
  clang-tools-extra/clangd/unittests/XRefsTests.cpp

Index: clang-tools-extra/clangd/unittests/XRefsTests.cpp
===
--- clang-tools-extra/clangd/unittests/XRefsTests.cpp
+++ clang-tools-extra/clangd/unittests/XRefsTests.cpp
@@ -968,6 +968,7 @@
   // Only preamble is built, and no AST is built in this request.
   Server.addDocument(FooCpp, FooWithoutHeader.code(), "null",
  WantDiagnostics::No);
+  ASSERT_TRUE(Server.blockUntilIdleForTest());
   // We build AST here, and it should use the latest preamble rather than the
   // stale one.
   EXPECT_THAT(
@@ -979,6 +980,7 @@
   // Both preamble and AST are built in this request.
   Server.addDocument(FooCpp, FooWithoutHeader.code(), "null",
  WantDiagnostics::Yes);
+  ASSERT_TRUE(Server.blockUntilIdleForTest());
   // Use the AST being built in above request.
   EXPECT_THAT(
   cantFail(runLocateSymbolAt(Server, FooCpp, FooWithoutHeader.point())),
Index: clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
===
--- clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
+++ clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
@@ -322,9 +322,11 @@
 // Helper to schedule a named update and return a function to cancel it.
 auto Update = [&](std::string ID) -> Canceler {
   auto T = cancelableTask();
+  auto Inp = getInputs(Path, "//" + ID);
+  Inp.Version = ID;
   WithContext C(std::move(T.first));
   updateWithDiags(
-  S, Path, "//" + ID, WantDiagnostics::Yes,
+  S, Path, std::move(Inp), WantDiagnostics::Yes,
   [&, ID](std::vector Diags) { DiagsSeen.push_back(ID); });
   return std::move(T.second);
 };
@@ -497,7 +499,7 @@
   WithContextValue WithNonce(NonceKey, ++Nonce);
   Inputs.Version = std::to_string(Nonce);
   updateWithDiags(
-  S, File, Inputs, WantDiagnostics::Auto,
+  S, File, Inputs, WantDiagnostics::Yes,
   [File, Nonce, &Mut, &TotalUpdates](std::vector) {
 EXPECT_THAT(Context::current().get(NonceKey), Pointee(Nonce));
 
@@ -734,11 +736,15 @@
 )cpp";
 
   ParseInputs Inputs = getInputs(Source, SourceContents);
+  Inputs.Version = "MissingHeader";
+  std::atomic UpdateCount(0);
 
   // Update the source contents, which should trigger an initial build with
   // the header file missing.
   updateWithDiags(
-  S, Source, Inputs, WantDiagnostics::Yes, [](std::vector Diags) {
+  S, Source, Inputs, WantDiagnostics::Yes,
+  [&UpdateCount](std::vector Diags) {
+++UpdateCount;
 EXPECT_THAT(Diags,
 ElementsAre(Field(&Diag::Message, "'foo.h' file not found"),
 Field(&Diag::Message,
@@ -750,6 +756,7 @@
   Files[Header] = "int a;";
   Timestamps[Header] = time_t(1);
   Inputs = getInputs(Source, SourceContents);
+  Inputs.Version = "WithHeader";
 
   // The addition of the missing header file shouldn't trigger a rebuild since
   // we don't track missing files.
@@ -761,11 +768,15 @@
   // Forcing the reload should should cause a rebuild which no longer has any
   // errors.
   Inputs.ForceRebuild = true;
-  updateWithDiags(
-  S, Source, Inputs, WantDiagnostics::Yes,
-  [](std::vector Diags) { EXPECT_THAT(Diags, IsEmpty()); });
+  Inputs.Version = "ForceRebuild";
+  updateWithDiags(S, Source, Inputs, WantDiagnostics::Yes,
+  [&UpdateCount](std::vector Diags) {
+++UpdateCount;
+EXPECT_THAT(Diags, IsEmpty());
+  });
 
   ASSERT_TRUE(S.blockUntilIdle(timeoutSeconds(10)));
+  EXPECT_EQ(UpdateCount, 2);
 }
 TEST_F(TUSchedulerTests, NoChangeDiags) {
   TUScheduler S(CDB, optsForTest(), captureDiags());
@@ -849,27 +860,20 @@
 
   ASSERT_TRUE(Server.blockUntilIdleForTest());
 
-  EXPECT_THAT(CaptureTUStatus.allStatus(),
-  ElementsAre(
-  // Everything starts with ASTWorker starting to execute an
-  // update
-  TUState(PreambleAction::Idle, ASTAction::RunningAction),
-  // We build the preamble
-  TUState(PreambleAction::Building, ASTAction::

[PATCH] D77013: [AMDGPU] Add options -mamdgpu-ieee -mno-amdgpu-ieee

2020-03-30 Thread Matt Arsenault via Phabricator via cfe-commits
arsenm added inline comments.



Comment at: clang/include/clang/Basic/CodeGenOptions.def:399
 
+/// Whether to emit IEEE754-2008 NaN compliant instructions if available 
(AMDGPU Only)
+CODEGENOPT(EmitIEEENaNCompliantInsts, 1, 1)

Description is misleading. Better description would be the first line from the 
manual, 
"Floating point opcodes that support exception flag gathering quiet and 
propagate sig- naling NaN inputs per IEEE 754-2008"



Comment at: clang/include/clang/Driver/Options.td:2406
+def mamdgpu_ieee : Flag<["-"], "mamdgpu-ieee">, Flags<[CC1Option]>,
+  Group, HelpText<"Enable IEEE754-2008 NaN compliance in supported 
AMDGPU instructions">;
+def mno_amdgpu_ieee : Flag<["-"], "mno-amdgpu-ieee">, Flags<[CC1Option]>,

Ditto



Comment at: clang/lib/Frontend/CompilerInvocation.cpp:1434
+
+  Opts.EmitIEEENaNCompliantInsts =
+  Args.hasFlag(options::OPT_mamdgpu_ieee, options::OPT_mno_amdgpu_ieee,

Add a comment explaining why to turn it off? Also should note this is only 
really concerns signaling nans



Comment at: clang/test/CodeGenOpenCL/amdgpu-ieee.cl:20
+}
+
+// ON-NOT: attributes [[ATTRS]] = {{.*}} "amdgpu-ieee"

Should also test a non-kernel function


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

https://reviews.llvm.org/D77013



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


[PATCH] D77013: [AMDGPU] Add options -mamdgpu-ieee -mno-amdgpu-ieee

2020-03-30 Thread Matt Arsenault via Phabricator via cfe-commits
arsenm added inline comments.



Comment at: clang/test/CodeGenOpenCL/amdgpu-ieee.cl:20
+}
+
+// ON-NOT: attributes [[ATTRS]] = {{.*}} "amdgpu-ieee"

arsenm wrote:
> Should also test a non-kernel function
I think we should also have some ISA check run lines that show the final result 
for minnum/maxnum lowering, as well as if output modifiers are used


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

https://reviews.llvm.org/D77013



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


[PATCH] D77063: [WIP][clangd] Dont block for preamble builds

2020-03-30 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added a comment.

This requires patched-up ASTs and getting rid of consistent preamble needs 
first.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D77063



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


[PATCH] D77064: [clang-format] Correct line breaks in C# generic type constraints

2020-03-30 Thread Jonathan B Coe via Phabricator via cfe-commits
jbcoe created this revision.
jbcoe added a reviewer: krasimir.
jbcoe added a project: clang-format.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D77064

Files:
  clang/lib/Format/TokenAnnotator.cpp
  clang/lib/Format/UnwrappedLineParser.cpp
  clang/unittests/Format/FormatTestCSharp.cpp


Index: clang/unittests/Format/FormatTestCSharp.cpp
===
--- clang/unittests/Format/FormatTestCSharp.cpp
+++ clang/unittests/Format/FormatTestCSharp.cpp
@@ -702,12 +702,13 @@
 })",
Style);
 
+  Style.ColumnLimit = 50; // Force lines to be wrapped.
   verifyFormat(R"(//
-class ItemFactory
-where T : new(),
-  IAnInterface,
-  IAnotherInterface,
-  IAnotherInterfaceStill {})",
+class ItemFactory
+where T : new(), 
+  IAnInterface, 
+  IAnotherInterface, 
+  IAnotherInterfaceStill {})",
Style);
 
   // In other languages `where` can be used as a normal identifier.
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -2339,7 +2339,13 @@
   break;
   }
   if (FormatTok->Tok.is(tok::semi))
+return;  
+  if (Style.isCSharp() && FormatTok->is(Keywords.kw_where)) {
+addUnwrappedLine();
+nextToken();
+parseCSharpGenericTypeConstraint();
 return;
+  }
   nextToken();
 }
   }
@@ -2354,6 +2360,11 @@
  /*MunchSemi=*/false);
 }
   }
+  // if (Style.isCSharp() && FormatTok->is(Keywords.kw_where)) {
+  //   addUnwrappedLine();
+  //   nextToken();
+  //   parseCSharpGenericTypeConstraint();
+  // }
   // There is no addUnwrappedLine() here so that we fall through to parsing a
   // structural element afterwards. Thus, in "class A {} n, m;",
   // "} n, m;" will end up in one unwrapped line.
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -1060,15 +1060,20 @@
   }
 
   void parseCSharpGenericTypeConstraint() {
+int OpenAngleBracketsCount = 0;
 while (CurrentToken) {
   if (CurrentToken->is(tok::less)) {
 // parseAngle is too greedy and will consume the whole line.
 CurrentToken->Type = TT_TemplateOpener;
+++OpenAngleBracketsCount;
 next();
   } else if (CurrentToken->is(tok::greater)) {
 CurrentToken->Type = TT_TemplateCloser;
+--OpenAngleBracketsCount;
 next();
-  } else if (CurrentToken->is(tok::comma)) {
+  } else if (CurrentToken->is(tok::comma) && OpenAngleBracketsCount==0) {
+// We allow line breaks after GenericTypeConstraintComma's
+// so do not flag commas in Generics as GenericTypeConstraintComma's.
 CurrentToken->Type = TT_CSharpGenericTypeConstraintComma;
 next();
   } else if (CurrentToken->is(Keywords.kw_where)) {


Index: clang/unittests/Format/FormatTestCSharp.cpp
===
--- clang/unittests/Format/FormatTestCSharp.cpp
+++ clang/unittests/Format/FormatTestCSharp.cpp
@@ -702,12 +702,13 @@
 })",
Style);
 
+  Style.ColumnLimit = 50; // Force lines to be wrapped.
   verifyFormat(R"(//
-class ItemFactory
-where T : new(),
-  IAnInterface,
-  IAnotherInterface,
-  IAnotherInterfaceStill {})",
+class ItemFactory
+where T : new(), 
+  IAnInterface, 
+  IAnotherInterface, 
+  IAnotherInterfaceStill {})",
Style);
 
   // In other languages `where` can be used as a normal identifier.
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -2339,7 +2339,13 @@
   break;
   }
   if (FormatTok->Tok.is(tok::semi))
+return;  
+  if (Style.isCSharp() && FormatTok->is(Keywords.kw_where)) {
+addUnwrappedLine();
+nextToken();
+parseCSharpGenericTypeConstraint();
 return;
+  }
   nextToken();
 }
   }
@@ -2354,6 +2360,11 @@
  /*MunchSemi=*/false);
 }
   }
+  // if (Style.isCSharp() && FormatTok->is(Keywords.kw_where)) {
+  //   addUnwrappedLine();
+  //   nextToken();
+  //   parseCSharpGenericTypeConstraint();
+  // }
   // There is no addUnwrappedLine() here so that we fall through to parsing a
   // structural element afterwards. Thus, in "class A {} n, m;",
   // "} n, m;" will end up in one unwrapped line.
Index: clang/lib/Format/TokenAnnotator.cpp
=

[clang] 1a1bb87 - [analyzer] Add core.CallAndMessage to StdCLibraryFunctionArgsChecker's dependency

2020-03-30 Thread Gabor Marton via cfe-commits

Author: Gabor Marton
Date: 2020-03-30T17:57:15+02:00
New Revision: 1a1bb876dba41066f6e9a273c24fad04e0f9f2da

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

LOG: [analyzer] Add core.CallAndMessage to StdCLibraryFunctionArgsChecker's 
dependency

Reviewers: Szelethus, NoQ

Subscribers: whisperity, xazax.hun, baloghadamsoftware, szepet, rnkovacs, 
a.sidorin, mikhail.ramalho, donat.nagy, dkrupp, gamesh411, Charusso, steakhal, 
ASDenysPetrov, cfe-commits

Tags: #clang

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

Added: 


Modified: 
clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
clang/test/Analysis/analyzer-enabled-checkers.c

Removed: 




diff  --git a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td 
b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
index a21107cd4c2d..136a0fb6a374 100644
--- a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
+++ b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
@@ -299,7 +299,7 @@ def StdCLibraryFunctionArgsChecker : 
Checker<"StdCLibraryFunctionArgs">,
   HelpText<"Check constraints of arguments of C standard library functions, "
"such as whether the parameter of isalpha is in the range [0, 255] "
"or is EOF.">,
-  Dependencies<[StdCLibraryFunctionsChecker]>,
+  Dependencies<[StdCLibraryFunctionsChecker, CallAndMessageChecker]>,
   Documentation;
 
 def TrustNonnullChecker : Checker<"TrustNonnull">,

diff  --git a/clang/test/Analysis/analyzer-enabled-checkers.c 
b/clang/test/Analysis/analyzer-enabled-checkers.c
index 55f15f6d37c8..6f719ec15d4f 100644
--- a/clang/test/Analysis/analyzer-enabled-checkers.c
+++ b/clang/test/Analysis/analyzer-enabled-checkers.c
@@ -7,11 +7,11 @@
 // CHECK:  OVERVIEW: Clang Static Analyzer Enabled Checkers List
 // CHECK-EMPTY:
 // CHECK-NEXT: apiModeling.StdCLibraryFunctions
+// CHECK-NEXT: core.CallAndMessage
 // CHECK-NEXT: apiModeling.StdCLibraryFunctionArgs
 // CHECK-NEXT: apiModeling.TrustNonnull
 // CHECK-NEXT: apiModeling.llvm.CastValue
 // CHECK-NEXT: apiModeling.llvm.ReturnValue
-// CHECK-NEXT: core.CallAndMessage
 // CHECK-NEXT: core.DivideZero
 // CHECK-NEXT: core.DynamicTypePropagation
 // CHECK-NEXT: core.NonNullParamChecker



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


[PATCH] D76937: Fix infinite recursion in deferred diagnostic emitter

2020-03-30 Thread John McCall via Phabricator via cfe-commits
rjmccall added a comment.

Can you explain what exactly the emission/semantic model is for variables?  
Normal code-generation absolutely triggers the emission of many variables 
lazily (e.g. internal-linkage globals, C++ inline variables); and any variable 
that's *not* being emitted lazily actually needs to be treated as a potential 
root into the delayed-diagnostic graph.


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

https://reviews.llvm.org/D76937



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


[PATCH] D77066: [analyzer] ApiModeling: Add buffer size arg constraint

2020-03-30 Thread Gabor Marton via Phabricator via cfe-commits
martong created this revision.
martong added reviewers: NoQ, Szelethus, Charusso, steakhal.
Herald added subscribers: cfe-commits, ASDenysPetrov, gamesh411, dkrupp, 
donat.nagy, mikhail.ramalho, a.sidorin, rnkovacs, szepet, baloghadamsoftware, 
xazax.hun, whisperity.
Herald added a project: clang.
martong added a parent revision: D76790: [analyzer] StdLibraryFunctionsChecker: 
fix bug with arg constraints.

Introducing a new argument constraint to confine buffer sizes. It is typical in
C APIs that a parameter represents a buffer and another param holds the size of
the buffer (or the size of the data we want to handle from the buffer).


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D77066

Files:
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicSize.h
  clang/lib/StaticAnalyzer/Checkers/CheckPlacementNew.cpp
  clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
  clang/lib/StaticAnalyzer/Core/DynamicSize.cpp
  clang/test/Analysis/std-c-library-functions-arg-constraints.c

Index: clang/test/Analysis/std-c-library-functions-arg-constraints.c
===
--- clang/test/Analysis/std-c-library-functions-arg-constraints.c
+++ clang/test/Analysis/std-c-library-functions-arg-constraints.c
@@ -114,3 +114,30 @@
   // bugpath-note{{Assuming 'x' is < 1}} \
   // bugpath-note{{Left side of '||' is true}}
 }
+
+int __buf_size_arg_constraint(const void *, size_t);
+void test_buf_size_concrete() {
+  char buf[3]; // bugpath-note{{'buf' initialized here}}
+  __buf_size_arg_constraint(buf, 4); // \
+  // report-warning{{Function argument constraint is not satisfied}} \
+  // bugpath-warning{{Function argument constraint is not satisfied}} \
+  // bugpath-note{{Function argument constraint is not satisfied}}
+}
+void test_buf_size_symbolic(int s) {
+  char buf[3];
+  __buf_size_arg_constraint(buf, s);
+  clang_analyzer_eval(s <= 3); // \
+  // report-warning{{TRUE}} \
+  // bugpath-warning{{TRUE}} \
+  // bugpath-note{{TRUE}} \
+  // bugpath-note{{'s' is <= 3}}
+}
+void test_buf_size_symbolic_and_offset(int s) {
+  char buf[3];
+  __buf_size_arg_constraint(buf + 1, s);
+  clang_analyzer_eval(s <= 2); // \
+  // report-warning{{TRUE}} \
+  // bugpath-warning{{TRUE}} \
+  // bugpath-note{{TRUE}} \
+  // bugpath-note{{'s' is <= 2}}
+}
Index: clang/lib/StaticAnalyzer/Core/DynamicSize.cpp
===
--- clang/lib/StaticAnalyzer/Core/DynamicSize.cpp
+++ clang/lib/StaticAnalyzer/Core/DynamicSize.cpp
@@ -10,6 +10,7 @@
 //
 //===--===//
 
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/DynamicSize.h"
 #include "clang/AST/Expr.h"
 #include "clang/Basic/LLVM.h"
@@ -44,5 +45,28 @@
   return DivisionV.castAs();
 }
 
+SVal getBufferDynamicSize(const SVal &BufV, ProgramStateRef State,
+CheckerContext &C) {
+  const MemRegion *MRegion = BufV.getAsRegion();
+  if (!MRegion)
+return UnknownVal();
+  RegionOffset Offset = MRegion->getAsOffset();
+  if (Offset.hasSymbolicOffset())
+return UnknownVal();
+  const MemRegion *BaseRegion = MRegion->getBaseRegion();
+  if (!BaseRegion)
+return UnknownVal();
+
+  SValBuilder &SvalBuilder = C.getSValBuilder();
+  NonLoc OffsetInBytes = SvalBuilder.makeArrayIndex(
+  Offset.getOffset() / C.getASTContext().getCharWidth());
+  DefinedOrUnknownSVal ExtentInBytes =
+  getDynamicSize(State, BaseRegion, SvalBuilder);
+
+  return SvalBuilder.evalBinOp(State, BinaryOperator::Opcode::BO_Sub,
+   ExtentInBytes, OffsetInBytes,
+   SvalBuilder.getArrayIndexType());
+}
+
 } // namespace ento
 } // namespace clang
Index: clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
@@ -56,6 +56,7 @@
 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerHelpers.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/DynamicSize.h"
 
 using namespace clang;
 using namespace clang::ento;
@@ -108,7 +109,8 @@
 /// Apply the effects of the constraint on the given program state. If null
 /// is returned then the constraint is not feasible.
 virtual ProgramStateRef apply(ProgramStateRef State, const CallEvent &Call,
-  const Summary &Summary) const = 0;
+  const Summary &Summary,
+  CheckerContext &C) const = 0;
 virtual ValueConstraintPtr negate() const {
   llvm_unreachable

[PATCH] D77013: [AMDGPU] Add options -mamdgpu-ieee -mno-amdgpu-ieee

2020-03-30 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl planned changes to this revision.
yaxunl added a comment.

This patch is put on hold due to some concerns.


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

https://reviews.llvm.org/D77013



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


[PATCH] D77068: [XCore] fix crash on unused inline in EmitTargetMetadata

2020-03-30 Thread Nigel Perks via Phabricator via cfe-commits
nigelp-xmos created this revision.
nigelp-xmos added a reviewer: rsmith.
nigelp-xmos added a project: clang.

EmitTargetMetadata passes to emitTargetMD a null pointer as returned from 
GetGlobalValue for an unused inline function which has been removed from the 
module at that point.

Richard Smith comments in CodeGenModule.cpp that the calling code in 
EmitTargetMetadata should be moved into the one target that needs it (XCore). I 
thought it best to start with the quicker change, restricted to XCore code, 
checking for null, to prevent the crash.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D77068

Files:
  clang/lib/CodeGen/TargetInfo.cpp
  clang/test/CodeGen/xcore-unused-inline.c


Index: clang/test/CodeGen/xcore-unused-inline.c
===
--- /dev/null
+++ clang/test/CodeGen/xcore-unused-inline.c
@@ -0,0 +1,4 @@
+// REQUIRES: xcore-registered-target
+// RUN: %clang_cc1 -triple xcore-unknown-unknown -emit-llvm -o - %s
+
+inline void dead_function(void) {}
Index: clang/lib/CodeGen/TargetInfo.cpp
===
--- clang/lib/CodeGen/TargetInfo.cpp
+++ clang/lib/CodeGen/TargetInfo.cpp
@@ -9354,6 +9354,8 @@
 /// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
 void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
   CodeGen::CodeGenModule &CGM) const {
+  if (!GV)
+return;
   SmallStringEnc Enc;
   if (getTypeString(Enc, D, CGM, TSC)) {
 llvm::LLVMContext &Ctx = CGM.getModule().getContext();


Index: clang/test/CodeGen/xcore-unused-inline.c
===
--- /dev/null
+++ clang/test/CodeGen/xcore-unused-inline.c
@@ -0,0 +1,4 @@
+// REQUIRES: xcore-registered-target
+// RUN: %clang_cc1 -triple xcore-unknown-unknown -emit-llvm -o - %s
+
+inline void dead_function(void) {}
Index: clang/lib/CodeGen/TargetInfo.cpp
===
--- clang/lib/CodeGen/TargetInfo.cpp
+++ clang/lib/CodeGen/TargetInfo.cpp
@@ -9354,6 +9354,8 @@
 /// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
 void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
   CodeGen::CodeGenModule &CGM) const {
+  if (!GV)
+return;
   SmallStringEnc Enc;
   if (getTypeString(Enc, D, CGM, TSC)) {
 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D77061: [analyzer] Add core.CallAndMessage to StdCLibraryFunctionArgsChecker's dependency

2020-03-30 Thread Gabor Marton via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG1a1bb876dba4: [analyzer] Add core.CallAndMessage to 
StdCLibraryFunctionArgsChecker's… (authored by martong).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D77061

Files:
  clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
  clang/test/Analysis/analyzer-enabled-checkers.c


Index: clang/test/Analysis/analyzer-enabled-checkers.c
===
--- clang/test/Analysis/analyzer-enabled-checkers.c
+++ clang/test/Analysis/analyzer-enabled-checkers.c
@@ -7,11 +7,11 @@
 // CHECK:  OVERVIEW: Clang Static Analyzer Enabled Checkers List
 // CHECK-EMPTY:
 // CHECK-NEXT: apiModeling.StdCLibraryFunctions
+// CHECK-NEXT: core.CallAndMessage
 // CHECK-NEXT: apiModeling.StdCLibraryFunctionArgs
 // CHECK-NEXT: apiModeling.TrustNonnull
 // CHECK-NEXT: apiModeling.llvm.CastValue
 // CHECK-NEXT: apiModeling.llvm.ReturnValue
-// CHECK-NEXT: core.CallAndMessage
 // CHECK-NEXT: core.DivideZero
 // CHECK-NEXT: core.DynamicTypePropagation
 // CHECK-NEXT: core.NonNullParamChecker
Index: clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
===
--- clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
+++ clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
@@ -299,7 +299,7 @@
   HelpText<"Check constraints of arguments of C standard library functions, "
"such as whether the parameter of isalpha is in the range [0, 255] "
"or is EOF.">,
-  Dependencies<[StdCLibraryFunctionsChecker]>,
+  Dependencies<[StdCLibraryFunctionsChecker, CallAndMessageChecker]>,
   Documentation;
 
 def TrustNonnullChecker : Checker<"TrustNonnull">,


Index: clang/test/Analysis/analyzer-enabled-checkers.c
===
--- clang/test/Analysis/analyzer-enabled-checkers.c
+++ clang/test/Analysis/analyzer-enabled-checkers.c
@@ -7,11 +7,11 @@
 // CHECK:  OVERVIEW: Clang Static Analyzer Enabled Checkers List
 // CHECK-EMPTY:
 // CHECK-NEXT: apiModeling.StdCLibraryFunctions
+// CHECK-NEXT: core.CallAndMessage
 // CHECK-NEXT: apiModeling.StdCLibraryFunctionArgs
 // CHECK-NEXT: apiModeling.TrustNonnull
 // CHECK-NEXT: apiModeling.llvm.CastValue
 // CHECK-NEXT: apiModeling.llvm.ReturnValue
-// CHECK-NEXT: core.CallAndMessage
 // CHECK-NEXT: core.DivideZero
 // CHECK-NEXT: core.DynamicTypePropagation
 // CHECK-NEXT: core.NonNullParamChecker
Index: clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
===
--- clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
+++ clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
@@ -299,7 +299,7 @@
   HelpText<"Check constraints of arguments of C standard library functions, "
"such as whether the parameter of isalpha is in the range [0, 255] "
"or is EOF.">,
-  Dependencies<[StdCLibraryFunctionsChecker]>,
+  Dependencies<[StdCLibraryFunctionsChecker, CallAndMessageChecker]>,
   Documentation;
 
 def TrustNonnullChecker : Checker<"TrustNonnull">,
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D74387: [SYCL] Defer __float128 type usage diagnostics

2020-03-30 Thread Mariya Podchishchaeva via Phabricator via cfe-commits
Fznamznon added inline comments.



Comment at: clang/include/clang/Sema/Sema.h:12248
+  ///   SYCLDiagIfDeviceCode(Loc, diag::err_type_unsupported) << "__float128";
+  DeviceDiagBuilder SYCLDiagIfDeviceCode(SourceLocation Loc, unsigned DiagID);
+

rjmccall wrote:
> Will this collect notes associated with the diagnostic correctly?
Could you please make your question a bit more concrete?
This function is supposed to work in the same way as 
`Sema::CUDADiagIfDeviceCode` and `Sema::diagIfOpenMPDeviceCode` . It emits 
given diagnostic if the current context is known as "device code" and makes 
this diagnostic deferred otherwise. It uses the `DeviceDiagBuilder` which was 
implemented earlier. This `DeviceDiagBuilder` also tries to emit callstack 
notes for the given diagnostics. Do you mean these callstack notes or something 
else?



Comment at: clang/lib/Sema/SemaAvailability.cpp:479
+case UnavailableAttr::IR_SYCLForbiddenType:
+  diag_available_here = diag::err_type_unsupported;
+  break;

rjmccall wrote:
> All of the other cases are setting this to a note, not an error, so I suspect 
> this will read wrong.
Yes, this is not a note. For such samples:

```
int main() {
  __float128 CapturedToDevice = 1;
  kernel([=]() {
decltype(CapturedToDevice) D;
  });
}
```
It looks like this:
```
float128.cpp:63:14: error: 'CapturedToDevice' is unavailable
decltype(CapturedToDevice) D;
 ^
float128.cpp:59:14: error: '__float128' is not supported on this target   /// 
This emitted instead of note 
  __float128 CapturedToDevice = 1;
 ^
```
I had feeling that it should probably be a note. But there is no implemented 
note for unsupported types. I think I can add a new one if it will make it 
better. Should I?



Comment at: clang/lib/Sema/SemaAvailability.cpp:534
+if (S.getLangOpts().SYCLIsDevice)
+  S.SYCLDiagIfDeviceCode(Loc, diag) << ReferringDecl;
+else

rjmccall wrote:
> Are you sure you want to be applying this to all of the possible diagnostics 
> here, rather than just for SYCLForbiddenType unavailable attributes?
I suppose it is reasonable if we want to reuse unavaliable attribute for other 
SYCL use cases. Plus, In SYCL we don't know where is device code until we 
instantiate templates, it happens late, so we have to defer any diagnostic 
while compiling for device, otherwise we can point to host code where much more 
is allowed.



Comment at: clang/lib/Sema/SemaDecl.cpp:18030
+  if (LangOpts.SYCLIsDevice && FD->hasAttr())
+return FunctionEmissionStatus::Emitted;
+

rjmccall wrote:
> So you want to emit it for the definition in addition to emitting it for 
> specific specializations?
Somehow diagnostics are emitted only for the definitions. 
Without this change diagnostics aren't emitted at all.



Comment at: clang/lib/Sema/SemaDeclAttr.cpp:7771
+return true;
+  }
+

rjmccall wrote:
> I wonder if it's reasonable to treat all forbidden types the same here or if 
> we want different functions for the ARC and SYCL use cases.
I think it could be reasonable if we will have forbidden type cases for SYCL 
sometime. For now, I don't see the purpose in a separate function for SYCL.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D74387



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


[PATCH] D74387: [SYCL] Defer __float128 type usage diagnostics

2020-03-30 Thread Mariya Podchishchaeva via Phabricator via cfe-commits
Fznamznon updated this revision to Diff 253615.
Fznamznon added a comment.
Herald added a reviewer: jdoerfert.

Rebased to fresh version. Applied fixes after https://reviews.llvm.org/D70172


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D74387

Files:
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Sema/Sema.h
  clang/lib/Sema/CMakeLists.txt
  clang/lib/Sema/SemaAvailability.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaSYCL.cpp
  clang/lib/Sema/SemaType.cpp
  clang/test/SemaSYCL/float128.cpp

Index: clang/test/SemaSYCL/float128.cpp
===
--- /dev/null
+++ clang/test/SemaSYCL/float128.cpp
@@ -0,0 +1,93 @@
+// RUN: %clang_cc1 -triple spir64 -fsycl -fsycl-is-device -verify -fsyntax-only %s
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -fsycl -fsycl-is-device -fsyntax-only %s
+
+template 
+class Z {
+public:
+  // TODO: If T is __float128 This might be a problem
+  T field;
+  //expected-error@+1 2{{'__float128' is not supported on this target}}
+  __float128 field1;
+};
+
+void host_ok(void) {
+  __float128 A;
+  int B = sizeof(__float128);
+  Z<__float128> C;
+  C.field1 = A;
+}
+
+void usage() {
+  //expected-error@+1 5{{'__float128' is not supported on this target}}
+  __float128 A;
+  Z<__float128> C;
+  //expected-error@+2 {{'A' is unavailable}}
+  //expected-error@+1 {{'field1' is unavailable}}
+  C.field1 = A;
+  //expected-error@+1 {{'A' is unavailable}}
+  decltype(A) D;
+
+  //expected-error@+1 {{'A' is unavailable}}
+  auto foo1 = [=]() {
+//expected-error@+1 {{'__float128' is not supported on this target}}
+__float128 AA;
+//expected-error@+1 {{'A' is unavailable}}
+auto BB = A;
+BB += 1;
+  };
+
+  //expected-note@+1 {{called by 'usage'}}
+  foo1();
+}
+
+template 
+void foo2(){};
+
+//expected-error@+1 {{'__float128 (__float128)' is not supported on this target}}
+__float128 foo(__float128 P) { return P; }
+
+template 
+__attribute__((sycl_kernel)) void kernel(Func kernelFunc) {
+  //expected-note@+1 5{{called by 'kernel}}
+  kernelFunc();
+  //expected-error@+1 {{'__float128' is not supported on this target}}
+  __float128 A;
+}
+
+int main() {
+  //expected-error@+1 2{{'__float128' is not supported on this target}}
+  __float128 CapturedToDevice = 1;
+  host_ok();
+  kernel([=]() {
+//expected-error@+1 {{'CapturedToDevice' is unavailable}}
+decltype(CapturedToDevice) D;
+//expected-error@+1 {{'CapturedToDevice' is unavailable}}
+auto C = CapturedToDevice;
+//expected-error@+1 {{'__float128' is not supported on this target}}
+__float128 ;
+Z<__float128> S;
+//expected-error@+1 {{'field1' is unavailable}}
+S.field1 += 1;
+S.field = 1;
+  });
+
+  kernel([=]() {
+//expected-note@+1 2{{called by 'operator()'}}
+usage();
+// expected-error@+1 2{{'__float128' is not supported on this target}}
+__float128 ;
+// expected-error@+2 {{'' is unavailable}}
+// expected-error@+1 {{'foo' is unavailable}}
+auto A = foo();
+  });
+
+  kernel([=]() {
+Z<__float128> S;
+foo2<__float128>();
+// TODO: this shouldn't be diagnosed
+// expected-error@+1 {{'__float128' is not supported on this target}}
+int E = sizeof(__float128);
+  });
+
+  return 0;
+}
Index: clang/lib/Sema/SemaType.cpp
===
--- clang/lib/Sema/SemaType.cpp
+++ clang/lib/Sema/SemaType.cpp
@@ -1517,10 +1517,21 @@
 break;
   case DeclSpec::TST_float128:
 if (!S.Context.getTargetInfo().hasFloat128Type() &&
+!S.getLangOpts().SYCLIsDevice &&
 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsDevice))
   S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
 << "__float128";
 Result = Context.Float128Ty;
+if (!S.Context.getTargetInfo().hasFloat128Type() &&
+S.getLangOpts().SYCLIsDevice &&
+S.DelayedDiagnostics.shouldDelayDiagnostics()) {
+  S.DelayedDiagnostics.add(sema::DelayedDiagnostic::makeForbiddenType(
+  DS.getTypeSpecTypeLoc(), diag::err_type_unsupported, Result,
+  /*ignored*/ 0));
+  S.SYCLDiagIfDeviceCode(DS.getTypeSpecTypeLoc(),
+ diag::err_type_unsupported)
+  << Result;
+}
 break;
   case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool
 break;
Index: clang/lib/Sema/SemaSYCL.cpp
===
--- /dev/null
+++ clang/lib/Sema/SemaSYCL.cpp
@@ -0,0 +1,54 @@
+//===- SemaSYCL.cpp - Semantic Analysis for SYCL constructs ---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-L

[PATCH] D77070: [SemaObjC] Add a warning for declarations of BOOL:1 when BOOL is a signed char

2020-03-30 Thread Erik Pilkington via Phabricator via cfe-commits
erik.pilkington created this revision.
erik.pilkington added reviewers: rjmccall, steven_wu.
Herald added subscribers: ributzka, dexonsmith, jkorous.

Instead, recommend using a real boolean type. Its possible to get away with 
BOOL:1, if you only read from it in a context where its contextually converted 
to bool, but its still broken if you, for instance, store it into a BOOL 
variable or try to compare it with another BOOL. Given that, I don't think 
there is any good reason to use it when there are better alternatives available.

rdar://29707989


https://reviews.llvm.org/D77070

Files:
  clang/include/clang/Basic/DiagnosticGroups.td
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Sema/Sema.h
  clang/lib/Sema/SemaDecl.cpp
  clang/test/SemaObjC/signed-char-bool-bitfield-fixit.m
  clang/test/SemaObjC/signed-char-bool-bitfield.m

Index: clang/test/SemaObjC/signed-char-bool-bitfield.m
===
--- /dev/null
+++ clang/test/SemaObjC/signed-char-bool-bitfield.m
@@ -0,0 +1,15 @@
+// RUN: %clang_cc1 -verify %s -Wobjc-signed-char-bool
+// RUN: %clang_cc1 -xobjective-c++ -verify %s -Wobjc-signed-char-bool
+
+typedef signed char BOOL;
+
+struct S {
+  BOOL b : 1; // expected-warning {{BOOL bit-field of width 1 cannot represent YES when BOOL is a signed type}}
+  BOOL b2 : 2;
+};
+
+@interface X {
+  BOOL b : 1; // expected-warning {{BOOL bit-field of width 1 cannot represent YES when BOOL is a signed type}}
+  BOOL b2 : 2;
+}
+@end
Index: clang/test/SemaObjC/signed-char-bool-bitfield-fixit.m
===
--- /dev/null
+++ clang/test/SemaObjC/signed-char-bool-bitfield-fixit.m
@@ -0,0 +1,14 @@
+// RUN: %clang_cc1 -Wobjc-signed-char-bool %s -fdiagnostics-parseable-fixits 2>&1 | FileCheck %s
+
+typedef signed char BOOL;
+
+struct S {
+  BOOL bf : 1;
+  // CHECK: fix-it:"{{.*}}.m":{6:3-6:7}:"bool"
+};
+
+@interface X {
+  BOOL bf : 1;
+  // CHECK: fix-it:"{{.*}}.m":{11:3-11:7}:"bool"
+}
+@end
Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -16169,6 +16169,7 @@
 
 // Note that FieldName may be null for anonymous bitfields.
 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
+SourceRange TypeRange,
 IdentifierInfo *FieldName,
 QualType FieldTy, bool IsMsStruct,
 Expr *BitWidth, bool *ZeroWidth) {
@@ -16259,6 +16260,16 @@
 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
 << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
 }
+
+if (getLangOpts().ObjC && NSAPIObj->isObjCBOOLType(FieldTy) &&
+FieldTy->isSpecificBuiltinType(BuiltinType::SChar) &&
+Value == 1) {
+  auto Builder = Diag(FieldLoc, diag::warn_objc_signed_char_bool_bitfield);
+  // The Foundation headers that define BOOL include , so its
+  // reasonable to assume that 'bool' is available.
+  if (TypeRange.isValid())
+Builder << FixItHint::CreateReplacement(TypeRange, "bool");
+}
   }
 
   return BitWidth;
@@ -16485,7 +16496,8 @@
 BitWidth = nullptr;
   // If this is declared as a bit-field, check the bit-field.
   if (BitWidth) {
-BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
+BitWidth = VerifyBitField(Loc, TInfo->getTypeLoc().getSourceRange(),
+  II, T, Record->isMsStruct(Context), BitWidth,
   &ZeroWidth).get();
 if (!BitWidth) {
   InvalidDecl = true;
@@ -16676,7 +16688,8 @@
 
   if (BitWidth) {
 // 6.7.2.1p3, 6.7.2.1p4
-BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
+BitWidth = VerifyBitField(Loc, TInfo->getTypeLoc().getSourceRange(),
+  II, T, /*IsMsStruct*/false, BitWidth).get();
 if (!BitWidth)
   D.setInvalidType();
   } else {
Index: clang/include/clang/Sema/Sema.h
===
--- clang/include/clang/Sema/Sema.h
+++ clang/include/clang/Sema/Sema.h
@@ -11401,9 +11401,10 @@
 
   /// VerifyBitField - verifies that a bit field expression is an ICE and has
   /// the correct width, and that the field type is valid.
-  /// Returns false on success.
+  /// Returns BitWidth on success.
   /// Can optionally return whether the bit-field is of width 0
-  ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
+  ExprResult VerifyBitField(SourceLocation FieldLoc, SourceRange TypeRange,
+IdentifierInfo *FieldName,
 QualType FieldTy, bool IsMsStruct,
 Expr *BitWidth, bool *ZeroWidth = nullptr);
 
Index: clang/include/clang/Basic/DiagnosticSemaKin

[PATCH] D68165: [analyzer][MallocChecker][NFC] Split checkPostCall up, deploy CallDescriptionMap

2020-03-30 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ added a comment.

**`$ git show --pretty=full 703a1b8caf09`**

  commit 703a1b8caf09a5262a45c2179b8131922f71cf25
  Author: Louis Dionne 
  Commit: Kirstóf Umann 
  
  [analyzer][MallocChecker][NFC] Split checkPostCall up, deploy 
CallDescriptionMap
  
  ...

Not a phabricator bug. Maybe @Szelethus's local git somehow got in a weird 
state(?)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68165



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


[PATCH] D76365: [cuda][hip] Add CUDA builtin surface/texture reference support.

2020-03-30 Thread Artem Belevich via Phabricator via cfe-commits
tra added a comment.

In D76365#1947479 , @hliao wrote:

>


Nice! I'll file a bug with NVIDIA.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76365



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


[PATCH] D76887: AMDGPU: Make HIPToolChain a subclass of ROCMToolChain

2020-03-30 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl accepted this revision.
yaxunl added a comment.
This revision is now accepted and ready to land.

LGTM. Thanks!


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

https://reviews.llvm.org/D76887



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


[PATCH] D75951: Keep a list of already-included pragma-once files for mods.

2020-03-30 Thread Vy Nguyen via Phabricator via cfe-commits
oontvoo updated this revision to Diff 253623.
oontvoo added a comment.

Rebaase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D75951

Files:
  clang/include/clang/Lex/HeaderSearch.h
  clang/include/clang/Lex/Preprocessor.h
  clang/include/clang/Serialization/ASTBitCodes.h
  clang/include/clang/Serialization/ASTReader.h
  clang/include/clang/Serialization/ASTWriter.h
  clang/lib/Lex/HeaderSearch.cpp
  clang/lib/Lex/Preprocessor.cpp
  clang/lib/Serialization/ASTReader.cpp
  clang/lib/Serialization/ASTWriter.cpp
  clang/test/Modules/Inputs/dummy_pragma_once.h
  clang/test/Modules/Inputs/dummy_textual_header.h
  clang/test/Modules/Inputs/header_in_imported_module.h
  clang/test/Modules/Inputs/imported_module.cppm
  clang/test/Modules/Inputs/module.map
  clang/test/Modules/header-in-imported-module.c
  clang/test/Modules/import-pragma-once.c

Index: clang/test/Modules/import-pragma-once.c
===
--- /dev/null
+++ clang/test/Modules/import-pragma-once.c
@@ -0,0 +1,8 @@
+// RUN: rm -rf %t
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -fimplicit-module-maps -I%S/Inputs -verify -x c %s
+// expected-no-diagnostics
+#include "dummy_pragma_once.h"
+#include "dummy_textual_header.h"
+
+void *p = &x;
+void *q = &y;
Index: clang/test/Modules/header-in-imported-module.c
===
--- /dev/null
+++ clang/test/Modules/header-in-imported-module.c
@@ -0,0 +1,16 @@
+// RUN: rm -rf %t
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -fimplicit-module-maps -I%S/Inputs -verify  -x c++ %s
+//
+// RUN: %clang_cc1 -x c++ -fmodules-ts --precompile -o %t/ModuleB39206.pcm %S/Inputs/imported_module.cppm
+// RUN: %clang_cc1 -x c++ -fmodules-ts -c %t/ModuleB39206.pcm -o %t/ModuleB39206.o
+// RUN: %clang_cc1 -x c++ -fmodules-ts -fmodule-file=%t/ModuleB39206.pcm -verify  -c %s
+// expected-no-diagnostics
+
+// Bug 39206
+
+#include "header_in_imported_module.h"
+module ModuleB39206;
+
+#ifndef ALL_GOOD
+#error "missing macro in impl"
+#endif
Index: clang/test/Modules/Inputs/module.map
===
--- clang/test/Modules/Inputs/module.map
+++ clang/test/Modules/Inputs/module.map
@@ -282,6 +282,11 @@
   header "dummy.h"
 }
 
+module dummy_pragma_once {
+  header "dummy_pragma_once.h"
+  textual header "dummy_textual_header.h"
+}
+
 module builtin {
   header "builtin.h"
   explicit module sub {
Index: clang/test/Modules/Inputs/imported_module.cppm
===
--- /dev/null
+++ clang/test/Modules/Inputs/imported_module.cppm
@@ -0,0 +1,5 @@
+export module ModuleB39206;
+#include "header.h"
+
+#ifndef ALL_GOOD
+#error "Missing macro in module decl"
\ No newline at end of file
Index: clang/test/Modules/Inputs/header_in_imported_module.h
===
--- /dev/null
+++ clang/test/Modules/Inputs/header_in_imported_module.h
@@ -0,0 +1,3 @@
+#pragma once
+
+#define ALL_GOOD
Index: clang/test/Modules/Inputs/dummy_textual_header.h
===
--- /dev/null
+++ clang/test/Modules/Inputs/dummy_textual_header.h
@@ -0,0 +1,2 @@
+#pragma once
+int y = 6;
Index: clang/test/Modules/Inputs/dummy_pragma_once.h
===
--- /dev/null
+++ clang/test/Modules/Inputs/dummy_pragma_once.h
@@ -0,0 +1,3 @@
+#include "dummy_textual_header.h"
+
+int x = 5;
Index: clang/lib/Serialization/ASTWriter.cpp
===
--- clang/lib/Serialization/ASTWriter.cpp
+++ clang/lib/Serialization/ASTWriter.cpp
@@ -1621,7 +1621,7 @@
   endian::Writer LE(Out, little);
   unsigned KeyLen = key.Filename.size() + 1 + 8 + 8;
   LE.write(KeyLen);
-  unsigned DataLen = 1 + 2 + 4 + 4;
+  unsigned DataLen = 1 + 2 + 4 + 4 + 4;
   for (auto ModInfo : Data.KnownHeaders)
 if (Writer.getLocalOrImportedSubmoduleID(ModInfo.getModule()))
   DataLen += 4;
@@ -1678,6 +1678,9 @@
   }
   LE.write(Offset);
 
+  // Write this file UID.
+  LE.write(Data.HFI.UID);
+
   auto EmitModule = [&](Module *M, ModuleMap::ModuleHeaderRole Role) {
 if (uint32_t ModID = Writer.getLocalOrImportedSubmoduleID(M)) {
   uint32_t Value = (ModID << 2) | (unsigned)Role;
@@ -1705,7 +1708,7 @@
 /// Write the header search block for the list of files that
 ///
 /// \param HS The header search structure to save.
-void ASTWriter::WriteHeaderSearch(const HeaderSearch &HS) {
+void ASTWriter::WriteHeaderSearch(HeaderSearch &HS) {
   HeaderFileInfoTrait GeneratorTrait(*this);
   llvm::OnDiskChainedHashTableGenerator Generator;
   SmallVector SavedStrings;
@@ -1783,8 +1786,7 @@
 // changed since it was loaded. Also skip 

[PATCH] D77074: [FPEnv][AArch64] Platform-specific builtin constrained FP enablement

2020-03-30 Thread Kevin P. Neal via Phabricator via cfe-commits
kpn marked 3 inline comments as done.
kpn added a comment.

Note that the AArch64 backend isn't ready for some of these changes. That's why 
the test is marked XFAIL.




Comment at: clang/lib/CodeGen/CGBuiltin.cpp:5706
+Function *F;
+//exit(2); // XXX
+if (Builder.getIsFPConstrained())

These exit() calls tie back into my test matrix. They'll be removed when I 
eventually push.



Comment at: clang/test/CodeGen/aarch64-neon-intrinsics-constrained.c:288
+
+// XXX FIXME do we need to check for both w and x registers?
+// COMMON-LABEL: test_vceq_f64

Anyone? I'm not an ARM expert.



Comment at: clang/test/CodeGen/aarch64-neon-intrinsics-constrained.c:889
+
+// FIXME why the unused bitcast? There are several of them!
+// COMMON-LABEL: test_vrnda_f64

???


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D77074



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


[PATCH] D76996: [analyzer] Improve PlacementNewChecker

2020-03-30 Thread Karasev Nikita via Phabricator via cfe-commits
f00kat updated this revision to Diff 253628.
f00kat marked 3 inline comments as done.
f00kat added a comment.

1. Removed code and tests for ConcreteInt cases
2. Fixed FieldRegion check
3. Added handling for ElementRegion cases such as

  void f7() {
short b[10];
  
// ok. 2(short align) + 3*2(index '1' offset)
::new (&b[3]) long;
  }

4. Fixed align error message
5. Maybe fixed lint warnings


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76996

Files:
  clang/lib/StaticAnalyzer/Checkers/CheckPlacementNew.cpp
  clang/test/Analysis/placement-new.cpp

Index: clang/test/Analysis/placement-new.cpp
===
--- clang/test/Analysis/placement-new.cpp
+++ clang/test/Analysis/placement-new.cpp
@@ -155,3 +155,147 @@
   (void)dp;
 }
 } // namespace testHierarchy
+
+namespace testArrayTypesAllocation {
+void f1() {
+  struct S {
+short a;
+  };
+
+  // bad (not enough space).
+  const unsigned N = 32;
+  alignas(S) unsigned char buffer1[sizeof(S) * N]; // expected-note {{'buffer1' initialized here}}
+  ::new (buffer1) S[N];// expected-warning{{Storage provided to placement new is only 64 bytes, whereas the allocated array type requires more space for internal needs}} expected-note 1 {{}}
+}
+
+void f2() {
+  struct S {
+short a;
+  };
+
+  // maybe ok but we need to warn.
+  const unsigned N = 32;
+  alignas(S) unsigned char buffer2[sizeof(S) * N + sizeof(int)]; // expected-note {{'buffer2' initialized here}}
+  ::new (buffer2) S[N];  // expected-warning{{Possibly not enough 68 bytes for array allocation which requires 64 bytes. Current overhead requires the size of 4 bytes}} expected-note 1 {{}}
+}
+} // namespace testArrayTypesAllocation
+
+namespace testStructAlign {
+void f1() {
+  struct X {
+char a[9];
+  } Xi; // expected-note {{'Xi' initialized here}}
+
+  // bad (struct X is aligned to char).
+  ::new (&Xi.a) long; // expected-warning{{Storage type is aligned to 1 bytes but allocated type is aligned to 8 bytes}} expected-note 1 {{}}
+}
+
+void f2() {
+  struct X {
+char a;
+char b;
+long c;
+  } Xi;
+
+  // ok (struct X is aligned to long).
+  ::new (&Xi.a) long;
+}
+
+void f3() {
+  struct X {
+char a;
+char b;
+long c;
+  } Xi; // expected-note {{'Xi' initialized here}}
+
+  // bad (struct X is aligned to long but field 'b' is aligned to 1 because of its offset)
+  ::new (&Xi.b) long; // expected-warning{{Storage type is aligned to 1 bytes but allocated type is aligned to 8 bytes}} expected-note 1 {{}}
+}
+
+void f4() {
+  struct X {
+char a;
+struct alignas(alignof(short)) Y {
+  char b;
+  char c;
+} y;
+long d;
+  } Xi; // expected-note {{'Xi' initialized here}}
+
+  // bad. 'b' is aligned to short
+  ::new (&Xi.y.b) long; // expected-warning{{Storage type is aligned to 2 bytes but allocated type is aligned to 8 bytes}} expected-note 1 {{}}
+}
+
+void f5() {
+  short b[10]; // expected-note {{'b' initialized here}}
+
+  ::new (&b) long; // expected-warning{{Storage type is aligned to 2 bytes but allocated type is aligned to 8 bytes}} expected-note 1 {{}}
+}
+
+void f6() {
+  short b[10]; // expected-note {{'b' initialized here}}
+
+  // bad (same as previous but checks ElementRegion case)
+  ::new (&b[0]) long; // expected-warning{{Storage type is aligned to 2 bytes but allocated type is aligned to 8 bytes}} expected-note 1 {{}}
+}
+
+void f7() {
+  short b[10];
+
+  // ok. 2(short align) + 3*2(index '1' offset)
+  ::new (&b[3]) long;
+}
+
+void f8() {
+  short b[10]; // expected-note {{'b' initialized here}}
+
+  // bad. 2(short align) + 2*2(index '2' offset)
+  ::new (&b[2]) long; // expected-warning{{Storage type is aligned to 6 bytes but allocated type is aligned to 8 bytes}} expected-note 1 {{}}
+}
+
+void f9() {
+  struct X {
+char a;
+alignas(alignof(short)) char b[20];
+  } Xi; // expected-note {{'Xi' initialized here}}
+
+  // ok 2(custom align) + 6(index '2' offset)
+  ::new (&Xi.b[6]) long;
+
+  // bad 2(custom align) + 1(index '2' offset)
+  ::new (&Xi.b[1]) long; // expected-warning{{Storage type is aligned to 3 bytes but allocated type is aligned to 8 bytes}} expected-note 1 {{}}
+}
+
+void f10() {
+  struct X {
+char a[8];
+alignas(2) char b;
+  } Xi; // expected-note {{'Xi' initialized here}}
+
+  // bad (struct X is aligned to 2).
+  ::new (&Xi.a) long; // expected-warning{{Storage type is aligned to 2 bytes but allocated type is aligned to 8 bytes}} expected-note 1 {{}}
+}
+
+void f11() {
+  struct X {
+char a;
+char b;
+struct Y {
+  long c;
+} d;
+  } Xi;
+
+  // ok (struct X is aligned to long).
+  ::new (&Xi.a) long;
+}
+
+void f12() {
+  struct alignas(alignof(long)) X {
+char a;
+char b;
+  } Xi;
+
+  // ok (struct X is aligned to long).
+  ::new (&Xi.a) lon

[clang] 81194bf - [Hexagon] MaxAtomicPromoteWidth and MaxAtomicInlineWidth are not getting set.

2020-03-30 Thread Sid Manning via cfe-commits

Author: Sid Manning
Date: 2020-03-30T12:33:51-05:00
New Revision: 81194bfeea7b40b6e8c543bb4ae49b59f590475b

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

LOG: [Hexagon] MaxAtomicPromoteWidth and MaxAtomicInlineWidth are not getting 
set.

Noticed when building llvm's c++ library.

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

Added: 


Modified: 
clang/lib/Basic/Targets/Hexagon.h
clang/test/Preprocessor/hexagon-predefines.c

Removed: 




diff  --git a/clang/lib/Basic/Targets/Hexagon.h 
b/clang/lib/Basic/Targets/Hexagon.h
index 89e3fa3fa6bf..7e173df81683 100644
--- a/clang/lib/Basic/Targets/Hexagon.h
+++ b/clang/lib/Basic/Targets/Hexagon.h
@@ -57,6 +57,7 @@ class LLVM_LIBRARY_VISIBILITY HexagonTargetInfo : public 
TargetInfo {
 LargeArrayAlign = 64;
 UseBitFieldTypeAlignment = true;
 ZeroLengthBitfieldBoundary = 32;
+MaxAtomicPromoteWidth = MaxAtomicInlineWidth = 64;
 
 // These are the default values anyway, but explicitly make sure
 // that the size of the boolean type is 8 bits. Bool vectors are used

diff  --git a/clang/test/Preprocessor/hexagon-predefines.c 
b/clang/test/Preprocessor/hexagon-predefines.c
index 54013ceffa64..7979d567134b 100644
--- a/clang/test/Preprocessor/hexagon-predefines.c
+++ b/clang/test/Preprocessor/hexagon-predefines.c
@@ -113,3 +113,18 @@
 // CHECK-LINUX: #define __unix__ 1
 // CHECK-LINUX: #define linux 1
 // CHECK-LINUX: #define unix 1
+
+// RUN: %clang_cc1 -E -dM -triple hexagon-unknown-linux-musl \
+// RUN: -target-cpu hexagonv67 -target-feature +hvxv67 \
+// RUN: -target-feature +hvx-length128b %s | FileCheck \
+// RUN: %s -check-prefix CHECK-ATOMIC
+// CHECK-ATOMIC: #define __CLANG_ATOMIC_BOOL_LOCK_FREE 2
+// CHECK-ATOMIC: #define __CLANG_ATOMIC_CHAR16_T_LOCK_FREE 2
+// CHECK-ATOMIC: #define __CLANG_ATOMIC_CHAR32_T_LOCK_FREE 2
+// CHECK-ATOMIC: #define __CLANG_ATOMIC_CHAR_LOCK_FREE 2
+// CHECK-ATOMIC: #define __CLANG_ATOMIC_INT_LOCK_FREE 2
+// CHECK-ATOMIC: #define __CLANG_ATOMIC_LLONG_LOCK_FREE 2
+// CHECK-ATOMIC: #define __CLANG_ATOMIC_LONG_LOCK_FREE 2
+// CHECK-ATOMIC: #define __CLANG_ATOMIC_POINTER_LOCK_FREE 2
+// CHECK-ATOMIC: #define __CLANG_ATOMIC_SHORT_LOCK_FREE 2
+// CHECK-ATOMIC: #define __CLANG_ATOMIC_WCHAR_T_LOCK_FREE 2



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


[clang] 7842e7e - [OPENMP50]Add codegen support for array shaping expression in depend

2020-03-30 Thread Alexey Bataev via cfe-commits

Author: Alexey Bataev
Date: 2020-03-30T13:37:21-04:00
New Revision: 7842e7ebbf3b68ebe52592d51aaf7a20f94d047b

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

LOG: [OPENMP50]Add codegen support for array shaping expression in depend
clauses.

Implemented codegen for array shaping operation in depend clauses. The
begin of the expression is the pointer itself, while the size of the
dependence data is the mukltiplacation of all dimensions in the array
shaping expression.

Added: 


Modified: 
clang/lib/CodeGen/CGOpenMPRuntime.cpp
clang/test/OpenMP/depobj_ast_print.cpp
clang/test/OpenMP/depobj_codegen.cpp
clang/test/OpenMP/task_codegen.c

Removed: 




diff  --git a/clang/lib/CodeGen/CGOpenMPRuntime.cpp 
b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
index 1bb001ced31a..4b913607c1db 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntime.cpp
+++ b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
@@ -5363,11 +5363,29 @@ std::pair 
CGOpenMPRuntime::emitDependClause(
   if (Dependencies[I].first == OMPC_DEPEND_depobj)
 continue;
   const Expr *E = Dependencies[I].second;
-  LValue Addr = CGF.EmitLValue(E);
+  const auto *OASE = dyn_cast(E);
+  LValue Addr;
+  if (OASE) {
+const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
+Addr =
+CGF.EmitLoadOfPointerLValue(CGF.EmitLValue(Base).getAddress(CGF),
+
Base->getType()->castAs());
+  } else {
+Addr = CGF.EmitLValue(E);
+  }
   llvm::Value *Size;
   QualType Ty = E->getType();
-  if (const auto *ASE =
-  dyn_cast(E->IgnoreParenImpCasts())) {
+  if (OASE) {
+Size = llvm::ConstantInt::get(CGF.SizeTy,/*V=*/1);
+for (const Expr *SE : OASE->getDimensions()) {
+   llvm::Value *Sz = CGF.EmitScalarExpr(SE);
+   Sz = CGF.EmitScalarConversion(Sz, SE->getType(),
+CGF.getContext().getSizeType(),
+SE->getExprLoc());
+   Size = CGF.Builder.CreateNUWMul(Size, Sz);
+}
+  } else if (const auto *ASE =
+ dyn_cast(E->IgnoreParenImpCasts())) {
 LValue UpAddrLVal =
 CGF.EmitOMPArraySectionExpr(ASE, /*IsLowerBound=*/false);
 llvm::Value *UpAddr = CGF.Builder.CreateConstGEP1_32(

diff  --git a/clang/test/OpenMP/depobj_ast_print.cpp 
b/clang/test/OpenMP/depobj_ast_print.cpp
index 8b6586ca2b26..f3076646a25e 100644
--- a/clang/test/OpenMP/depobj_ast_print.cpp
+++ b/clang/test/OpenMP/depobj_ast_print.cpp
@@ -17,17 +17,20 @@ void foo() {}
 template 
 T tmain(T argc) {
   static T a;
-#pragma omp depobj(a) depend(in:argc)
+  int *b;
+#pragma omp depobj(a) depend(in:argc, ([4][*b][4])b)
 #pragma omp depobj(argc) destroy
 #pragma omp depobj(argc) update(inout)
   return argc;
 }
 // CHECK:  static T a;
-// CHECK-NEXT: #pragma omp depobj (a) depend(in : argc){{$}}
+// CHECK-NEXT: int *b;
+// CHECK-NEXT: #pragma omp depobj (a) depend(in : argc,([4][*b][4])b){{$}}
 // CHECK-NEXT: #pragma omp depobj (argc) destroy{{$}}
 // CHECK-NEXT: #pragma omp depobj (argc) update(inout){{$}}
 // CHECK:  static void *a;
-// CHECK-NEXT: #pragma omp depobj (a) depend(in : argc){{$}}
+// CHECK-NEXT: int *b;
+// CHECK-NEXT: #pragma omp depobj (a) depend(in : argc,([4][*b][4])b){{$}}
 // CHECK-NEXT: #pragma omp depobj (argc) destroy{{$}}
 // CHECK-NEXT: #pragma omp depobj (argc) update(inout){{$}}
 

diff  --git a/clang/test/OpenMP/depobj_codegen.cpp 
b/clang/test/OpenMP/depobj_codegen.cpp
index 61b97d0b8479..2c7509babc17 100644
--- a/clang/test/OpenMP/depobj_codegen.cpp
+++ b/clang/test/OpenMP/depobj_codegen.cpp
@@ -22,7 +22,7 @@ template 
 T tmain(T argc) {
   static T a;
   void *argv;
-#pragma omp depobj(a) depend(in:argv)
+#pragma omp depobj(a) depend(in:argv, ([3][*(int*)argv][4])argv)
 #pragma omp depobj(argc) destroy
 #pragma omp depobj(argc) update(inout)
   return argc;
@@ -87,19 +87,30 @@ int main(int argc, char **argv) {
 // CHECK-LABEL: tmain
 // CHECK: [[ARGC_ADDR:%.+]] = alloca i8*,
 // CHECK: [[GTID:%.+]] = call i32 @__kmpc_global_thread_num(
-// CHECK: [[DEP_ADDR_VOID:%.+]] = call i8* @__kmpc_alloc(i32 [[GTID]], i64 48, 
i8* null)
-// CHECK: [[DEP_ADDR:%.+]] = bitcast i8* [[DEP_ADDR_VOID]] to [2 x 
%struct.kmp_depend_info]*
-// CHECK: [[BASE_ADDR:%.+]] = getelementptr inbounds [2 x 
%struct.kmp_depend_info], [2 x %struct.kmp_depend_info]* [[DEP_ADDR]], i{{.+}} 
0, i{{.+}} 0
+// CHECK: [[DEP_ADDR_VOID:%.+]] = call i8* @__kmpc_alloc(i32 [[GTID]], i64 72, 
i8* null)
+// CHECK: [[DEP_ADDR:%.+]] = bitcast i8* [[DEP_ADDR_VOID]] to [3 x 
%struct.kmp_depend_info]*
+// CHECK: [[BASE_ADDR:%.+]] = getelementptr inbounds [3 x 
%struct.kmp_depend_info], [3 x %struct.kmp_depend_inf

[PATCH] D77056: RFC: [Sema][SVE] Allow non-member operators for SVE types

2020-03-30 Thread Eli Friedman via Phabricator via cfe-commits
efriedma added a comment.

I'm concerned we're going to run into trouble if two people define different 
SVE "libraries", and you try to link both of them into the same program.  If 
you're not careful, you end up with ODR violations.  The scope of this is sort 
of restricted in normal C++: class and enumerated types sort of have an 
informal "owner", and people tend to respect that.  I mean, you could say it's 
the user's own fault if they break ODR, but we're essentially making a trap 
here.  Maybe it would make sense to require that SVE operators are defined in a 
namespace?  That would make the user think about the issue.

We're also basically committing to never building these operators into the 
compiler, for all sizeless types for all targets.

It would probably make sense to send this to cfe-dev, to get more perspectives 
on the language change.




Comment at: clang/include/clang/AST/Type.h:6833
 inline bool Type::isOverloadableType() const {
-  return isDependentType() || isRecordType() || isEnumeralType();
+  return (isDependentType() || isRecordType() || isEnumeralType() ||
+  isSizelessBuiltinType());

Unnecessary parentheses



Comment at: clang/test/SemaCXX/sizeless-1.cpp:659
+svint8_t &operator--(svint8_t &, int);
+int operator,(svint8_t, svint8_t);
+

Need some testcases with template operators.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D77056



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


[PATCH] D68165: [analyzer][MallocChecker][NFC] Split checkPostCall up, deploy CallDescriptionMap

2020-03-30 Thread Kristóf Umann via Phabricator via cfe-commits
Szelethus added a comment.

In D68165#1949954 , @ldionne wrote:

> > Closed by commit rG703a1b8caf09 
> > : 
> > [analyzer][MallocChecker][NFC] Split checkPostCall up, deploy 
> > CallDescriptionMap (authored by ldionne, committed by Szelethus). · Explain 
> > Why
>
> This is really strange -- it looks like 703a1b8caf09 
>  was 
> attributed to me in git, but I have nothing to do with this change. How did 
> you commit the patch? Is that some Phabricator bug?


Ugh, I squashed my local commits and pushed, it seems like for some reason it 
made you the author... it has happened to me before (always with you, for some 
reason), but was able to notice and correct it. There is little we can do about 
this, right?

In D68165#1950212 , @NoQ wrote:

> Not a phabricator bug. Maybe @Szelethus's local git somehow got in a weird 
> state(?)


Its been a source of endless misery :)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68165



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


[PATCH] D76987: Rename options --cuda-gpu-arch and --no-cuda-gpu-arch

2020-03-30 Thread Greg Rodgers via Phabricator via cfe-commits
gregrodgers added a comment.

This was discussed on llvm-dev three years ago.  Here is the thread.

http://lists.llvm.org/pipermail/llvm-dev/2017-February/109930.html

The last name discussed was "-- offload-arch".   I don't believe we need a list 
option anymore.   So ignore the very old request for --offload-archs.

I am ok with the patch the way it is.   In the future, we should consider 
renaming the CudaArch class to OffloadArch class .  Also the GpuArchList is 
currently only initialized in CudaActionBuilder.   Eventually this is will have 
to be done for HIPActionBuilder and OpenMPActionBuilder.   Could you consider 
creating a function to  InitializeGpuArchList ?


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

https://reviews.llvm.org/D76987



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


[PATCH] D76546: [Hexagon] MaxAtomicPromoteWidth, MaxAtomicInlineWidth are not getting set.

2020-03-30 Thread Sid Manning via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG81194bfeea7b: [Hexagon] MaxAtomicPromoteWidth and 
MaxAtomicInlineWidth are not getting set. (authored by sidneym).

Changed prior to commit:
  https://reviews.llvm.org/D76546?vs=251896&id=253640#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76546

Files:
  clang/lib/Basic/Targets/Hexagon.h
  clang/test/Preprocessor/hexagon-predefines.c


Index: clang/test/Preprocessor/hexagon-predefines.c
===
--- clang/test/Preprocessor/hexagon-predefines.c
+++ clang/test/Preprocessor/hexagon-predefines.c
@@ -113,3 +113,18 @@
 // CHECK-LINUX: #define __unix__ 1
 // CHECK-LINUX: #define linux 1
 // CHECK-LINUX: #define unix 1
+
+// RUN: %clang_cc1 -E -dM -triple hexagon-unknown-linux-musl \
+// RUN: -target-cpu hexagonv67 -target-feature +hvxv67 \
+// RUN: -target-feature +hvx-length128b %s | FileCheck \
+// RUN: %s -check-prefix CHECK-ATOMIC
+// CHECK-ATOMIC: #define __CLANG_ATOMIC_BOOL_LOCK_FREE 2
+// CHECK-ATOMIC: #define __CLANG_ATOMIC_CHAR16_T_LOCK_FREE 2
+// CHECK-ATOMIC: #define __CLANG_ATOMIC_CHAR32_T_LOCK_FREE 2
+// CHECK-ATOMIC: #define __CLANG_ATOMIC_CHAR_LOCK_FREE 2
+// CHECK-ATOMIC: #define __CLANG_ATOMIC_INT_LOCK_FREE 2
+// CHECK-ATOMIC: #define __CLANG_ATOMIC_LLONG_LOCK_FREE 2
+// CHECK-ATOMIC: #define __CLANG_ATOMIC_LONG_LOCK_FREE 2
+// CHECK-ATOMIC: #define __CLANG_ATOMIC_POINTER_LOCK_FREE 2
+// CHECK-ATOMIC: #define __CLANG_ATOMIC_SHORT_LOCK_FREE 2
+// CHECK-ATOMIC: #define __CLANG_ATOMIC_WCHAR_T_LOCK_FREE 2
Index: clang/lib/Basic/Targets/Hexagon.h
===
--- clang/lib/Basic/Targets/Hexagon.h
+++ clang/lib/Basic/Targets/Hexagon.h
@@ -57,6 +57,7 @@
 LargeArrayAlign = 64;
 UseBitFieldTypeAlignment = true;
 ZeroLengthBitfieldBoundary = 32;
+MaxAtomicPromoteWidth = MaxAtomicInlineWidth = 64;
 
 // These are the default values anyway, but explicitly make sure
 // that the size of the boolean type is 8 bits. Bool vectors are used


Index: clang/test/Preprocessor/hexagon-predefines.c
===
--- clang/test/Preprocessor/hexagon-predefines.c
+++ clang/test/Preprocessor/hexagon-predefines.c
@@ -113,3 +113,18 @@
 // CHECK-LINUX: #define __unix__ 1
 // CHECK-LINUX: #define linux 1
 // CHECK-LINUX: #define unix 1
+
+// RUN: %clang_cc1 -E -dM -triple hexagon-unknown-linux-musl \
+// RUN: -target-cpu hexagonv67 -target-feature +hvxv67 \
+// RUN: -target-feature +hvx-length128b %s | FileCheck \
+// RUN: %s -check-prefix CHECK-ATOMIC
+// CHECK-ATOMIC: #define __CLANG_ATOMIC_BOOL_LOCK_FREE 2
+// CHECK-ATOMIC: #define __CLANG_ATOMIC_CHAR16_T_LOCK_FREE 2
+// CHECK-ATOMIC: #define __CLANG_ATOMIC_CHAR32_T_LOCK_FREE 2
+// CHECK-ATOMIC: #define __CLANG_ATOMIC_CHAR_LOCK_FREE 2
+// CHECK-ATOMIC: #define __CLANG_ATOMIC_INT_LOCK_FREE 2
+// CHECK-ATOMIC: #define __CLANG_ATOMIC_LLONG_LOCK_FREE 2
+// CHECK-ATOMIC: #define __CLANG_ATOMIC_LONG_LOCK_FREE 2
+// CHECK-ATOMIC: #define __CLANG_ATOMIC_POINTER_LOCK_FREE 2
+// CHECK-ATOMIC: #define __CLANG_ATOMIC_SHORT_LOCK_FREE 2
+// CHECK-ATOMIC: #define __CLANG_ATOMIC_WCHAR_T_LOCK_FREE 2
Index: clang/lib/Basic/Targets/Hexagon.h
===
--- clang/lib/Basic/Targets/Hexagon.h
+++ clang/lib/Basic/Targets/Hexagon.h
@@ -57,6 +57,7 @@
 LargeArrayAlign = 64;
 UseBitFieldTypeAlignment = true;
 ZeroLengthBitfieldBoundary = 32;
+MaxAtomicPromoteWidth = MaxAtomicInlineWidth = 64;
 
 // These are the default values anyway, but explicitly make sure
 // that the size of the boolean type is 8 bits. Bool vectors are used
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] c506adc - Move CLANG_SYSTEMZ_DEFAULT_ARCH to config.h.

2020-03-30 Thread Nico Weber via cfe-commits

Author: Nico Weber
Date: 2020-03-30T14:16:17-04:00
New Revision: c506adcdf2ca3ba6459e52e09c55868e3b57af46

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

LOG: Move CLANG_SYSTEMZ_DEFAULT_ARCH to config.h.

Instead of using a global define; see comments on D75914.

While here, port 9c9d88d8b1b to the GN build.

Added: 


Modified: 
clang/CMakeLists.txt
clang/include/clang/Config/config.h.cmake
clang/lib/Driver/ToolChains/Arch/SystemZ.cpp
llvm/utils/gn/secondary/clang/include/clang/Config/BUILD.gn

Removed: 




diff  --git a/clang/CMakeLists.txt b/clang/CMakeLists.txt
index c9e76c5e4518..88e556fd88a0 100644
--- a/clang/CMakeLists.txt
+++ b/clang/CMakeLists.txt
@@ -306,9 +306,7 @@ if (NOT DEFINED MATCHED_ARCH OR "${CMAKE_MATCH_1}" LESS 35)
 "Default architecture for OpenMP offloading to Nvidia GPUs." FORCE)
 endif()
 
-set(CLANG_SYSTEMZ_DEFAULT_ARCH "z10" CACHE STRING
-  "SystemZ Default Arch")
-add_definitions( -DCLANG_SYSTEMZ_DEFAULT_ARCH="${CLANG_SYSTEMZ_DEFAULT_ARCH}")
+set(CLANG_SYSTEMZ_DEFAULT_ARCH "z10" CACHE STRING "SystemZ Default Arch")
 
 set(CLANG_VENDOR ${PACKAGE_VENDOR} CACHE STRING
   "Vendor-specific text for showing with version information.")

diff  --git a/clang/include/clang/Config/config.h.cmake 
b/clang/include/clang/Config/config.h.cmake
index 261b3841b86f..a0f8b6b1b0da 100644
--- a/clang/include/clang/Config/config.h.cmake
+++ b/clang/include/clang/Config/config.h.cmake
@@ -83,4 +83,7 @@
 /* Spawn a new process clang.exe for the CC1 tool invocation, when necessary */
 #cmakedefine01 CLANG_SPAWN_CC1
 
+/* Default  to all compiler invocations for --sysroot=. */
+#define CLANG_SYSTEMZ_DEFAULT_ARCH "${CLANG_SYSTEMZ_DEFAULT_ARCH}"
+
 #endif

diff  --git a/clang/lib/Driver/ToolChains/Arch/SystemZ.cpp 
b/clang/lib/Driver/ToolChains/Arch/SystemZ.cpp
index b263fb7df09e..f81bf68172de 100644
--- a/clang/lib/Driver/ToolChains/Arch/SystemZ.cpp
+++ b/clang/lib/Driver/ToolChains/Arch/SystemZ.cpp
@@ -7,6 +7,7 @@
 
//===--===//
 
 #include "SystemZ.h"
+#include "clang/Config/config.h"
 #include "clang/Driver/DriverDiagnostic.h"
 #include "clang/Driver/Options.h"
 #include "llvm/Option/ArgList.h"

diff  --git a/llvm/utils/gn/secondary/clang/include/clang/Config/BUILD.gn 
b/llvm/utils/gn/secondary/clang/include/clang/Config/BUILD.gn
index cc2c4e19ad49..7fbfb46a41c5 100644
--- a/llvm/utils/gn/secondary/clang/include/clang/Config/BUILD.gn
+++ b/llvm/utils/gn/secondary/clang/include/clang/Config/BUILD.gn
@@ -36,6 +36,7 @@ write_cmake_config("Config") {
 "ENABLE_X86_RELAX_RELOCATIONS=",
 "ENABLE_EXPERIMENTAL_NEW_PASS_MANAGER=",
 "CLANG_ENABLE_OBJC_REWRITER=1",  # FIXME: flag?
+"CLANG_SYSTEMZ_DEFAULT_ARCH=z10",
   ]
 
   if (clang_enable_arcmt) {



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


[PATCH] D77022: [analyzer] Use IgnoreImpCasts() instead of reimplementing it.

2020-03-30 Thread Nico Weber via Phabricator via cfe-commits
thakis marked an inline comment as done.
thakis added inline comments.



Comment at: clang/lib/StaticAnalyzer/Checkers/NullabilityChecker.cpp:512
+  return E->IgnoreImpCasts();
 }
 

NoQ wrote:
> Charusso wrote:
> > I think it would make sense to remove the helper-function completely. 
> > (Being used 2 times.)
> Yup.
I didn't do that because I liked the comment that this is for the _Nonnull 
implicit ARC casts – if I inline the function I have to duplicate the comment.


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

https://reviews.llvm.org/D77022



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


[PATCH] D75914: systemz: allow configuring default CLANG_SYSTEMZ_ARCH

2020-03-30 Thread Nico Weber via Phabricator via cfe-commits
thakis added inline comments.



Comment at: clang/CMakeLists.txt:311
+  "SystemZ Default Arch")
+add_definitions( -DCLANG_SYSTEMZ_DEFAULT_ARCH="${CLANG_SYSTEMZ_DEFAULT_ARCH}")
+

Hahnfeld wrote:
> Passing values like this is unusual for CMake and causes all source files to 
> be recompiled if the value is changed. Instead could we add this to 
> `include/clang/Config/config.h.cmake` like other `CLANG_DEFAULT_*` options?
+1


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D75914



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


[PATCH] D76996: [analyzer] Improve PlacementNewChecker

2020-03-30 Thread Karasev Nikita via Phabricator via cfe-commits
f00kat updated this revision to Diff 253642.
f00kat marked an inline comment as done.
f00kat added a comment.

test fix


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76996

Files:
  clang/lib/StaticAnalyzer/Checkers/CheckPlacementNew.cpp
  clang/test/Analysis/placement-new.cpp

Index: clang/test/Analysis/placement-new.cpp
===
--- clang/test/Analysis/placement-new.cpp
+++ clang/test/Analysis/placement-new.cpp
@@ -155,3 +155,147 @@
   (void)dp;
 }
 } // namespace testHierarchy
+
+namespace testArrayTypesAllocation {
+void f1() {
+  struct S {
+short a;
+  };
+
+  // bad (not enough space).
+  const unsigned N = 32;
+  alignas(S) unsigned char buffer1[sizeof(S) * N]; // expected-note {{'buffer1' initialized here}}
+  ::new (buffer1) S[N];// expected-warning{{Storage provided to placement new is only 64 bytes, whereas the allocated array type requires more space for internal needs}} expected-note 1 {{}}
+}
+
+void f2() {
+  struct S {
+short a;
+  };
+
+  // maybe ok but we need to warn.
+  const unsigned N = 32;
+  alignas(S) unsigned char buffer2[sizeof(S) * N + sizeof(int)]; // expected-note {{'buffer2' initialized here}}
+  ::new (buffer2) S[N];  // expected-warning{{68 bytes is possibly not enough for array allocation which requires 64 bytes. Current overhead requires the size of 4 bytes}} expected-note 1 {{}}
+}
+} // namespace testArrayTypesAllocation
+
+namespace testStructAlign {
+void f1() {
+  struct X {
+char a[9];
+  } Xi; // expected-note {{'Xi' initialized here}}
+
+  // bad (struct X is aligned to char).
+  ::new (&Xi.a) long; // expected-warning{{Storage type is aligned to 1 bytes but allocated type is aligned to 8 bytes}} expected-note 1 {{}}
+}
+
+void f2() {
+  struct X {
+char a;
+char b;
+long c;
+  } Xi;
+
+  // ok (struct X is aligned to long).
+  ::new (&Xi.a) long;
+}
+
+void f3() {
+  struct X {
+char a;
+char b;
+long c;
+  } Xi; // expected-note {{'Xi' initialized here}}
+
+  // bad (struct X is aligned to long but field 'b' is aligned to 1 because of its offset)
+  ::new (&Xi.b) long; // expected-warning{{Storage type is aligned to 1 bytes but allocated type is aligned to 8 bytes}} expected-note 1 {{}}
+}
+
+void f4() {
+  struct X {
+char a;
+struct alignas(alignof(short)) Y {
+  char b;
+  char c;
+} y;
+long d;
+  } Xi; // expected-note {{'Xi' initialized here}}
+
+  // bad. 'b' is aligned to short
+  ::new (&Xi.y.b) long; // expected-warning{{Storage type is aligned to 2 bytes but allocated type is aligned to 8 bytes}} expected-note 1 {{}}
+}
+
+void f5() {
+  short b[10]; // expected-note {{'b' initialized here}}
+
+  ::new (&b) long; // expected-warning{{Storage type is aligned to 2 bytes but allocated type is aligned to 8 bytes}} expected-note 1 {{}}
+}
+
+void f6() {
+  short b[10]; // expected-note {{'b' initialized here}}
+
+  // bad (same as previous but checks ElementRegion case)
+  ::new (&b[0]) long; // expected-warning{{Storage type is aligned to 2 bytes but allocated type is aligned to 8 bytes}} expected-note 1 {{}}
+}
+
+void f7() {
+  short b[10];
+
+  // ok. 2(short align) + 3*2(index '1' offset)
+  ::new (&b[3]) long;
+}
+
+void f8() {
+  short b[10]; // expected-note {{'b' initialized here}}
+
+  // bad. 2(short align) + 2*2(index '2' offset)
+  ::new (&b[2]) long; // expected-warning{{Storage type is aligned to 6 bytes but allocated type is aligned to 8 bytes}} expected-note 1 {{}}
+}
+
+void f9() {
+  struct X {
+char a;
+alignas(alignof(short)) char b[20];
+  } Xi; // expected-note {{'Xi' initialized here}}
+
+  // ok 2(custom align) + 6(index '2' offset)
+  ::new (&Xi.b[6]) long;
+
+  // bad 2(custom align) + 1(index '2' offset)
+  ::new (&Xi.b[1]) long; // expected-warning{{Storage type is aligned to 3 bytes but allocated type is aligned to 8 bytes}} expected-note 1 {{}}
+}
+
+void f10() {
+  struct X {
+char a[8];
+alignas(2) char b;
+  } Xi; // expected-note {{'Xi' initialized here}}
+
+  // bad (struct X is aligned to 2).
+  ::new (&Xi.a) long; // expected-warning{{Storage type is aligned to 2 bytes but allocated type is aligned to 8 bytes}} expected-note 1 {{}}
+}
+
+void f11() {
+  struct X {
+char a;
+char b;
+struct Y {
+  long c;
+} d;
+  } Xi;
+
+  // ok (struct X is aligned to long).
+  ::new (&Xi.a) long;
+}
+
+void f12() {
+  struct alignas(alignof(long)) X {
+char a;
+char b;
+  } Xi;
+
+  // ok (struct X is aligned to long).
+  ::new (&Xi.a) long;
+}
+} // namespace testStructAlign
Index: clang/lib/StaticAnalyzer/Checkers/CheckPlacementNew.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/CheckPlacementNew.cpp
+++ clang/lib/StaticAnalyzer/Checkers/CheckPlacementNew.

[PATCH] D76932: [AIX] emit .extern and .weak directive linkage

2020-03-30 Thread Hubert Tong via Phabricator via cfe-commits
hubert.reinterpretcast added inline comments.



Comment at: llvm/include/llvm/MC/MCDirectives.h:47
+  MCSA_WeakReference,   ///< .weak_reference (MachO)
+  MCSA_WeakDefAutoPrivate   ///< .weak_def_can_be_hidden (MachO)
 };

DiggerLin wrote:
> @hubert.reinterpretcast , @jasonliu , do we need to create a NFC patch for 
> the clang format problem of the above first ?
I think it would help; yes. Please drop one at your earliest convenience and 
then rebase this patch on top of it.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76932



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


[PATCH] D75914: systemz: allow configuring default CLANG_SYSTEMZ_ARCH

2020-03-30 Thread Nico Weber via Phabricator via cfe-commits
thakis added inline comments.



Comment at: clang/CMakeLists.txt:311
+  "SystemZ Default Arch")
+add_definitions( -DCLANG_SYSTEMZ_DEFAULT_ARCH="${CLANG_SYSTEMZ_DEFAULT_ARCH}")
+

thakis wrote:
> thakis wrote:
> > Hahnfeld wrote:
> > > Passing values like this is unusual for CMake and causes all source files 
> > > to be recompiled if the value is changed. Instead could we add this to 
> > > `include/clang/Config/config.h.cmake` like other `CLANG_DEFAULT_*` 
> > > options?
> > +1
> Also, this is used in one cpp file; passing the define to every compilation 
> unit seems a bit aggressive.
> 
> I'll try to land a patch to fix this.
Done in c506adcdf2ca3ba6459e52e09c55868e3b57af46. (This only changes the 
implementation of the feature; the way people who build clang tell cmake what 
they want didn't change.)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D75914



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


[PATCH] D75914: systemz: allow configuring default CLANG_SYSTEMZ_ARCH

2020-03-30 Thread Nico Weber via Phabricator via cfe-commits
thakis added inline comments.



Comment at: clang/CMakeLists.txt:311
+  "SystemZ Default Arch")
+add_definitions( -DCLANG_SYSTEMZ_DEFAULT_ARCH="${CLANG_SYSTEMZ_DEFAULT_ARCH}")
+

thakis wrote:
> Hahnfeld wrote:
> > Passing values like this is unusual for CMake and causes all source files 
> > to be recompiled if the value is changed. Instead could we add this to 
> > `include/clang/Config/config.h.cmake` like other `CLANG_DEFAULT_*` options?
> +1
Also, this is used in one cpp file; passing the define to every compilation 
unit seems a bit aggressive.

I'll try to land a patch to fix this.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D75914



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


[PATCH] D76140: [InlineFunction] update attributes during inlining

2020-03-30 Thread Philip Reames via Phabricator via cfe-commits
reames accepted this revision.
reames added a comment.
This revision is now accepted and ready to land.

LGTM, but with two specific required follow ups.  If you're not comfortable 
committing to both, please don't land this one.




Comment at: llvm/lib/Transforms/Utils/InlineFunction.cpp:93
+static cl::opt MaxInstCheckedForThrow(
+"max-inst-checked-for-throw-during-inlining", cl::Hidden,
+cl::desc("the maximum number of instructions analyzed for may throw during 
"

I'd suggest a name change here.  Maybe: "inliner-attribute-window"?



Comment at: llvm/lib/Transforms/Utils/InlineFunction.cpp:1159
+
+  auto MayContainThrowingOrExitingCall = [&](Instruction *RVal,
+ Instruction *RInst) {

Pull this out as a static helper instead of a lambda, add an assert internally 
that the two instructions are in the same block.  

Why?  Because I'm 80% sure the state capture on the lambda isn't needed, and 
having it as a separate function forces that discipline.  



Comment at: llvm/lib/Transforms/Utils/InlineFunction.cpp:1175
+  continue;
+// Sanity check that the cloned return instruction exists and is a return
+// instruction itself.

Ok, after staring at it a bit, I've convinced myself the code here is correct, 
just needlessly conservative.

What you're doing is:
If the callees return instruction and returned call both map to the same 
instructions once inlined, determine whether there's a possible exit between 
the inlined copy.

What you could be doing:
If the callee returns a call, check if *in the callee* there's a possible exit 
between call and return, then apply attribute to cloned call.

The key difference is when the caller directly returns the result vs uses it 
locally.  The result here is that your transform is much more narrow in 
applicability than it first appears.



Comment at: llvm/test/Transforms/Inline/ret_attr_update.ll:112
+  ret i8* %s
+}

There's a critical missing test case here:
- Callee and caller have the same attributes w/different values (i.e. deref)

And thinking through the code, I think there might be a bug here.  It's not a 
serious one, but the if the callee specifies a larger deref than the caller, it 
looks like the the smaller value is being written over the larger.

Actually, digging through the attribute code, I think I'm wrong about the bug.  
However, you should definitely write the test to confirm and document merging 
behaviour!

If it does turn out I'm correct, I'm fine with this being addressed in a follow 
up patch provided that the test is added in this one and isn't a functional 
issue.  


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76140



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


  1   2   >