[PATCH] D79800: [Sema] Implement DR2233

2020-05-25 Thread Raul Tambre via Phabricator via cfe-commits
tambre updated this revision to Diff 265855.
tambre marked an inline comment as done.
tambre added a comment.

Improve comment


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79800

Files:
  clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
  clang/test/CXX/drs/dr22xx.cpp
  clang/test/CXX/drs/dr7xx.cpp
  clang/www/cxx_dr_status.html

Index: clang/www/cxx_dr_status.html
===
--- clang/www/cxx_dr_status.html
+++ clang/www/cxx_dr_status.html
@@ -4681,7 +4681,7 @@
 https://wg21.link/cwg777";>777
 CD2
 Default arguments and parameter packs
-Clang 3.7
+Superseded by 2233
   
   
 https://wg21.link/cwg778";>778
@@ -13213,7 +13213,7 @@
 https://wg21.link/cwg2233";>2233
 DRWP
 Function parameter packs following default arguments
-Unknown
+Clang 11
   
   
 https://wg21.link/cwg2234";>2234
Index: clang/test/CXX/drs/dr7xx.cpp
===
--- clang/test/CXX/drs/dr7xx.cpp
+++ clang/test/CXX/drs/dr7xx.cpp
@@ -219,16 +219,4 @@
   Collision c; // expected-note {{in instantiation of}}
 }
 
-namespace dr777 { // dr777: 3.7
-#if __cplusplus >= 201103L
-template 
-void f(int i = 0, T ...args) {}
-void ff() { f(); }
-
-template 
-void g(int i = 0, T ...args, T ...args2) {}
-
-template 
-void h(int i = 0, T ...args, int j = 1) {}
-#endif
-}
+// dr777 superseded by dr2233
Index: clang/test/CXX/drs/dr22xx.cpp
===
--- clang/test/CXX/drs/dr22xx.cpp
+++ clang/test/CXX/drs/dr22xx.cpp
@@ -35,3 +35,44 @@
   }
 #endif
 }
+
+namespace dr2233 { // dr2233: 11
+#if __cplusplus >= 201103L
+template 
+void f(int i = 0, T... args) {}
+
+template 
+void g(int i = 0, T... args, T... args2) {}
+
+template 
+void h(int i = 0, T... args, int j = 1) {}
+
+template 
+void i(int i = 0, T... args, int j = 1, U... args2) {}
+
+template 
+void j(int i = 0, Ts... ts) {}
+
+template <>
+void j(int i, int j) {}
+
+// PR23029
+// Ensure instantiating the templates works.
+void use() {
+  f();
+  f(0, 1);
+  f(1, 2);
+  g(1, 2, 3);
+  h(0, 1);
+  i();
+  i(3);
+  i(3, 2);
+  i(3, 2, 1);
+  i(1, 2, 3, 4, 5);
+  j();
+  j(1);
+  j(1, 2);
+  j(1, 2);
+}
+#endif
+} // namespace dr2233
Index: clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
===
--- clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
+++ clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
@@ -1974,6 +1974,48 @@
 TemplateArgumentList::CreateCopy(SemaRef.Context,
  Innermost),
 /*InsertPos=*/nullptr);
+
+// DR777, DR2233.
+// Parameter packs are allowed after and inbetween parameters with default
+// values. We need to remove default arguments for parameters before the
+// first expanded parameter pack to prevent the declaration being diagnosed
+// as invalid due to the expanded parameters after parameters with default
+// values lacking default values. This is safe to do because if a parameter
+// pack is expanded the user must've provided arguments for all parameters
+// before it.
+FunctionDecl *TemplatedDecl = FunctionTemplate->getTemplatedDecl();
+unsigned FirstPack = Function->getNumParams();
+bool RemoveDefaults = false;
+
+// Go backwards through the template declaration parameters and find the
+// first parameter pack, which has non-zero number of arguments.
+for (unsigned p = TemplatedDecl->getNumParams(); p-- > 0;) {
+  ParmVarDecl *Param = TemplatedDecl->getParamDecl(p);
+
+  if (Param->isParameterPack()) {
+llvm::Optional Args =
+SemaRef.getNumArgumentsInExpansion(Param->getType(), TemplateArgs);
+assert(Args != None && "Unknown number of pack expansion arguments.");
+
+if (Args.getValue() == 0)
+  continue;
+
+FirstPack -= Args.getValue();
+RemoveDefaults = true;
+break;
+  } else {
+FirstPack--;
+  }
+}
+
+// If we found such a parameter pack, then remove default arguments for all
+// parameters before it.
+if (RemoveDefaults) {
+  for (unsigned p = 0; p < FirstPack; p++) {
+ParmVarDecl *Param = Function->getParamDecl(p);
+Param->setDefaultArg(nullptr);
+  }
+}
   } else if (isFriend && D->isThisDeclarationADefinition()) {
 // Do not connect the friend to the template unless it's actually a
 // definition. We don't want non-template functions to be marked as being
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D79800: [Sema] Implement DR2233

2020-05-25 Thread Raul Tambre via Phabricator via cfe-commits
tambre added a comment.

Thanks for the reviews!
I believe this now handles all cases and with this we're standards-conforming 
in regard to DR777 and DR2233.




Comment at: clang/lib/Sema/SemaTemplateInstantiateDecl.cpp:1987
+
+if (Function->getNumParams() >= NumTemplatedParams) {
+  unsigned FirstDefault = 0;

rjmccall wrote:
> I don't think this simple comparison works; the relationship can be 
> complicated because there might be multiple packs in play.  By the same 
> token, I think it's possible that there can be multiple interleavings of 
> defaultable parameters with packs.  I think you need to scan backwards 
> looking for a parameter without a default argument that was instantiated from 
> a pack expansion and then remove any earlier parameters with defaults.
> 
> That is, assuming this is a reasonable implementation approach at all 
> compared to just teaching other parts of the compiler about this case, which 
> I think Richard needs to weigh in on.
Good point, my current change doesn't work in the following case:


```
template
void g(int i = 1, Ts... ts, int j = 3, As... as)
{
}

void testg()
{
g(2, 3, 4, 5);
}
```

Fixed and added that as a test case.

I think this approach is fine, as keeping info for each parameter for how they 
were expanded doesn't seem reasonable. Cases such as this ought to be checked 
and handled early during the actual template instantiation not during later 
checking of the instantiated function declaration.



Comment at: clang/test/CXX/drs/dr7xx.cpp:225
 template 
 void f(int i = 0, T ...args) {}
 void ff() { f(); }

Quuxplusone wrote:
> rjmccall wrote:
> > Quuxplusone wrote:
> > > Is this even supposed to compile? The only valid specializations of `f` 
> > > require `T...` to be an empty pack, which violates 
> > > [temp.res/8.3](https://timsong-cpp.github.io/cppwp/temp.res#8.3).
> > > 
> > > The comment mentions 
> > > [DR777](http://cwg-issue-browser.herokuapp.com/cwg777), but DR777 doesn't 
> > > explain the circumstances under which its wording change matters. It 
> > > //seems// only to apply to templates that are already ill-formed by 
> > > temp.res/8.3.
> > Yeah, Richard made this point in 
> > [[http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#2233|DR2233]],
> >  and the wording was weakened to allow it, in a way that essentially makes 
> > the earlier default arguments dead.
> Huh. Ick. Indeed the other vendors seem to be implementing DR777/DR2233, so I 
> guess Clang ought to catch up even if it's a silly direction to go in. :( I 
> do see a small bit of implementation divergence in 
> https://godbolt.org/z/ZMCvAX —
> ```
> template
> int f(int i=1, Ts... ts) { return (i + ... + ts); }
> 
> template<>
> int f(int i, int j) { return 42; }
> ```
> GCC rejects as ill-formed. MSVC makes the specialization callable with 2 
> arguments only. EDG (ICC) makes the specialization callable with 0 or 2 
> arguments (and does [crazy things](https://godbolt.org/z/QTrVeh) when you 
> call it with 0 arguments).
MSVC [[ https://godbolt.org/z/FCtrcs | seems to be the most standard-conforming 
]] in this regard. And now with the revised patch Clang is on par. :)

[[ https://gcc.gnu.org/bugzilla/show_bug.cgi?id=95287 | GCC bug ]]
[[ 
https://developercommunity.visualstudio.com/content/problem/1046639/incorrect-intellisense-for-functions-with-a-defaul.html
 | IntelliSense bug ]]

I also submitted bug reports to ICC, but those seem to need moderator approval 
before they're public.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79800



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


[PATCH] D69764: [clang-format] Add Left/Right Const fixer capability

2020-05-25 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D69764#2050226 , @steveire wrote:

> I like the approach of using clang-format to implement this. It's much faster 
> than a `clang-tidy` approach.
>
> The broader C++ community has already chosen `East`/`West` and it has 
> momentum. If you choose `Left`/`Right` now, you will get pressure to add 
> `East`/`West` in the future, which means we'll have the synonyms we want to 
> avoid.
>
> The broader C++ community already has understanding of `East`/`West`. Trying 
> to change that now should be out of scope for this patch. This patch should 
> use `East`/`West`.


As a member of the C++ committee, I'm aware that any statements about what the 
broader C++ community understands are not to be taken too seriously; none of us 
know what ~5M people understand or don't.

I would like to reiterate my discomfort with using East/West as the identifiers 
here. The purpose to this functionality is to decide whether to put qualifiers 
before or after the base type -- use of east/west to describe relative 
locations like these is not idiomatic in the same way as left/right or 
before/after (e.g., I'm not east-handed and you don't put the cart to the west 
of the horse). Qualifiers have been in C++ for ~40 years and the notion of 
east/west terminology is a very recent evolution by comparison. Also, 
clang-format is not a formatter for C++ alone and the east/west terminology is 
likely even less-known to users of the other languages despite also having 
qualifiers that need formatting (e.g., C and Obj). I think these are valid 
technical concerns with the patch that we should not hand-wave away as matters 
of preference.




Comment at: clang/lib/Format/Format.cpp:2547
 
+  if (Style.isCpp() || Style.Language == FormatStyle::LK_ObjC) {
+if (Style.ConstStyle != FormatStyle::CS_Leave)

This prevents us from using this in C code despite C having qualifiers that can 
go to the left or right of the base type but still allows you to use if from 
Objective-C. That seems incorrect.


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

https://reviews.llvm.org/D69764



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


[PATCH] D80344: [Windows SEH]: HARDWARE EXCEPTION HANDLING (MSVC -EHa) - Part 1

2020-05-25 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri added a comment.

In D80344#2051804 , @tentzen wrote:

> > It may be helpful (even for the reviewers) to first specify their behavior,
> >  instead of writing that after-the-fact "backwardly" based on the 
> > implementation.
>
> For reviewers, the purpose of those intrinsic are described in Summary 
> section:


Like the disscussion we just had in HWLoops patch, unless the behavior of new 
intrinsics/etc is stated in langref, they are unspecified.

> - Two intrinsic are created to track CPP object scopes; eha_scope_begin() and 
> eha_scope_end(). _scope_begin() is immediately added after ctor() is called 
> and EHStack is pushed. So it must be an invoke, not a call. With that it's 
> also guaranteed an EH-cleanup-pad is created regardless whether there exists 
> a call in this scope. _scope_end is added before dtor(). These two intrinsics 
> make the computation of Block-State possible in downstream code gen pass, 
> even in the presence of ctor/dtor inlining.
> - Two intrinsic, seh_try_begin() and seh_try_end(), are added for C-code to 
> mark _try boundary and to prevent from exceptions being moved across _try 
> boundary.




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80344



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


[PATCH] D79773: [clang-format] Improve clang-formats handling of concepts

2020-05-25 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay updated this revision to Diff 265847.
MyDeveloperDay added a comment.

Rebase


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

https://reviews.llvm.org/D79773

Files:
  clang/docs/ClangFormatStyleOptions.rst
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Format/Format.h
  clang/lib/Format/Format.cpp
  clang/lib/Format/FormatToken.h
  clang/lib/Format/TokenAnnotator.cpp
  clang/lib/Format/UnwrappedLineParser.cpp
  clang/lib/Format/UnwrappedLineParser.h
  clang/unittests/Format/FormatTest.cpp

Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -13537,6 +13537,7 @@
   CHECK_PARSE_BOOL(AlignConsecutiveBitFields);
   CHECK_PARSE_BOOL(AlignConsecutiveDeclarations);
   CHECK_PARSE_BOOL(AlignConsecutiveMacros);
+  CHECK_PARSE_BOOL(AlwaysBreakBeforeConceptDeclarations);
   CHECK_PARSE_BOOL(AllowAllArgumentsOnNextLine);
   CHECK_PARSE_BOOL(AllowAllConstructorInitializersOnNextLine);
   CHECK_PARSE_BOOL(AllowAllParametersOfDeclarationOnNextLine);
@@ -13557,6 +13558,7 @@
   CHECK_PARSE_BOOL(IndentCaseLabels);
   CHECK_PARSE_BOOL(IndentCaseBlocks);
   CHECK_PARSE_BOOL(IndentGotoLabels);
+  CHECK_PARSE_BOOL(IndentRequires);
   CHECK_PARSE_BOOL(IndentWrappedFunctionNames);
   CHECK_PARSE_BOOL(KeepEmptyLinesAtTheStartOfBlocks);
   CHECK_PARSE_BOOL(ObjCSpaceAfterProperty);
@@ -16567,6 +16569,222 @@
"}",
Style);
 }
+
+TEST_F(FormatTest, ConceptsAndRequires) {
+  FormatStyle Style = getLLVMStyle();
+  Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
+
+  verifyFormat("template \n"
+   "concept Hashable = requires(T a) {\n"
+   "  { std::hash{}(a) } -> std::convertible_to;\n"
+   "};",
+   Style);
+  verifyFormat("template \n"
+   "concept EqualityComparable = requires(T a, T b) {\n"
+   "  { a == b } -> bool;\n"
+   "};",
+   Style);
+  verifyFormat("template \n"
+   "concept EqualityComparable = requires(T a, T b) {\n"
+   "  { a == b } -> bool;\n"
+   "  { a != b } -> bool;\n"
+   "};",
+   Style);
+  verifyFormat("template \n"
+   "concept EqualityComparable = requires(T a, T b) {\n"
+   "  { a == b } -> bool;\n"
+   "  { a != b } -> bool;\n"
+   "};",
+   Style);
+
+  verifyFormat("template \n"
+   "requires Iterator\n"
+   "void sort(It begin, It end) {\n"
+   "  //\n"
+   "}",
+   Style);
+
+  verifyFormat("template \n"
+   "concept Large = sizeof(T) > 10;",
+   Style);
+
+  verifyFormat("template \n"
+   "concept FooableWith = requires(T t, U u) {\n"
+   "  typename T::foo_type;\n"
+   "  { t.foo(u) } -> typename T::foo_type;\n"
+   "  t++;\n"
+   "};\n"
+   "void doFoo(FooableWith auto t) {\n"
+   "  t.foo(3);\n"
+   "}",
+   Style);
+  verifyFormat("template \n"
+   "concept Context = sizeof(T) == 1;",
+   Style);
+  verifyFormat("template \n"
+   "concept Context = is_specialization_of_v;",
+   Style);
+  verifyFormat("template \n"
+   "concept Node = std::is_object_v;",
+   Style);
+  verifyFormat("template \n"
+   "concept Tree = true;",
+   Style);
+
+  verifyFormat("template  int g(T i) requires Concept1 {\n"
+   "  //...\n"
+   "}",
+   Style);
+
+  verifyFormat(
+  "template  int g(T i) requires Concept1 && Concept2 {\n"
+  "  //...\n"
+  "}",
+  Style);
+
+  verifyFormat(
+  "template  int g(T i) requires Concept1 || Concept2 {\n"
+  "  //...\n"
+  "}",
+  Style);
+
+  verifyFormat("template \n"
+   "veryveryvery_long_return_type g(T i) requires Concept1 || "
+   "Concept2 {\n"
+   "  //...\n"
+   "}",
+   Style);
+
+  verifyFormat("template \n"
+   "veryveryvery_long_return_type g(T i) requires Concept1 && "
+   "Concept2 {\n"
+   "  //...\n"
+   "}",
+   Style);
+
+  verifyFormat(
+  "template \n"
+  "veryveryvery_long_return_type g(T i) requires Concept1 && Concept2 {\n"
+  "  //...\n"
+  "}",
+  Style);
+
+  verifyFormat(
+  "template \n"
+  "veryveryvery_long_return_type g(T i) requires Concept1 || Concept2 {\n"
+  "  //...\n"
+  "}",
+  Style);
+
+  verifyFormat("template \n"
+   "requires Foo() && Bar {\n"
+   "  //\n"
+   "}",
+   Style);
+
+  verifyFormat("template \n"
+   "requires F

[PATCH] D80383: Add AST_SIGNATURE record to unhashed control block of PCM files

2020-05-25 Thread Daniel Grumberg via Phabricator via cfe-commits
dang updated this revision to Diff 265848.
dang added a comment.

This should address the Windows test failure as well as some offline feedback

- Ensure that DeclOffset instances can only be read by providing an offset to 
the AST block
- Simplify ASTSignature test by using -fdisable-module-hash


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80383

Files:
  clang/include/clang/Serialization/ASTBitCodes.h
  clang/include/clang/Serialization/ASTReader.h
  clang/include/clang/Serialization/ASTWriter.h
  clang/include/clang/Serialization/ModuleFile.h
  clang/lib/Serialization/ASTReader.cpp
  clang/lib/Serialization/ASTReaderDecl.cpp
  clang/lib/Serialization/ASTWriter.cpp
  clang/lib/Serialization/ASTWriterDecl.cpp
  clang/test/Modules/ASTSignature.c
  clang/test/Modules/Inputs/ASTHash/module.modulemap
  clang/test/Modules/Inputs/ASTHash/my_header_1.h
  clang/test/Modules/Inputs/ASTHash/my_header_2.h

Index: clang/test/Modules/Inputs/ASTHash/my_header_2.h
===
--- /dev/null
+++ clang/test/Modules/Inputs/ASTHash/my_header_2.h
@@ -0,0 +1,3 @@
+#include "my_header_1.h"
+
+extern my_int var;
Index: clang/test/Modules/Inputs/ASTHash/my_header_1.h
===
--- /dev/null
+++ clang/test/Modules/Inputs/ASTHash/my_header_1.h
@@ -0,0 +1 @@
+typedef int my_int;
Index: clang/test/Modules/Inputs/ASTHash/module.modulemap
===
--- /dev/null
+++ clang/test/Modules/Inputs/ASTHash/module.modulemap
@@ -0,0 +1,8 @@
+module MyHeader1 {
+  header "my_header_1.h"
+}
+
+module MyHeader2 {
+  header "my_header_2.h"
+  export *
+}
Index: clang/test/Modules/ASTSignature.c
===
--- /dev/null
+++ clang/test/Modules/ASTSignature.c
@@ -0,0 +1,24 @@
+// RUN: rm -rf %t
+// RUN: %clang_cc1 -iquote %S/Inputs/ASTHash/ -fsyntax-only -fmodules \
+// RUN:   -fimplicit-module-maps -fmodules-strict-context-hash \
+// RUN:   -fmodules-cache-path=%t -fdisable-module-hash %s
+// RUN: cp %t/MyHeader2.pcm %t1.pcm
+// RUN: rm -rf %t
+// RUN: %clang_cc1 -iquote "/dev/null" -iquote %S/Inputs/ASTHash/ -fsyntax-only \
+// RUN:   -fmodules -fimplicit-module-maps -fmodules-strict-context-hash \
+// RUN:   -fmodules-cache-path=%t -fdisable-module-hash %s
+// RUN: cp %t/MyHeader2.pcm %t2.pcm
+// RUN: llvm-bcanalyzer --dump --disable-histogram %t1.pcm > %t1.dump
+// RUN: llvm-bcanalyzer --dump --disable-histogram %t2.pcm > %t2.dump
+// RUN: cat %t1.dump %t2.dump | FileCheck %s
+
+#include "my_header_2.h"
+
+my_int var = 42;
+
+// CHECK: [[AST_SIGNATURE:]]
+// CHECK: [[SIGNATURE:]]
+// CHECK: [[AST_SIGNATURE]]
+// CHECK-NOT: [[SIGNATURE]]
+// The modules built by this test are designed to yield the same AST. If this
+// test fails, it means that the AST block is has become non-relocatable.
Index: clang/lib/Serialization/ASTWriterDecl.cpp
===
--- clang/lib/Serialization/ASTWriterDecl.cpp
+++ clang/lib/Serialization/ASTWriterDecl.cpp
@@ -2434,12 +2434,12 @@
   SourceLocation Loc = D->getLocation();
   unsigned Index = ID - FirstDeclID;
   if (DeclOffsets.size() == Index)
-DeclOffsets.emplace_back(Loc, Offset);
+DeclOffsets.emplace_back(Loc, Offset, ASTBlockRange.first);
   else if (DeclOffsets.size() < Index) {
 // FIXME: Can/should this happen?
 DeclOffsets.resize(Index+1);
 DeclOffsets[Index].setLocation(Loc);
-DeclOffsets[Index].setBitOffset(Offset);
+DeclOffsets[Index].setBitOffset(Offset, ASTBlockRange.first);
   } else {
 llvm_unreachable("declarations should be emitted in ID order");
   }
Index: clang/lib/Serialization/ASTWriter.cpp
===
--- clang/lib/Serialization/ASTWriter.cpp
+++ clang/lib/Serialization/ASTWriter.cpp
@@ -10,14 +10,12 @@
 //
 //===--===//
 
-#include "clang/AST/OpenMPClause.h"
-#include "clang/Serialization/ASTRecordWriter.h"
 #include "ASTCommon.h"
 #include "ASTReaderInternals.h"
 #include "MultiOnDiskHashTable.h"
-#include "clang/AST/AbstractTypeWriter.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/ASTUnresolvedSet.h"
+#include "clang/AST/AbstractTypeWriter.h"
 #include "clang/AST/Attr.h"
 #include "clang/AST/Decl.h"
 #include "clang/AST/DeclBase.h"
@@ -31,6 +29,7 @@
 #include "clang/AST/ExprCXX.h"
 #include "clang/AST/LambdaCapture.h"
 #include "clang/AST/NestedNameSpecifier.h"
+#include "clang/AST/OpenMPClause.h"
 #include "clang/AST/RawCommentList.h"
 #include "clang/AST/TemplateName.h"
 #include "clang/AST/Type.h"
@@ -65,7 +64,9 @@
 #include "clang/Sema/ObjCMethodList.h"
 #include "clang/Sema/Sema.h"
 #include "clang/Sema/Weak.h"
+#include "clang/Serialization/ASTBitCodes.h

[clang-tools-extra] 10f0f98 - Add a way to set traversal mode in clang-query

2020-05-25 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2020-05-23T14:57:10+01:00
New Revision: 10f0f98eac5b20796ae804a2df2a9d853d59d3bd

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

LOG: Add a way to set traversal mode in clang-query

Reviewers: aaron.ballman

Subscribers: cfe-commits

Tags: #clang

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

Added: 


Modified: 
clang-tools-extra/clang-query/Query.cpp
clang-tools-extra/clang-query/Query.h
clang-tools-extra/clang-query/QueryParser.cpp
clang-tools-extra/clang-query/QueryParser.h
clang-tools-extra/clang-query/QuerySession.h
clang-tools-extra/unittests/clang-query/QueryParserTest.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-query/Query.cpp 
b/clang-tools-extra/clang-query/Query.cpp
index 8eafc5eed750..2fc7af6a56e1 100644
--- a/clang-tools-extra/clang-query/Query.cpp
+++ b/clang-tools-extra/clang-query/Query.cpp
@@ -43,6 +43,15 @@ bool HelpQuery::run(llvm::raw_ostream &OS, QuerySession &QS) 
const {
 "Set whether to bind the root matcher to \"root\".\n"
 "  set print-matcher (true|false)"
 "Set whether to print the current matcher,\n"
+"  set traversal   "
+"Set traversal kind of clang-query session. Available kinds are:\n"
+"AsIs"
+"Print and match the AST as clang sees it.\n"
+"IgnoreImplicitCastsAndParentheses  "
+"Omit implicit casts and parens in matching and dumping.\n"
+"IgnoreUnlessSpelledInSource "
+"Omit AST nodes unless spelled in the source.  This mode is the "
+"default.\n"
 "  set output   "
 "Set whether to output only  content.\n"
 "  enable output"
@@ -98,6 +107,8 @@ bool MatchQuery::run(llvm::raw_ostream &OS, QuerySession 
&QS) const {
   OS << "Not a valid top-level matcher.\n";
   return false;
 }
+
+AST->getASTContext().getParentMapContext().setTraversalKind(QS.TK);
 Finder.matchAST(AST->getASTContext());
 
 if (QS.PrintMatcher) {
@@ -148,6 +159,7 @@ bool MatchQuery::run(llvm::raw_ostream &OS, QuerySession 
&QS) const {
   const SourceManager &SM = Ctx.getSourceManager();
   ASTDumper Dumper(OS, &Ctx.getCommentCommandTraits(), &SM,
 SM.getDiagnostics().getShowColors(), Ctx.getPrintingPolicy());
+  Dumper.SetTraversalKind(QS.TK);
   Dumper.Visit(BI->second);
   OS << "\n";
 }

diff  --git a/clang-tools-extra/clang-query/Query.h 
b/clang-tools-extra/clang-query/Query.h
index 78bcbc79cdf8..223644fe2e51 100644
--- a/clang-tools-extra/clang-query/Query.h
+++ b/clang-tools-extra/clang-query/Query.h
@@ -28,6 +28,7 @@ enum QueryKind {
   QK_Match,
   QK_SetBool,
   QK_SetOutputKind,
+  QK_SetTraversalKind,
   QK_EnableOutputKind,
   QK_DisableOutputKind,
   QK_Quit
@@ -119,6 +120,10 @@ template <> struct SetQueryKind {
   static const QueryKind value = QK_SetOutputKind;
 };
 
+template <> struct SetQueryKind {
+  static const QueryKind value = QK_SetTraversalKind;
+};
+
 /// Query for "set VAR VALUE".
 template  struct SetQuery : Query {
   SetQuery(T QuerySession::*Var, T Value)

diff  --git a/clang-tools-extra/clang-query/QueryParser.cpp 
b/clang-tools-extra/clang-query/QueryParser.cpp
index ecc189a7db2f..2f1965e77ab4 100644
--- a/clang-tools-extra/clang-query/QueryParser.cpp
+++ b/clang-tools-extra/clang-query/QueryParser.cpp
@@ -128,6 +128,24 @@ template  QueryRef 
QueryParser::parseSetOutputKind() {
   llvm_unreachable("Invalid output kind");
 }
 
+QueryRef QueryParser::parseSetTraversalKind(
+ast_type_traits::TraversalKind QuerySession::*Var) {
+  StringRef ValStr;
+  unsigned Value =
+  LexOrCompleteWord(this, ValStr)
+  .Case("AsIs", ast_type_traits::TK_AsIs)
+  .Case("IgnoreImplicitCastsAndParentheses",
+ast_type_traits::TK_IgnoreImplicitCastsAndParentheses)
+  .Case("IgnoreUnlessSpelledInSource",
+ast_type_traits::TK_IgnoreUnlessSpelledInSource)
+  .Default(~0u);
+  if (Value == ~0u) {
+return new InvalidQuery("expected traversal kind, got '" + ValStr + "'");
+  }
+  return new SetQuery(
+  Var, static_cast(Value));
+}
+
 QueryRef QueryParser::endQuery(QueryRef Q) {
   StringRef Extra = Line;
   StringRef ExtraTrimmed = Extra.drop_while(
@@ -171,7 +189,8 @@ enum ParsedQueryVariable {
   PQV_Invalid,
   PQV_Output,
   PQV_BindRoot,
-  PQV_PrintMatcher
+  PQV_PrintMatcher,
+  PQV_Traversal
 };
 
 QueryRef makeInvalidQueryFromDiagnostics(const Diagnostics &Diag) {
@@ -272,6 +291,7 @@ QueryRef QueryParser::doParse() {
 .Case("output", PQV_Output)
 .Case("bind-root", PQV_BindRoot)
 .Case("prin

[PATCH] D80371: [clang-tidy] Fix potential assert in use-noexcept check

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

LGTM, but please add a test case for the changes.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80371



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


[PATCH] D73037: Add a way to set traversal mode in clang-query

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

LGTM!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D73037



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


[PATCH] D79773: [clang-format] Improve clang-formats handling of concepts

2020-05-25 Thread Michael Schellenberger Costa via Phabricator via cfe-commits
miscco added inline comments.



Comment at: clang/lib/Format/UnwrappedLineParser.cpp:2296
+
+void UnwrappedLineParser::parseRequiresExpression(int OriginalLevel) {
+  // requires (R range)

Line->Level is an unsigned int so this gives me a warning. I guess it should be 
`unsigned int OriginalLevel` same below


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

https://reviews.llvm.org/D79773



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


[PATCH] D79800: [Sema] Remove default values for arguments prior to a parameter pack if the pack is used

2020-05-25 Thread Raul Tambre via Phabricator via cfe-commits
tambre updated this revision to Diff 265850.
tambre marked 5 inline comments as done.
tambre added a comment.

Handle multiple parameter packs interleaved with default values.
Mark DR777 as superseded by DR2233. Mark DR2233 as resolved.
Moved tests from dr7xx.cpp to dr22xx.cpp. Added note in dr7xx.cpp about DR777 
being superseded.
Add more tests that cover bugs observed in other implementations and the 
deficiency in my first implementation.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79800

Files:
  clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
  clang/test/CXX/drs/dr22xx.cpp
  clang/test/CXX/drs/dr7xx.cpp
  clang/www/cxx_dr_status.html

Index: clang/www/cxx_dr_status.html
===
--- clang/www/cxx_dr_status.html
+++ clang/www/cxx_dr_status.html
@@ -4681,7 +4681,7 @@
 https://wg21.link/cwg777";>777
 CD2
 Default arguments and parameter packs
-Clang 3.7
+Superseded by 2233
   
   
 https://wg21.link/cwg778";>778
@@ -13213,7 +13213,7 @@
 https://wg21.link/cwg2233";>2233
 DRWP
 Function parameter packs following default arguments
-Unknown
+Clang 11
   
   
 https://wg21.link/cwg2234";>2234
Index: clang/test/CXX/drs/dr7xx.cpp
===
--- clang/test/CXX/drs/dr7xx.cpp
+++ clang/test/CXX/drs/dr7xx.cpp
@@ -219,16 +219,4 @@
   Collision c; // expected-note {{in instantiation of}}
 }
 
-namespace dr777 { // dr777: 3.7
-#if __cplusplus >= 201103L
-template 
-void f(int i = 0, T ...args) {}
-void ff() { f(); }
-
-template 
-void g(int i = 0, T ...args, T ...args2) {}
-
-template 
-void h(int i = 0, T ...args, int j = 1) {}
-#endif
-}
+// dr777 superseded by dr2233
Index: clang/test/CXX/drs/dr22xx.cpp
===
--- clang/test/CXX/drs/dr22xx.cpp
+++ clang/test/CXX/drs/dr22xx.cpp
@@ -35,3 +35,44 @@
   }
 #endif
 }
+
+namespace dr2233 { // dr2233: 11
+#if __cplusplus >= 201103L
+template 
+void f(int i = 0, T... args) {}
+
+template 
+void g(int i = 0, T... args, T... args2) {}
+
+template 
+void h(int i = 0, T... args, int j = 1) {}
+
+template 
+void i(int i = 0, T... args, int j = 1, U... args2) {}
+
+template 
+void j(int i = 0, Ts... ts) {}
+
+template <>
+void j(int i, int j) {}
+
+// PR23029
+// Ensure instantiating the templates works.
+void use() {
+  f();
+  f(0, 1);
+  f(1, 2);
+  g(1, 2, 3);
+  h(0, 1);
+  i();
+  i(3);
+  i(3, 2);
+  i(3, 2, 1);
+  i(1, 2, 3, 4, 5);
+  j();
+  j(1);
+  j(1, 2);
+  j(1, 2);
+}
+#endif
+} // namespace dr2233
Index: clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
===
--- clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
+++ clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
@@ -1974,6 +1974,47 @@
 TemplateArgumentList::CreateCopy(SemaRef.Context,
  Innermost),
 /*InsertPos=*/nullptr);
+
+// DR777, DR2233.
+// Parameter packs are allowed after and inbetween parameters with default
+// values. We need to remove default arguments for parameters before the
+// first expanded parameter pack to prevent prevent it being diagnosed as
+// invalid code due to the expanded parameters lacking default values. This
+// is safe to do because if a parameter pack is expanded the user must've
+// provided arguments for all parameters before it.
+FunctionDecl *TemplatedDecl = FunctionTemplate->getTemplatedDecl();
+unsigned FirstPack = Function->getNumParams();
+bool RemoveDefaults = false;
+
+// Go backwards through the template declaration parameters and find the
+// first parameter pack, which has non-zero number of arguments.
+for (unsigned p = TemplatedDecl->getNumParams(); p-- > 0;) {
+  ParmVarDecl *Param = TemplatedDecl->getParamDecl(p);
+
+  if (Param->isParameterPack()) {
+llvm::Optional Args =
+SemaRef.getNumArgumentsInExpansion(Param->getType(), TemplateArgs);
+assert(Args != None && "Unknown number of pack expansion arguments.");
+
+if (Args.getValue() == 0)
+  continue;
+
+FirstPack -= Args.getValue();
+RemoveDefaults = true;
+break;
+  } else {
+FirstPack--;
+  }
+}
+
+// If we found such a parameter pack, then remove default arguments for all
+// parameters before it.
+if (RemoveDefaults) {
+  for (unsigned p = 0; p < FirstPack; p++) {
+ParmVarDecl *Param = Function->getParamDecl(p);
+Param->setDefaultArg(nullptr);
+  }
+}
   } else if (isFriend && D->isThisDeclarationADefinition()) {
 // Do not connect the friend to the template unless it's actually a
 // definition. We don't want non-temp

[PATCH] D80425: Fix LLVM/Clang builds with mingw toolchain

2020-05-25 Thread Mateusz Mikuła via Phabricator via cfe-commits
mati865 added inline comments.



Comment at: llvm/cmake/modules/HandleLLVMOptions.cmake:967
CMAKE_EXE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS)
-  elseif(LINKER_IS_LLD_LINK)
+  elseif(LINKER_IS_LLD_LINK AND NOT MINGW)
 append("/lldltocache:${PROJECT_BINARY_DIR}/lto.cache"

mstorsjo wrote:
> mati865 wrote:
> > thieta wrote:
> > > mstorsjo wrote:
> > > > Do you happen to know why `LINKER_IS_LLD_LINK` gets set in this case? 
> > > > `ld.lld` (the ELF linker interface, which then the MinGW driver remaps 
> > > > onto the COFF backend with the `lld-link` interface) certainly doesn't 
> > > > take `lld-link` style options. I believe (without diving further into 
> > > > it) that we shouldn't be setting this flag in this combination, but 
> > > > with the option implemented, we should fit it into the case further 
> > > > above, `elseif((UNIX OR MINGW) AND LLVM_USE_LINKER STREQUAL "lld")`
> > > Yeah I bet that variable is set because I pass `LLVM_USE_LINKER=lld` but 
> > > I haven't digged to deeply. I can rework the if statement here when we 
> > > have the lld option in there.
> > > Yeah I bet that variable is set because I pass LLVM_USE_LINKER=lld but I 
> > > haven't digged to deeply. 
> > 
> > It does use `lld-link` when you use `LLVM_USE_LINKER=lld`.
> > 
> > The problem lies in this line:
> > ```
> > append("/lldltocache:${PROJECT_BINARY_DIR}/lto.cache"
> > ```
> > For MinGW that should read:
> > ```
> > append("-Wl,/lldltocache:${PROJECT_BINARY_DIR}/lto.cache"
> > ```
> > That's because you are passing this flag to GCC/Clang.
> > For MinGW that should read:
> > 
> > append("-Wl,/lldltocache:${PROJECT_BINARY_DIR}/lto.cache"
> 
> We're adding this option properly in the mingw frontend, so we shouldn't do 
> the hacky way of passing lld-link options via the mingw frontend by passing 
> them as `/option`.
> 
> And the reason `LINKER_IS_LLD_LINK` is set seems to be this:
> 
> ```
> if(CMAKE_LINKER MATCHES "lld-link" OR (WIN32 AND LLVM_USE_LINKER STREQUAL 
> "lld") OR LLVM_ENABLE_LLD)
> ```
> 
> Perhaps that should be changed into
> 
> ```
> if(CMAKE_LINKER MATCHES "lld-link" OR (WIN32 AND LLVM_USE_LINKER STREQUAL 
> "lld" AND NOT MINGW) OR LLVM_ENABLE_LLD)
> ```
> 
> We're adding this option properly in the mingw frontend, so we shouldn't do 
> the hacky way of passing lld-link options via the mingw frontend by passing 
> them as /option.

I was about to add that and one more LTO related option but thought "what if 
LLVM should link with lld-link on MinGW?" and eventually forgot about it.



> And the reason LINKER_IS_LLD_LINK is set seems to be this:
> ```
> if(CMAKE_LINKER MATCHES "lld-link" OR (WIN32 AND LLVM_USE_LINKER STREQUAL 
> "lld") OR LLVM_ENABLE_LLD)
> ```
> Perhaps that should be changed into
> ```
> if(CMAKE_LINKER MATCHES "lld-link" OR (WIN32 AND LLVM_USE_LINKER STREQUAL 
> "lld" AND NOT MINGW) OR LLVM_ENABLE_LLD)
> ```

It won't work if somebody uses `LLVM_ENABLE_LLD=ON` instead of 
`LLVM_USE_LINKER=lld` which is supposed to be equivalent.
That raises question how `LLVM_ENABLE_LLD=ON` does even work on UNIX platforms.

IMO this would be better:
```
if(CMAKE_LINKER MATCHES "lld-link" OR MSVC AND (LLVM_USE_LINKER STREQUAL "lld" 
OR LLVM_ENABLE_LLD))
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80425



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


[PATCH] D66564: [clang-tidy] new altera struct pack align check

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

Aside from a minor nit with the matcher, this LGTM!




Comment at: clang-tools-extra/clang-tidy/altera/StructPackAlignCheck.cpp:50-53
+  // Do not trigger on template instantiations because the packing and
+  // alignment requirements are unknown.
+  if (Struct->isTemplated())
+return;

I think this should be hoisted into the AST matcher using 
`unless(isTemplateInstantiation())`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66564



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


[PATCH] D77572: [clang-tidy] add new check readability-use-anyofallof

2020-05-25 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D77572#1981871 , @mgehre wrote:

> Thanks for the comments so far.
>  I'm a bit lost now. Which changes that cannot wait for the next PR do you 
> see necessary to get this check merged?


I'd be curious to know what @njames93 thinks -- I spot-checked the diagnostics 
you attached earlier (thank you for those!) and all of them seemed reasonable 
to me, which suggests there's not an extraordinary amount of false positives. 
The functionality seems useful in its current state, though as you point out, 
there are improvements you want to make in follow-up patches. That seems 
reasonable to me.




Comment at: 
clang-tools-extra/clang-tidy/readability/UseAnyOfAllOfCheck.cpp:22-24
+/// Matches a Stmt whose parent is a CompoundStmt,
+/// and which is directly followed by
+/// a Stmt matching the inner matcher.

It looks like these comments got formatted a bit strangely -- probably should 
re-flow them.



Comment at: clang-tools-extra/clang-tidy/readability/UseAnyOfAllOfCheck.cpp:36
+  const auto *I = llvm::find(C->body(), &Node);
+  assert(I != C->body_end()); // C is parent of Node.
+  if (++I == C->body_end())

I think the comment should turn into a string literal that's part of the 
assertion.



Comment at: clang-tools-extra/clang-tidy/readability/UseAnyOfAllOfCheck.cpp:61
+  hasBody(allOf(hasDescendant(returns(true)),
+unless(anyOf(hasDescendant(breakStmt()),
+ hasDescendant(returnsButNotTrue))

Should we reject other ways to break out of the loop, like `goto` or `throw`?



Comment at: clang-tools-extra/clang-tidy/readability/UseAnyOfAllOfCheck.cpp:98
+
+diag(S->getForLoc(), "Replace loop by std%0::any_of() from ")
+<< Ranges;

clang-tidy diagnostics don't start with a capital letter, and I'd probably drop 
the `from ` part under the assumption the user can figure out the 
header pretty easily from the diagnostic wording. Also, you should put single 
quotes around the `std%0::any_of()`. Similar below.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D77572



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


[PATCH] D73037: Add a way to set traversal mode in clang-query

2020-05-25 Thread Stephen Kelly via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG10f0f98eac5b: Add a way to set traversal mode in clang-query 
(authored by stephenkelly).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D73037

Files:
  clang-tools-extra/clang-query/Query.cpp
  clang-tools-extra/clang-query/Query.h
  clang-tools-extra/clang-query/QueryParser.cpp
  clang-tools-extra/clang-query/QueryParser.h
  clang-tools-extra/clang-query/QuerySession.h
  clang-tools-extra/unittests/clang-query/QueryParserTest.cpp

Index: clang-tools-extra/unittests/clang-query/QueryParserTest.cpp
===
--- clang-tools-extra/unittests/clang-query/QueryParserTest.cpp
+++ clang-tools-extra/unittests/clang-query/QueryParserTest.cpp
@@ -110,6 +110,18 @@
   ASSERT_TRUE(isa >(Q));
   EXPECT_EQ(&QuerySession::BindRoot, cast >(Q)->Var);
   EXPECT_EQ(true, cast >(Q)->Value);
+
+  Q = parse("set traversal AsIs");
+  ASSERT_TRUE(isa>(Q));
+  EXPECT_EQ(&QuerySession::TK,
+cast>(Q)->Var);
+  EXPECT_EQ(ast_type_traits::TK_AsIs,
+cast>(Q)->Value);
+
+  Q = parse("set traversal NotATraversal");
+  ASSERT_TRUE(isa(Q));
+  EXPECT_EQ("expected traversal kind, got 'NotATraversal'",
+cast(Q)->ErrStr);
 }
 
 TEST_F(QueryParserTest, Match) {
@@ -197,6 +209,11 @@
   EXPECT_EQ("utput ", Comps[0].TypedText);
   EXPECT_EQ("output", Comps[0].DisplayText);
 
+  Comps = QueryParser::complete("set t", 5, QS);
+  ASSERT_EQ(1u, Comps.size());
+  EXPECT_EQ("raversal ", Comps[0].TypedText);
+  EXPECT_EQ("traversal", Comps[0].DisplayText);
+
   Comps = QueryParser::complete("enable ", 7, QS);
   ASSERT_EQ(1u, Comps.size());
   EXPECT_EQ("output ", Comps[0].TypedText);
@@ -214,6 +231,16 @@
   EXPECT_EQ("dump ", Comps[3].TypedText);
   EXPECT_EQ("dump", Comps[3].DisplayText);
 
+  Comps = QueryParser::complete("set traversal ", 14, QS);
+  ASSERT_EQ(3u, Comps.size());
+
+  EXPECT_EQ("AsIs ", Comps[0].TypedText);
+  EXPECT_EQ("AsIs", Comps[0].DisplayText);
+  EXPECT_EQ("IgnoreImplicitCastsAndParentheses ", Comps[1].TypedText);
+  EXPECT_EQ("IgnoreImplicitCastsAndParentheses", Comps[1].DisplayText);
+  EXPECT_EQ("IgnoreUnlessSpelledInSource ", Comps[2].TypedText);
+  EXPECT_EQ("IgnoreUnlessSpelledInSource", Comps[2].DisplayText);
+
   Comps = QueryParser::complete("match while", 11, QS);
   ASSERT_EQ(1u, Comps.size());
   EXPECT_EQ("Stmt(", Comps[0].TypedText);
Index: clang-tools-extra/clang-query/QuerySession.h
===
--- clang-tools-extra/clang-query/QuerySession.h
+++ clang-tools-extra/clang-query/QuerySession.h
@@ -9,6 +9,7 @@
 #ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_QUERY_QUERY_SESSION_H
 #define LLVM_CLANG_TOOLS_EXTRA_CLANG_QUERY_QUERY_SESSION_H
 
+#include "clang/AST/ASTTypeTraits.h"
 #include "clang/ASTMatchers/Dynamic/VariantValue.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/StringMap.h"
@@ -25,7 +26,7 @@
   QuerySession(llvm::ArrayRef> ASTs)
   : ASTs(ASTs), PrintOutput(false), DiagOutput(true),
 DetailedASTOutput(false), BindRoot(true), PrintMatcher(false),
-Terminate(false) {}
+Terminate(false), TK(ast_type_traits::TK_IgnoreUnlessSpelledInSource) {}
 
   llvm::ArrayRef> ASTs;
 
@@ -36,6 +37,8 @@
   bool BindRoot;
   bool PrintMatcher;
   bool Terminate;
+
+  ast_type_traits::TraversalKind TK;
   llvm::StringMap NamedValues;
 };
 
Index: clang-tools-extra/clang-query/QueryParser.h
===
--- clang-tools-extra/clang-query/QueryParser.h
+++ clang-tools-extra/clang-query/QueryParser.h
@@ -43,6 +43,8 @@
   template  struct LexOrCompleteWord;
 
   QueryRef parseSetBool(bool QuerySession::*Var);
+  QueryRef
+  parseSetTraversalKind(ast_type_traits::TraversalKind QuerySession::*Var);
   template  QueryRef parseSetOutputKind();
   QueryRef completeMatcherExpression();
 
Index: clang-tools-extra/clang-query/QueryParser.cpp
===
--- clang-tools-extra/clang-query/QueryParser.cpp
+++ clang-tools-extra/clang-query/QueryParser.cpp
@@ -128,6 +128,24 @@
   llvm_unreachable("Invalid output kind");
 }
 
+QueryRef QueryParser::parseSetTraversalKind(
+ast_type_traits::TraversalKind QuerySession::*Var) {
+  StringRef ValStr;
+  unsigned Value =
+  LexOrCompleteWord(this, ValStr)
+  .Case("AsIs", ast_type_traits::TK_AsIs)
+  .Case("IgnoreImplicitCastsAndParentheses",
+ast_type_traits::TK_IgnoreImplicitCastsAndParentheses)
+  .Case("IgnoreUnlessSpelledInSource",
+ast_type_traits::TK_IgnoreUnlessSpelledInSource)
+  .Default(~0u);
+  if (Value == ~0u) {
+return new InvalidQuery("expected traversal kind, got '" + ValStr + "'");
+  }
+  return new SetQuery(
+  Var, static_cast(Value));
+}
+
 Que

[PATCH] D60620: [HIP] Support target id by --offload-arch

2020-05-25 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl marked 2 inline comments as done.
yaxunl added inline comments.



Comment at: clang/lib/Driver/ToolChains/HIP.cpp:121-123
+  auto Pos = SubArchName.find_first_of("+-");
+  if (Pos != SubArchName.npos)
+SubArchName = SubArchName.substr(0, Pos);

tra wrote:
> Parsing should probably be extracted into a separate function to avoid 
> replicating it all over the place.
> 
> I'd also propose use a different syntax for the properties.
> * use explicit character to separate individual elements. This way splitting 
> the properties becomes independent of what those properties are. If you 
> decide to make properties with values or change their meaning some other way, 
> it would not affect how you compose them.
> * use `name=value` or `name[+-]` for individual properties. This makes it 
> easy to parse individual properties and normalize their names. This makes 
> property map creation independent of the property values.
> 
> Right now `[+-]` serves as both a separator and as the value, which would 
> present problems if you ever need more flexible parametrization of 
> properties. What if a property must be a number or a string. Granted, you can 
> always encode them as a set of bools, but that's rather unpractical. 
> 
> E.g. something like this would work a bit better: 
> `gfx111:foo+:bar=33:buz=string`.
> 
I discussed this with our team.

The target id features are not raw GPU properties. They are distilled to become 
a few target features to decide what the compiler should do.

Each target feature has 3 values: on, off, and default, which are encoded as 
+feature, -feature, and not present.

For runtime, it is simple and clear how to choose device binaries based on the 
target features: it will try exact match, otherwise choose the default.

For compiler, it is also simple and clear what to do for each target feature 
value, since they corresponding to backend target features.

Basically we expect the target id feature to be like flags, not key/value 
pairs. In case we do need key/value pairs, they can still use + as delimiter.

Another reason we use +/- format is that it is more in line with the format of 
existing clang-offload-bundler id and target triple, which uses - as delimiter.

Since the target id is an extension of offload arch and users will put it into 
command line, we want to make it short, concise and aesthetically appealing, we 
would avoid using non-alpha-numeric characters in the target id features. 
Target triple components have similar requirements. Using : as delimiter seems 
unnecessary, longer, and more difficult to read.

Consider the following example


```
clang -offload-id gfx908+xnack-sramecc a.hip

clang -offload-id gfx908:xnack+:sramecc- a.hip
```

We are more inclined to keep the original format. 


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

https://reviews.llvm.org/D60620



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


[PATCH] D79437: [clang-tidy] Add fsetpos argument checker

2020-05-25 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

Thank you for working on this check, I think it's useful functionality. One 
concern I have, though, is that it's not flow-sensitive and should probably be 
implemented as a clang static analyzer check instead of a clang-tidy check. For 
instance, consider these three plausible issues:

  // This only sets the offset on one code path.
  void func(FILE *fp) {
fpos_t offset;
if (condition) {
  // ... code
  if (0 != fgetpos(fp, &offset))
return;
  // ... code
} else {
 // ... code
}
fsetpos(fp, &offset);
  }
  
  // This doesn't check the failure from getting the position and sets the 
position regardless.
  void func(FILE *fp) {
fpos_t offset;
fgetpos(fp, &offset);
// ... code
fsetpos(fp, &offset);
  }
  
  // This function accepts the offset from the caller but the caller passes an 
invalid offset.
  void func(FILE *fp, const fpos_t *offset) {
fsetpos(fp, offset);
  }
  void caller(FILE *fp) {
fpos_t offset;
func(fp, &offset);
  }

Have you considered writing a static analyzer check so you can do data and 
control flow analysis to catch issues like these?




Comment at: clang-tools-extra/clang-tidy/cert/CERTTidyModule.cpp:103
 // FIO
+
CheckFactories.registerCheck("cert-fio44-c");
 
CheckFactories.registerCheck("cert-fio38-c");

Can you reorder to below fio38-c?



Comment at: 
clang-tools-extra/docs/clang-tidy/checks/bugprone-fsetpos-argument-check.rst:4
+bugprone-fsetpos-argument-check
+
+

The underlines here don't look like they are correct.



Comment at: 
clang-tools-extra/docs/clang-tidy/checks/bugprone-fsetpos-argument-check.rst:35
+
+This check corresponds to the CERT C++ Coding Standard rule
+`FIO44-C. Only use values for fsetpos() that are returned from fgetpos()

the CERT C Coding Standard rule


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D79437



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


[PATCH] D60620: [HIP] Support target id by --offload-arch

2020-05-25 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl marked 3 inline comments as done.
yaxunl added inline comments.



Comment at: clang/lib/Basic/HIP.cpp:16
+const llvm::SmallVector
+getAllPossibleTargetIdFeatures(llvm::StringRef Device) {
+  llvm::SmallVector Ret;

tra wrote:
> Nit: there's an unfortunate clash with already [[ 
> https://github.com/llvm/llvm-project/blob/6a3469f58d0c230e86043f6975f048968334dfa4/clang/include/clang/Driver/CC1Options.td#L23
>  | target-feature ]] in clang & LLVM.
> 
> Would something like `GPUProperties` be a reasonable name?
We call it target id feature to differentiate it from target feature. A target 
id feature usually corresponds to a target feature although it may not 
necessarily true.

Since target id feature sounds too close to target feature, it is reasonable to 
give it a different name.

How about OffloadArchFeatures ? Since they are used as features of the extended 
-offload-arch option.


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

https://reviews.llvm.org/D60620



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


[clang] 0591329 - [Analyzer][WebKit][NFC] Correct documentation to avoid sphinx build error

2020-05-25 Thread via cfe-commits

Author: mydeveloperday
Date: 2020-05-23T11:28:06+01:00
New Revision: 0591329dd1f1b1691c65e700c2805590a090b7d8

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

LOG: [Analyzer][WebKit][NFC] Correct documentation to avoid sphinx build error

This was introduced with commit 54e91a3c7010

Added: 


Modified: 
clang/docs/analyzer/checkers.rst

Removed: 




diff  --git a/clang/docs/analyzer/checkers.rst 
b/clang/docs/analyzer/checkers.rst
index ea3f0e838b6a..dcf1f28994de 100644
--- a/clang/docs/analyzer/checkers.rst
+++ b/clang/docs/analyzer/checkers.rst
@@ -1395,6 +1395,7 @@ All uncounted types used as base classes must have a 
virtual destructor.
 Ref-counted types hold their ref-countable data by a raw pointer and allow 
implicit upcasting from ref-counted pointer to derived type to ref-counted 
pointer to base type. This might lead to an object of (dynamic) derived type 
being deleted via pointer to the base class type which C++ standard defines as 
UB in case the base class doesn't have virtual destructor ``[expr.delete]``.
 
 .. code-block:: cpp
+
  struct RefCntblBase {
void ref() {}
void deref() {}



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


[PATCH] D80472: [clangd] Add access specifier information to hover contents

2020-05-25 Thread Daniel Martín via Phabricator via cfe-commits
danielmartin created this revision.
Herald added subscribers: cfe-commits, usaxena95, kadircet, arphaman, jkorous, 
MaskRay, ilya-biryukov.
Herald added a project: clang.
danielmartin edited the summary of this revision.

For https://github.com/clangd/clangd/issues/382

This commit adds access specifier information to the hover
contents. For example, the hover information of a class field or
member function will now indicate if the field or member is private,
public, or protected. This can be particularly useful when a developer
is in the implementation file and wants to know if a particular member
definition is public or private.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D80472

Files:
  clang-tools-extra/clangd/Hover.cpp
  clang-tools-extra/clangd/Hover.h
  clang-tools-extra/clangd/unittests/HoverTests.cpp

Index: clang-tools-extra/clangd/unittests/HoverTests.cpp
===
--- clang-tools-extra/clangd/unittests/HoverTests.cpp
+++ clang-tools-extra/clangd/unittests/HoverTests.cpp
@@ -12,6 +12,7 @@
 #include "TestIndex.h"
 #include "TestTU.h"
 #include "index/MemIndex.h"
+#include "clang/Basic/Specifiers.h"
 #include "clang/Index/IndexSymbol.h"
 #include "llvm/ADT/None.h"
 #include "llvm/ADT/StringRef.h"
@@ -1964,7 +1965,51 @@
 // In test::Bar
 def)",
   },
-  };
+  {
+  [](HoverInfo &HI) {
+HI.Kind = index::SymbolKind::Field;
+HI.AccessSpecifier = AccessSpecifier::AS_public;
+HI.Name = "foo";
+HI.LocalScope = "test::Bar::";
+HI.Definition = "def";
+  },
+  R"(public field foo
+
+// In test::Bar
+def)",
+  },
+  {
+  [](HoverInfo &HI) {
+HI.Definition = "int method()";
+HI.AccessSpecifier = AccessSpecifier::AS_protected;
+HI.Kind = index::SymbolKind::InstanceMethod;
+HI.NamespaceScope = "";
+HI.LocalScope = "cls::";
+HI.Name = "method";
+HI.Parameters.emplace();
+HI.ReturnType = "int";
+HI.Type = "int ()";
+  },
+  R"(protected instance-method method
+
+→ int
+
+// In cls
+int method())",
+  },
+  {
+  [](HoverInfo &HI) {
+HI.Kind = index::SymbolKind::Union;
+HI.AccessSpecifier = AccessSpecifier::AS_private;
+HI.Name = "foo";
+HI.NamespaceScope = "ns1::";
+HI.Definition = "union foo {}";
+  },
+  R"(private union foo
+
+// In namespace ns1
+union foo {})",
+  }};
 
   for (const auto &C : Cases) {
 HoverInfo HI;
Index: clang-tools-extra/clangd/Hover.h
===
--- clang-tools-extra/clangd/Hover.h
+++ clang-tools-extra/clangd/Hover.h
@@ -59,6 +59,8 @@
   /// Source code containing the definition of the symbol.
   std::string Definition;
 
+  /// Access specifier. Applies to members of class/structs or unions.
+  AccessSpecifier AccessSpecifier = AccessSpecifier::AS_none;
   /// Pretty-printed variable type.
   /// Set only for variables.
   llvm::Optional Type;
Index: clang-tools-extra/clangd/Hover.cpp
===
--- clang-tools-extra/clangd/Hover.cpp
+++ clang-tools-extra/clangd/Hover.cpp
@@ -468,6 +468,7 @@
   HoverInfo HI;
   const ASTContext &Ctx = D->getASTContext();
 
+  HI.AccessSpecifier = D->getAccess();
   HI.NamespaceScope = getNamespaceScope(D);
   if (!HI.NamespaceScope->empty())
 HI.NamespaceScope->append("::");
@@ -676,6 +677,20 @@
   }
 }
 
+StringRef getAccessString(AccessSpecifier AS) {
+  switch (AS) {
+  case AccessSpecifier::AS_public:
+return "public";
+  case AccessSpecifier::AS_protected:
+return "protected";
+  case AccessSpecifier::AS_private:
+return "private";
+  case AccessSpecifier::AS_none:
+return {};
+  }
+  llvm_unreachable("Unknown AccessSpecifier");
+}
+
 } // namespace
 
 llvm::Optional getHover(ParsedAST &AST, Position Pos,
@@ -774,6 +789,8 @@
   // level 1 and 2 headers in a huge font, see
   // https://github.com/microsoft/vscode/issues/88417 for details.
   markup::Paragraph &Header = Output.addHeading(3);
+  if (AccessSpecifier != AccessSpecifier::AS_none)
+Header.appendText(getAccessString(AccessSpecifier)).appendSpace();
   if (Kind != index::SymbolKind::Unknown)
 Header.appendText(index::getSymbolKindString(Kind)).appendSpace();
   assert(!Name.empty() && "hover triggered on a nameless symbol");
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D69585: Add option to instantiate templates already in the PCH

2020-05-25 Thread Luboš Luňák via Phabricator via cfe-commits
llunak marked an inline comment as done.
llunak added inline comments.



Comment at: clang/lib/Driver/ToolChains/Clang.cpp:5610
+  if (Args.hasFlag(options::OPT_fpch_instantiate_templates,
+   options::OPT_fno_pch_instantiate_templates, false))
+CmdArgs.push_back("-fpch-instantiate-templates");

rnk wrote:
> Does MSVC default to this behavior? Should this default to true with clang-cl 
> /Yu / /Yc? This can be future work and does not need to be part of this patch.
Since MSVC is noticeably faster for an equivalent PCH compile than current 
Clang, presumably it instantiates templates already in the PCH. But that 
doesn't really matter for this patch, if it were ok to enable this by default 
for clang-cl, than it would be ok also for clang itself. That cannot be done 
now though, https://reviews.llvm.org/D69585#1946765 points out a corner case 
where this change makes a valid compilation error out, and that's the reason 
for having this behind a flag. I expect Clang could possibly be adjusted to 
bail out and delay template instantiantion in such a case until it can be 
performed successfully, but given the response rate to my PCH patches I first 
wanted to get the feature in somehow, and I can try to make the flag 
default/irrelevant later.



Repository:
  rC Clang

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

https://reviews.llvm.org/D69585



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


[PATCH] D69585: Add option to instantiate templates already in the PCH

2020-05-25 Thread Reid "Away June-Sep" Kleckner via Phabricator via cfe-commits
rnk added inline comments.



Comment at: clang/lib/Driver/ToolChains/Clang.cpp:5610
+  if (Args.hasFlag(options::OPT_fpch_instantiate_templates,
+   options::OPT_fno_pch_instantiate_templates, false))
+CmdArgs.push_back("-fpch-instantiate-templates");

llunak wrote:
> rnk wrote:
> > Does MSVC default to this behavior? Should this default to true with 
> > clang-cl /Yu / /Yc? This can be future work and does not need to be part of 
> > this patch.
> Since MSVC is noticeably faster for an equivalent PCH compile than current 
> Clang, presumably it instantiates templates already in the PCH. But that 
> doesn't really matter for this patch, if it were ok to enable this by default 
> for clang-cl, than it would be ok also for clang itself. That cannot be done 
> now though, https://reviews.llvm.org/D69585#1946765 points out a corner case 
> where this change makes a valid compilation error out, and that's the reason 
> for having this behind a flag. I expect Clang could possibly be adjusted to 
> bail out and delay template instantiantion in such a case until it can be 
> performed successfully, but given the response rate to my PCH patches I first 
> wanted to get the feature in somehow, and I can try to make the flag 
> default/irrelevant later.
> 
Right, I guess what I mean is, for that example where instantiation at the end 
of the PCH creates an error, does MSVC emit an error? I just checked, and it 
looks like the answer is yes, so it seems like we could make this the default 
behavior for `clang-cl /Yc` without much further discussion.


Repository:
  rC Clang

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

https://reviews.llvm.org/D69585



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


[PATCH] D77491: [Sema] Introduce BuiltinAttr, per-declaration builtin-ness

2020-05-25 Thread Raul Tambre via Phabricator via cfe-commits
tambre updated this revision to Diff 265872.
tambre marked 4 inline comments as done.
tambre added a comment.

Remove memcpy overload tests from warn-fortify-source.c, which relied on 
identifier-based builtin identification.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D77491

Files:
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/IdentifierTable.h
  clang/include/clang/Sema/Sema.h
  clang/lib/AST/Decl.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaLookup.cpp
  clang/test/AST/ast-dump-attr.cpp
  clang/test/CodeGen/builtin-redeclaration.c
  clang/test/CodeGen/callback_pthread_create.c
  clang/test/CodeGen/ms-intrinsics.c
  clang/test/Sema/implicit-builtin-decl.c
  clang/test/Sema/warn-fortify-source.c
  clang/test/SemaCXX/cxx11-compat.cpp
  clang/test/SemaCXX/warn-unused-local-typedef.cpp

Index: clang/test/SemaCXX/warn-unused-local-typedef.cpp
===
--- clang/test/SemaCXX/warn-unused-local-typedef.cpp
+++ clang/test/SemaCXX/warn-unused-local-typedef.cpp
@@ -67,10 +67,10 @@
 
 void test() {
   typedef signed long int superint; // no diag
-  printf("%f", (superint) 42);
+  printf("%ld", (superint)42);
 
   typedef signed long int superint2; // no diag
-  printf("%f", static_cast(42));
+  printf("%ld", static_cast(42));
 
 #pragma clang diagnostic push
 #pragma clang diagnostic ignored "-Wunused-local-typedef"
Index: clang/test/SemaCXX/cxx11-compat.cpp
===
--- clang/test/SemaCXX/cxx11-compat.cpp
+++ clang/test/SemaCXX/cxx11-compat.cpp
@@ -31,7 +31,7 @@
 s = { n }, // expected-warning {{non-constant-expression cannot be narrowed from type 'int' to 'char' in initializer list in C++11}} expected-note {{explicit cast}}
 t = { 1234 }; // expected-warning {{constant expression evaluates to 1234 which cannot be narrowed to type 'char' in C++11}} expected-warning {{changes value}} expected-note {{explicit cast}}
 
-#define PRIuS "uS"
+#define PRIuS "zu"
 int printf(const char *, ...);
 typedef __typeof(sizeof(int)) size_t;
 void h(size_t foo, size_t bar) {
Index: clang/test/Sema/warn-fortify-source.c
===
--- clang/test/Sema/warn-fortify-source.c
+++ clang/test/Sema/warn-fortify-source.c
@@ -1,8 +1,6 @@
 // RUN: %clang_cc1 -triple x86_64-apple-macosx10.14.0 %s -verify
-// RUN: %clang_cc1 -triple x86_64-apple-macosx10.14.0 %s -verify -DUSE_PASS_OBJECT_SIZE
 // RUN: %clang_cc1 -triple x86_64-apple-macosx10.14.0 %s -verify -DUSE_BUILTINS
 // RUN: %clang_cc1 -xc++ -triple x86_64-apple-macosx10.14.0 %s -verify
-// RUN: %clang_cc1 -xc++ -triple x86_64-apple-macosx10.14.0 %s -verify -DUSE_PASS_OBJECT_SIZE
 // RUN: %clang_cc1 -xc++ -triple x86_64-apple-macosx10.14.0 %s -verify -DUSE_BUILTINS
 
 typedef unsigned long size_t;
@@ -13,13 +11,7 @@
 
 extern int sprintf(char *str, const char *format, ...);
 
-#if defined(USE_PASS_OBJECT_SIZE)
-void *memcpy(void *dst, const void *src, size_t c);
-static void *memcpy(void *dst __attribute__((pass_object_size(1))), const void *src, size_t c) __attribute__((overloadable)) __asm__("merp");
-static void *memcpy(void *const dst __attribute__((pass_object_size(1))), const void *src, size_t c) __attribute__((overloadable)) {
-  return 0;
-}
-#elif defined(USE_BUILTINS)
+#if defined(USE_BUILTINS)
 #define memcpy(x,y,z) __builtin_memcpy(x,y,z)
 #else
 void *memcpy(void *dst, const void *src, size_t c);
@@ -45,14 +37,7 @@
   };
   struct pair p;
   char buf[20];
-  memcpy(&p.first, buf, 20);
-#ifdef USE_PASS_OBJECT_SIZE
-  // Use the more strict checking mode on the pass_object_size attribute:
-  // expected-warning@-3 {{memcpy' will always overflow; destination buffer has size 4, but size argument is 20}}
-#else
-  // Or just fallback to type 0:
-  // expected-warning@-6 {{memcpy' will always overflow; destination buffer has size 8, but size argument is 20}}
-#endif
+  memcpy(&p.first, buf, 20); // expected-warning {{memcpy' will always overflow; destination buffer has size 8, but size argument is 20}}
 }
 
 void call_strncat() {
Index: clang/test/Sema/implicit-builtin-decl.c
===
--- clang/test/Sema/implicit-builtin-decl.c
+++ clang/test/Sema/implicit-builtin-decl.c
@@ -60,12 +60,15 @@
 
 extern float fmaxf(float, float);
 
-struct __jmp_buf_tag {};
-void sigsetjmp(struct __jmp_buf_tag[1], int); // expected-warning{{declaration of built-in function 'sigsetjmp' requires the declaration of the 'jmp_buf' type, commonly provided in the header .}}
+typedef struct __jmp_buf_tag {
+} sigjmp_buf[1];
 
-// CHECK: FunctionDecl {{.*}}  col:6 sigsetjmp '
+int sigsetjmp(struct __jmp_buf_tag[1], int);
+
+// CHECK: FunctionDecl {{.*}}  col:5 implicit sigsetjmp '
+// CHECK: FunctionDecl {{.*}}  col:5 sigsetj

[PATCH] D77491: [Sema] Introduce BuiltinAttr, per-declaration builtin-ness

2020-05-25 Thread Raul Tambre via Phabricator via cfe-commits
tambre updated this revision to Diff 265871.
tambre marked 6 inline comments as done.
tambre added a comment.

Weakened noexcept checking.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D77491

Files:
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/IdentifierTable.h
  clang/include/clang/Sema/Sema.h
  clang/lib/AST/Decl.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaLookup.cpp
  clang/test/AST/ast-dump-attr.cpp
  clang/test/CodeGen/builtin-redeclaration.c
  clang/test/CodeGen/callback_pthread_create.c
  clang/test/CodeGen/ms-intrinsics.c
  clang/test/Sema/implicit-builtin-decl.c
  clang/test/Sema/warn-fortify-source.c
  clang/test/SemaCXX/cxx11-compat.cpp
  clang/test/SemaCXX/warn-unused-local-typedef.cpp

Index: clang/test/SemaCXX/warn-unused-local-typedef.cpp
===
--- clang/test/SemaCXX/warn-unused-local-typedef.cpp
+++ clang/test/SemaCXX/warn-unused-local-typedef.cpp
@@ -67,10 +67,10 @@
 
 void test() {
   typedef signed long int superint; // no diag
-  printf("%f", (superint) 42);
+  printf("%ld", (superint)42);
 
   typedef signed long int superint2; // no diag
-  printf("%f", static_cast(42));
+  printf("%ld", static_cast(42));
 
 #pragma clang diagnostic push
 #pragma clang diagnostic ignored "-Wunused-local-typedef"
Index: clang/test/SemaCXX/cxx11-compat.cpp
===
--- clang/test/SemaCXX/cxx11-compat.cpp
+++ clang/test/SemaCXX/cxx11-compat.cpp
@@ -31,7 +31,7 @@
 s = { n }, // expected-warning {{non-constant-expression cannot be narrowed from type 'int' to 'char' in initializer list in C++11}} expected-note {{explicit cast}}
 t = { 1234 }; // expected-warning {{constant expression evaluates to 1234 which cannot be narrowed to type 'char' in C++11}} expected-warning {{changes value}} expected-note {{explicit cast}}
 
-#define PRIuS "uS"
+#define PRIuS "zu"
 int printf(const char *, ...);
 typedef __typeof(sizeof(int)) size_t;
 void h(size_t foo, size_t bar) {
Index: clang/test/Sema/warn-fortify-source.c
===
--- clang/test/Sema/warn-fortify-source.c
+++ clang/test/Sema/warn-fortify-source.c
@@ -1,10 +1,12 @@
 // RUN: %clang_cc1 -triple x86_64-apple-macosx10.14.0 %s -verify
-// RUN: %clang_cc1 -triple x86_64-apple-macosx10.14.0 %s -verify -DUSE_PASS_OBJECT_SIZE
 // RUN: %clang_cc1 -triple x86_64-apple-macosx10.14.0 %s -verify -DUSE_BUILTINS
 // RUN: %clang_cc1 -xc++ -triple x86_64-apple-macosx10.14.0 %s -verify
-// RUN: %clang_cc1 -xc++ -triple x86_64-apple-macosx10.14.0 %s -verify -DUSE_PASS_OBJECT_SIZE
 // RUN: %clang_cc1 -xc++ -triple x86_64-apple-macosx10.14.0 %s -verify -DUSE_BUILTINS
 
+// FIXME: Incompatible builtin redeclarations aren't considered builtins and thus don't call the builtin nor inherit their attributes.
+// %clang_cc1 -triple x86_64-apple-macosx10.14.0 %s -verify -DUSE_PASS_OBJECT_SIZE
+// %clang_cc1 -xc++ -triple x86_64-apple-macosx10.14.0 %s -verify -DUSE_PASS_OBJECT_SIZE
+
 typedef unsigned long size_t;
 
 #ifdef __cplusplus
Index: clang/test/Sema/implicit-builtin-decl.c
===
--- clang/test/Sema/implicit-builtin-decl.c
+++ clang/test/Sema/implicit-builtin-decl.c
@@ -60,12 +60,15 @@
 
 extern float fmaxf(float, float);
 
-struct __jmp_buf_tag {};
-void sigsetjmp(struct __jmp_buf_tag[1], int); // expected-warning{{declaration of built-in function 'sigsetjmp' requires the declaration of the 'jmp_buf' type, commonly provided in the header .}}
+typedef struct __jmp_buf_tag {
+} sigjmp_buf[1];
 
-// CHECK: FunctionDecl {{.*}}  col:6 sigsetjmp '
+int sigsetjmp(struct __jmp_buf_tag[1], int);
+
+// CHECK: FunctionDecl {{.*}}  col:5 implicit sigsetjmp '
+// CHECK: FunctionDecl {{.*}}  col:5 sigsetjmp '
 // CHECK-NOT: FunctionDecl
-// CHECK: ReturnsTwiceAttr {{.*}} <{{.*}}> Implicit
+// CHECK: ReturnsTwiceAttr {{.*}} <{{.*}}> Inherited Implicit
 
 // PR40692
 void pthread_create(); // no warning expected
Index: clang/test/CodeGen/ms-intrinsics.c
===
--- clang/test/CodeGen/ms-intrinsics.c
+++ clang/test/CodeGen/ms-intrinsics.c
@@ -17,6 +17,7 @@
 
 #include 
 
+// FIXME: Why aren't these builtins recognized as builtins?
 #if defined(__i386__) || defined(__x86_64__)
 void test__stosb(unsigned char *Dest, unsigned char Data, size_t Count) {
   return __stosb(Dest, Data, Count);
Index: clang/test/CodeGen/callback_pthread_create.c
===
--- clang/test/CodeGen/callback_pthread_create.c
+++ clang/test/CodeGen/callback_pthread_create.c
@@ -14,6 +14,7 @@
 typedef __darwin_pthread_t pthread_t;
 typedef __darwin_pthread_attr_t pthread_attr_t;
 
+// FIXME: Why isn't this reco

[PATCH] D77491: [Sema] Introduce BuiltinAttr, per-declaration builtin-ness

2020-05-25 Thread Raul Tambre via Phabricator via cfe-commits
tambre added inline comments.



Comment at: clang/lib/Sema/SemaDecl.cpp:8880
+  }
+}
+

rjmccall wrote:
> tambre wrote:
> > rjmccall wrote:
> > > Hmm.  I'm concerned about not doing any sort of semantic compatibility 
> > > check here before we assign the function special semantics.  Have we 
> > > really never done those in C++?
> > > 
> > > If not, I wonder if we can reasonably make an implicit declaration but 
> > > just make it hidden from lookup.
> > Currently there's no semantic compatibility checking for builtin 
> > redeclarations. There is for initial declarations though.
> > 
> > I've added this checking by splitting the actual builtin declaration 
> > creation off from `LazilyCreateBuiltin` into `CreateBuiltin` and checking 
> > if the current declaration is compatible with what the builtin's would be.
> > This results in stronger typechecking than before for builtin declarations, 
> > so some incompatible declarations are no longer marked as builtin. See 
> > `cxx1z-noexcept-function-type.cpp` for an example.
> That makes sense to me in principle.  I'm definitely concerned about 
> `noexcept` differences causing C library functions to not be treated as 
> builtins, though; that seems stricter than we want.  How reasonable is it to 
> weaken this?
I agree having `noexcept` weakened is reasonable.
I've changed it to create an identical type to the NewFD with the exception 
spec removed for the comparison. This fixes it.



Comment at: clang/test/CodeGen/ms-intrinsics.c:23
 void test__stosb(unsigned char *Dest, unsigned char Data, size_t Count) {
   return __stosb(Dest, Data, Count);
 }

`__stosb` and friends aren't marked as builtin because they're declared as 
`static`.
I don't think there's a good reason to have builtins as `static` and we should 
simply remove the `static` specifier from those intrinsics in headers.
Alternatively, we could weaken compatibility checking similar to `noexcept`.
Thoughts?



Comment at: clang/test/Sema/warn-fortify-source.c:20
 void *memcpy(void *dst, const void *src, size_t c);
 static void *memcpy(void *dst __attribute__((pass_object_size(1))), const void 
*src, size_t c) __attribute__((overloadable)) __asm__("merp");
 static void *memcpy(void *const dst __attribute__((pass_object_size(1))), 
const void *src, size_t c) __attribute__((overloadable)) {

rjmccall wrote:
> tambre wrote:
> > Not quite sure what to do here. These were previously recognized as 
> > builtins due to their name despite being incompatible and thus had fortify 
> > checking similar to the real `memcpy`.
> > 
> > Maybe:
> > 1. Introduce a generic version of `ArmBuiltinAliasAttr`.
> > 2. Something like `FormatAttr`.
> That's interesting.  It definitely seems wrong to apply builtin logic to a 
> function that doesn't have a compatible low-level signature.  My inclination 
> is to disable builtin checking here, but to notify the contributors so that 
> they can figure out an appropriate response.
Agreed.
I've removed this test, as there doesn't seem to be an easy way to replicate 
this behaviour.



Comment at: clang/test/SemaCXX/cxx1z-noexcept-function-type.cpp:120
   extern "C" int strcmp(const char *, const char *);
-  extern "C" int strncmp(const char *, const char *, decltype(sizeof(0))) 
noexcept;
+  extern "C" int strncmp(const char *, const char *, decltype(sizeof(0)));
 

tambre wrote:
> This doesn't work anymore since we now properly check builtin declaration 
> compatibility and since C++17 noexcept is part of the function type but 
> builtins aren't noexcept.
> Thoughts?
Fixed by removing `noexcept` for the declaration compatibility comparison.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D77491



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


[PATCH] D78938: Fixing all comparisons for C++20 compilation.

2020-05-25 Thread Barry Revzin via Phabricator via cfe-commits
BRevzin marked 2 inline comments as done.
BRevzin added a comment.

I hadn't build the tests before, updated with a few more changes. Some of the 
tests require `u8` literals, whose type changes in C++20. I had no idea what to 
do with that, so I just `#ifdef`-ed out those tests with the appropriate 
feature test macro.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D78938



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


[PATCH] D78938: Fixing all comparisons for C++20 compilation.

2020-05-25 Thread Barry Revzin via Phabricator via cfe-commits
BRevzin updated this revision to Diff 265874.
BRevzin added a comment.
Herald added a subscriber: martong.

- A few more changes from tests.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D78938

Files:
  clang/include/clang/AST/StmtIterator.h
  clang/lib/Parse/ParseOpenMP.cpp
  clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp
  llvm/include/llvm/ADT/AllocatorList.h
  llvm/include/llvm/ADT/DenseMap.h
  llvm/include/llvm/ADT/DenseSet.h
  llvm/include/llvm/ADT/DirectedGraph.h
  llvm/include/llvm/ADT/STLExtras.h
  llvm/include/llvm/ADT/StringMap.h
  llvm/include/llvm/ADT/iterator.h
  llvm/include/llvm/CodeGen/LiveInterval.h
  llvm/include/llvm/IR/Attributes.h
  llvm/include/llvm/IR/BasicBlock.h
  llvm/include/llvm/Object/StackMapParser.h
  llvm/include/llvm/ProfileData/Coverage/CoverageMappingReader.h
  llvm/include/llvm/ProfileData/InstrProfReader.h
  llvm/include/llvm/Support/BinaryStreamRef.h
  llvm/lib/CodeGen/MachineOutliner.cpp
  llvm/lib/CodeGen/PeepholeOptimizer.cpp
  llvm/lib/IR/Attributes.cpp
  llvm/lib/IR/DebugInfo.cpp
  llvm/lib/Transforms/Scalar/GVNHoist.cpp
  llvm/unittests/ADT/STLExtrasTest.cpp
  llvm/unittests/Support/DJBTest.cpp
  llvm/unittests/Support/JSONTest.cpp

Index: llvm/unittests/Support/JSONTest.cpp
===
--- llvm/unittests/Support/JSONTest.cpp
+++ llvm/unittests/Support/JSONTest.cpp
@@ -173,12 +173,14 @@
   Compare(R"("\"\\\b\f\n\r\t")", "\"\\\b\f\n\r\t");
   Compare(R"("\u")", llvm::StringRef("\0", 1));
   Compare("\"\x7f\"", "\x7f");
+#ifndef __cpp_char8_t
   Compare(R"("\ud801\udc37")", u8"\U00010437"); // UTF16 surrogate pair escape.
   Compare("\"\xE2\x82\xAC\xF0\x9D\x84\x9E\"", u8"\u20ac\U0001d11e"); // UTF8
   Compare(
   R"("LoneLeading=\ud801, LoneTrailing=\udc01, LeadingLeadingTrailing=\ud801\ud801\udc37")",
   u8"LoneLeading=\ufffd, LoneTrailing=\ufffd, "
   u8"LeadingLeadingTrailing=\ufffd\U00010437"); // Invalid unicode.
+#endif
 
   Compare(R"({"":0,"":0})", Object{{"", 0}});
   Compare(R"({"obj":{},"arr":[]})", Object{{"obj", Object{}}, {"arr", {}}});
Index: llvm/unittests/Support/DJBTest.cpp
===
--- llvm/unittests/Support/DJBTest.cpp
+++ llvm/unittests/Support/DJBTest.cpp
@@ -24,6 +24,7 @@
   {{""}, {""}},
 
   {{"I"}, {"i"}},
+#ifndef __cpp_char8_t
   // Latin Small Letter Dotless I
   {{u8"\u0130"}, {"i"}},
   // Latin Capital Letter I With Dot Above
@@ -47,6 +48,7 @@
   {{u8"\uff2d"}, {u8"\uff4d"}},
   // Old Hungarian Capital Letter Ej
   {{u8"\U00010c92"}, {u8"\U00010cd2"}},
+#endif
   };
 
   for (const TestCase &T : Tests) {
@@ -79,6 +81,7 @@
   }
 }
 
+#ifndef __cpp_char8_t
 TEST(DJBTest, knownValuesUnicode) {
   EXPECT_EQ(5866553u, djbHash(u8"\u0130"));
   EXPECT_EQ(177678u, caseFoldingDjbHash(u8"\u0130"));
@@ -93,3 +96,4 @@
   u8"\u0130\u0131\u00c0\u00e0\u0100\u0101\u0139\u013a\u0415\u0435\u1ea6"
   u8"\u1ea7\u212a\u006b\u2c1d\u2c4d\uff2d\uff4d\U00010c92\U00010cd2"));
 }
+#endif
\ No newline at end of file
Index: llvm/unittests/ADT/STLExtrasTest.cpp
===
--- llvm/unittests/ADT/STLExtrasTest.cpp
+++ llvm/unittests/ADT/STLExtrasTest.cpp
@@ -463,21 +463,21 @@
 
   // Check fancy pointer overload for unique_ptr
   std::unique_ptr V2 = std::make_unique(0);
-  EXPECT_EQ(V2.get(), to_address(V2));
+  EXPECT_EQ(V2.get(), (to_address)(V2));
 
   V2.reset(V1);
-  EXPECT_EQ(V1, to_address(V2));
+  EXPECT_EQ(V1, (to_address)(V2));
   V2.release();
 
   // Check fancy pointer overload for shared_ptr
   std::shared_ptr V3 = std::make_shared(0);
   std::shared_ptr V4 = V3;
   EXPECT_EQ(V3.get(), V4.get());
-  EXPECT_EQ(V3.get(), to_address(V3));
-  EXPECT_EQ(V4.get(), to_address(V4));
+  EXPECT_EQ(V3.get(), (to_address)(V3));
+  EXPECT_EQ(V4.get(), (to_address)(V4));
 
   V3.reset(V1);
-  EXPECT_EQ(V1, to_address(V3));
+  EXPECT_EQ(V1, (to_address)(V3));
 }
 
 TEST(STLExtrasTest, partition_point) {
Index: llvm/lib/Transforms/Scalar/GVNHoist.cpp
===
--- llvm/lib/Transforms/Scalar/GVNHoist.cpp
+++ llvm/lib/Transforms/Scalar/GVNHoist.cpp
@@ -149,8 +149,8 @@
   // The instruction (VN) which uses the values flowing out of CHI.
   Instruction *I;
 
-  bool operator==(const CHIArg &A) { return VN == A.VN; }
-  bool operator!=(const CHIArg &A) { return !(*this == A); }
+  bool operator==(const CHIArg &A) const { return VN == A.VN; }
+  bool operator!=(const CHIArg &A) const { return !(*this == A); }
 };
 
 using CHIIt = SmallVectorImpl::iterator;
Index: llvm/lib/IR/DebugInfo.cpp
===
--- llvm/lib/IR/DebugInfo.cpp
+++ llvm/lib/IR/DebugInfo.cpp
@@ -665,7 +665,7 @@
   i

[PATCH] D78938: Fixing all comparisons for C++20 compilation.

2020-05-25 Thread Barry Revzin via Phabricator via cfe-commits
BRevzin updated this revision to Diff 265875.
BRevzin added a comment.

- Adding missing return.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D78938

Files:
  clang/include/clang/AST/StmtIterator.h
  clang/lib/Parse/ParseOpenMP.cpp
  clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp
  llvm/include/llvm/ADT/AllocatorList.h
  llvm/include/llvm/ADT/DenseMap.h
  llvm/include/llvm/ADT/DenseSet.h
  llvm/include/llvm/ADT/DirectedGraph.h
  llvm/include/llvm/ADT/STLExtras.h
  llvm/include/llvm/ADT/StringMap.h
  llvm/include/llvm/ADT/iterator.h
  llvm/include/llvm/CodeGen/LiveInterval.h
  llvm/include/llvm/IR/Attributes.h
  llvm/include/llvm/IR/BasicBlock.h
  llvm/include/llvm/Object/StackMapParser.h
  llvm/include/llvm/ProfileData/Coverage/CoverageMappingReader.h
  llvm/include/llvm/ProfileData/InstrProfReader.h
  llvm/include/llvm/Support/BinaryStreamRef.h
  llvm/lib/CodeGen/MachineOutliner.cpp
  llvm/lib/CodeGen/PeepholeOptimizer.cpp
  llvm/lib/IR/Attributes.cpp
  llvm/lib/IR/DebugInfo.cpp
  llvm/lib/Transforms/Scalar/GVNHoist.cpp
  llvm/unittests/ADT/STLExtrasTest.cpp
  llvm/unittests/Support/DJBTest.cpp
  llvm/unittests/Support/JSONTest.cpp

Index: llvm/unittests/Support/JSONTest.cpp
===
--- llvm/unittests/Support/JSONTest.cpp
+++ llvm/unittests/Support/JSONTest.cpp
@@ -173,12 +173,14 @@
   Compare(R"("\"\\\b\f\n\r\t")", "\"\\\b\f\n\r\t");
   Compare(R"("\u")", llvm::StringRef("\0", 1));
   Compare("\"\x7f\"", "\x7f");
+#ifndef __cpp_char8_t
   Compare(R"("\ud801\udc37")", u8"\U00010437"); // UTF16 surrogate pair escape.
   Compare("\"\xE2\x82\xAC\xF0\x9D\x84\x9E\"", u8"\u20ac\U0001d11e"); // UTF8
   Compare(
   R"("LoneLeading=\ud801, LoneTrailing=\udc01, LeadingLeadingTrailing=\ud801\ud801\udc37")",
   u8"LoneLeading=\ufffd, LoneTrailing=\ufffd, "
   u8"LeadingLeadingTrailing=\ufffd\U00010437"); // Invalid unicode.
+#endif
 
   Compare(R"({"":0,"":0})", Object{{"", 0}});
   Compare(R"({"obj":{},"arr":[]})", Object{{"obj", Object{}}, {"arr", {}}});
Index: llvm/unittests/Support/DJBTest.cpp
===
--- llvm/unittests/Support/DJBTest.cpp
+++ llvm/unittests/Support/DJBTest.cpp
@@ -24,6 +24,7 @@
   {{""}, {""}},
 
   {{"I"}, {"i"}},
+#ifndef __cpp_char8_t
   // Latin Small Letter Dotless I
   {{u8"\u0130"}, {"i"}},
   // Latin Capital Letter I With Dot Above
@@ -47,6 +48,7 @@
   {{u8"\uff2d"}, {u8"\uff4d"}},
   // Old Hungarian Capital Letter Ej
   {{u8"\U00010c92"}, {u8"\U00010cd2"}},
+#endif
   };
 
   for (const TestCase &T : Tests) {
@@ -79,6 +81,7 @@
   }
 }
 
+#ifndef __cpp_char8_t
 TEST(DJBTest, knownValuesUnicode) {
   EXPECT_EQ(5866553u, djbHash(u8"\u0130"));
   EXPECT_EQ(177678u, caseFoldingDjbHash(u8"\u0130"));
@@ -93,3 +96,4 @@
   u8"\u0130\u0131\u00c0\u00e0\u0100\u0101\u0139\u013a\u0415\u0435\u1ea6"
   u8"\u1ea7\u212a\u006b\u2c1d\u2c4d\uff2d\uff4d\U00010c92\U00010cd2"));
 }
+#endif
\ No newline at end of file
Index: llvm/unittests/ADT/STLExtrasTest.cpp
===
--- llvm/unittests/ADT/STLExtrasTest.cpp
+++ llvm/unittests/ADT/STLExtrasTest.cpp
@@ -463,21 +463,21 @@
 
   // Check fancy pointer overload for unique_ptr
   std::unique_ptr V2 = std::make_unique(0);
-  EXPECT_EQ(V2.get(), to_address(V2));
+  EXPECT_EQ(V2.get(), (to_address)(V2));
 
   V2.reset(V1);
-  EXPECT_EQ(V1, to_address(V2));
+  EXPECT_EQ(V1, (to_address)(V2));
   V2.release();
 
   // Check fancy pointer overload for shared_ptr
   std::shared_ptr V3 = std::make_shared(0);
   std::shared_ptr V4 = V3;
   EXPECT_EQ(V3.get(), V4.get());
-  EXPECT_EQ(V3.get(), to_address(V3));
-  EXPECT_EQ(V4.get(), to_address(V4));
+  EXPECT_EQ(V3.get(), (to_address)(V3));
+  EXPECT_EQ(V4.get(), (to_address)(V4));
 
   V3.reset(V1);
-  EXPECT_EQ(V1, to_address(V3));
+  EXPECT_EQ(V1, (to_address)(V3));
 }
 
 TEST(STLExtrasTest, partition_point) {
Index: llvm/lib/Transforms/Scalar/GVNHoist.cpp
===
--- llvm/lib/Transforms/Scalar/GVNHoist.cpp
+++ llvm/lib/Transforms/Scalar/GVNHoist.cpp
@@ -149,8 +149,8 @@
   // The instruction (VN) which uses the values flowing out of CHI.
   Instruction *I;
 
-  bool operator==(const CHIArg &A) { return VN == A.VN; }
-  bool operator!=(const CHIArg &A) { return !(*this == A); }
+  bool operator==(const CHIArg &A) const { return VN == A.VN; }
+  bool operator!=(const CHIArg &A) const { return !(*this == A); }
 };
 
 using CHIIt = SmallVectorImpl::iterator;
Index: llvm/lib/IR/DebugInfo.cpp
===
--- llvm/lib/IR/DebugInfo.cpp
+++ llvm/lib/IR/DebugInfo.cpp
@@ -665,7 +665,7 @@
   if (auto *T = dyn_cast_or_null(Attachment.sec

[clang] 1d96dca - HIP: Try to deal with more llvm package layouts

2020-05-25 Thread Matt Arsenault via cfe-commits

Author: Matt Arsenault
Date: 2020-05-23T13:28:24-04:00
New Revision: 1d96dca9491e3d75c11c3cd1acff5fcda8c2f613

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

LOG: HIP: Try to deal with more llvm package layouts

The various HIP builds are all inconsistent.

The default llvm install goes to ${INSTALL_PREFIX}/bin/clang, but the
rocm packaging scripts move this under
${INSTALL_PREFIX}/llvm/bin/clang. Some other builds further pollute
this with ${INSTALL_PREFIX}/bin/x86_64/clang. These should really be
consolidated, but try to handle them for now.

Added: 


Modified: 
clang/lib/Driver/ToolChains/AMDGPU.cpp

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/AMDGPU.cpp 
b/clang/lib/Driver/ToolChains/AMDGPU.cpp
index 193ccad98f52..3e51bd00bae4 100644
--- a/clang/lib/Driver/ToolChains/AMDGPU.cpp
+++ b/clang/lib/Driver/ToolChains/AMDGPU.cpp
@@ -107,11 +107,18 @@ RocmInstallationDetector::RocmInstallationDetector(
 // the Windows-esque layout the ROCm packages use with the host 
architecture
 // subdirectory of bin.
 
+// Strip off directory (usually bin)
 StringRef ParentDir = llvm::sys::path::parent_path(InstallDir);
-if (ParentDir == HostTriple.getArchName())
+StringRef ParentName = llvm::sys::path::filename(ParentDir);
+
+// Some builds use bin/{host arch}, so go up again.
+if (ParentName == "bin") {
   ParentDir = llvm::sys::path::parent_path(ParentDir);
+  ParentName = llvm::sys::path::filename(ParentDir);
+}
 
-if (ParentDir == "bin") {
+if (ParentName == "llvm") {
+  // Some versions of the rocm llvm package install to /opt/rocm/llvm/bin
   Candidates.emplace_back(llvm::sys::path::parent_path(ParentDir).str(),
   /*StrictChecking=*/true);
 }



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


[PATCH] D80461: HIP: Try to deal with more llvm package layouts

2020-05-25 Thread Matt Arsenault via Phabricator via cfe-commits
arsenm closed this revision.
arsenm added a comment.

1d96dca9491e3d75c11c3cd1acff5fcda8c2f613 



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

https://reviews.llvm.org/D80461



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


[PATCH] D80289: [Driver][X86] Support branch align options with LTO

2020-05-25 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added a comment.

In D80289#2051947 , @skan wrote:

> Ping.


`https://reviews.llvm.org/D80168#2046093`

"Unless something is urgent, the usual practice is to ping after a week rather 
than 24 hours, as many people have big piles on their review plate, so can't 
always get to it the next day."




Comment at: clang/test/Driver/x86-malign-branch.c:6
 // BOUNDARY: "-mllvm" "-x86-align-branch-boundary=16"
+// RUN: %clang -target x86_64-unknown-linux -malign-branch-boundary=16 -flto 
%s -### 2>&1 | FileCheck %s --check-prefix=BOUNDARY-LTO
+// BOUNDARY-LTO: "-plugin-opt=-x86-align-branch-boundary=16"

Drop `-unknown-linux`

ditto below


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80289



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


[PATCH] D76801: [AST] Print a> without extra spaces in C++11 or later.

2020-05-25 Thread Douglas Yung via Phabricator via cfe-commits
dyung added a comment.

Hi, we noticed an issue with the GDB test suite that was bisected back to this 
change and I have put the details in PR46052. Can you take a look?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76801



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


[PATCH] D80239: [libTooling] In Transformer, allow atomic changes to span multiple files.

2020-05-25 Thread Dmitri Gribenko via Phabricator via cfe-commits
gribozavr2 accepted this revision.
gribozavr2 added inline comments.
This revision is now accepted and ready to land.



Comment at: clang/lib/Tooling/Transformer/Transformer.cpp:65
 
-  for (const auto &I : Case.AddedIncludes) {
-auto &Header = I.first;
-switch (I.second) {
-case transformer::IncludeFormat::Quoted:
-  AC.addHeader(Header);
-  break;
-case transformer::IncludeFormat::Angled:
-  AC.addHeader((llvm::Twine("<") + Header + ">").str());
-  break;
+  for (auto &IDChangePair : ChangesByFileID) {
+auto &AC = IDChangePair.second;

The test shows an example transformer that removes code, so the header 
insertion logic is not triggered there. However, for a change that would be 
adding code, is it correct to insert the header into every file being edited? I 
think not necessarily. Or do you prefer to deal with this issue when we have a 
sample use case?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80239



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


[clang] 2e43bab - [docs] Fix warnings in ConstantInterpreter

2020-05-25 Thread Jinsong Ji via cfe-commits

Author: Jinsong Ji
Date: 2020-05-23T19:36:05Z
New Revision: 2e43bab1c161a97df4883def3c4c4a8b92883377

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

LOG: [docs] Fix warnings in ConstantInterpreter

Fixed following trivial issues that caught by warnings by adding
indents.

clang/docs/ConstantInterpreter.rst:133: WARNING: Bullet list ends
without a blank line; unexpected unindent.
clang/docs/ConstantInterpreter.rst:136: WARNING: Bullet list ends
without a blank line; unexpected unindent.
clang/docs/ConstantInterpreter.rst:153: WARNING: Bullet list ends
without a blank line; unexpected unindent.
clang/docs/ConstantInterpreter.rst:195: WARNING: Bullet list ends
without a blank line; unexpected unindent.
clang/docs/ConstantInterpreter.rst:225: WARNING: Bullet list ends
without a blank line; unexpected unindent.
clang/docs/ConstantInterpreter.rst:370: WARNING: Bullet list ends
without a blank line; unexpected unindent.
clang/docs/ConstantInterpreter.rst:383: WARNING: Bullet list ends
without a blank line; unexpected unindent.

Added: 


Modified: 
clang/docs/ConstantInterpreter.rst

Removed: 




diff  --git a/clang/docs/ConstantInterpreter.rst 
b/clang/docs/ConstantInterpreter.rst
index c976f35a67c5..eba637585b8f 100644
--- a/clang/docs/ConstantInterpreter.rst
+++ b/clang/docs/ConstantInterpreter.rst
@@ -13,7 +13,7 @@ clang, improving performance on constructs which are executed 
inefficiently
 by the evaluator. The interpreter is activated using the following flags:
 
 * ``-fexperimental-new-constant-interpreter`` enables the interpreter,
-emitting an error if an unsupported feature is encountered
+  emitting an error if an unsupported feature is encountered
 
 Bytecode Compilation
 
@@ -130,11 +130,11 @@ descriptor that characterises the entire allocation, 
along with a few
 additional attributes:
 
 * ``IsStatic`` indicates whether the block has static duration in the
-interpreter, i.e. it is not a local in a frame.
+  interpreter, i.e. it is not a local in a frame.
 
 * ``DeclID`` identifies each global declaration (it is set to an invalid
-and irrelevant value for locals) in order to prevent illegal writes and
-reads involving globals and temporaries with static storage duration.
+  and irrelevant value for locals) in order to prevent illegal writes and
+  reads involving globals and temporaries with static storage duration.
 
 Static blocks are never deallocated, but local ones might be deallocated
 even when there are live pointers to them. Pointers are only valid as
@@ -150,8 +150,8 @@ The lifetime of blocks is managed through 3 methods stored 
in the
 descriptor of the block:
 
 * **CtorFn**: initializes the metadata which is store in the block,
-alongside actual data. Invokes the default constructors of objects
-which are not trivial (``Pointer``, ``RealFP``, etc.)
+  alongside actual data. Invokes the default constructors of objects
+  which are not trivial (``Pointer``, ``RealFP``, etc.)
 
 * **DtorFn**: invokes the destructors of non-trivial objects.
 
@@ -192,13 +192,13 @@ The interpreter distinguishes 3 
diff erent kinds of blocks:
   has the following fields:
 
* **Offset**: byte offset into the array or record, used to step back to the
-   parent array or record.
+ parent array or record.
* **IsConst**: flag indicating if the field is const-qualified.
* **IsInitialized**: flag indicating whether the field or element was
-   initialized. For non-primitive fields, this is only relevant to determine
-   the dynamic type of objects during construction.
+ initialized. For non-primitive fields, this is only relevant to determine
+ the dynamic type of objects during construction.
* **IsBase**: flag indicating whether the record is a base class. In that
-   case, the offset can be used to identify the derived class.
+ case, the offset can be used to identify the derived class.
* **IsActive**: indicates if the field is the active field of a union.
* **IsMutable**: indicates if the field is marked as mutable.
 
@@ -222,19 +222,19 @@ Pointers, implemented in ``Pointer.h`` are represented as 
a tagged union.
 Some of these may not yet be available in upstream ``clang``.
 
  * **BlockPointer**: used to reference memory allocated and managed by the
- interpreter, being the only pointer kind which allows dereferencing in the
- interpreter
+   interpreter, being the only pointer kind which allows dereferencing in the
+   interpreter
  * **ExternPointer**: points to memory which can be addressed, but not read by
- the interpreter. It is equivalent to APValue, tracking a declaration and a 
path
- of fields and indices into that allocation.
+   the interpreter. It is equivalent to APValue, tracking a declaration and a 
path

[PATCH] D80425: Fix LLVM/Clang builds with mingw toolchain

2020-05-25 Thread Tobias Hieta via Phabricator via cfe-commits
thieta added a comment.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80425



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


[PATCH] D80425: Fix LLVM/Clang builds with mingw toolchain

2020-05-25 Thread Martin Storsjö via Phabricator via cfe-commits
mstorsjo added inline comments.



Comment at: llvm/cmake/modules/HandleLLVMOptions.cmake:967
CMAKE_EXE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS)
-  elseif(LINKER_IS_LLD_LINK)
+  elseif(LINKER_IS_LLD_LINK AND NOT MINGW)
 append("/lldltocache:${PROJECT_BINARY_DIR}/lto.cache"

mati865 wrote:
> mstorsjo wrote:
> > mati865 wrote:
> > > thieta wrote:
> > > > mstorsjo wrote:
> > > > > Do you happen to know why `LINKER_IS_LLD_LINK` gets set in this case? 
> > > > > `ld.lld` (the ELF linker interface, which then the MinGW driver 
> > > > > remaps onto the COFF backend with the `lld-link` interface) certainly 
> > > > > doesn't take `lld-link` style options. I believe (without diving 
> > > > > further into it) that we shouldn't be setting this flag in this 
> > > > > combination, but with the option implemented, we should fit it into 
> > > > > the case further above, `elseif((UNIX OR MINGW) AND LLVM_USE_LINKER 
> > > > > STREQUAL "lld")`
> > > > Yeah I bet that variable is set because I pass `LLVM_USE_LINKER=lld` 
> > > > but I haven't digged to deeply. I can rework the if statement here when 
> > > > we have the lld option in there.
> > > > Yeah I bet that variable is set because I pass LLVM_USE_LINKER=lld but 
> > > > I haven't digged to deeply. 
> > > 
> > > It does use `lld-link` when you use `LLVM_USE_LINKER=lld`.
> > > 
> > > The problem lies in this line:
> > > ```
> > > append("/lldltocache:${PROJECT_BINARY_DIR}/lto.cache"
> > > ```
> > > For MinGW that should read:
> > > ```
> > > append("-Wl,/lldltocache:${PROJECT_BINARY_DIR}/lto.cache"
> > > ```
> > > That's because you are passing this flag to GCC/Clang.
> > > For MinGW that should read:
> > > 
> > > append("-Wl,/lldltocache:${PROJECT_BINARY_DIR}/lto.cache"
> > 
> > We're adding this option properly in the mingw frontend, so we shouldn't do 
> > the hacky way of passing lld-link options via the mingw frontend by passing 
> > them as `/option`.
> > 
> > And the reason `LINKER_IS_LLD_LINK` is set seems to be this:
> > 
> > ```
> > if(CMAKE_LINKER MATCHES "lld-link" OR (WIN32 AND LLVM_USE_LINKER STREQUAL 
> > "lld") OR LLVM_ENABLE_LLD)
> > ```
> > 
> > Perhaps that should be changed into
> > 
> > ```
> > if(CMAKE_LINKER MATCHES "lld-link" OR (WIN32 AND LLVM_USE_LINKER STREQUAL 
> > "lld" AND NOT MINGW) OR LLVM_ENABLE_LLD)
> > ```
> > 
> > We're adding this option properly in the mingw frontend, so we shouldn't do 
> > the hacky way of passing lld-link options via the mingw frontend by passing 
> > them as /option.
> 
> I was about to add that and one more LTO related option but thought "what if 
> LLVM should link with lld-link on MinGW?" and eventually forgot about it.
> 
> 
> 
> > And the reason LINKER_IS_LLD_LINK is set seems to be this:
> > ```
> > if(CMAKE_LINKER MATCHES "lld-link" OR (WIN32 AND LLVM_USE_LINKER STREQUAL 
> > "lld") OR LLVM_ENABLE_LLD)
> > ```
> > Perhaps that should be changed into
> > ```
> > if(CMAKE_LINKER MATCHES "lld-link" OR (WIN32 AND LLVM_USE_LINKER STREQUAL 
> > "lld" AND NOT MINGW) OR LLVM_ENABLE_LLD)
> > ```
> 
> It won't work if somebody uses `LLVM_ENABLE_LLD=ON` instead of 
> `LLVM_USE_LINKER=lld` which is supposed to be equivalent.
> That raises question how `LLVM_ENABLE_LLD=ON` does even work on UNIX 
> platforms.
> 
> IMO this would be better:
> ```
> if(CMAKE_LINKER MATCHES "lld-link" OR MSVC AND (LLVM_USE_LINKER STREQUAL 
> "lld" OR LLVM_ENABLE_LLD))
> ```
> I was about to add that and one more LTO related option but thought "what if 
> LLVM should link with lld-link on MinGW?" and eventually forgot about it.

I don't think that really is a supposedly supported setup - lld-link wouldn't 
find any libs to link against etc, as the compiler driver is supposed to pass 
those as `-L` options in mingw/unix style tools.

> It won't work if somebody uses LLVM_ENABLE_LLD=ON instead of 
> LLVM_USE_LINKER=lld which is supposed to be equivalent.
> That raises question how LLVM_ENABLE_LLD=ON does even work on UNIX platforms.

Either it doesn't work and nobody actually use it that way, or the effects of 
`LINKER_IS_LLD_LINK` are mostly harmless.

> IMO this would be better:
> 
> `if(CMAKE_LINKER MATCHES "lld-link" OR MSVC AND (LLVM_USE_LINKER STREQUAL 
> "lld" OR LLVM_ENABLE_LLD))`

Yeah, that looks sensible.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80425



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


Re: Bug in QualTypeNames.cpp and adding an option to prepend "::" to fully qualified names.

2020-05-25 Thread Jean-Baptiste Lespiau via cfe-commits
Hi,

should we submit this CL, adding the option to prepend classes and struct
fully qualified names with "::"?

This can then allow people to slowly switch to the new function, and I can
close my fix/close my bug in CLIF. I can do more on this CL if it is
needed, but I would like to be sure this will get submitted and I will not
waste my time, and know exactly what you want me to do.

Possible options include:
- adding the full context, with the bug, in the CL description
- adding documentation on `getFullyQualifiedName` expliciting in which
context the bug can occur
- adding a FullyQualifiedTypePrinter() that will take an AST or a
TypePolicy, and set the correct fields, so one can do
QualType.getAsString(FullyQualifiedTypePrinter(ast)) to replace the
hereabove one.
- add some tests, but I do not know where and how.

When this few lines are submitted, I can update google3 for clang, and I
can start changing some internal occurrences, and finally fix the CLIF bug.

Thanks!

On Tue, May 12, 2020 at 11:19 PM Jean-Baptiste Lespiau 
wrote:

>
>
> On Tue, May 12, 2020 at 11:11 PM David Blaikie  wrote:
>
>> On Tue, May 12, 2020 at 12:40 PM Jean-Baptiste Lespiau <
>> jblesp...@google.com> wrote:
>>
>>> Hi,
>>>
>>> thanks for your answer.
>>>
>>> Just a few remarks:
>>>
>>> 1. I imagine that we cannot know if people are using
>>> getFullyQualifiedName. In particular, people could have developed their own
>>> internal tools, thus we cannot be aware of all callers. I do not know
>>> Clang's policy, but can we delete or completely change a function without
>>> deprecating it first?
>>>
>>
>> The LLVM project offers little/no API guarantees - potentially/especially
>> for a function with no use in-tree. But, yes, as Googlers we'd be
>> encouraged not to commit an API change knowing this might cause widespread
>> internal breakage without a plan/pre-emptively fixing things.
>>
>>
>>> I was imagining that the process was to deprecate it, document the case
>>> where it can be incorrect, and that in a next release it gets
>>> deleted/replaced (or someone steps up to fix it).
>>>
>>
>> Sometimes deprecation is used - certain APIs have a lot of out of tree
>> surface area
>>
>>
>>> 2. As example of different behaviors:
>>> (a) the qual_type.getAsString() will print implementation namespace
>>> details (e.g. ::std*::__u*::variant instead of std::variant).
>>>
>>
>> Yep, that's probably not ideal for most source generating use cases.
>>
>>
>>> (b) It will also display default template arguments, e.g.
>>> template 
>>> class MyClass
>>> is printed as MyClass (I think) in getFullyQualifiedName, while
>>> getAsString() will use MyClass.
>>>
>>
>> That seems better/correct - did CLIF actually want/rely on/benefit from
>> the old behavior of only printing the template name?
>>
>
> I did check to replace all of the getFullyQualifiedName in CLIF with the
> new version: it worked like a charm. The error messages are just changed
> accordingly (so they will have longer types).
> And the generated code was also less verbose.
>
>>
>>
>>> (c) the example of the nested template argument above.
>>>
>>
>> Which seems just wrong/inconsistent/not-behaving-to-spec to me - I don't
>> imagine any caller actually wanted that behavior?
>>
>
> I agree.
>
>>
>>
>>>
>>> At the end,what matters is that getAsString() is semantically always
>>> correct, even if it can be overly verbose.
>>>
>>
>> The presence of inline namespaces is about the only bit I'd find a touch
>> questionable. (Hopefully Sam can chime in on some of that)
>>
>
> Me too, I would be curious if it is easy to remove.
>
>>
>>
>>> I tried to fix getFullyQualifiedName, but I do not understand its code.
>>>
>>> 3. When the goal we want to reach has been decided, there is also the
>>> question on how to transition from the current state to the next state, and
>>> who can help with that. To be way clearer, I won't be able to fix all of
>>> Google internal usage of this function (I am not at all working on Clang,
>>> Clif, or any tools, I just hit the bug and decided to look into it, and it
>>> happened that I found a fix). Thus, if we can do the changes using
>>> iterative steps, such as
>>> (a) add the new "::" prefix configuration,
>>> (b) Deprecate/document the fact that getFullyQualifiedName has a bug,
>>> and people should move to use qual_type.getAsString(Policy) instead, using
>>> "FullyQualifiedName" and "GlobalScopeQualifiedName". We can for example
>>> provide :
>>>
>>
>> It'd still fall to one of us Googlers to clean this all up inside Google
>> - since we build with -Werror, it's not like folks'll just get soft
>> encouragement to migrate away from the API, either the warning will be on
>> and their build will be broken (in which case we'll probably pick it up
>> when we integrate changes from upstream & have to fix it to complete that
>> integration) or no signal, and it'll break when the function is finally
>> removed.
>>
>>
>>> std::string GetFullyQualifiedCanonicalType(Qual

[PATCH] D80425: Fix LLVM/Clang builds with mingw toolchain

2020-05-25 Thread Mateusz Mikuła via Phabricator via cfe-commits
mati865 added inline comments.



Comment at: llvm/cmake/modules/HandleLLVMOptions.cmake:967
CMAKE_EXE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS)
-  elseif(LINKER_IS_LLD_LINK)
+  elseif(LINKER_IS_LLD_LINK AND NOT MINGW)
 append("/lldltocache:${PROJECT_BINARY_DIR}/lto.cache"

mstorsjo wrote:
> mati865 wrote:
> > mstorsjo wrote:
> > > mati865 wrote:
> > > > thieta wrote:
> > > > > mstorsjo wrote:
> > > > > > Do you happen to know why `LINKER_IS_LLD_LINK` gets set in this 
> > > > > > case? `ld.lld` (the ELF linker interface, which then the MinGW 
> > > > > > driver remaps onto the COFF backend with the `lld-link` interface) 
> > > > > > certainly doesn't take `lld-link` style options. I believe (without 
> > > > > > diving further into it) that we shouldn't be setting this flag in 
> > > > > > this combination, but with the option implemented, we should fit it 
> > > > > > into the case further above, `elseif((UNIX OR MINGW) AND 
> > > > > > LLVM_USE_LINKER STREQUAL "lld")`
> > > > > Yeah I bet that variable is set because I pass `LLVM_USE_LINKER=lld` 
> > > > > but I haven't digged to deeply. I can rework the if statement here 
> > > > > when we have the lld option in there.
> > > > > Yeah I bet that variable is set because I pass LLVM_USE_LINKER=lld 
> > > > > but I haven't digged to deeply. 
> > > > 
> > > > It does use `lld-link` when you use `LLVM_USE_LINKER=lld`.
> > > > 
> > > > The problem lies in this line:
> > > > ```
> > > > append("/lldltocache:${PROJECT_BINARY_DIR}/lto.cache"
> > > > ```
> > > > For MinGW that should read:
> > > > ```
> > > > append("-Wl,/lldltocache:${PROJECT_BINARY_DIR}/lto.cache"
> > > > ```
> > > > That's because you are passing this flag to GCC/Clang.
> > > > For MinGW that should read:
> > > > 
> > > > append("-Wl,/lldltocache:${PROJECT_BINARY_DIR}/lto.cache"
> > > 
> > > We're adding this option properly in the mingw frontend, so we shouldn't 
> > > do the hacky way of passing lld-link options via the mingw frontend by 
> > > passing them as `/option`.
> > > 
> > > And the reason `LINKER_IS_LLD_LINK` is set seems to be this:
> > > 
> > > ```
> > > if(CMAKE_LINKER MATCHES "lld-link" OR (WIN32 AND LLVM_USE_LINKER STREQUAL 
> > > "lld") OR LLVM_ENABLE_LLD)
> > > ```
> > > 
> > > Perhaps that should be changed into
> > > 
> > > ```
> > > if(CMAKE_LINKER MATCHES "lld-link" OR (WIN32 AND LLVM_USE_LINKER STREQUAL 
> > > "lld" AND NOT MINGW) OR LLVM_ENABLE_LLD)
> > > ```
> > > 
> > > We're adding this option properly in the mingw frontend, so we shouldn't 
> > > do the hacky way of passing lld-link options via the mingw frontend by 
> > > passing them as /option.
> > 
> > I was about to add that and one more LTO related option but thought "what 
> > if LLVM should link with lld-link on MinGW?" and eventually forgot about it.
> > 
> > 
> > 
> > > And the reason LINKER_IS_LLD_LINK is set seems to be this:
> > > ```
> > > if(CMAKE_LINKER MATCHES "lld-link" OR (WIN32 AND LLVM_USE_LINKER STREQUAL 
> > > "lld") OR LLVM_ENABLE_LLD)
> > > ```
> > > Perhaps that should be changed into
> > > ```
> > > if(CMAKE_LINKER MATCHES "lld-link" OR (WIN32 AND LLVM_USE_LINKER STREQUAL 
> > > "lld" AND NOT MINGW) OR LLVM_ENABLE_LLD)
> > > ```
> > 
> > It won't work if somebody uses `LLVM_ENABLE_LLD=ON` instead of 
> > `LLVM_USE_LINKER=lld` which is supposed to be equivalent.
> > That raises question how `LLVM_ENABLE_LLD=ON` does even work on UNIX 
> > platforms.
> > 
> > IMO this would be better:
> > ```
> > if(CMAKE_LINKER MATCHES "lld-link" OR MSVC AND (LLVM_USE_LINKER STREQUAL 
> > "lld" OR LLVM_ENABLE_LLD))
> > ```
> > I was about to add that and one more LTO related option but thought "what 
> > if LLVM should link with lld-link on MinGW?" and eventually forgot about it.
> 
> I don't think that really is a supposedly supported setup - lld-link wouldn't 
> find any libs to link against etc, as the compiler driver is supposed to pass 
> those as `-L` options in mingw/unix style tools.
> 
> > It won't work if somebody uses LLVM_ENABLE_LLD=ON instead of 
> > LLVM_USE_LINKER=lld which is supposed to be equivalent.
> > That raises question how LLVM_ENABLE_LLD=ON does even work on UNIX 
> > platforms.
> 
> Either it doesn't work and nobody actually use it that way, or the effects of 
> `LINKER_IS_LLD_LINK` are mostly harmless.
> 
> > IMO this would be better:
> > 
> > `if(CMAKE_LINKER MATCHES "lld-link" OR MSVC AND (LLVM_USE_LINKER STREQUAL 
> > "lld" OR LLVM_ENABLE_LLD))`
> 
> Yeah, that looks sensible.
> I don't think that really is a supposedly supported setup - lld-link wouldn't 
> find any libs to link against etc, as the compiler driver is supposed to pass 
> those as -L options in mingw/unix style tools.

Well, it worked both ways (`lld-link` and `ld.lld`) with slight changes to 
CMake files when using your toolchain ;)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.or

[PATCH] D79773: [clang-format] Improve clang-formats handling of concepts

2020-05-25 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay updated this revision to Diff 265885.
MyDeveloperDay added a comment.

switch function to unsigned


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

https://reviews.llvm.org/D79773

Files:
  clang/docs/ClangFormatStyleOptions.rst
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Format/Format.h
  clang/lib/Format/Format.cpp
  clang/lib/Format/FormatToken.h
  clang/lib/Format/TokenAnnotator.cpp
  clang/lib/Format/UnwrappedLineParser.cpp
  clang/lib/Format/UnwrappedLineParser.h
  clang/unittests/Format/FormatTest.cpp

Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -13537,6 +13537,7 @@
   CHECK_PARSE_BOOL(AlignConsecutiveBitFields);
   CHECK_PARSE_BOOL(AlignConsecutiveDeclarations);
   CHECK_PARSE_BOOL(AlignConsecutiveMacros);
+  CHECK_PARSE_BOOL(AlwaysBreakBeforeConceptDeclarations);
   CHECK_PARSE_BOOL(AllowAllArgumentsOnNextLine);
   CHECK_PARSE_BOOL(AllowAllConstructorInitializersOnNextLine);
   CHECK_PARSE_BOOL(AllowAllParametersOfDeclarationOnNextLine);
@@ -13557,6 +13558,7 @@
   CHECK_PARSE_BOOL(IndentCaseLabels);
   CHECK_PARSE_BOOL(IndentCaseBlocks);
   CHECK_PARSE_BOOL(IndentGotoLabels);
+  CHECK_PARSE_BOOL(IndentRequires);
   CHECK_PARSE_BOOL(IndentWrappedFunctionNames);
   CHECK_PARSE_BOOL(KeepEmptyLinesAtTheStartOfBlocks);
   CHECK_PARSE_BOOL(ObjCSpaceAfterProperty);
@@ -16567,6 +16569,223 @@
"}",
Style);
 }
+
+TEST_F(FormatTest, ConceptsAndRequires) {
+  FormatStyle Style = getLLVMStyle();
+  Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
+
+  verifyFormat("template \n"
+   "concept Hashable = requires(T a) {\n"
+   "  { std::hash{}(a) } -> std::convertible_to;\n"
+   "};",
+   Style);
+  verifyFormat("template \n"
+   "concept EqualityComparable = requires(T a, T b) {\n"
+   "  { a == b } -> bool;\n"
+   "};",
+   Style);
+  verifyFormat("template \n"
+   "concept EqualityComparable = requires(T a, T b) {\n"
+   "  { a == b } -> bool;\n"
+   "  { a != b } -> bool;\n"
+   "};",
+   Style);
+  verifyFormat("template \n"
+   "concept EqualityComparable = requires(T a, T b) {\n"
+   "  { a == b } -> bool;\n"
+   "  { a != b } -> bool;\n"
+   "};",
+   Style);
+
+  verifyFormat("template \n"
+   "requires Iterator\n"
+   "void sort(It begin, It end) {\n"
+   "  //\n"
+   "}",
+   Style);
+
+  verifyFormat("template \n"
+   "concept Large = sizeof(T) > 10;",
+   Style);
+
+  verifyFormat("template \n"
+   "concept FooableWith = requires(T t, U u) {\n"
+   "  typename T::foo_type;\n"
+   "  { t.foo(u) } -> typename T::foo_type;\n"
+   "  t++;\n"
+   "};\n"
+   "void doFoo(FooableWith auto t) {\n"
+   "  t.foo(3);\n"
+   "}",
+   Style);
+  verifyFormat("template \n"
+   "concept Context = sizeof(T) == 1;",
+   Style);
+  verifyFormat("template \n"
+   "concept Context = is_specialization_of_v;",
+   Style);
+  verifyFormat("template \n"
+   "concept Node = std::is_object_v;",
+   Style);
+  verifyFormat("template \n"
+   "concept Tree = true;",
+   Style);
+
+  verifyFormat("template  int g(T i) requires Concept1 {\n"
+   "  //...\n"
+   "}",
+   Style);
+
+  verifyFormat(
+  "template  int g(T i) requires Concept1 && Concept2 {\n"
+  "  //...\n"
+  "}",
+  Style);
+
+  verifyFormat(
+  "template  int g(T i) requires Concept1 || Concept2 {\n"
+  "  //...\n"
+  "}",
+  Style);
+
+  verifyFormat("template \n"
+   "veryveryvery_long_return_type g(T i) requires Concept1 || "
+   "Concept2 {\n"
+   "  //...\n"
+   "}",
+   Style);
+
+  verifyFormat("template \n"
+   "veryveryvery_long_return_type g(T i) requires Concept1 && "
+   "Concept2 {\n"
+   "  //...\n"
+   "}",
+   Style);
+
+  verifyFormat(
+  "template \n"
+  "veryveryvery_long_return_type g(T i) requires Concept1 && Concept2 {\n"
+  "  //...\n"
+  "}",
+  Style);
+
+  verifyFormat(
+  "template \n"
+  "veryveryvery_long_return_type g(T i) requires Concept1 || Concept2 {\n"
+  "  //...\n"
+  "}",
+  Style);
+
+  verifyFormat("template \n"
+   "requires Foo() && Bar {\n"
+   "  //\n"
+   "}",
+   Style);
+
+  verifyFormat("template \n"
+ 

[PATCH] D80472: [clangd] Add access specifier information to hover contents

2020-05-25 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added a comment.

thanks for taking a look at this, this looks great!

mostly nits, but the one in tests is important and annoying (it might require 
you to update some existing cases)




Comment at: clang-tools-extra/clangd/Hover.cpp:680
 
+StringRef getAccessString(AccessSpecifier AS) {
+  switch (AS) {

it is annoying to have this function duplicated in each component (there are 
duplicates at least in text and json node dumpers too) :/

Feel free to provide a common implementation in 
`clang/include/clang/Basic/Specifiers.h` and migrate all other usages to it, or 
just put a FIXME in here saying we should converge those.

nit: prefer `llvm::StringRef` as return type



Comment at: clang-tools-extra/clangd/Hover.cpp:793
+  if (AccessSpecifier != AccessSpecifier::AS_none)
+Header.appendText(getAccessString(AccessSpecifier)).appendSpace();
   if (Kind != index::SymbolKind::Unknown)

I wonder if it would be more natural to put this at bottom, where we list the 
containing class/struct/union. e.g.

```
struct X { int fo^o; }
```

would result in

```
field foo
---

// In X
public: int foo
```

I find current one useful too, just listing options to see what you (and 
possibly others interested in) think.



Comment at: clang-tools-extra/clangd/Hover.h:63
+  /// Access specifier. Applies to members of class/structs or unions.
+  AccessSpecifier AccessSpecifier = AccessSpecifier::AS_none;
   /// Pretty-printed variable type.

Let's have `std::string` here, with a comment saying that `Access specifier for 
declarations inside class/struct/unions, empty for others.`



Comment at: clang-tools-extra/clangd/unittests/HoverTests.cpp:718
 EXPECT_EQ(H->Size, Expected.Size);
 EXPECT_EQ(H->Offset, Expected.Offset);
   }

could you also add an EXPECT_EQ for `H->AccessSpecifier` ?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80472



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


[clang] 9292ece - [clang driver] Spell "--export-dynamic-symbol" with two dashes.

2020-05-25 Thread Eli Friedman via cfe-commits

Author: Eli Friedman
Date: 2020-05-23T15:46:28-07:00
New Revision: 9292ece9956c98acf0cfa6e188316243ffbf4bed

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

LOG: [clang driver] Spell "--export-dynamic-symbol" with two dashes.

This doesn't make a difference for linkers that support the option, but
it improves the error message from older linkers that don't support it.

Added: 


Modified: 
clang/lib/Driver/ToolChains/CommonArgs.cpp
clang/test/Driver/sanitizer-ld.c

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/CommonArgs.cpp 
b/clang/lib/Driver/ToolChains/CommonArgs.cpp
index d6451447a924..85a1a4e1ac07 100644
--- a/clang/lib/Driver/ToolChains/CommonArgs.cpp
+++ b/clang/lib/Driver/ToolChains/CommonArgs.cpp
@@ -774,7 +774,7 @@ bool tools::addSanitizerRuntimes(const ToolChain &TC, const 
ArgList &Args,
 CmdArgs.push_back("--export-dynamic");
 
   if (SanArgs.hasCrossDsoCfi() && !AddExportDynamic)
-CmdArgs.push_back("-export-dynamic-symbol=__cfi_check");
+CmdArgs.push_back("--export-dynamic-symbol=__cfi_check");
 
   return !StaticRuntimes.empty() || !NonWholeStaticRuntimes.empty();
 }

diff  --git a/clang/test/Driver/sanitizer-ld.c 
b/clang/test/Driver/sanitizer-ld.c
index 52a432ca1803..a3070d26d16c 100644
--- a/clang/test/Driver/sanitizer-ld.c
+++ b/clang/test/Driver/sanitizer-ld.c
@@ -571,7 +571,7 @@
 // RUN:   | FileCheck --check-prefix=CHECK-CFI-CROSS-DSO-DIAG-ANDROID %s
 // CHECK-CFI-CROSS-DSO-DIAG-ANDROID: "{{.*}}ld{{(.exe)?}}"
 // CHECK-CFI-CROSS-DSO-DIAG-ANDROID: 
"{{[^"]*}}libclang_rt.ubsan_standalone-aarch64-android.so"
-// CHECK-CFI-CROSS-DSO-DIAG-ANDROID: "-export-dynamic-symbol=__cfi_check"
+// CHECK-CFI-CROSS-DSO-DIAG-ANDROID: "--export-dynamic-symbol=__cfi_check"
 
 // RUN: %clangxx -fsanitize=address %s -### -o %t.o 2>&1 \
 // RUN: -mmacosx-version-min=10.6 \



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


[PATCH] D80371: [clang-tidy] Fix potential assert in use-noexcept check

2020-05-25 Thread Nathan James via Phabricator via cfe-commits
njames93 updated this revision to Diff 265899.
njames93 added a comment.

- Isolated exact cause of the assert.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80371

Files:
  clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.cpp
  clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.h


Index: clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.h
===
--- clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.h
+++ clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.h
@@ -41,7 +41,7 @@
 
 private:
   const std::string NoexceptMacro;
-  bool UseNoexceptFalse;
+  const bool UseNoexceptFalse;
 };
 
 } // namespace modernize
Index: clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.cpp
===
--- clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.cpp
+++ clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.cpp
@@ -16,6 +16,10 @@
 namespace tidy {
 namespace modernize {
 
+namespace {
+AST_MATCHER(NamedDecl, isValid) { return !Node.isInvalidDecl(); }
+} // namespace
+
 UseNoexceptCheck::UseNoexceptCheck(StringRef Name, ClangTidyContext *Context)
 : ClangTidyCheck(Name, Context),
   NoexceptMacro(Options.get("ReplacementString", "")),
@@ -29,20 +33,12 @@
 void UseNoexceptCheck::registerMatchers(MatchFinder *Finder) {
   Finder->addMatcher(
   functionDecl(
-  cxxMethodDecl(
-  hasTypeLoc(loc(functionProtoType(hasDynamicExceptionSpec(,
-  anyOf(hasOverloadedOperatorName("delete[]"),
-hasOverloadedOperatorName("delete"), cxxDestructorDecl()))
-  .bind("del-dtor"))
-  .bind("funcDecl"),
-  this);
-
-  Finder->addMatcher(
-  functionDecl(
+  isValid(),
   hasTypeLoc(loc(functionProtoType(hasDynamicExceptionSpec(,
-  unless(anyOf(hasOverloadedOperatorName("delete[]"),
-   hasOverloadedOperatorName("delete"),
-   cxxDestructorDecl(
+  optionally(cxxMethodDecl(anyOf(hasAnyOverloadedOperatorName(
+ "delete[]", "delete"),
+ cxxDestructorDecl()))
+ .bind("del-dtor")))
   .bind("funcDecl"),
   this);
 
@@ -80,6 +76,9 @@
   .castAs()
   .getExceptionSpecRange();
   }
+
+  assert(Range.isValid() && "Exception Source Range is invalid.");
+
   CharSourceRange CRange = Lexer::makeFileCharRange(
   CharSourceRange::getTokenRange(Range), *Result.SourceManager,
   Result.Context->getLangOpts());


Index: clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.h
===
--- clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.h
+++ clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.h
@@ -41,7 +41,7 @@
 
 private:
   const std::string NoexceptMacro;
-  bool UseNoexceptFalse;
+  const bool UseNoexceptFalse;
 };
 
 } // namespace modernize
Index: clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.cpp
===
--- clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.cpp
+++ clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.cpp
@@ -16,6 +16,10 @@
 namespace tidy {
 namespace modernize {
 
+namespace {
+AST_MATCHER(NamedDecl, isValid) { return !Node.isInvalidDecl(); }
+} // namespace
+
 UseNoexceptCheck::UseNoexceptCheck(StringRef Name, ClangTidyContext *Context)
 : ClangTidyCheck(Name, Context),
   NoexceptMacro(Options.get("ReplacementString", "")),
@@ -29,20 +33,12 @@
 void UseNoexceptCheck::registerMatchers(MatchFinder *Finder) {
   Finder->addMatcher(
   functionDecl(
-  cxxMethodDecl(
-  hasTypeLoc(loc(functionProtoType(hasDynamicExceptionSpec(,
-  anyOf(hasOverloadedOperatorName("delete[]"),
-hasOverloadedOperatorName("delete"), cxxDestructorDecl()))
-  .bind("del-dtor"))
-  .bind("funcDecl"),
-  this);
-
-  Finder->addMatcher(
-  functionDecl(
+  isValid(),
   hasTypeLoc(loc(functionProtoType(hasDynamicExceptionSpec(,
-  unless(anyOf(hasOverloadedOperatorName("delete[]"),
-   hasOverloadedOperatorName("delete"),
-   cxxDestructorDecl(
+  optionally(cxxMethodDecl(anyOf(hasAnyOverloadedOperatorName(
+ "delete[]", "delete"),
+ cxxDestructorDecl()))
+ .bind("del-dtor")))
   .bind("funcDecl"),
   this);
 
@@ -80,6 +76,9 @@
   .castAs()
   .getExceptionSpecRange();
   }
+
+  assert(Range.isValid() && "Exceptio

[PATCH] D80371: [clang-tidy] Fix potential assert in use-noexcept check

2020-05-25 Thread Nathan James via Phabricator via cfe-commits
njames93 added a comment.

In D80371#2052069 , @aaron.ballman 
wrote:

> LGTM, but please add a test case for the changes.


As this fix is preventing a crash in error causing code I can't include a 
specific test case as the clang-tidy tests will fail if there is any error 
emitted from clang.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80371



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


[PATCH] D79945: [Sema] Comparison of pointers to complete and incomplete types

2020-05-25 Thread Benson Chu via Phabricator via cfe-commits
pestctrl updated this revision to Diff 265898.
pestctrl added a comment.

Added warning to group c99-extensions, only enable warning when C99 or less


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79945

Files:
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaExpr.cpp
  clang/test/Sema/c89.c


Index: clang/test/Sema/c89.c
===
--- clang/test/Sema/c89.c
+++ clang/test/Sema/c89.c
@@ -127,3 +127,11 @@
   struct Test17 t1 = test17_aux(); /* this is allowed */
 }
 
+int incomplete[]; /* expected-warning {{tentative array definition assumed to 
have one element}} */
+int complete[5];
+
+void test18() {
+  if (&incomplete < &complete) { /* expected-warning {{ordered comparison of 
complete and incomplete pointers}} */
+return;
+  }
+}
Index: clang/lib/Sema/SemaExpr.cpp
===
--- clang/lib/Sema/SemaExpr.cpp
+++ clang/lib/Sema/SemaExpr.cpp
@@ -11422,11 +11422,23 @@
 // C99 6.5.9p2 and C99 6.5.8p2
 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
RCanPointeeTy.getUnqualifiedType())) {
-  // Valid unless a relational comparison of function pointers
-  if (IsRelational && LCanPointeeTy->isFunctionType()) {
-Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
-  << LHSType << RHSType << LHS.get()->getSourceRange()
-  << RHS.get()->getSourceRange();
+  if (IsRelational) {
+// Pointers both need to point to complete or incomplete types
+if (LCanPointeeTy->isIncompleteType() !=
+RCanPointeeTy->isIncompleteType()) {
+  Diag(Loc,
+   getLangOpts().C11
+   ? diag::ext_typecheck_compare_complete_incomplete_pointers
+   : diag::warn_typecheck_compare_complete_incomplete_pointers)
+  << LHSType << RHSType << LHS.get()->getSourceRange()
+  << RHS.get()->getSourceRange();
+}
+if (LCanPointeeTy->isFunctionType()) {
+  // Valid unless a relational comparison of function pointers
+  Diag(Loc, 
diag::ext_typecheck_ordered_comparison_of_function_pointers)
+  << LHSType << RHSType << LHS.get()->getSourceRange()
+  << RHS.get()->getSourceRange();
+}
   }
 } else if (!IsRelational &&
(LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
Index: clang/include/clang/Basic/DiagnosticSemaKinds.td
===
--- clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -6441,6 +6441,11 @@
   "ordered comparison between pointer and zero (%0 and %1)">;
 def err_typecheck_three_way_comparison_of_pointer_and_zero : Error<
   "three-way comparison between pointer and zero">;
+def ext_typecheck_compare_complete_incomplete_pointers : Extension<
+  "ordered comparison of complete and incomplete pointers (%0 and %1)">;
+def warn_typecheck_compare_complete_incomplete_pointers : ExtWarn<
+  "ordered comparison of complete and incomplete pointers (%0 and %1)">,
+  InGroup;
 def ext_typecheck_ordered_comparison_of_function_pointers : ExtWarn<
   "ordered comparison of function pointers (%0 and %1)">,
   InGroup>;


Index: clang/test/Sema/c89.c
===
--- clang/test/Sema/c89.c
+++ clang/test/Sema/c89.c
@@ -127,3 +127,11 @@
   struct Test17 t1 = test17_aux(); /* this is allowed */
 }
 
+int incomplete[]; /* expected-warning {{tentative array definition assumed to have one element}} */
+int complete[5];
+
+void test18() {
+  if (&incomplete < &complete) { /* expected-warning {{ordered comparison of complete and incomplete pointers}} */
+return;
+  }
+}
Index: clang/lib/Sema/SemaExpr.cpp
===
--- clang/lib/Sema/SemaExpr.cpp
+++ clang/lib/Sema/SemaExpr.cpp
@@ -11422,11 +11422,23 @@
 // C99 6.5.9p2 and C99 6.5.8p2
 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
RCanPointeeTy.getUnqualifiedType())) {
-  // Valid unless a relational comparison of function pointers
-  if (IsRelational && LCanPointeeTy->isFunctionType()) {
-Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
-  << LHSType << RHSType << LHS.get()->getSourceRange()
-  << RHS.get()->getSourceRange();
+  if (IsRelational) {
+// Pointers both need to point to complete or incomplete types
+if (LCanPointeeTy->isIncompleteType() !=
+RCanPointeeTy->isIncompleteType()) {
+  Diag(Loc,
+   getLangOpts().C11
+   ? diag::ext_typecheck_compare_complete_incomple

[clang] 088fb97 - [NFC, StackSafety] LTO tests for MTE and StackSafety

2020-05-25 Thread Vitaly Buka via cfe-commits

Author: Vitaly Buka
Date: 2020-05-23T17:39:54-07:00
New Revision: 088fb9734843c09493d5965baed775c4ec32d5fb

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

LOG: [NFC, StackSafety] LTO tests for MTE and StackSafety

Summary:
The test demonstrates the current state of the compiler and
I am going to resolve FIXME in followup patches.

Reviewers: eugenis

Reviewed By: eugenis

Subscribers: inglorion, hiraditya, steven_wu, dexonsmith, cfe-commits

Tags: #clang

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

Added: 
clang/test/Driver/memtag_lto.c

Modified: 


Removed: 




diff  --git a/clang/test/Driver/memtag_lto.c b/clang/test/Driver/memtag_lto.c
new file mode 100644
index ..49edfdc9ec2a
--- /dev/null
+++ b/clang/test/Driver/memtag_lto.c
@@ -0,0 +1,143 @@
+// REQUIRES: aarch64-registered-target
+
+// RUN: rm -f %t*
+
+// -O1, no tagging: both are unsafe.
+// RUN: %clang -fno-experimental-new-pass-manager -O1 -target 
aarch64-unknown-linux -S -emit-llvm -c %s -o - | FileCheck %s
+// RUN: %clang-fexperimental-new-pass-manager -O1 -target 
aarch64-unknown-linux -S -emit-llvm -c %s -o - | FileCheck %s
+
+// Full LTO: both are unsafe.
+// RUN: %clang -fno-experimental-new-pass-manager -O1 -target 
aarch64-unknown-linux -c %s -flto=full -o %t.lto1.bc
+// RUN: %clang -fno-experimental-new-pass-manager -O1 -target 
aarch64-unknown-linux -c -DBUILD2 %s -flto=full -o %t.lto2.bc
+// RUN: llvm-lto2 run -o %t.lto %t.lto1.bc %t.lto2.bc -save-temps -O1 \
+// RUN:  -r %t.lto1.bc,fn,plx \
+// RUN:  -r %t.lto1.bc,use,lx \
+// RUN:  -r %t.lto1.bc,use_local,plx \
+// RUN:  -r %t.lto1.bc,w, \
+// RUN:  -r %t.lto2.bc,use,plx \
+// RUN:  -r %t.lto2.bc,z,
+// RUN: llvm-dis %t.lto.0.5.precodegen.bc -o - | FileCheck %s
+
+// Full LTO, new PM: both are unsafe.
+// RUN: %clang -fexperimental-new-pass-manager -O1 -target 
aarch64-unknown-linux -c %s -flto=full -o %t.ltonewpm1.bc
+// RUN: %clang -fexperimental-new-pass-manager -O1 -target 
aarch64-unknown-linux -c -DBUILD2 %s -flto=full -o %t.ltonewpm2.bc
+// RUN: llvm-lto2 run -use-new-pm -o %t.ltonewpm %t.ltonewpm1.bc 
%t.ltonewpm2.bc -save-temps -O1 \
+// RUN:  -r %t.ltonewpm1.bc,fn,plx \
+// RUN:  -r %t.ltonewpm1.bc,use,lx \
+// RUN:  -r %t.ltonewpm1.bc,use_local,plx \
+// RUN:  -r %t.ltonewpm1.bc,w, \
+// RUN:  -r %t.ltonewpm2.bc,use,plx \
+// RUN:  -r %t.ltonewpm2.bc,z,
+// RUN: llvm-dis %t.ltonewpm.0.5.precodegen.bc -o - | FileCheck %s
+
+// Thin LTO: both are unsafe.
+// RUN: %clang -fno-experimental-new-pass-manager -O1 -target 
aarch64-unknown-linux -c %s -flto=thin -o %t.thinlto1.bc
+// RUN: %clang -fno-experimental-new-pass-manager -O1 -target 
aarch64-unknown-linux -c -DBUILD2 %s -flto=thin -o %t.thinlto2.bc
+// RUN: llvm-lto2 run -o %t.thinlto %t.thinlto1.bc %t.thinlto2.bc -save-temps 
-O1 \
+// RUN:  -r %t.thinlto1.bc,fn,plx \
+// RUN:  -r %t.thinlto1.bc,use,lx \
+// RUN:  -r %t.thinlto1.bc,use_local,plx \
+// RUN:  -r %t.thinlto1.bc,w, \
+// RUN:  -r %t.thinlto2.bc,use,plx \
+// RUN:  -r %t.thinlto2.bc,z,
+// RUN: llvm-dis %t.thinlto.1.5.precodegen.bc -o - | FileCheck %s
+
+// Thin LTO, new PM: both are unsafe.
+// RUN: %clang -fexperimental-new-pass-manager -O1 -target 
aarch64-unknown-linux -c %s -flto=thin -o %t.thinltonewpm1.bc
+// RUN: %clang -fexperimental-new-pass-manager -O1 -target 
aarch64-unknown-linux -c -DBUILD2 %s -flto=thin -o %t.thinltonewpm2.bc
+// RUN: llvm-lto2 run -use-new-pm -o %t.thinltonewpm %t.thinltonewpm1.bc 
%t.thinltonewpm2.bc -save-temps -O1 \
+// RUN:  -r %t.thinltonewpm1.bc,fn,plx \
+// RUN:  -r %t.thinltonewpm1.bc,use,lx \
+// RUN:  -r %t.thinltonewpm1.bc,use_local,plx \
+// RUN:  -r %t.thinltonewpm1.bc,w, \
+// RUN:  -r %t.thinltonewpm2.bc,use,plx \
+// RUN:  -r %t.thinltonewpm2.bc,z,
+// RUN: llvm-dis %t.thinltonewpm.1.5.precodegen.bc -o - | FileCheck %s
+
+// Now with MTE.
+// RUN: rm -f %t*
+
+// -O0: both are unsafe.
+// RUN: %clang -fno-experimental-new-pass-manager -O0 -target 
aarch64-unknown-linux -march=armv8+memtag -fsanitize=memtag -S -emit-llvm -c %s 
-o - | FileCheck %s
+// RUN: %clang-fexperimental-new-pass-manager -O0 -target 
aarch64-unknown-linux -march=armv8+memtag -fsanitize=memtag -S -emit-llvm -c %s 
-o - | FileCheck %s
+
+// No LTO: just one is safe.
+// RUN: %clang -fno-experimental-new-pass-manager -O1 -target 
aarch64-unknown-linux -march=armv8+memtag -fsanitize=memtag -S -emit-llvm -c %s 
-o - | FileCheck %s -check-prefixes=XUNSAFE,YSAFE
+// RUN: %clang-fexperimental-new-pass-manager -O1 -target 
aarch64-unknown-linux -march=armv8+memtag -fsanitize=memtag -S -emit-llvm -c %s 
-o - | FileCheck %s -check-prefixes=XUNSAFE,YSAFE
+
+// FIXME: Full LTO: both are safe.
+// RUN: %clang -fno-experimental-new-pass-manager -O1 -target 
aarch64-unknown-linux -marc

[PATCH] D80039: [NFC, StackSafety] LTO tests for MTE and StackSafety

2020-05-25 Thread Vitaly Buka via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG088fb9734843: [NFC, StackSafety] LTO tests for MTE and 
StackSafety (authored by vitalybuka).

Changed prior to commit:
  https://reviews.llvm.org/D80039?vs=264361&id=265902#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80039

Files:
  clang/test/Driver/memtag_lto.c

Index: clang/test/Driver/memtag_lto.c
===
--- /dev/null
+++ clang/test/Driver/memtag_lto.c
@@ -0,0 +1,143 @@
+// REQUIRES: aarch64-registered-target
+
+// RUN: rm -f %t*
+
+// -O1, no tagging: both are unsafe.
+// RUN: %clang -fno-experimental-new-pass-manager -O1 -target aarch64-unknown-linux -S -emit-llvm -c %s -o - | FileCheck %s
+// RUN: %clang-fexperimental-new-pass-manager -O1 -target aarch64-unknown-linux -S -emit-llvm -c %s -o - | FileCheck %s
+
+// Full LTO: both are unsafe.
+// RUN: %clang -fno-experimental-new-pass-manager -O1 -target aarch64-unknown-linux -c %s -flto=full -o %t.lto1.bc
+// RUN: %clang -fno-experimental-new-pass-manager -O1 -target aarch64-unknown-linux -c -DBUILD2 %s -flto=full -o %t.lto2.bc
+// RUN: llvm-lto2 run -o %t.lto %t.lto1.bc %t.lto2.bc -save-temps -O1 \
+// RUN:  -r %t.lto1.bc,fn,plx \
+// RUN:  -r %t.lto1.bc,use,lx \
+// RUN:  -r %t.lto1.bc,use_local,plx \
+// RUN:  -r %t.lto1.bc,w, \
+// RUN:  -r %t.lto2.bc,use,plx \
+// RUN:  -r %t.lto2.bc,z,
+// RUN: llvm-dis %t.lto.0.5.precodegen.bc -o - | FileCheck %s
+
+// Full LTO, new PM: both are unsafe.
+// RUN: %clang -fexperimental-new-pass-manager -O1 -target aarch64-unknown-linux -c %s -flto=full -o %t.ltonewpm1.bc
+// RUN: %clang -fexperimental-new-pass-manager -O1 -target aarch64-unknown-linux -c -DBUILD2 %s -flto=full -o %t.ltonewpm2.bc
+// RUN: llvm-lto2 run -use-new-pm -o %t.ltonewpm %t.ltonewpm1.bc %t.ltonewpm2.bc -save-temps -O1 \
+// RUN:  -r %t.ltonewpm1.bc,fn,plx \
+// RUN:  -r %t.ltonewpm1.bc,use,lx \
+// RUN:  -r %t.ltonewpm1.bc,use_local,plx \
+// RUN:  -r %t.ltonewpm1.bc,w, \
+// RUN:  -r %t.ltonewpm2.bc,use,plx \
+// RUN:  -r %t.ltonewpm2.bc,z,
+// RUN: llvm-dis %t.ltonewpm.0.5.precodegen.bc -o - | FileCheck %s
+
+// Thin LTO: both are unsafe.
+// RUN: %clang -fno-experimental-new-pass-manager -O1 -target aarch64-unknown-linux -c %s -flto=thin -o %t.thinlto1.bc
+// RUN: %clang -fno-experimental-new-pass-manager -O1 -target aarch64-unknown-linux -c -DBUILD2 %s -flto=thin -o %t.thinlto2.bc
+// RUN: llvm-lto2 run -o %t.thinlto %t.thinlto1.bc %t.thinlto2.bc -save-temps -O1 \
+// RUN:  -r %t.thinlto1.bc,fn,plx \
+// RUN:  -r %t.thinlto1.bc,use,lx \
+// RUN:  -r %t.thinlto1.bc,use_local,plx \
+// RUN:  -r %t.thinlto1.bc,w, \
+// RUN:  -r %t.thinlto2.bc,use,plx \
+// RUN:  -r %t.thinlto2.bc,z,
+// RUN: llvm-dis %t.thinlto.1.5.precodegen.bc -o - | FileCheck %s
+
+// Thin LTO, new PM: both are unsafe.
+// RUN: %clang -fexperimental-new-pass-manager -O1 -target aarch64-unknown-linux -c %s -flto=thin -o %t.thinltonewpm1.bc
+// RUN: %clang -fexperimental-new-pass-manager -O1 -target aarch64-unknown-linux -c -DBUILD2 %s -flto=thin -o %t.thinltonewpm2.bc
+// RUN: llvm-lto2 run -use-new-pm -o %t.thinltonewpm %t.thinltonewpm1.bc %t.thinltonewpm2.bc -save-temps -O1 \
+// RUN:  -r %t.thinltonewpm1.bc,fn,plx \
+// RUN:  -r %t.thinltonewpm1.bc,use,lx \
+// RUN:  -r %t.thinltonewpm1.bc,use_local,plx \
+// RUN:  -r %t.thinltonewpm1.bc,w, \
+// RUN:  -r %t.thinltonewpm2.bc,use,plx \
+// RUN:  -r %t.thinltonewpm2.bc,z,
+// RUN: llvm-dis %t.thinltonewpm.1.5.precodegen.bc -o - | FileCheck %s
+
+// Now with MTE.
+// RUN: rm -f %t*
+
+// -O0: both are unsafe.
+// RUN: %clang -fno-experimental-new-pass-manager -O0 -target aarch64-unknown-linux -march=armv8+memtag -fsanitize=memtag -S -emit-llvm -c %s -o - | FileCheck %s
+// RUN: %clang-fexperimental-new-pass-manager -O0 -target aarch64-unknown-linux -march=armv8+memtag -fsanitize=memtag -S -emit-llvm -c %s -o - | FileCheck %s
+
+// No LTO: just one is safe.
+// RUN: %clang -fno-experimental-new-pass-manager -O1 -target aarch64-unknown-linux -march=armv8+memtag -fsanitize=memtag -S -emit-llvm -c %s -o - | FileCheck %s -check-prefixes=XUNSAFE,YSAFE
+// RUN: %clang-fexperimental-new-pass-manager -O1 -target aarch64-unknown-linux -march=armv8+memtag -fsanitize=memtag -S -emit-llvm -c %s -o - | FileCheck %s -check-prefixes=XUNSAFE,YSAFE
+
+// FIXME: Full LTO: both are safe.
+// RUN: %clang -fno-experimental-new-pass-manager -O1 -target aarch64-unknown-linux -march=armv8+memtag -fsanitize=memtag -c %s -flto=full -o %t.lto1.bc
+// RUN: %clang -fno-experimental-new-pass-manager -O1 -target aarch64-unknown-linux -march=armv8+memtag -fsanitize=memtag -c -DBUILD2 %s -flto=full -o %t.lto2.bc
+// RUN: llvm-lto2 run -o %t.lto %t.lto1.bc %t.lto2.bc -save-temps -O1 \
+// RUN:  -r %t.lto1.bc,fn,plx \
+// RUN:  -r %t.lto1.bc,use,lx \
+// RUN:  -r %t.lto1.bc,use_local,plx \
+// RUN:  -

[PATCH] D78938: Fixing all comparisons for C++20 compilation.

2020-05-25 Thread Barry Revzin via Phabricator via cfe-commits
BRevzin updated this revision to Diff 265900.
BRevzin added a comment.

- Backing out changes that aren't strictly comparison-related.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D78938

Files:
  clang/include/clang/AST/StmtIterator.h
  clang/lib/Parse/ParseOpenMP.cpp
  llvm/include/llvm/ADT/AllocatorList.h
  llvm/include/llvm/ADT/DenseMap.h
  llvm/include/llvm/ADT/DenseSet.h
  llvm/include/llvm/ADT/DirectedGraph.h
  llvm/include/llvm/ADT/STLExtras.h
  llvm/include/llvm/ADT/StringMap.h
  llvm/include/llvm/ADT/iterator.h
  llvm/include/llvm/CodeGen/LiveInterval.h
  llvm/include/llvm/IR/Attributes.h
  llvm/include/llvm/IR/BasicBlock.h
  llvm/include/llvm/Object/StackMapParser.h
  llvm/include/llvm/ProfileData/Coverage/CoverageMappingReader.h
  llvm/include/llvm/ProfileData/InstrProfReader.h
  llvm/include/llvm/Support/BinaryStreamRef.h
  llvm/lib/CodeGen/MachineOutliner.cpp
  llvm/lib/CodeGen/PeepholeOptimizer.cpp
  llvm/lib/IR/Attributes.cpp
  llvm/lib/IR/DebugInfo.cpp
  llvm/lib/Transforms/Scalar/GVNHoist.cpp
  llvm/unittests/ADT/STLExtrasTest.cpp

Index: llvm/unittests/ADT/STLExtrasTest.cpp
===
--- llvm/unittests/ADT/STLExtrasTest.cpp
+++ llvm/unittests/ADT/STLExtrasTest.cpp
@@ -463,21 +463,21 @@
 
   // Check fancy pointer overload for unique_ptr
   std::unique_ptr V2 = std::make_unique(0);
-  EXPECT_EQ(V2.get(), to_address(V2));
+  EXPECT_EQ(V2.get(), (to_address)(V2));
 
   V2.reset(V1);
-  EXPECT_EQ(V1, to_address(V2));
+  EXPECT_EQ(V1, (to_address)(V2));
   V2.release();
 
   // Check fancy pointer overload for shared_ptr
   std::shared_ptr V3 = std::make_shared(0);
   std::shared_ptr V4 = V3;
   EXPECT_EQ(V3.get(), V4.get());
-  EXPECT_EQ(V3.get(), to_address(V3));
-  EXPECT_EQ(V4.get(), to_address(V4));
+  EXPECT_EQ(V3.get(), (to_address)(V3));
+  EXPECT_EQ(V4.get(), (to_address)(V4));
 
   V3.reset(V1);
-  EXPECT_EQ(V1, to_address(V3));
+  EXPECT_EQ(V1, (to_address)(V3));
 }
 
 TEST(STLExtrasTest, partition_point) {
Index: llvm/lib/Transforms/Scalar/GVNHoist.cpp
===
--- llvm/lib/Transforms/Scalar/GVNHoist.cpp
+++ llvm/lib/Transforms/Scalar/GVNHoist.cpp
@@ -149,8 +149,8 @@
   // The instruction (VN) which uses the values flowing out of CHI.
   Instruction *I;
 
-  bool operator==(const CHIArg &A) { return VN == A.VN; }
-  bool operator!=(const CHIArg &A) { return !(*this == A); }
+  bool operator==(const CHIArg &A) const { return VN == A.VN; }
+  bool operator!=(const CHIArg &A) const { return !(*this == A); }
 };
 
 using CHIIt = SmallVectorImpl::iterator;
Index: llvm/lib/IR/DebugInfo.cpp
===
--- llvm/lib/IR/DebugInfo.cpp
+++ llvm/lib/IR/DebugInfo.cpp
@@ -665,7 +665,7 @@
   if (auto *T = dyn_cast_or_null(Attachment.second))
 for (unsigned N = 0; N < T->getNumOperands(); ++N)
   if (auto *Loc = dyn_cast_or_null(T->getOperand(N)))
-if (Loc != DebugLoc())
+if (Loc != DebugLoc().get())
   T->replaceOperandWith(N, remapDebugLoc(Loc));
   }
 }
Index: llvm/lib/IR/Attributes.cpp
===
--- llvm/lib/IR/Attributes.cpp
+++ llvm/lib/IR/Attributes.cpp
@@ -1729,7 +1729,7 @@
   return Alignment != 0;
 }
 
-bool AttrBuilder::operator==(const AttrBuilder &B) {
+bool AttrBuilder::operator==(const AttrBuilder &B) const {
   if (Attrs != B.Attrs)
 return false;
 
Index: llvm/lib/CodeGen/PeepholeOptimizer.cpp
===
--- llvm/lib/CodeGen/PeepholeOptimizer.cpp
+++ llvm/lib/CodeGen/PeepholeOptimizer.cpp
@@ -330,7 +330,7 @@
   return RegSrcs[Idx].SubReg;
 }
 
-bool operator==(const ValueTrackerResult &Other) {
+bool operator==(const ValueTrackerResult &Other) const {
   if (Other.getInst() != getInst())
 return false;
 
Index: llvm/lib/CodeGen/MachineOutliner.cpp
===
--- llvm/lib/CodeGen/MachineOutliner.cpp
+++ llvm/lib/CodeGen/MachineOutliner.cpp
@@ -590,10 +590,10 @@
   return It;
 }
 
-bool operator==(const RepeatedSubstringIterator &Other) {
+bool operator==(const RepeatedSubstringIterator &Other) const {
   return N == Other.N;
 }
-bool operator!=(const RepeatedSubstringIterator &Other) {
+bool operator!=(const RepeatedSubstringIterator &Other) const {
   return !(*this == Other);
 }
 
Index: llvm/include/llvm/Support/BinaryStreamRef.h
===
--- llvm/include/llvm/Support/BinaryStreamRef.h
+++ llvm/include/llvm/Support/BinaryStreamRef.h
@@ -121,12 +121,12 @@
 
   bool valid() const { return BorrowedImpl != nullptr; }
 
-  bool operator==(const

[PATCH] D80486: [clang-format][PR46043] Parse git config w/ implicit values

2020-05-25 Thread Jake Merdich via Phabricator via cfe-commits
JakeMerdichAMD created this revision.
JakeMerdichAMD added reviewers: MyDeveloperDay, krasimir, sammccall.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

https://bugs.llvm.org/show_bug.cgi?id=46043

Git's config is generally of the format 'key=val', but a setting
'key=true' can be written as just 'key'.  The git-clang-format script
expects a value and crashes in this case; this change handles implicit
'true' values in the script.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D80486

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


Index: clang/tools/clang-format/git-clang-format
===
--- clang/tools/clang-format/git-clang-format
+++ clang/tools/clang-format/git-clang-format
@@ -192,7 +192,12 @@
   out = {}
   for entry in run('git', 'config', '--list', '--null').split('\0'):
 if entry:
-  name, value = entry.split('\n', 1)
+  if '\n' in entry:
+name, value = entry.split('\n', 1)
+  else:
+# A setting with no '=' ('\n' with --null) is implicitly 'true'
+name = entry
+value = 'true'
   if name in non_string_options:
 value = run('git', 'config', non_string_options[name], name)
   out[name] = value


Index: clang/tools/clang-format/git-clang-format
===
--- clang/tools/clang-format/git-clang-format
+++ clang/tools/clang-format/git-clang-format
@@ -192,7 +192,12 @@
   out = {}
   for entry in run('git', 'config', '--list', '--null').split('\0'):
 if entry:
-  name, value = entry.split('\n', 1)
+  if '\n' in entry:
+name, value = entry.split('\n', 1)
+  else:
+# A setting with no '=' ('\n' with --null) is implicitly 'true'
+name = entry
+value = 'true'
   if name in non_string_options:
 value = run('git', 'config', non_string_options[name], name)
   out[name] = value
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D79945: [Sema] Comparison of pointers to complete and incomplete types

2020-05-25 Thread Benson Chu via Phabricator via cfe-commits
pestctrl updated this revision to Diff 265907.
pestctrl added a comment.

Both extension and extwarn need to be in the c99-extensions group


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79945

Files:
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaExpr.cpp
  clang/test/Sema/c89.c


Index: clang/test/Sema/c89.c
===
--- clang/test/Sema/c89.c
+++ clang/test/Sema/c89.c
@@ -127,3 +127,11 @@
   struct Test17 t1 = test17_aux(); /* this is allowed */
 }
 
+int incomplete[]; /* expected-warning {{tentative array definition assumed to 
have one element}} */
+int complete[5];
+
+void test18() {
+  if (&incomplete < &complete) { /* expected-warning {{ordered comparison of 
complete and incomplete pointers}} */
+return;
+  }
+}
Index: clang/lib/Sema/SemaExpr.cpp
===
--- clang/lib/Sema/SemaExpr.cpp
+++ clang/lib/Sema/SemaExpr.cpp
@@ -11422,11 +11422,23 @@
 // C99 6.5.9p2 and C99 6.5.8p2
 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
RCanPointeeTy.getUnqualifiedType())) {
-  // Valid unless a relational comparison of function pointers
-  if (IsRelational && LCanPointeeTy->isFunctionType()) {
-Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
-  << LHSType << RHSType << LHS.get()->getSourceRange()
-  << RHS.get()->getSourceRange();
+  if (IsRelational) {
+// Pointers both need to point to complete or incomplete types
+if (LCanPointeeTy->isIncompleteType() !=
+RCanPointeeTy->isIncompleteType()) {
+  Diag(Loc,
+   getLangOpts().C11
+   ? diag::ext_typecheck_compare_complete_incomplete_pointers
+   : diag::warn_typecheck_compare_complete_incomplete_pointers)
+  << LHSType << RHSType << LHS.get()->getSourceRange()
+  << RHS.get()->getSourceRange();
+}
+if (LCanPointeeTy->isFunctionType()) {
+  // Valid unless a relational comparison of function pointers
+  Diag(Loc, 
diag::ext_typecheck_ordered_comparison_of_function_pointers)
+  << LHSType << RHSType << LHS.get()->getSourceRange()
+  << RHS.get()->getSourceRange();
+}
   }
 } else if (!IsRelational &&
(LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
Index: clang/include/clang/Basic/DiagnosticSemaKinds.td
===
--- clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -6441,6 +6441,12 @@
   "ordered comparison between pointer and zero (%0 and %1)">;
 def err_typecheck_three_way_comparison_of_pointer_and_zero : Error<
   "three-way comparison between pointer and zero">;
+def ext_typecheck_compare_complete_incomplete_pointers : Extension<
+  "ordered comparison of complete and incomplete pointers (%0 and %1)">
+  InGroup;
+def warn_typecheck_compare_complete_incomplete_pointers : ExtWarn<
+  "ordered comparison of complete and incomplete pointers (%0 and %1)">,
+  InGroup;
 def ext_typecheck_ordered_comparison_of_function_pointers : ExtWarn<
   "ordered comparison of function pointers (%0 and %1)">,
   InGroup>;


Index: clang/test/Sema/c89.c
===
--- clang/test/Sema/c89.c
+++ clang/test/Sema/c89.c
@@ -127,3 +127,11 @@
   struct Test17 t1 = test17_aux(); /* this is allowed */
 }
 
+int incomplete[]; /* expected-warning {{tentative array definition assumed to have one element}} */
+int complete[5];
+
+void test18() {
+  if (&incomplete < &complete) { /* expected-warning {{ordered comparison of complete and incomplete pointers}} */
+return;
+  }
+}
Index: clang/lib/Sema/SemaExpr.cpp
===
--- clang/lib/Sema/SemaExpr.cpp
+++ clang/lib/Sema/SemaExpr.cpp
@@ -11422,11 +11422,23 @@
 // C99 6.5.9p2 and C99 6.5.8p2
 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
RCanPointeeTy.getUnqualifiedType())) {
-  // Valid unless a relational comparison of function pointers
-  if (IsRelational && LCanPointeeTy->isFunctionType()) {
-Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
-  << LHSType << RHSType << LHS.get()->getSourceRange()
-  << RHS.get()->getSourceRange();
+  if (IsRelational) {
+// Pointers both need to point to complete or incomplete types
+if (LCanPointeeTy->isIncompleteType() !=
+RCanPointeeTy->isIncompleteType()) {
+  Diag(Loc,
+   getLangOpts().C11
+   ? diag::ext_typecheck_compare_complete_incompl

[PATCH] D79945: [Sema] Comparison of pointers to complete and incomplete types

2020-05-25 Thread Benson Chu via Phabricator via cfe-commits
pestctrl updated this revision to Diff 265908.
pestctrl added a comment.

Rebase on master.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79945

Files:
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaExpr.cpp
  clang/test/Sema/c89.c


Index: clang/test/Sema/c89.c
===
--- clang/test/Sema/c89.c
+++ clang/test/Sema/c89.c
@@ -127,3 +127,11 @@
   struct Test17 t1 = test17_aux(); /* this is allowed */
 }
 
+int incomplete[]; /* expected-warning {{tentative array definition assumed to 
have one element}} */
+int complete[5];
+
+void test18() {
+  if (&incomplete < &complete) { /* expected-warning {{ordered comparison of 
complete and incomplete pointers}} */
+return;
+  }
+}
Index: clang/lib/Sema/SemaExpr.cpp
===
--- clang/lib/Sema/SemaExpr.cpp
+++ clang/lib/Sema/SemaExpr.cpp
@@ -11422,11 +11422,23 @@
 // C99 6.5.9p2 and C99 6.5.8p2
 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
RCanPointeeTy.getUnqualifiedType())) {
-  // Valid unless a relational comparison of function pointers
-  if (IsRelational && LCanPointeeTy->isFunctionType()) {
-Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
-  << LHSType << RHSType << LHS.get()->getSourceRange()
-  << RHS.get()->getSourceRange();
+  if (IsRelational) {
+// Pointers both need to point to complete or incomplete types
+if (LCanPointeeTy->isIncompleteType() !=
+RCanPointeeTy->isIncompleteType()) {
+  Diag(Loc,
+   getLangOpts().C11
+   ? diag::ext_typecheck_compare_complete_incomplete_pointers
+   : diag::warn_typecheck_compare_complete_incomplete_pointers)
+  << LHSType << RHSType << LHS.get()->getSourceRange()
+  << RHS.get()->getSourceRange();
+}
+if (LCanPointeeTy->isFunctionType()) {
+  // Valid unless a relational comparison of function pointers
+  Diag(Loc, 
diag::ext_typecheck_ordered_comparison_of_function_pointers)
+  << LHSType << RHSType << LHS.get()->getSourceRange()
+  << RHS.get()->getSourceRange();
+}
   }
 } else if (!IsRelational &&
(LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
Index: clang/include/clang/Basic/DiagnosticSemaKinds.td
===
--- clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -6441,6 +6441,12 @@
   "ordered comparison between pointer and zero (%0 and %1)">;
 def err_typecheck_three_way_comparison_of_pointer_and_zero : Error<
   "three-way comparison between pointer and zero">;
+def ext_typecheck_compare_complete_incomplete_pointers : Extension<
+  "ordered comparison of complete and incomplete pointers (%0 and %1)">
+  InGroup;
+def warn_typecheck_compare_complete_incomplete_pointers : ExtWarn<
+  "ordered comparison of complete and incomplete pointers (%0 and %1)">,
+  InGroup;
 def ext_typecheck_ordered_comparison_of_function_pointers : ExtWarn<
   "ordered comparison of function pointers (%0 and %1)">,
   InGroup>;


Index: clang/test/Sema/c89.c
===
--- clang/test/Sema/c89.c
+++ clang/test/Sema/c89.c
@@ -127,3 +127,11 @@
   struct Test17 t1 = test17_aux(); /* this is allowed */
 }
 
+int incomplete[]; /* expected-warning {{tentative array definition assumed to have one element}} */
+int complete[5];
+
+void test18() {
+  if (&incomplete < &complete) { /* expected-warning {{ordered comparison of complete and incomplete pointers}} */
+return;
+  }
+}
Index: clang/lib/Sema/SemaExpr.cpp
===
--- clang/lib/Sema/SemaExpr.cpp
+++ clang/lib/Sema/SemaExpr.cpp
@@ -11422,11 +11422,23 @@
 // C99 6.5.9p2 and C99 6.5.8p2
 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
RCanPointeeTy.getUnqualifiedType())) {
-  // Valid unless a relational comparison of function pointers
-  if (IsRelational && LCanPointeeTy->isFunctionType()) {
-Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
-  << LHSType << RHSType << LHS.get()->getSourceRange()
-  << RHS.get()->getSourceRange();
+  if (IsRelational) {
+// Pointers both need to point to complete or incomplete types
+if (LCanPointeeTy->isIncompleteType() !=
+RCanPointeeTy->isIncompleteType()) {
+  Diag(Loc,
+   getLangOpts().C11
+   ? diag::ext_typecheck_compare_complete_incomplete_pointers
+   : diag::warn_ty

[PATCH] D80425: Fix LLVM/Clang builds with mingw toolchain

2020-05-25 Thread Tobias Hieta via Phabricator via cfe-commits
thieta added a comment.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80425



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


[PATCH] D80488: Teach `-fsanitize=fuzzer` to respect `-static` and `-static-libstdc++` when adding C++ standard libraries.

2020-05-25 Thread Chandler Carruth via Phabricator via cfe-commits
chandlerc created this revision.
Herald added subscribers: cfe-commits, mcrosier.
Herald added a project: clang.

No idea if this is 'correct' or the right way to fix this, so just
sending this mostly as an FYI. Someone who works more closely on the
sanitizers might need to take it over and figure out how this should be
working and add relevant test cases, etc.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D80488

Files:
  clang/lib/Driver/ToolChains/CommonArgs.cpp


Index: clang/lib/Driver/ToolChains/CommonArgs.cpp
===
--- clang/lib/Driver/ToolChains/CommonArgs.cpp
+++ clang/lib/Driver/ToolChains/CommonArgs.cpp
@@ -747,8 +747,15 @@
   !Args.hasArg(options::OPT_shared)) {
 
 addSanitizerRuntime(TC, Args, CmdArgs, "fuzzer", false, true);
-if (!Args.hasArg(clang::driver::options::OPT_nostdlibxx))
+if (!Args.hasArg(clang::driver::options::OPT_nostdlibxx)) {
+  bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
+ !Args.hasArg(options::OPT_static);
+  if (OnlyLibstdcxxStatic)
+CmdArgs.push_back("-Bstatic");
   TC.AddCXXStdlibLibArgs(Args, CmdArgs);
+  if (OnlyLibstdcxxStatic)
+CmdArgs.push_back("-Bdynamic");
+}
   }
 
   for (auto RT : SharedRuntimes)


Index: clang/lib/Driver/ToolChains/CommonArgs.cpp
===
--- clang/lib/Driver/ToolChains/CommonArgs.cpp
+++ clang/lib/Driver/ToolChains/CommonArgs.cpp
@@ -747,8 +747,15 @@
   !Args.hasArg(options::OPT_shared)) {
 
 addSanitizerRuntime(TC, Args, CmdArgs, "fuzzer", false, true);
-if (!Args.hasArg(clang::driver::options::OPT_nostdlibxx))
+if (!Args.hasArg(clang::driver::options::OPT_nostdlibxx)) {
+  bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
+ !Args.hasArg(options::OPT_static);
+  if (OnlyLibstdcxxStatic)
+CmdArgs.push_back("-Bstatic");
   TC.AddCXXStdlibLibArgs(Args, CmdArgs);
+  if (OnlyLibstdcxxStatic)
+CmdArgs.push_back("-Bdynamic");
+}
   }
 
   for (auto RT : SharedRuntimes)
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 72210ce - Fix Wdocumentation warnings after argument renaming. NFC.

2020-05-25 Thread Simon Pilgrim via cfe-commits

Author: Simon Pilgrim
Date: 2020-05-24T11:18:20+01:00
New Revision: 72210ce7f57192652414ebbdf9f643f86532d700

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

LOG: Fix Wdocumentation warnings after argument renaming. NFC.

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 7fae3a62211d..a7c62a7e8046 100644
--- a/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
@@ -445,7 +445,7 @@ class MallocChecker
 
   /// Perform a zero-allocation check.
   ///
-  /// \param [in] E The expression that allocates memory.
+  /// \param [in] Call The expression that allocates memory.
   /// \param [in] IndexOfSizeArg Index of the argument that specifies the size
   ///   of the memory that needs to be allocated. E.g. for malloc, this would 
be
   ///   0.
@@ -469,7 +469,7 @@ class MallocChecker
   ///   - first: name of the resource (e.g. 'malloc')
   ///   - (OPTIONAL) second: size of the allocated region
   ///
-  /// \param [in] CE The expression that allocates memory.
+  /// \param [in] Call The expression that allocates memory.
   /// \param [in] Att The ownership_returns attribute.
   /// \param [in] State The \c ProgramState right before allocation.
   /// \returns The ProgramState right after allocation.
@@ -480,7 +480,7 @@ class MallocChecker
 
   /// Models memory allocation.
   ///
-  /// \param [in] CE The expression that allocates memory.
+  /// \param [in] Call The expression that allocates memory.
   /// \param [in] SizeEx Size of the memory that needs to be allocated.
   /// \param [in] Init The value the allocated memory needs to be initialized.
   /// with. For example, \c calloc initializes the allocated memory to 0,
@@ -495,7 +495,7 @@ class MallocChecker
 
   /// Models memory allocation.
   ///
-  /// \param [in] CE The expression that allocates memory.
+  /// \param [in] Call The expression that allocates memory.
   /// \param [in] Size Size of the memory that needs to be allocated.
   /// \param [in] Init The value the allocated memory needs to be initialized.
   /// with. For example, \c calloc initializes the allocated memory to 0,
@@ -532,7 +532,7 @@ class MallocChecker
   ///   - first: name of the resource (e.g. 'malloc')
   ///   - second: index of the parameter the attribute applies to
   ///
-  /// \param [in] CE The expression that frees memory.
+  /// \param [in] Call The expression that frees memory.
   /// \param [in] Att The ownership_takes or ownership_holds attribute.
   /// \param [in] State The \c ProgramState right before allocation.
   /// \returns The ProgramState right after deallocation.
@@ -543,7 +543,7 @@ class MallocChecker
 
   /// Models memory deallocation.
   ///
-  /// \param [in] CE The expression that frees memory.
+  /// \param [in] Call The expression that frees memory.
   /// \param [in] State The \c ProgramState right before allocation.
   /// \param [in] Num Index of the argument that needs to be freed. This is
   ///   normally 0, but for custom free functions it may be 
diff erent.
@@ -570,7 +570,7 @@ class MallocChecker
   /// Models memory deallocation.
   ///
   /// \param [in] ArgExpr The variable who's pointee needs to be freed.
-  /// \param [in] ParentExpr The expression that frees the memory.
+  /// \param [in] Call The expression that frees the memory.
   /// \param [in] State The \c ProgramState right before allocation.
   ///   normally 0, but for custom free functions it may be 
diff erent.
   /// \param [in] Hold Whether the parameter at \p Index has the 
ownership_holds
@@ -599,7 +599,7 @@ class MallocChecker
   //
   /// Models memory reallocation.
   ///
-  /// \param [in] CE The expression that reallocated memory
+  /// \param [in] Call The expression that reallocated memory
   /// \param [in] ShouldFreeOnFail Whether if reallocation fails, the supplied
   ///   memory should be freed.
   /// \param [in] State The \c ProgramState right before reallocation.
@@ -623,7 +623,7 @@ class MallocChecker
 
   /// Models zero initialized array allocation.
   ///
-  /// \param [in] CE The expression that reallocated memory
+  /// \param [in] Call The expression that reallocated memory
   /// \param [in] State The \c ProgramState right before reallocation.
   /// \returns The ProgramState right after allocation.
   LLVM_NODISCARD



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


[PATCH] D80490: Check for rule of five and zero.

2020-05-25 Thread Nithin VR via Phabricator via cfe-commits
vrnithinkumar created this revision.
vrnithinkumar added reviewers: aaron.ballman, alexfh, jbcoe, dblaikie, rsmith.
Herald added subscribers: cfe-commits, kbarton, mgorny, nemanjai.
Herald added a project: clang.

New check to check if a class defines all special members of none of them. This 
also known as rule of five and zero.
Specified in CppCoreGuidelines: 
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c21-if-you-define-or-delete-any-default-operation-define-or-delete-them-all.
In summary the check will

- Checks class defines all special members of none of them.
- It also see if the base class deletes the special members or not.
- Has two modes with the flag strict-check.
- Strict mode will check all or nothing strictly.

For some combination, compiler explicitly delete the special members or  does 
not declare implicitly. In that case don'nt have to define all the special 
members. 
For example, in case of defining all members except move constructor and move 
assignment compiler will not implicitly declare the move constructor and move 
assignment.
For non strict mode we will consider these combinations as safe.

I found one review https://reviews.llvm.org/D16376 already related to this. 
I modified my changes based on this. But I could not find out why this got 
abandoned.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D80490

Files:
  clang-tools-extra/clang-tidy/cppcoreguidelines/CMakeLists.txt
  clang-tools-extra/clang-tidy/cppcoreguidelines/CppCoreGuidelinesTidyModule.cpp
  clang-tools-extra/clang-tidy/cppcoreguidelines/RuleOfFiveAndZeroCheck.cpp
  clang-tools-extra/clang-tidy/cppcoreguidelines/RuleOfFiveAndZeroCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  
clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines-rule-of-five-and-zero.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-rule-of-five-and-zero-strict.cpp
  
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-rule-of-five-and-zero.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-rule-of-five-and-zero.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-rule-of-five-and-zero.cpp
@@ -0,0 +1,122 @@
+// RUN: %check_clang_tidy %s cppcoreguidelines-rule-of-five-and-zero %t
+
+class DefinesNothing {
+};
+
+class DefinesEverything {
+  DefinesEverything(const DefinesEverything &);
+  DefinesEverything &operator=(const DefinesEverything &);
+  DefinesEverything(DefinesEverything &&);
+  DefinesEverything &operator=(DefinesEverything &&);
+  ~DefinesEverything();
+};
+
+class DeletesEverything {
+  DeletesEverything(const DeletesEverything &);
+  DeletesEverything &operator=(const DeletesEverything &);
+  DeletesEverything(DeletesEverything &&);
+  DeletesEverything &operator=(DeletesEverything &&);
+  ~DeletesEverything();
+};
+
+// Safe cases
+class DefinesAllExceptMoves {
+  ~DefinesAllExceptMoves();
+  DefinesAllExceptMoves(DefinesAllExceptMoves &);
+  DefinesAllExceptMoves &operator=(DefinesAllExceptMoves &);
+};
+
+class DefinesAllExceptMoveConstructor {
+  ~DefinesAllExceptMoveConstructor();
+  DefinesAllExceptMoveConstructor(DefinesAllExceptMoveConstructor &);
+  DefinesAllExceptMoveConstructor &operator=(DefinesAllExceptMoveConstructor &);
+  DefinesAllExceptMoveConstructor &operator=(DefinesAllExceptMoveConstructor &&);
+};
+
+class DefinesAllExceptMoveAssignment {
+  ~DefinesAllExceptMoveAssignment();
+  DefinesAllExceptMoveAssignment(DefinesAllExceptMoveAssignment &);
+  DefinesAllExceptMoveAssignment &operator=(DefinesAllExceptMoveAssignment &);
+  DefinesAllExceptMoveAssignment(DefinesAllExceptMoveAssignment &&);
+};
+
+class DefinesDestructorAndMoveConstructor {
+  ~DefinesDestructorAndMoveConstructor();
+  DefinesDestructorAndMoveConstructor(DefinesDestructorAndMoveConstructor &&);
+};
+
+class DefinesDestructorAndMoveAssignment {
+  ~DefinesDestructorAndMoveAssignment();
+  DefinesDestructorAndMoveAssignment &operator=(DefinesDestructorAndMoveAssignment &&);
+};
+
+// CHECK-MESSAGES: :[[@LINE+1]]:7: warning: class 'DefinesOnlyDestructor' defines a destructor but does not define all other 5, define all other 5 or delete all other special member functions [cppcoreguidelines-rule-of-five-and-zero]
+class DefinesOnlyDestructor {
+  ~DefinesOnlyDestructor();
+};
+
+// CHECK-MESSAGES: :[[@LINE+1]]:7: warning: class 'DefinesOnlyCopyConstructor' defines a copy constructor but does not define all other 5, define all other 5 or delete all other special member functions [cppcoreguidelines-rule-of-five-and-zero]
+class DefinesOnlyCopyConstructor {
+  DefinesOnlyCopyConstructor(const DefinesOnlyCopyConstructor &);
+};
+
+// CHECK-MESSAGES: :[[@LINE+1]]:7: warning: class 'DefinesOnlyMoveConstructor' defines a move constructor but does not define all other 5, define all other 5 or delet

[clang] 3ed8ebc - Fix return values of some matcher functions

2020-05-25 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2020-05-24T12:37:44+01:00
New Revision: 3ed8ebc2f6b8172bed48cc5986d3b7af4cfca1bc

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

LOG: Fix return values of some matcher functions

The old return values mean

* implicit conversion
* not being able to write sizeOfExpr().bind() for example

Added: 


Modified: 
clang/include/clang/ASTMatchers/ASTMatchers.h

Removed: 




diff  --git a/clang/include/clang/ASTMatchers/ASTMatchers.h 
b/clang/include/clang/ASTMatchers/ASTMatchers.h
index 460962d9e73b..a750747c9aa3 100644
--- a/clang/include/clang/ASTMatchers/ASTMatchers.h
+++ b/clang/include/clang/ASTMatchers/ASTMatchers.h
@@ -2662,7 +2662,7 @@ AST_MATCHER_P(UnaryExprOrTypeTraitExpr, ofKind, 
UnaryExprOrTypeTrait, Kind) {
 
 /// Same as unaryExprOrTypeTraitExpr, but only matching
 /// alignof.
-inline internal::Matcher alignOfExpr(
+inline internal::BindableMatcher alignOfExpr(
 const internal::Matcher &InnerMatcher) {
   return stmt(unaryExprOrTypeTraitExpr(
   allOf(anyOf(ofKind(UETT_AlignOf), ofKind(UETT_PreferredAlignOf)),
@@ -2671,7 +2671,7 @@ inline internal::Matcher alignOfExpr(
 
 /// Same as unaryExprOrTypeTraitExpr, but only matching
 /// sizeof.
-inline internal::Matcher sizeOfExpr(
+inline internal::BindableMatcher sizeOfExpr(
 const internal::Matcher &InnerMatcher) {
   return stmt(unaryExprOrTypeTraitExpr(
   allOf(ofKind(UETT_SizeOf), InnerMatcher)));



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


[PATCH] D69585: Add option to instantiate templates already in the PCH

2020-05-25 Thread Luboš Luňák via Phabricator via cfe-commits
llunak updated this revision to Diff 265918.
llunak edited the summary of this revision.
llunak added a comment.

Enabled the option by default for clang-cl to match MSVC.


Repository:
  rC Clang

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

https://reviews.llvm.org/D69585

Files:
  clang/include/clang/Basic/LangOptions.def
  clang/include/clang/Driver/Options.td
  clang/include/clang/Sema/Sema.h
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/lib/Sema/Sema.cpp
  clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
  clang/test/PCH/codegen.cpp
  clang/test/PCH/crash-12631281.cpp
  clang/test/PCH/cxx-alias-decl.cpp
  clang/test/PCH/cxx-dependent-sized-ext-vector.cpp
  clang/test/PCH/cxx-explicit-specifier.cpp
  clang/test/PCH/cxx-exprs.cpp
  clang/test/PCH/cxx-friends.cpp
  clang/test/PCH/cxx-member-init.cpp
  clang/test/PCH/cxx-ms-function-specialization-class-scope.cpp
  clang/test/PCH/cxx-static_assert.cpp
  clang/test/PCH/cxx-templates.cpp
  clang/test/PCH/cxx-variadic-templates-with-default-params.cpp
  clang/test/PCH/cxx-variadic-templates.cpp
  clang/test/PCH/cxx0x-default-delete.cpp
  clang/test/PCH/cxx11-constexpr.cpp
  clang/test/PCH/cxx11-enum-template.cpp
  clang/test/PCH/cxx11-exception-spec.cpp
  clang/test/PCH/cxx11-inheriting-ctors.cpp
  clang/test/PCH/cxx11-user-defined-literals.cpp
  clang/test/PCH/cxx1y-decltype-auto.cpp
  clang/test/PCH/cxx1y-deduced-return-type.cpp
  clang/test/PCH/cxx1y-default-initializer.cpp
  clang/test/PCH/cxx1y-init-captures.cpp
  clang/test/PCH/cxx1y-variable-templates.cpp
  clang/test/PCH/cxx1z-aligned-alloc.cpp
  clang/test/PCH/cxx1z-decomposition.cpp
  clang/test/PCH/cxx1z-using-declaration.cpp
  clang/test/PCH/cxx2a-bitfield-init.cpp
  clang/test/PCH/cxx2a-concept-specialization-expr.cpp
  clang/test/PCH/cxx2a-constraints.cpp
  clang/test/PCH/cxx2a-defaulted-comparison.cpp
  clang/test/PCH/cxx2a-requires-expr.cpp
  clang/test/PCH/cxx2a-template-lambdas.cpp
  clang/test/PCH/delayed-pch-instantiate.cpp
  clang/test/PCH/friend-template.cpp
  clang/test/PCH/implicitly-deleted.cpp
  clang/test/PCH/late-parsed-instantiations.cpp
  clang/test/PCH/local_static.cpp
  clang/test/PCH/macro-undef.cpp
  clang/test/PCH/make-integer-seq.cpp
  clang/test/PCH/ms-if-exists.cpp
  clang/test/PCH/pch-instantiate-templates-forward-decl.cpp
  clang/test/PCH/pch-instantiate-templates.cpp
  clang/test/PCH/pr18806.cpp
  clang/test/PCH/pragma-diag-section.cpp
  clang/test/PCH/rdar10830559.cpp
  clang/test/PCH/specialization-after-instantiation.cpp
  clang/test/PCH/type_pack_element.cpp

Index: clang/test/PCH/type_pack_element.cpp
===
--- clang/test/PCH/type_pack_element.cpp
+++ clang/test/PCH/type_pack_element.cpp
@@ -1,6 +1,9 @@
 // RUN: %clang_cc1 -std=c++14 -x c++-header %s -emit-pch -o %t.pch
 // RUN: %clang_cc1 -std=c++14 -x c++ /dev/null -include-pch %t.pch
 
+// RUN: %clang_cc1 -std=c++14 -x c++-header %s -emit-pch -fpch-instantiate-templates -o %t.pch
+// RUN: %clang_cc1 -std=c++14 -x c++ /dev/null -include-pch %t.pch
+
 template 
 struct X { };
 
Index: clang/test/PCH/specialization-after-instantiation.cpp
===
--- /dev/null
+++ clang/test/PCH/specialization-after-instantiation.cpp
@@ -0,0 +1,32 @@
+// Test this without pch.
+// RUN: %clang_cc1 -fsyntax-only -verify -DBODY %s
+
+// Test with pch.
+// RUN: %clang_cc1 -emit-pch -o %t %s
+// RUN: %clang_cc1 -include-pch %t -fsyntax-only -verify -DBODY %s
+
+// RUN: %clang_cc1 -emit-pch -fpch-instantiate-templates -o %t %s
+// RUN: %clang_cc1 -include-pch %t -fsyntax-only -verify -DBODY %s
+
+#ifndef HEADER_H
+#define HEADER_H
+
+template 
+struct A {
+  int foo() const;
+};
+
+int bar(A *a) {
+  return a->foo();
+}
+
+#endif // HEADER_H
+
+#ifdef BODY
+
+template <>
+int A::foo() const { // expected-error {{explicit specialization of 'foo' after instantiation}}  // expected-note@20 {{implicit instantiation first required here}}
+  return 10;
+}
+
+#endif // BODY
Index: clang/test/PCH/rdar10830559.cpp
===
--- clang/test/PCH/rdar10830559.cpp
+++ clang/test/PCH/rdar10830559.cpp
@@ -6,6 +6,9 @@
 // RUN: %clang_cc1 -emit-pch -o %t %s
 // RUN: %clang_cc1 -include-pch %t -emit-llvm-only %t.empty.cpp 
 
+// RUN: %clang_cc1 -emit-pch -fpch-instantiate-templates -o %t %s
+// RUN: %clang_cc1 -include-pch %t -emit-llvm-only %t.empty.cpp
+
 // rdar://10830559
 
 //#pragma ms_struct on
Index: clang/test/PCH/pragma-diag-section.cpp
===
--- clang/test/PCH/pragma-diag-section.cpp
+++ clang/test/PCH/pragma-diag-section.cpp
@@ -5,6 +5,9 @@
 // RUN: %clang_cc1 %s -emit-pch -o %t
 // RUN: %clang_cc1 %s -include-pch %t -verify -fsyntax-only -Wuninitialized
 
+// RUN: %clang_cc1 %s -emit-pch -fpch-instantiate-templates -o %t
+// RUN: %clang_cc

[PATCH] D69585: Add option to instantiate templates already in the PCH

2020-05-25 Thread Luboš Luňák via Phabricator via cfe-commits
llunak marked an inline comment as done.
llunak added inline comments.



Comment at: clang/lib/Driver/ToolChains/Clang.cpp:5610
+  if (Args.hasFlag(options::OPT_fpch_instantiate_templates,
+   options::OPT_fno_pch_instantiate_templates, false))
+CmdArgs.push_back("-fpch-instantiate-templates");

rnk wrote:
> llunak wrote:
> > rnk wrote:
> > > Does MSVC default to this behavior? Should this default to true with 
> > > clang-cl /Yu / /Yc? This can be future work and does not need to be part 
> > > of this patch.
> > Since MSVC is noticeably faster for an equivalent PCH compile than current 
> > Clang, presumably it instantiates templates already in the PCH. But that 
> > doesn't really matter for this patch, if it were ok to enable this by 
> > default for clang-cl, than it would be ok also for clang itself. That 
> > cannot be done now though, https://reviews.llvm.org/D69585#1946765 points 
> > out a corner case where this change makes a valid compilation error out, 
> > and that's the reason for having this behind a flag. I expect Clang could 
> > possibly be adjusted to bail out and delay template instantiantion in such 
> > a case until it can be performed successfully, but given the response rate 
> > to my PCH patches I first wanted to get the feature in somehow, and I can 
> > try to make the flag default/irrelevant later.
> > 
> Right, I guess what I mean is, for that example where instantiation at the 
> end of the PCH creates an error, does MSVC emit an error? I just checked, and 
> it looks like the answer is yes, so it seems like we could make this the 
> default behavior for `clang-cl /Yc` without much further discussion.
That's a good point. Yes, since MSVC creates PCHs by basically compiling an 
empty .cpp, it apparently does instantiate templates as a side-effect of that, 
and https://reviews.llvm.org/D69585#1946765 indeed doesn't work with MSVC. So 
no harm in enabling the option for clang-cl.

I'll update the patch.



Repository:
  rC Clang

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

https://reviews.llvm.org/D69585



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


[clang] 04ed532 - Fix skip-invisible with overloaded method calls

2020-05-25 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2020-05-24T12:36:16+01:00
New Revision: 04ed532ef0ce76d53ca456cbc581756bb01d30e7

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

LOG: Fix skip-invisible with overloaded method calls

Added: 


Modified: 
clang/lib/AST/Expr.cpp
clang/unittests/AST/ASTTraverserTest.cpp

Removed: 




diff  --git a/clang/lib/AST/Expr.cpp b/clang/lib/AST/Expr.cpp
index f173c2408866..0184140ab07e 100644
--- a/clang/lib/AST/Expr.cpp
+++ b/clang/lib/AST/Expr.cpp
@@ -2931,8 +2931,10 @@ Expr *Expr::IgnoreUnlessSpelledInSource() {
 continue;
   }
   if (auto *PE = dyn_cast(ExprNode)) {
-E = PE;
-continue;
+if (PE->getSourceRange() == C->getSourceRange()) {
+  E = PE;
+  continue;
+}
   }
   ExprNode = ExprNode->IgnoreParenImpCasts();
   if (ExprNode->getSourceRange() == SR)

diff  --git a/clang/unittests/AST/ASTTraverserTest.cpp 
b/clang/unittests/AST/ASTTraverserTest.cpp
index f56a49bf8e51..affbbe76f0d2 100644
--- a/clang/unittests/AST/ASTTraverserTest.cpp
+++ b/clang/unittests/AST/ASTTraverserTest.cpp
@@ -265,6 +265,9 @@ TEST(Traverse, IgnoreUnlessSpelledInSourceVars) {
 struct String
 {
 String(const char*, int = -1) {}
+
+int overloaded() const;
+int& overloaded();
 };
 
 void stringConstruct()
@@ -273,6 +276,12 @@ void stringConstruct()
 s = "bar";
 }
 
+void overloadCall()
+{
+   String s = "foo";
+   (s).overloaded();
+}
+
 struct C1 {};
 struct C2 { operator C1(); };
 
@@ -331,6 +340,46 @@ FunctionDecl 'stringConstruct'
 )cpp");
   }
 
+  {
+auto FN =
+ast_matchers::match(functionDecl(hasName("overloadCall")).bind("fn"),
+AST->getASTContext());
+EXPECT_EQ(FN.size(), 1u);
+
+EXPECT_EQ(dumpASTString(TK_AsIs, FN[0].getNodeAs("fn")),
+  R"cpp(
+FunctionDecl 'overloadCall'
+`-CompoundStmt
+  |-DeclStmt
+  | `-VarDecl 's'
+  |   `-ExprWithCleanups
+  | `-CXXConstructExpr
+  |   `-MaterializeTemporaryExpr
+  | `-ImplicitCastExpr
+  |   `-CXXConstructExpr
+  | |-ImplicitCastExpr
+  | | `-StringLiteral
+  | `-CXXDefaultArgExpr
+  `-CXXMemberCallExpr
+`-MemberExpr
+  `-ParenExpr
+`-DeclRefExpr 's'
+)cpp");
+
+EXPECT_EQ(dumpASTString(TK_IgnoreUnlessSpelledInSource,
+FN[0].getNodeAs("fn")),
+  R"cpp(
+FunctionDecl 'overloadCall'
+`-CompoundStmt
+  |-DeclStmt
+  | `-VarDecl 's'
+  |   `-StringLiteral
+  `-CXXMemberCallExpr
+`-MemberExpr
+  `-DeclRefExpr 's'
+)cpp");
+  }
+
   {
 auto FN = ast_matchers::match(
 functionDecl(hasName("conversionOperator"),



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


[clang-tools-extra] 5e9392d - Add explicit traversal mode to matchers for implicit constructors

2020-05-25 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2020-05-24T12:36:15+01:00
New Revision: 5e9392deaf5bfa43846334e9b07a126ae3410a38

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

LOG: Add explicit traversal mode to matchers for implicit constructors

Added: 


Modified: 
clang-tools-extra/clang-tidy/bugprone/StringConstructorCheck.cpp
clang-tools-extra/clang-tidy/bugprone/StringLiteralWithEmbeddedNulCheck.cpp
clang-tools-extra/clang-tidy/readability/RedundantStringInitCheck.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/bugprone/StringConstructorCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/StringConstructorCheck.cpp
index 1c47f17d8a64..96d93a1d0413 100644
--- a/clang-tools-extra/clang-tidy/bugprone/StringConstructorCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/StringConstructorCheck.cpp
@@ -100,10 +100,11 @@ void StringConstructorCheck::registerMatchers(MatchFinder 
*Finder) {
   // Check the literal string constructor with char pointer.
   // [i.e. string (const char* s);]
   Finder->addMatcher(
+traverse(TK_AsIs,
   cxxConstructExpr(hasDeclaration(cxxMethodDecl(hasName("basic_string"))),
hasArgument(0, expr().bind("from-ptr")),
hasArgument(1, unless(hasType(isInteger()
-  .bind("constructor"),
+  .bind("constructor")),
   this);
 }
 

diff  --git 
a/clang-tools-extra/clang-tidy/bugprone/StringLiteralWithEmbeddedNulCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/StringLiteralWithEmbeddedNulCheck.cpp
index 815062618a97..b533db760d5e 100644
--- 
a/clang-tools-extra/clang-tidy/bugprone/StringLiteralWithEmbeddedNulCheck.cpp
+++ 
b/clang-tools-extra/clang-tidy/bugprone/StringLiteralWithEmbeddedNulCheck.cpp
@@ -49,8 +49,8 @@ void 
StringLiteralWithEmbeddedNulCheck::registerMatchers(MatchFinder *Finder) {
 
   // Detect passing a suspicious string literal to a string constructor.
   // example: std::string str = "abc\0def";
-  Finder->addMatcher(
-  cxxConstructExpr(StringConstructorExpr, hasArgument(0, StrLitWithNul)),
+  Finder->addMatcher(traverse(TK_AsIs,
+  cxxConstructExpr(StringConstructorExpr, hasArgument(0, StrLitWithNul))),
   this);
 
   // Detect passing a suspicious string literal through an overloaded operator.

diff  --git 
a/clang-tools-extra/clang-tidy/readability/RedundantStringInitCheck.cpp 
b/clang-tools-extra/clang-tidy/readability/RedundantStringInitCheck.cpp
index 78bf744eba8d..e5825bc4f0e3 100644
--- a/clang-tools-extra/clang-tidy/readability/RedundantStringInitCheck.cpp
+++ b/clang-tools-extra/clang-tidy/readability/RedundantStringInitCheck.cpp
@@ -96,8 +96,9 @@ void RedundantStringInitCheck::registerMatchers(MatchFinder 
*Finder) {
 
   const auto StringType = hasType(hasUnqualifiedDesugaredType(
   recordType(hasDeclaration(cxxRecordDecl(hasStringTypeName);
-  const auto EmptyStringInit = expr(ignoringImplicit(
-  anyOf(EmptyStringCtorExpr, EmptyStringCtorExprWithTemporaries)));
+  const auto EmptyStringInit =
+  traverse(ast_type_traits::TK_AsIs, expr(ignoringImplicit(
+  anyOf(EmptyStringCtorExpr, EmptyStringCtorExprWithTemporaries;
 
   // Match a variable declaration with an empty string literal as initializer.
   // Examples:



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


[PATCH] D80486: [clang-format][PR46043] Parse git config w/ implicit values

2020-05-25 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay accepted this revision.
MyDeveloperDay added a comment.
This revision is now accepted and ready to land.

LGTM


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80486



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


[PATCH] D80425: Fix LLVM/Clang builds with mingw toolchain

2020-05-25 Thread Tobias Hieta via Phabricator via cfe-commits
thieta added a comment.

I am planning to revise this one now that we have thinlto-cache-dir option 
landed here are my plans:

- Keep the libdl patch as is (seems like there are no more comments on this).
- Remove the symlink patch for now and potentially move that to another patch
- Rework the cache-dir option so that it passes the same option as we pass to 
ELF lld.

Is that what everyone would expect?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80425



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


[PATCH] D80490: Check for rule of five and zero.

2020-05-25 Thread Nithin VR via Phabricator via cfe-commits
vrnithinkumar updated this revision to Diff 265921.
vrnithinkumar added a comment.

fixed the clang-tidy warnig


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80490

Files:
  clang-tools-extra/clang-tidy/cppcoreguidelines/CMakeLists.txt
  clang-tools-extra/clang-tidy/cppcoreguidelines/CppCoreGuidelinesTidyModule.cpp
  clang-tools-extra/clang-tidy/cppcoreguidelines/RuleOfFiveAndZeroCheck.cpp
  clang-tools-extra/clang-tidy/cppcoreguidelines/RuleOfFiveAndZeroCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  
clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines-rule-of-five-and-zero.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-rule-of-five-and-zero-strict.cpp
  
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-rule-of-five-and-zero.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-rule-of-five-and-zero.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-rule-of-five-and-zero.cpp
@@ -0,0 +1,122 @@
+// RUN: %check_clang_tidy %s cppcoreguidelines-rule-of-five-and-zero %t
+
+class DefinesNothing {
+};
+
+class DefinesEverything {
+  DefinesEverything(const DefinesEverything &);
+  DefinesEverything &operator=(const DefinesEverything &);
+  DefinesEverything(DefinesEverything &&);
+  DefinesEverything &operator=(DefinesEverything &&);
+  ~DefinesEverything();
+};
+
+class DeletesEverything {
+  DeletesEverything(const DeletesEverything &);
+  DeletesEverything &operator=(const DeletesEverything &);
+  DeletesEverything(DeletesEverything &&);
+  DeletesEverything &operator=(DeletesEverything &&);
+  ~DeletesEverything();
+};
+
+// Safe cases
+class DefinesAllExceptMoves {
+  ~DefinesAllExceptMoves();
+  DefinesAllExceptMoves(DefinesAllExceptMoves &);
+  DefinesAllExceptMoves &operator=(DefinesAllExceptMoves &);
+};
+
+class DefinesAllExceptMoveConstructor {
+  ~DefinesAllExceptMoveConstructor();
+  DefinesAllExceptMoveConstructor(DefinesAllExceptMoveConstructor &);
+  DefinesAllExceptMoveConstructor &operator=(DefinesAllExceptMoveConstructor &);
+  DefinesAllExceptMoveConstructor &operator=(DefinesAllExceptMoveConstructor &&);
+};
+
+class DefinesAllExceptMoveAssignment {
+  ~DefinesAllExceptMoveAssignment();
+  DefinesAllExceptMoveAssignment(DefinesAllExceptMoveAssignment &);
+  DefinesAllExceptMoveAssignment &operator=(DefinesAllExceptMoveAssignment &);
+  DefinesAllExceptMoveAssignment(DefinesAllExceptMoveAssignment &&);
+};
+
+class DefinesDestructorAndMoveConstructor {
+  ~DefinesDestructorAndMoveConstructor();
+  DefinesDestructorAndMoveConstructor(DefinesDestructorAndMoveConstructor &&);
+};
+
+class DefinesDestructorAndMoveAssignment {
+  ~DefinesDestructorAndMoveAssignment();
+  DefinesDestructorAndMoveAssignment &operator=(DefinesDestructorAndMoveAssignment &&);
+};
+
+// CHECK-MESSAGES: :[[@LINE+1]]:7: warning: class 'DefinesOnlyDestructor' defines a destructor but does not define all other 5, define all other 5 or delete all other special member functions [cppcoreguidelines-rule-of-five-and-zero]
+class DefinesOnlyDestructor {
+  ~DefinesOnlyDestructor();
+};
+
+// CHECK-MESSAGES: :[[@LINE+1]]:7: warning: class 'DefinesOnlyCopyConstructor' defines a copy constructor but does not define all other 5, define all other 5 or delete all other special member functions [cppcoreguidelines-rule-of-five-and-zero]
+class DefinesOnlyCopyConstructor {
+  DefinesOnlyCopyConstructor(const DefinesOnlyCopyConstructor &);
+};
+
+// CHECK-MESSAGES: :[[@LINE+1]]:7: warning: class 'DefinesOnlyMoveConstructor' defines a move constructor but does not define all other 5, define all other 5 or delete all other special member functions [cppcoreguidelines-rule-of-five-and-zero]
+class DefinesOnlyMoveConstructor {
+  DefinesOnlyMoveConstructor(DefinesOnlyMoveConstructor &&);
+};
+
+// CHECK-MESSAGES: :[[@LINE+1]]:7: warning: class 'DefinesOnlyCopyAssignment' defines a copy assignment operator but does not define all other 5, define all other 5 or delete all other special member functions [cppcoreguidelines-rule-of-five-and-zero]
+class DefinesOnlyCopyAssignment {
+  DefinesOnlyCopyAssignment &operator=(const DefinesOnlyCopyAssignment &);
+};
+
+// CHECK-MESSAGES: :[[@LINE+1]]:7: warning: class 'DefinesOnlyMoveAssignment' defines a move assignment operator but does not define all other 5, define all other 5 or delete all other special member functions [cppcoreguidelines-rule-of-five-and-zero]
+class DefinesOnlyMoveAssignment {
+  DefinesOnlyMoveAssignment &operator=(DefinesOnlyMoveAssignment &&);
+};
+
+// check inheritance
+class NoCopyBase {
+public:
+  ~NoCopyBase();
+  NoCopyBase(NoCopyBase &&);
+  NoCopyBase &operator=(NoCopyBase &&);
+
+private:
+  NoCopyBase(const NoCopyBase &) = delete;
+  NoCopyBase &operator=(const NoCopyBase 

[PATCH] D80371: [clang-tidy] Fix potential assert in use-noexcept check

2020-05-25 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D80371#2052454 , @njames93 wrote:

> In D80371#2052069 , @aaron.ballman 
> wrote:
>
> > LGTM, but please add a test case for the changes.
>
>
> As this fix is preventing a crash in error causing code I can't include a 
> specific test case as the clang-tidy tests will fail if there is any error 
> emitted from clang.


We support that case as well. See 
test/clang-tidy/checkers/misc-unused-using-decls-errors.cpp as an example.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80371



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


[PATCH] D80425: Fix LLVM/Clang builds with mingw toolchain

2020-05-25 Thread Martin Storsjö via Phabricator via cfe-commits
mstorsjo added a comment.

In D80425#2052607 , @thieta wrote:

> I am planning to revise this one now that we have thinlto-cache-dir option 
> landed here are my plans:
>
> - Keep the libdl patch as is (seems like there are no more comments on this).
> - Remove the symlink patch for now and potentially move that to another patch
> - Rework the cache-dir option so that it passes the same option as we pass to 
> ELF lld.
>
>   Is that what everyone would expect?


Sounds good to me, but ideally I'd like to split all three issues to separate 
commits/reviews, as it's three quite independent issues.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80425



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


[PATCH] D80371: [clang-tidy] Fix potential assert in use-noexcept check

2020-05-25 Thread Nathan James via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG4c5818dd8cd9: [clang-tidy] Fix potential assert in 
use-noexcept check (authored by njames93).

Changed prior to commit:
  https://reviews.llvm.org/D80371?vs=265923&id=265924#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80371

Files:
  clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.cpp
  clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.h
  clang-tools-extra/test/clang-tidy/checkers/modernize-use-noexcept-error.cpp


Index: 
clang-tools-extra/test/clang-tidy/checkers/modernize-use-noexcept-error.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/modernize-use-noexcept-error.cpp
@@ -0,0 +1,6 @@
+// RUN: %check_clang_tidy -expect-clang-tidy-error %s modernize-use-noexcept %t
+
+// We're not interested in the check issuing a warning here, just making sure
+// clang-tidy doesn't assert.
+undefined_type doesThrow() throw();
+// CHECK-MESSAGES: :[[@LINE-1]]:1: error: unknown type name 'undefined_type' 
[clang-diagnostic-error]
Index: clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.h
===
--- clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.h
+++ clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.h
@@ -41,7 +41,7 @@
 
 private:
   const std::string NoexceptMacro;
-  bool UseNoexceptFalse;
+  const bool UseNoexceptFalse;
 };
 
 } // namespace modernize
Index: clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.cpp
===
--- clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.cpp
+++ clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.cpp
@@ -16,6 +16,10 @@
 namespace tidy {
 namespace modernize {
 
+namespace {
+AST_MATCHER(NamedDecl, isValid) { return !Node.isInvalidDecl(); }
+} // namespace
+
 UseNoexceptCheck::UseNoexceptCheck(StringRef Name, ClangTidyContext *Context)
 : ClangTidyCheck(Name, Context),
   NoexceptMacro(Options.get("ReplacementString", "")),
@@ -29,20 +33,12 @@
 void UseNoexceptCheck::registerMatchers(MatchFinder *Finder) {
   Finder->addMatcher(
   functionDecl(
-  cxxMethodDecl(
-  hasTypeLoc(loc(functionProtoType(hasDynamicExceptionSpec(,
-  anyOf(hasOverloadedOperatorName("delete[]"),
-hasOverloadedOperatorName("delete"), cxxDestructorDecl()))
-  .bind("del-dtor"))
-  .bind("funcDecl"),
-  this);
-
-  Finder->addMatcher(
-  functionDecl(
+  isValid(),
   hasTypeLoc(loc(functionProtoType(hasDynamicExceptionSpec(,
-  unless(anyOf(hasOverloadedOperatorName("delete[]"),
-   hasOverloadedOperatorName("delete"),
-   cxxDestructorDecl(
+  optionally(cxxMethodDecl(anyOf(hasAnyOverloadedOperatorName(
+ "delete[]", "delete"),
+ cxxDestructorDecl()))
+ .bind("del-dtor")))
   .bind("funcDecl"),
   this);
 
@@ -80,6 +76,9 @@
   .castAs()
   .getExceptionSpecRange();
   }
+
+  assert(Range.isValid() && "Exception Source Range is invalid.");
+
   CharSourceRange CRange = Lexer::makeFileCharRange(
   CharSourceRange::getTokenRange(Range), *Result.SourceManager,
   Result.Context->getLangOpts());


Index: clang-tools-extra/test/clang-tidy/checkers/modernize-use-noexcept-error.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/modernize-use-noexcept-error.cpp
@@ -0,0 +1,6 @@
+// RUN: %check_clang_tidy -expect-clang-tidy-error %s modernize-use-noexcept %t
+
+// We're not interested in the check issuing a warning here, just making sure
+// clang-tidy doesn't assert.
+undefined_type doesThrow() throw();
+// CHECK-MESSAGES: :[[@LINE-1]]:1: error: unknown type name 'undefined_type' [clang-diagnostic-error]
Index: clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.h
===
--- clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.h
+++ clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.h
@@ -41,7 +41,7 @@
 
 private:
   const std::string NoexceptMacro;
-  bool UseNoexceptFalse;
+  const bool UseNoexceptFalse;
 };
 
 } // namespace modernize
Index: clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.cpp
===
--- clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.cpp
+++ clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.cpp
@@ -16,6 +16,10 @@
 namespace tidy {
 namespace modernize {
 
+namespace {
+AST_MATCHER(NamedDecl, isValid)

[clang-tools-extra] 4c5818d - [clang-tidy] Fix potential assert in use-noexcept check

2020-05-25 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-05-24T14:40:58+01:00
New Revision: 4c5818dd8cd9336136a80a02b262b501b23f6492

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

LOG: [clang-tidy] Fix potential assert in use-noexcept check

Summary: Fix a potential assert in use-noexcept check if there is an issue 
getting the `TypeSourceInfo` as well as a small clean up.

Reviewers: aaron.ballman, alexfh, gribozavr2

Reviewed By: aaron.ballman

Subscribers: xazax.hun, cfe-commits

Tags: #clang

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

Added: 
clang-tools-extra/test/clang-tidy/checkers/modernize-use-noexcept-error.cpp

Modified: 
clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.cpp
clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.h

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.cpp
index bbda8d58f103..cc4bc05a35dd 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.cpp
@@ -16,6 +16,10 @@ namespace clang {
 namespace tidy {
 namespace modernize {
 
+namespace {
+AST_MATCHER(NamedDecl, isValid) { return !Node.isInvalidDecl(); }
+} // namespace
+
 UseNoexceptCheck::UseNoexceptCheck(StringRef Name, ClangTidyContext *Context)
 : ClangTidyCheck(Name, Context),
   NoexceptMacro(Options.get("ReplacementString", "")),
@@ -29,20 +33,12 @@ void 
UseNoexceptCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
 void UseNoexceptCheck::registerMatchers(MatchFinder *Finder) {
   Finder->addMatcher(
   functionDecl(
-  cxxMethodDecl(
-  hasTypeLoc(loc(functionProtoType(hasDynamicExceptionSpec(,
-  anyOf(hasOverloadedOperatorName("delete[]"),
-hasOverloadedOperatorName("delete"), cxxDestructorDecl()))
-  .bind("del-dtor"))
-  .bind("funcDecl"),
-  this);
-
-  Finder->addMatcher(
-  functionDecl(
+  isValid(),
   hasTypeLoc(loc(functionProtoType(hasDynamicExceptionSpec(,
-  unless(anyOf(hasOverloadedOperatorName("delete[]"),
-   hasOverloadedOperatorName("delete"),
-   cxxDestructorDecl(
+  optionally(cxxMethodDecl(anyOf(hasAnyOverloadedOperatorName(
+ "delete[]", "delete"),
+ cxxDestructorDecl()))
+ .bind("del-dtor")))
   .bind("funcDecl"),
   this);
 
@@ -80,6 +76,9 @@ void UseNoexceptCheck::check(const MatchFinder::MatchResult 
&Result) {
   .castAs()
   .getExceptionSpecRange();
   }
+
+  assert(Range.isValid() && "Exception Source Range is invalid.");
+
   CharSourceRange CRange = Lexer::makeFileCharRange(
   CharSourceRange::getTokenRange(Range), *Result.SourceManager,
   Result.Context->getLangOpts());

diff  --git a/clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.h 
b/clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.h
index 4f3ba321483e..b87d3e629ff6 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.h
+++ b/clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.h
@@ -41,7 +41,7 @@ class UseNoexceptCheck : public ClangTidyCheck {
 
 private:
   const std::string NoexceptMacro;
-  bool UseNoexceptFalse;
+  const bool UseNoexceptFalse;
 };
 
 } // namespace modernize

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/modernize-use-noexcept-error.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/modernize-use-noexcept-error.cpp
new file mode 100644
index ..9a80b075d65e
--- /dev/null
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/modernize-use-noexcept-error.cpp
@@ -0,0 +1,6 @@
+// RUN: %check_clang_tidy -expect-clang-tidy-error %s modernize-use-noexcept %t
+
+// We're not interested in the check issuing a warning here, just making sure
+// clang-tidy doesn't assert.
+undefined_type doesThrow() throw();
+// CHECK-MESSAGES: :[[@LINE-1]]:1: error: unknown type name 'undefined_type' 
[clang-diagnostic-error]



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


[PATCH] D80371: [clang-tidy] Fix potential assert in use-noexcept check

2020-05-25 Thread Nathan James via Phabricator via cfe-commits
njames93 updated this revision to Diff 265923.
njames93 added a comment.

- Added test case


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80371

Files:
  clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.cpp
  clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.h
  clang-tools-extra/test/clang-tidy/checkers/modernize-use-noexcept-error.cpp


Index: 
clang-tools-extra/test/clang-tidy/checkers/modernize-use-noexcept-error.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/modernize-use-noexcept-error.cpp
@@ -0,0 +1,6 @@
+// RUN: %check_clang_tidy -expect-clang-tidy-error %s modernize-use-noexcept %t
+
+// We're not interested in the check issuing a warning here, just making sure
+// clang-tidy doesn't assert.
+undefined_type doesThrow() throw();
+// CHECK-MESSAGES: :[[@LINE-1]]:1: error: unknown type name 'undefined_type' 
[clang-diagnostic-error]
\ No newline at end of file
Index: clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.h
===
--- clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.h
+++ clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.h
@@ -41,7 +41,7 @@
 
 private:
   const std::string NoexceptMacro;
-  bool UseNoexceptFalse;
+  const bool UseNoexceptFalse;
 };
 
 } // namespace modernize
Index: clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.cpp
===
--- clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.cpp
+++ clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.cpp
@@ -16,6 +16,10 @@
 namespace tidy {
 namespace modernize {
 
+namespace {
+AST_MATCHER(NamedDecl, isValid) { return !Node.isInvalidDecl(); }
+} // namespace
+
 UseNoexceptCheck::UseNoexceptCheck(StringRef Name, ClangTidyContext *Context)
 : ClangTidyCheck(Name, Context),
   NoexceptMacro(Options.get("ReplacementString", "")),
@@ -29,20 +33,12 @@
 void UseNoexceptCheck::registerMatchers(MatchFinder *Finder) {
   Finder->addMatcher(
   functionDecl(
-  cxxMethodDecl(
-  hasTypeLoc(loc(functionProtoType(hasDynamicExceptionSpec(,
-  anyOf(hasOverloadedOperatorName("delete[]"),
-hasOverloadedOperatorName("delete"), cxxDestructorDecl()))
-  .bind("del-dtor"))
-  .bind("funcDecl"),
-  this);
-
-  Finder->addMatcher(
-  functionDecl(
+  isValid(),
   hasTypeLoc(loc(functionProtoType(hasDynamicExceptionSpec(,
-  unless(anyOf(hasOverloadedOperatorName("delete[]"),
-   hasOverloadedOperatorName("delete"),
-   cxxDestructorDecl(
+  optionally(cxxMethodDecl(anyOf(hasAnyOverloadedOperatorName(
+ "delete[]", "delete"),
+ cxxDestructorDecl()))
+ .bind("del-dtor")))
   .bind("funcDecl"),
   this);
 
@@ -80,6 +76,9 @@
   .castAs()
   .getExceptionSpecRange();
   }
+
+  assert(Range.isValid() && "Exception Source Range is invalid.");
+
   CharSourceRange CRange = Lexer::makeFileCharRange(
   CharSourceRange::getTokenRange(Range), *Result.SourceManager,
   Result.Context->getLangOpts());


Index: clang-tools-extra/test/clang-tidy/checkers/modernize-use-noexcept-error.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/modernize-use-noexcept-error.cpp
@@ -0,0 +1,6 @@
+// RUN: %check_clang_tidy -expect-clang-tidy-error %s modernize-use-noexcept %t
+
+// We're not interested in the check issuing a warning here, just making sure
+// clang-tidy doesn't assert.
+undefined_type doesThrow() throw();
+// CHECK-MESSAGES: :[[@LINE-1]]:1: error: unknown type name 'undefined_type' [clang-diagnostic-error]
\ No newline at end of file
Index: clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.h
===
--- clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.h
+++ clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.h
@@ -41,7 +41,7 @@
 
 private:
   const std::string NoexceptMacro;
-  bool UseNoexceptFalse;
+  const bool UseNoexceptFalse;
 };
 
 } // namespace modernize
Index: clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.cpp
===
--- clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.cpp
+++ clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.cpp
@@ -16,6 +16,10 @@
 namespace tidy {
 namespace modernize {
 
+namespace {
+AST_MATCHER(NamedDecl, isValid) { return !Node.isInvalidDecl(); }
+} // namespace
+
 UseNoexceptCheck::UseNoexceptCheck(StringRef Name, ClangTidyContext *

[PATCH] D79704: [Analyzer] [NFC] Parameter Regions

2020-05-25 Thread Balogh , Ádám via Phabricator via cfe-commits
baloghadamsoftware updated this revision to Diff 265928.
baloghadamsoftware marked an inline comment as done.
baloghadamsoftware added a comment.

`FIXME` and assertions added.


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

https://reviews.llvm.org/D79704

Files:
  clang/include/clang/StaticAnalyzer/Checkers/SValExplainer.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/Regions.def
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/Store.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h
  clang/lib/StaticAnalyzer/Checkers/NSErrorChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp
  
clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp
  clang/lib/StaticAnalyzer/Checkers/ValistChecker.cpp
  clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
  clang/lib/StaticAnalyzer/Core/CallEvent.cpp
  clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
  clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
  clang/lib/StaticAnalyzer/Core/ExprEngineCallAndReturn.cpp
  clang/lib/StaticAnalyzer/Core/MemRegion.cpp
  clang/lib/StaticAnalyzer/Core/RegionStore.cpp
  clang/lib/StaticAnalyzer/Core/Store.cpp
  clang/lib/StaticAnalyzer/Core/SymbolManager.cpp
  clang/test/Analysis/explain-svals.c
  clang/test/Analysis/explain-svals.cpp
  clang/test/Analysis/explain-svals.m
  clang/unittests/StaticAnalyzer/CMakeLists.txt
  clang/unittests/StaticAnalyzer/ParamRegionTest.cpp

Index: clang/unittests/StaticAnalyzer/ParamRegionTest.cpp
===
--- /dev/null
+++ clang/unittests/StaticAnalyzer/ParamRegionTest.cpp
@@ -0,0 +1,92 @@
+//===- unittests/StaticAnalyzer/ParamRegionTest.cpp ---===//
+//
+// 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 "Reusables.h"
+
+#include "clang/Tooling/Tooling.h"
+#include "gtest/gtest.h"
+
+namespace clang {
+namespace ento {
+namespace {
+
+class ParamRegionTestConsumer : public ExprEngineConsumer {
+  void performTest(const Decl *D) {
+StoreManager &StMgr = Eng.getStoreManager();
+MemRegionManager &MRMgr = StMgr.getRegionManager();
+const StackFrameContext *SFC =
+Eng.getAnalysisDeclContextManager().getStackFrame(D);
+
+if (const auto *FD = dyn_cast(D)) {
+  for (const auto *P : FD->parameters()) {
+const TypedValueRegion *Reg = MRMgr.getRegionForParam(P, SFC);
+if (SFC->inTopFrame())
+  assert(isa(Reg));
+else
+  assert(isa(Reg));
+  }
+} else if (const auto *CD = dyn_cast(D)) {
+  for (const auto *P : CD->parameters()) {
+const TypedValueRegion *Reg = MRMgr.getRegionForParam(P, SFC);
+if (SFC->inTopFrame())
+  assert(isa(Reg));
+else
+  assert(isa(Reg));
+  }
+} else if (const auto *MD = dyn_cast(D)) {
+  for (const auto *P : MD->parameters()) {
+const TypedValueRegion *Reg = MRMgr.getRegionForParam(P, SFC);
+if (SFC->inTopFrame())
+  assert(isa(Reg));
+else
+  assert(isa(Reg));
+  }
+}
+  }
+
+public:
+  ParamRegionTestConsumer(CompilerInstance &C) : ExprEngineConsumer(C) {}
+
+  bool HandleTopLevelDecl(DeclGroupRef DG) override {
+for (const auto *D : DG) {
+  performTest(D);
+}
+return true;
+  }
+};
+
+class ParamRegionTestAction : public ASTFrontendAction {
+public:
+  std::unique_ptr CreateASTConsumer(CompilerInstance &Compiler,
+ StringRef File) override {
+return std::make_unique(Compiler);
+  }
+};
+
+TEST(ParamRegion, ParamRegionTest) {
+  EXPECT_TRUE(tooling::runToolOnCode(
+  std::make_unique(),
+  "void foo(int n) { "
+  "auto lambda = [n](int m) { return n + m; }; "
+  "int k = lambda(2); } "
+  "void bar(int l) { foo(l); }"
+  "struct S { int n; S(int nn): n(nn) {} };"
+  "void baz(int p) { S s(p); }"));
+  EXPECT_TRUE(tooling::runToolOnCode(
+  std::make_unique(),
+  "@interface O \n"
+  "+alloc; \n"
+  "-initWithInt:(int)q; \n"
+  "@end \n"
+  "void qix(int r) { O *o = [[O alloc] initWithInt:r]; }",
+  "input.m"));
+}
+
+} // namespace
+} // namespace ento
+} // namespace clang
Index: clang/unittests/StaticAnalyzer/CMakeLists.txt
=

[PATCH] D79704: [Analyzer] [NFC] Parameter Regions

2020-05-25 Thread Balogh , Ádám via Phabricator via cfe-commits
baloghadamsoftware added a comment.

The big question to decide: Either we keep `ParamRegion` as a separate region 
in the class hierarchy and at the few places where `DeclRegion` or `VarRegion` 
is used and parameters are possible we duplicate the few lines. (Current 
status.)

The other way is to remove `Decl` from `DeclRegion` and make `getDecl()` pure 
virtual. Also we split `VarRegion` into two subclasses, one of the is the 
non-parameter variable regions and the other is `ParamVarRegion`. The first one 
stores the `Decl`, the second one calculates it. This saves code duplication, 
however after we implement creation of stack frames for calls without `Decl` we 
must update all the code using `DeclRegion` and `VarRegion` where parameters 
are possible to handle `nullptr` as return value for `getDecl()`.

@NoQ, please decide, which way to go.


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

https://reviews.llvm.org/D79704



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


[PATCH] D80366: [Analyzer] Add `getReturnValueUnderConstruction()` to `CallEvent`

2020-05-25 Thread Balogh , Ádám via Phabricator via cfe-commits
baloghadamsoftware updated this revision to Diff 265926.
baloghadamsoftware added a comment.

Merged `retrieveFromConstructionContext()` to `handleConstructionContext()`.


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

https://reviews.llvm.org/D80366

Files:
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
  clang/lib/StaticAnalyzer/Core/CallEvent.cpp
  clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
  clang/unittests/StaticAnalyzer/CMakeLists.txt
  clang/unittests/StaticAnalyzer/TestReturnValueUnderConstruction.cpp

Index: clang/unittests/StaticAnalyzer/TestReturnValueUnderConstruction.cpp
===
--- /dev/null
+++ clang/unittests/StaticAnalyzer/TestReturnValueUnderConstruction.cpp
@@ -0,0 +1,55 @@
+//===- unittests/StaticAnalyzer/TestReturnValueUnderConstruction.cpp --===//
+//
+// 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 "CheckerRegistration.h"
+#include "clang/StaticAnalyzer/Core/Checker.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
+#include "clang/StaticAnalyzer/Frontend/AnalysisConsumer.h"
+#include "clang/StaticAnalyzer/Frontend/CheckerRegistry.h"
+#include "clang/Tooling/Tooling.h"
+#include "gtest/gtest.h"
+
+namespace clang {
+namespace ento {
+namespace {
+
+class TestReturnValueUnderConstructionChecker
+  : public Checker {
+public:
+  void checkPostCall(const CallEvent &Call, CheckerContext &C) const {
+if (!Call.getOriginExpr())
+  return;
+
+Optional RetVal = Call.getReturnValueUnderConstruction(0);
+assert(RetVal);
+assert(RetVal->getAsRegion());
+  }
+};
+
+void addTestReturnValueUnderConstructionChecker(
+AnalysisASTConsumer &AnalysisConsumer, AnalyzerOptions &AnOpts) {
+  AnOpts.CheckersAndPackages =
+{{"test.TestReturnValueUnderConstruction", true}};
+  AnalysisConsumer.AddCheckerRegistrationFn([](CheckerRegistry &Registry) {
+  Registry.addChecker(
+  "test.TestReturnValueUnderConstruction", "", "");
+});
+}
+
+TEST(TestReturnValueUnderConstructionChecker,
+ ReturnValueUnderConstructionChecker) {
+  EXPECT_TRUE(runCheckerOnCode(
+  "class C { public: C(int nn): n(nn) {} virtual ~C() {} "
+  "  private: int n; };"
+  "C returnC(int m) { C c(m); return c; }"
+  "void foo() { C c = returnC(1); }"));
+}
+
+} // namespace
+} // namespace ento
+} // namespace clang
Index: clang/unittests/StaticAnalyzer/CMakeLists.txt
===
--- clang/unittests/StaticAnalyzer/CMakeLists.txt
+++ clang/unittests/StaticAnalyzer/CMakeLists.txt
@@ -10,6 +10,7 @@
   StoreTest.cpp
   RegisterCustomCheckersTest.cpp
   SymbolReaperTest.cpp
+  TestReturnValueUnderConstruction.cpp
   )
 
 clang_target_link_libraries(StaticAnalysisTests
Index: clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
===
--- clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
+++ clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
@@ -124,6 +124,10 @@
 case ConstructionContext::SimpleVariableKind: {
   const auto *DSCC = cast(CC);
   const auto *DS = DSCC->getDeclStmt();
+  Optional ExistingVal = getObjectUnderConstruction(State, DS, LCtx);
+  if (ExistingVal.hasValue())
+return std::make_pair(State, *ExistingVal);
+
   const auto *Var = cast(DS->getSingleDecl());
   SVal LValue = State->getLValue(Var, LCtx);
   QualType Ty = Var->getType();
@@ -137,6 +141,11 @@
 case ConstructionContext::SimpleConstructorInitializerKind: {
   const auto *ICC = cast(CC);
   const auto *Init = ICC->getCXXCtorInitializer();
+  Optional ExistingVal =
+getObjectUnderConstruction(State, Init, LCtx);
+  if (ExistingVal.hasValue())
+return std::make_pair(State, *ExistingVal);
+
   assert(Init->isAnyMemberInitializer());
   const CXXMethodDecl *CurCtor = cast(LCtx->getDecl());
   Loc ThisPtr =
@@ -235,6 +244,9 @@
   const CXXBindTemporaryExpr *BTE = TCC->getCXXBindTemporaryExpr();
   const MaterializeTemporaryExpr *MTE = TCC->getMaterializedTemporaryExpr();
   const CXXConstructExpr *CE = TCC->getConstructorAfterElision();
+  Optional ExistingVal = getObjectUnderConstruction(State, CE, LCtx);
+  if (ExistingVal.hasValue())
+return std::make_pair(State, *ExistingVal);
 
   // Support pre-C++17 copy elision. We'll have the elidable copy
   // constructor in the AST and in the CFG, but we'll skip it
@@ -281,7 +293,19 @@
   const MaterializeTemporaryExpr *MTE = TCC->getMateri

[PATCH] D80366: [Analyzer] Add `getReturnValueUnderConstruction()` to `CallEvent`

2020-05-25 Thread Balogh , Ádám via Phabricator via cfe-commits
baloghadamsoftware marked 2 inline comments as done.
baloghadamsoftware added inline comments.



Comment at: clang/lib/StaticAnalyzer/Core/CallEvent.cpp:575
+  std::tie(State, RetVal) =
+
static_cast(&Engine)->handleConstructionContext(getOriginExpr(),
+ getState(),

This is extremely ugly and was one of the reasons I originally did not reuse 
`handleConstructionContext()`. What should I do here? Create a pure virtual 
`handleConstructionContext()` into `SubEngine`? Or somehow make 
`handleConstructionContext` static? Is there maybe a more proper way to access 
`ExprEngine` from `CallEvent`?



Comment at: clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp:112
 
+Optional ExprEngine::retrieveFromConstructionContext(
+ProgramStateRef State, const LocationContext *LCtx,

NoQ wrote:
> Please instead re-use the code that computes the object under construction. 
> That'll save you ~50 lines of code and will be more future-proof (eg., 
> standalone temporaries without destructor technically have a construction 
> context with 0 items so when we implement them correctly your procedure will 
> stop working).
That was so my first thought. However, `handleConstructionContext()` is private 
and non-static. Now I tried to merge the two methods: if the value is already 
in the construction context, we return it, if not then we add it. Is this what 
you suggest? Or did I misunderstand you? At the very beginning I tried to 
simply use `handleConstructionContext()`, but it asserted because the value was 
already in the map.


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

https://reviews.llvm.org/D80366



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


[PATCH] D79437: [clang-tidy] Add fsetpos argument checker

2020-05-25 Thread Beka Grdzelishvili via Phabricator via cfe-commits
DerWaschbar updated this revision to Diff 265930.
DerWaschbar marked 3 inline comments as done.

Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D79437

Files:
  clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
  clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
  clang-tools-extra/clang-tidy/bugprone/FsetposArgumentCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/FsetposArgumentCheck.h
  clang-tools-extra/clang-tidy/cert/CERTTidyModule.cpp
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/bugprone-fsetpos-argument-check.rst
  clang-tools-extra/docs/clang-tidy/checks/cert-fio44-c.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  clang-tools-extra/test/clang-tidy/checkers/bugprone-fsetpos-argument-check.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/bugprone-fsetpos-argument-check.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/bugprone-fsetpos-argument-check.cpp
@@ -0,0 +1,59 @@
+// RUN: %check_clang_tidy %s bugprone-fsetpos-argument-check %t
+
+typedef unsigned int size_t;
+class FILE;
+struct fpos_t {};
+int fsetpos(FILE *stream, const fpos_t *pos);
+int fgetpos(FILE *stream, fpos_t *pos);
+void *memset(void *ptr, int value, size_t num);
+
+//-
+
+int opener1(FILE *file) {
+  int rc;
+  fpos_t offset;
+
+  if (file == nullptr ) {
+return -1;
+  }
+
+  rc = fgetpos(file, &offset);
+  if (rc != 0 ) {
+return rc;
+  }
+
+  /* Read in data from file */
+
+  rc = fsetpos(file, &offset);
+  if (rc != 0 ) {
+return rc;
+  }
+
+  return 0;
+}
+
+//-
+
+int opener2(FILE *file) {
+  int rc;
+  fpos_t offset;
+
+  memset(&offset, 0, sizeof(offset));
+
+  if (file == nullptr) {
+return -1;
+  }
+
+  /* Read in data from file */
+
+  rc = fsetpos(file, &offset);
+  // CHECK-MESSAGES: :[[@LINE-1]]:8: warning: file position indicator should be obtained only from 'fgetpos' [bugprone-fsetpos-argument-check]
+  if (rc != 0 ) {
+return rc;
+  }
+
+  return 0;
+}
+
+
+//-
Index: clang-tools-extra/docs/clang-tidy/checks/list.rst
===
--- clang-tools-extra/docs/clang-tidy/checks/list.rst
+++ clang-tools-extra/docs/clang-tidy/checks/list.rst
@@ -57,6 +57,7 @@
`bugprone-fold-init-type `_,
`bugprone-forward-declaration-namespace `_,
`bugprone-forwarding-reference-overload `_,
+   `bugprone-fsetpos-argument-check ` _,
`bugprone-inaccurate-erase `_, "Yes"
`bugprone-incorrect-roundings `_,
`bugprone-infinite-loop `_,
@@ -315,6 +316,7 @@
`cert-err09-cpp `_, `misc-throw-by-value-catch-by-reference `_,
`cert-err61-cpp `_, `misc-throw-by-value-catch-by-reference `_,
`cert-fio38-c `_, `misc-non-copyable-objects `_,
+   `cert-fio44-c `_, `bugprone-fsetpos-argument-check `_,
`cert-msc30-c `_, `cert-msc50-cpp `_,
`cert-msc32-c `_, `cert-msc51-cpp `_,
`cert-oop11-cpp `_, `performance-move-constructor-init `_, "Yes"
Index: clang-tools-extra/docs/clang-tidy/checks/cert-fio44-c.rst
===
--- /dev/null
+++ clang-tools-extra/docs/clang-tidy/checks/cert-fio44-c.rst
@@ -0,0 +1,10 @@
+.. title:: clang-tidy - cert-fio44-c
+.. meta::
+   :http-equiv=refresh: 5;URL=bugprone-fsetpos-argument-check.html
+
+cert-fio44-c
+
+
+The cert-fio44-c check is an alias, please see
+`bugprone-fsetpos-argument-check `_
+for more information.
Index: clang-tools-extra/docs/clang-tidy/checks/bugprone-fsetpos-argument-check.rst
===
--- /dev/null
+++ clang-tools-extra/docs/clang-tidy/checks/bugprone-fsetpos-argument-check.rst
@@ -0,0 +1,37 @@
+.. title:: clang-tidy - bugprone-fsetpos-argument-check
+
+bugprone-fsetpos-argument-check
+===
+
+Finds call of ``fsetpos`` functions, which does not have file position indicator
+obtained from ``fgetpos``.
+
+.. code-block:: c
+
+#include 
+#include 
+
+int opener(FILE *file) {
+int rc;
+fpos_t offset;
+
+memset(&offset, 0, sizeof(offset));
+
+if (file == NULL) {
+return -1;
+}
+
+/* Read in data from file */
+
+rc = fsetpos(file, &offset);
+if (rc != 0 ) {
+return rc;
+}
+
+return 0;
+}
+
+
+This check corresponds to the CERT C Coding Standard rule
+`FIO44-C. Only use values for fsetpos() that are returned from fgetpos()
+`_.
Index: clang-tools-extra/docs/ReleaseNotes.rst
==

[PATCH] D80425: Fix LLVM/Clang builds with mingw toolchain

2020-05-25 Thread Tobias Hieta via Phabricator via cfe-commits
thieta added a comment.

Sounds good - I'll close this one and open three new ones.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80425



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


[PATCH] D80492: Avoid linking libdl unless needed

2020-05-25 Thread Tobias Hieta via Phabricator via cfe-commits
thieta created this revision.
thieta added a reviewer: mstorsjo.
thieta added a project: clang.
Herald added subscribers: cfe-commits, mgorny.

This fixes cross-compilation when targeting a platform not using libdl and 
mirrors libdl linking in other parts of the code.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D80492

Files:
  clang/tools/libclang/CMakeLists.txt


Index: clang/tools/libclang/CMakeLists.txt
===
--- clang/tools/libclang/CMakeLists.txt
+++ clang/tools/libclang/CMakeLists.txt
@@ -66,9 +66,8 @@
   endif ()
 endif ()
 
-find_library(DL_LIBRARY_PATH dl)
-if (DL_LIBRARY_PATH)
-  list(APPEND LIBS dl)
+if (HAVE_LIBDL)
+  list(APPEND LIBS ${CMAKE_DL_LIBS})
 endif()
 
 option(LIBCLANG_BUILD_STATIC


Index: clang/tools/libclang/CMakeLists.txt
===
--- clang/tools/libclang/CMakeLists.txt
+++ clang/tools/libclang/CMakeLists.txt
@@ -66,9 +66,8 @@
   endif ()
 endif ()
 
-find_library(DL_LIBRARY_PATH dl)
-if (DL_LIBRARY_PATH)
-  list(APPEND LIBS dl)
+if (HAVE_LIBDL)
+  list(APPEND LIBS ${CMAKE_DL_LIBS})
 endif()
 
 option(LIBCLANG_BUILD_STATIC
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D80492: Avoid linking libdl unless needed

2020-05-25 Thread Martin Storsjö via Phabricator via cfe-commits
mstorsjo added a reviewer: beanz.
mstorsjo added a subscriber: beanz.
mstorsjo added a comment.

I think this is ok, but adding @beanz who knows the cmake conventions better 
than me.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80492



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


[PATCH] D79437: [clang-tidy] Add fsetpos argument checker

2020-05-25 Thread Beka Grdzelishvili via Phabricator via cfe-commits
DerWaschbar added a comment.

In D79437#2052109 , @aaron.ballman 
wrote:

> Thank you for working on this check, I think it's useful functionality. One 
> concern I have, though, is that it's not flow-sensitive and should probably 
> be implemented as a clang static analyzer check instead of a clang-tidy 
> check. For instance, consider these three plausible issues:
>
>   // This only sets the offset on one code path.
>   void func(FILE *fp) {
> fpos_t offset;
> if (condition) {
>   // ... code
>   if (0 != fgetpos(fp, &offset))
> return;
>   // ... code
> } else {
>  // ... code
> }
> fsetpos(fp, &offset);
>   }
>  
>   // This doesn't check the failure from getting the position and sets the 
> position regardless.
>   void func(FILE *fp) {
> fpos_t offset;
> fgetpos(fp, &offset);
> // ... code
> fsetpos(fp, &offset);
>   }
>  
>   // This function accepts the offset from the caller but the caller passes 
> an invalid offset.
>   void func(FILE *fp, const fpos_t *offset) {
> fsetpos(fp, offset);
>   }
>   void caller(FILE *fp) {
> fpos_t offset;
> func(fp, &offset);
>   }
>
>
> Have you considered writing a static analyzer check so you can do data and 
> control flow analysis to catch issues like these?


I have noticed those issues too, but most likely the getter/setter will be in 
the same function body and we could measure fast how common is that issue in 
the wild. Also, this was my first introductory project for Clang and with that, 
I can rewrite this as a Static Analyzer project or start working on another 
Clang-Tidy project.


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D79437



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


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

2020-05-25 Thread Joe Burzinski via Phabricator via cfe-commits
Tridacnid added a comment.

Ping


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

https://reviews.llvm.org/D79912



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


[clang] e60de8c - Add missing test

2020-05-25 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2020-05-24T22:50:50+01:00
New Revision: e60de8c825d3087dca26d97985febbf97e179311

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

LOG: Add missing test

Added: 


Modified: 
clang/lib/AST/Expr.cpp
clang/unittests/AST/ASTTraverserTest.cpp
clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp

Removed: 




diff  --git a/clang/lib/AST/Expr.cpp b/clang/lib/AST/Expr.cpp
index b9b7ca95b218..4c175fff6421 100644
--- a/clang/lib/AST/Expr.cpp
+++ b/clang/lib/AST/Expr.cpp
@@ -2909,7 +2909,8 @@ Expr *Expr::IgnoreUnlessSpelledInSource() {
   Expr *LastE = nullptr;
   while (E != LastE) {
 LastE = E;
-E = IgnoreExprNodes(E, IgnoreImplicitSingleStep, 
IgnoreImpCastsExtraSingleStep,
+E = IgnoreExprNodes(E, IgnoreImplicitSingleStep,
+IgnoreImpCastsExtraSingleStep,
 IgnoreParensOnlySingleStep);
 
 auto SR = E->getSourceRange();

diff  --git a/clang/unittests/AST/ASTTraverserTest.cpp 
b/clang/unittests/AST/ASTTraverserTest.cpp
index affbbe76f0d2..5585238939fe 100644
--- a/clang/unittests/AST/ASTTraverserTest.cpp
+++ b/clang/unittests/AST/ASTTraverserTest.cpp
@@ -291,6 +291,13 @@ void conversionOperator()
 C1 c1 = (*c2);
 }
 
+template 
+void template_test() {
+  static_assert(alignment, "");
+}
+void actual_template_test() {
+  template_test<4>();
+}
 )cpp");
 
   {
@@ -408,6 +415,31 @@ VarDecl 'c1'
 VarDecl 'c1'
 `-UnaryOperator
   `-DeclRefExpr 'c2'
+)cpp");
+  }
+
+  {
+auto FN = ast_matchers::match(
+functionDecl(hasName("template_test"),
+ hasDescendant(staticAssertDecl().bind("staticAssert"))),
+AST->getASTContext());
+EXPECT_EQ(FN.size(), 2u);
+
+EXPECT_EQ(dumpASTString(TK_AsIs, FN[1].getNodeAs("staticAssert")),
+  R"cpp(
+StaticAssertDecl
+|-ImplicitCastExpr
+| `-SubstNonTypeTemplateParmExpr
+|   `-IntegerLiteral
+`-StringLiteral
+)cpp");
+
+EXPECT_EQ(dumpASTString(TK_IgnoreUnlessSpelledInSource,
+FN[1].getNodeAs("staticAssert")),
+  R"cpp(
+StaticAssertDecl
+|-IntegerLiteral
+`-StringLiteral
 )cpp");
   }
 }

diff  --git a/clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp 
b/clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
index e8b0a312d0a3..6bd8fcf66498 100644
--- a/clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
+++ b/clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
@@ -1867,6 +1867,26 @@ void conversionOperator()
 hasDescendant(varDecl(
 hasName("c1"), hasInitializer(unaryOperator(

hasOperatorName("*");
+
+  Code = R"cpp(
+
+template 
+void template_test() {
+  static_assert(alignment, "");
+}
+void actual_template_test() {
+  template_test<4>();
+}
+
+)cpp";
+  EXPECT_TRUE(matches(
+  Code,
+  traverse(TK_AsIs,
+   staticAssertDecl(has(implicitCastExpr(has(
+   substNonTypeTemplateParmExpr(has(integerLiteral());
+
+  EXPECT_TRUE(matches(Code, traverse(TK_IgnoreUnlessSpelledInSource,
+ 
staticAssertDecl(has(integerLiteral());
 }
 
 template 



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


[clang-tools-extra] 2be92b7 - Fix ignore-traversal to call correct method

2020-05-25 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2020-05-24T22:33:10+01:00
New Revision: 2be92b7f7e41037e051096df8a9c4de35502c036

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

LOG: Fix ignore-traversal to call correct method

As is done by ignoreParenImpCasts(). We were not previously calling the
correct internal method.  Adjust tests to account for this.

Added: 


Modified: 
clang-tools-extra/clang-tidy/readability/UppercaseLiteralSuffixCheck.cpp
clang/lib/AST/Expr.cpp
clang/unittests/ASTMatchers/ASTMatchersNodeTest.cpp

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/readability/UppercaseLiteralSuffixCheck.cpp 
b/clang-tools-extra/clang-tidy/readability/UppercaseLiteralSuffixCheck.cpp
index 70d2a10ae2d8..aab45faa6cb3 100644
--- a/clang-tools-extra/clang-tidy/readability/UppercaseLiteralSuffixCheck.cpp
+++ b/clang-tools-extra/clang-tidy/readability/UppercaseLiteralSuffixCheck.cpp
@@ -196,12 +196,12 @@ void 
UppercaseLiteralSuffixCheck::registerMatchers(MatchFinder *Finder) {
   // Sadly, we can't check whether the literal has suffix or not.
   // E.g. i32 suffix still results in 'BuiltinType::Kind::Int'.
   // And such an info is not stored in the *Literal itself.
-  Finder->addMatcher(
+  Finder->addMatcher(traverse(TK_AsIs,
   stmt(eachOf(integerLiteral().bind(IntegerLiteralCheck::Name),
   floatLiteral().bind(FloatingLiteralCheck::Name)),
unless(anyOf(hasParent(userDefinedLiteral()),
 hasAncestor(isImplicit()),
-hasAncestor(substNonTypeTemplateParmExpr(),
+hasAncestor(substNonTypeTemplateParmExpr()),
   this);
 }
 

diff  --git a/clang/lib/AST/Expr.cpp b/clang/lib/AST/Expr.cpp
index 0184140ab07e..b9b7ca95b218 100644
--- a/clang/lib/AST/Expr.cpp
+++ b/clang/lib/AST/Expr.cpp
@@ -2909,7 +2909,7 @@ Expr *Expr::IgnoreUnlessSpelledInSource() {
   Expr *LastE = nullptr;
   while (E != LastE) {
 LastE = E;
-E = IgnoreExprNodes(E, IgnoreImplicitSingleStep, IgnoreImpCastsSingleStep,
+E = IgnoreExprNodes(E, IgnoreImplicitSingleStep, 
IgnoreImpCastsExtraSingleStep,
 IgnoreParensOnlySingleStep);
 
 auto SR = E->getSourceRange();

diff  --git a/clang/unittests/ASTMatchers/ASTMatchersNodeTest.cpp 
b/clang/unittests/ASTMatchers/ASTMatchersNodeTest.cpp
index d38086616460..82a28d00cebf 100644
--- a/clang/unittests/ASTMatchers/ASTMatchersNodeTest.cpp
+++ b/clang/unittests/ASTMatchers/ASTMatchersNodeTest.cpp
@@ -303,11 +303,13 @@ TEST(Matcher, SubstNonTypeTemplateParm) {
   EXPECT_FALSE(matches("template\n"
  "struct A {  static const int n = 0; };\n"
  "struct B : public A<42> {};",
-   substNonTypeTemplateParmExpr()));
+ traverse(TK_AsIs,
+   substNonTypeTemplateParmExpr(;
   EXPECT_TRUE(matches("template\n"
 "struct A {  static const int n = N; };\n"
 "struct B : public A<42> {};",
-  substNonTypeTemplateParmExpr()));
+ traverse(TK_AsIs,
+  substNonTypeTemplateParmExpr(;
 }
 
 TEST(Matcher, NonTypeTemplateParmDecl) {



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


[PATCH] D80472: [clangd] Add access specifier information to hover contents

2020-05-25 Thread Daniel Martín via Phabricator via cfe-commits
danielmartin updated this revision to Diff 265942.
danielmartin added a comment.

Move clang::getAccess to Specifiers.h and refactor logic in clang-doc
to use that function instead of its own.

Also changes where "public", "private" etc. is shown in the hover
contents. Now it's shown at the bottom.

Strengthens an existing unit test to also check for access specifiers.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80472

Files:
  clang-tools-extra/clang-doc/Generators.cpp
  clang-tools-extra/clang-doc/Generators.h
  clang-tools-extra/clang-doc/HTMLGenerator.cpp
  clang-tools-extra/clang-doc/MDGenerator.cpp
  clang-tools-extra/clangd/Hover.cpp
  clang-tools-extra/clangd/Hover.h
  clang-tools-extra/clangd/unittests/HoverTests.cpp
  clang/include/clang/Basic/Specifiers.h

Index: clang/include/clang/Basic/Specifiers.h
===
--- clang/include/clang/Basic/Specifiers.h
+++ clang/include/clang/Basic/Specifiers.h
@@ -365,6 +365,20 @@
   };
 
   llvm::StringRef getParameterABISpelling(ParameterABI kind);
+
+  inline llvm::StringRef getAccess(AccessSpecifier AS) {
+switch (AS) {
+case AccessSpecifier::AS_public:
+  return "public";
+case AccessSpecifier::AS_protected:
+  return "protected";
+case AccessSpecifier::AS_private:
+  return "private";
+case AccessSpecifier::AS_none:
+  return {};
+}
+llvm_unreachable("Unknown AccessSpecifier");
+  }
 } // end namespace clang
 
 #endif // LLVM_CLANG_BASIC_SPECIFIERS_H
Index: clang-tools-extra/clangd/unittests/HoverTests.cpp
===
--- clang-tools-extra/clangd/unittests/HoverTests.cpp
+++ clang-tools-extra/clangd/unittests/HoverTests.cpp
@@ -80,6 +80,7 @@
  HI.Type = "char";
  HI.Offset = 0;
  HI.Size = 1;
+ HI.AccessSpecifier = "public";
}},
   // Local to class method.
   {R"cpp(
@@ -116,6 +117,7 @@
  HI.Type = "char";
  HI.Offset = 0;
  HI.Size = 1;
+ HI.AccessSpecifier = "public";
}},
   // Struct definition shows size.
   {R"cpp(
@@ -345,6 +347,7 @@
  HI.Kind = index::SymbolKind::Constructor;
  HI.Definition = "X()";
  HI.Parameters.emplace();
+ HI.AccessSpecifier = "public";
}},
   {"class X { [[^~]]X(); };", // FIXME: Should be [[~X]]()
[](HoverInfo &HI) {
@@ -354,6 +357,7 @@
  HI.Kind = index::SymbolKind::Destructor;
  HI.Definition = "~X()";
  HI.Parameters.emplace();
+ HI.AccessSpecifier = "private";
}},
   {"class X { [[op^erator]] int(); };",
[](HoverInfo &HI) {
@@ -363,6 +367,7 @@
  HI.Kind = index::SymbolKind::ConversionFunction;
  HI.Definition = "operator int()";
  HI.Parameters.emplace();
+ HI.AccessSpecifier = "private";
}},
   {"class X { operator [[^X]](); };",
[](HoverInfo &HI) {
@@ -495,6 +500,7 @@
  HI.NamespaceScope = "";
  HI.LocalScope = "Add<1, 2>::";
  HI.Value = "3";
+ HI.AccessSpecifier = "public";
}},
   {R"cpp(
 constexpr int answer() { return 40 + 2; }
@@ -607,6 +613,7 @@
  HI.Definition = "typename T = int";
  HI.LocalScope = "foo::";
  HI.Type = "typename";
+ HI.AccessSpecifier = "public";
}},
   {// TemplateTemplate Type Parameter
R"cpp(
@@ -619,6 +626,7 @@
  HI.Definition = "template  class T";
  HI.LocalScope = "foo::";
  HI.Type = "template  class";
+ HI.AccessSpecifier = "public";
}},
   {// NonType Template Parameter
R"cpp(
@@ -631,6 +639,7 @@
  HI.Definition = "int T = 5";
  HI.LocalScope = "foo::";
  HI.Type = "int";
+ HI.AccessSpecifier = "public";
}},
 
   {// Getter
@@ -647,6 +656,7 @@
  HI.Type = "float ()";
  HI.ReturnType = "float";
  HI.Parameters.emplace();
+ HI.AccessSpecifier = "public";
}},
   {// Setter
R"cpp(
@@ -665,6 +675,7 @@
  HI.Parameters->emplace_back();
  HI.Parameters->back().Type = "float";
  HI.Parameters->back().Name = "v";
+ HI.AccessSpecifier = "public";
}},
   {// Setter (builder)
R"cpp(
@@ -683,6 +694,7 @@
  HI.Parameters->emplace_back();
  HI.Parameters->back().Type = "float";
  HI.Parameters->back().Name = "v";
+ HI.AccessSpecifier = "public";
}},
   };
   for (const auto &Case : Cases) {
@@ -716,6 +728,7 @@
 EXPECT_EQ(H->Value, Expected.Value);
 EXPECT_EQ(H->Size, Expected.Size);
 EXPECT_EQ(H->Offset, Expected.Offset);
+EXPECT_EQ(H->AccessSpecifier, Expected.AccessSpecifier);
   }
 }
 
@@ -1968,20 +1981,20 @@
   {
   [](HoverInfo &HI) {
   

[PATCH] D80472: [clangd] Add access specifier information to hover contents

2020-05-25 Thread Daniel Martín via Phabricator via cfe-commits
danielmartin marked 6 inline comments as done.
danielmartin added inline comments.



Comment at: clang-tools-extra/clangd/Hover.cpp:680
 
+StringRef getAccessString(AccessSpecifier AS) {
+  switch (AS) {

kadircet wrote:
> it is annoying to have this function duplicated in each component (there are 
> duplicates at least in text and json node dumpers too) :/
> 
> Feel free to provide a common implementation in 
> `clang/include/clang/Basic/Specifiers.h` and migrate all other usages to it, 
> or just put a FIXME in here saying we should converge those.
> 
> nit: prefer `llvm::StringRef` as return type
I've only found usages in clang-doc, I don't know if there's more. 

I've changed them to use the new common logic in `Specifiers.h`.



Comment at: clang-tools-extra/clangd/Hover.cpp:793
+  if (AccessSpecifier != AccessSpecifier::AS_none)
+Header.appendText(getAccessString(AccessSpecifier)).appendSpace();
   if (Kind != index::SymbolKind::Unknown)

kadircet wrote:
> I wonder if it would be more natural to put this at bottom, where we list the 
> containing class/struct/union. e.g.
> 
> ```
> struct X { int fo^o; }
> ```
> 
> would result in
> 
> ```
> field foo
> ---
> 
> // In X
> public: int foo
> ```
> 
> I find current one useful too, just listing options to see what you (and 
> possibly others interested in) think.
I think it's a bit less visible, but one good thing your suggestion has is that 
in the Emacs client we use that part of the hover content to show a one liner 
with type information. So I followed your suggestion to also have access 
specifier information in our one-liner.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80472



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


[PATCH] D69764: [clang-format] Add East/West Const fixer capability

2020-05-25 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay updated this revision to Diff 265949.
MyDeveloperDay retitled this revision from "[clang-format] Add Left/Right Const 
fixer capability" to "[clang-format] Add East/West Const fixer capability".
MyDeveloperDay added a comment.

Add more test cases
Cover more template and namespace cases


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

https://reviews.llvm.org/D69764

Files:
  clang/docs/ClangFormatStyleOptions.rst
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Format/Format.h
  clang/lib/Format/CMakeLists.txt
  clang/lib/Format/EastWestConstFixer.cpp
  clang/lib/Format/EastWestConstFixer.h
  clang/lib/Format/Format.cpp
  clang/tools/clang-format/ClangFormat.cpp
  clang/unittests/Format/FormatTest.cpp

Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -13628,6 +13628,11 @@
   CHECK_PARSE("ContinuationIndentWidth: 11", ContinuationIndentWidth, 11u);
   CHECK_PARSE("CommentPragmas: '// abc$'", CommentPragmas, "// abc$");
 
+  Style.ConstStyle = FormatStyle::CS_West;
+  CHECK_PARSE("ConstStyle: Leave", ConstStyle, FormatStyle::CS_Leave);
+  CHECK_PARSE("ConstStyle: East", ConstStyle, FormatStyle::CS_East);
+  CHECK_PARSE("ConstStyle: West", ConstStyle, FormatStyle::CS_West);
+
   Style.PointerAlignment = FormatStyle::PAS_Middle;
   CHECK_PARSE("PointerAlignment: Left", PointerAlignment,
   FormatStyle::PAS_Left);
@@ -16567,6 +16572,245 @@
"}",
Style);
 }
+
+TEST_F(FormatTest, EastWestConst) {
+  FormatStyle Style = getLLVMStyle();
+
+  // keep the const style unaltered
+  verifyFormat("const int a;", Style);
+  verifyFormat("const int *a;", Style);
+  verifyFormat("const int &a;", Style);
+  verifyFormat("const int &&a;", Style);
+  verifyFormat("int const b;", Style);
+  verifyFormat("int const *b;", Style);
+  verifyFormat("int const &b;", Style);
+  verifyFormat("int const &&b;", Style);
+  verifyFormat("int const *b const;", Style);
+  verifyFormat("int *const c;", Style);
+
+  verifyFormat("const Foo a;", Style);
+  verifyFormat("const Foo *a;", Style);
+  verifyFormat("const Foo &a;", Style);
+  verifyFormat("const Foo &&a;", Style);
+  verifyFormat("Foo const b;", Style);
+  verifyFormat("Foo const *b;", Style);
+  verifyFormat("Foo const &b;", Style);
+  verifyFormat("Foo const &&b;", Style);
+  verifyFormat("Foo const *b const;", Style);
+
+  verifyFormat("LLVM_NODISCARD const int &Foo();", Style);
+  verifyFormat("LLVM_NODISCARD int const &Foo();", Style);
+
+  verifyFormat("volatile const int *restrict;", Style);
+  verifyFormat("const volatile int *restrict;", Style);
+  verifyFormat("const int volatile *restrict;", Style);
+}
+
+TEST_F(FormatTest, EastConst) {
+  FormatStyle Style = getLLVMStyle();
+  Style.ConstStyle = FormatStyle::CS_East;
+
+  verifyFormat("int const a;", Style);
+  verifyFormat("int const *a;", Style);
+  verifyFormat("int const &a;", Style);
+  verifyFormat("int const &&a;", Style);
+  verifyFormat("int const b;", Style);
+  verifyFormat("int const *b;", Style);
+  verifyFormat("int const &b;", Style);
+  verifyFormat("int const &&b;", Style);
+  verifyFormat("int const *b const;", Style);
+  verifyFormat("int *const c;", Style);
+
+  verifyFormat("Foo const a;", Style);
+  verifyFormat("Foo const *a;", Style);
+  verifyFormat("Foo const &a;", Style);
+  verifyFormat("Foo const &&a;", Style);
+  verifyFormat("Foo const b;", Style);
+  verifyFormat("Foo const *b;", Style);
+  verifyFormat("Foo const &b;", Style);
+  verifyFormat("Foo const &&b;", Style);
+  verifyFormat("Foo const *b const;", Style);
+  verifyFormat("Foo *const b;", Style);
+  verifyFormat("Foo const *const b;", Style);
+  verifyFormat("auto const v = get_value();", Style);
+  verifyFormat("long long const &a;", Style);
+  verifyFormat("unsigned char const *a;", Style);
+  verifyFormat("int main(int const argc, char const *const *const argv)",
+   Style);
+
+  verifyFormat("LLVM_NODISCARD int const &Foo();", Style);
+  verifyFormat("SourceRange getSourceRange() const override LLVM_READONLY",
+   Style);
+  verifyFormat("void foo() const override;", Style);
+  verifyFormat("void foo() const override LLVM_READONLY;", Style);
+  verifyFormat("void foo() const final;", Style);
+  verifyFormat("void foo() const final LLVM_READONLY;", Style);
+  verifyFormat("void foo() const LLVM_READONLY;", Style);
+
+  verifyFormat(
+  "template  explicit Action(Action const &action);",
+  Style);
+  verifyFormat(
+  "template  explicit Action(Action const &action);",
+  "template  explicit Action(const Action& action);",
+  Style);
+  verifyFormat(
+  "template  explicit Action(Action const &action);",
+  "template \nexplicit Action(const Action& action);",
+  Style);
+
+  verifyFormat("int const a;", "const int a;", Style);
+  verifyFormat("int

[PATCH] D72534: Change default traversal in AST Matchers to ignore invisible nodes

2020-05-25 Thread Stephen Kelly via Phabricator via cfe-commits
steveire updated this revision to Diff 265946.
steveire added a comment.

Rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D72534

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/AST/ParentMapContext.h


Index: clang/include/clang/AST/ParentMapContext.h
===
--- clang/include/clang/AST/ParentMapContext.h
+++ clang/include/clang/AST/ParentMapContext.h
@@ -67,7 +67,7 @@
 private:
   ASTContext &ASTCtx;
   class ParentMap;
-  TraversalKind Traversal = TK_AsIs;
+  TraversalKind Traversal = TK_IgnoreUnlessSpelledInSource;
   std::unique_ptr Parents;
 };
 
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -246,7 +246,14 @@
 AST Matchers
 
 
-- ...
+- Traversal in AST Matchers was simplified to use the
+  ``TK_IgnoreUnlessSpelledInSource`` mode by default, instead of ``TK_AsIs``.
+  This means that many uses of the ``ignoringImplicit()`` and similar matchers
+  is no longer necessary.  Clients of AST Matchers which wish to match on
+  implicit AST nodes can wrap their matcher in ``traverse(TK_AsIs, ...)`` or
+  use ``TraversalKindScope`` if appropriate.  The ``clang-query`` tool also
+  uses ``IgnoreUnlessSpelledInSource`` by default.  The mode can be changed
+  using ``set traversal AsIs`` in the ``clang-query`` environment.
 
 clang-format
 


Index: clang/include/clang/AST/ParentMapContext.h
===
--- clang/include/clang/AST/ParentMapContext.h
+++ clang/include/clang/AST/ParentMapContext.h
@@ -67,7 +67,7 @@
 private:
   ASTContext &ASTCtx;
   class ParentMap;
-  TraversalKind Traversal = TK_AsIs;
+  TraversalKind Traversal = TK_IgnoreUnlessSpelledInSource;
   std::unique_ptr Parents;
 };
 
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -246,7 +246,14 @@
 AST Matchers
 
 
-- ...
+- Traversal in AST Matchers was simplified to use the
+  ``TK_IgnoreUnlessSpelledInSource`` mode by default, instead of ``TK_AsIs``.
+  This means that many uses of the ``ignoringImplicit()`` and similar matchers
+  is no longer necessary.  Clients of AST Matchers which wish to match on
+  implicit AST nodes can wrap their matcher in ``traverse(TK_AsIs, ...)`` or
+  use ``TraversalKindScope`` if appropriate.  The ``clang-query`` tool also
+  uses ``IgnoreUnlessSpelledInSource`` by default.  The mode can be changed
+  using ``set traversal AsIs`` in the ``clang-query`` environment.
 
 clang-format
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D69764: [clang-format] Add East/West Const fixer capability

2020-05-25 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay marked an inline comment as done.
MyDeveloperDay added a comment.

> I would like to reiterate my discomfort with using East/West as the 
> identifiers here

I'd like to think that I can see it from both angles, @steveire is correct, if 
I just supply Left/Right then we'll have a request almost immediately for for 
East/West, Ultimately we'll likely not know what people prefer until its been 
used. (I'll be interested to do a search in github.com if I ever get this 
landed)




Comment at: clang/lib/Format/Format.cpp:2547
 
+  if (Style.isCpp() || Style.Language == FormatStyle::LK_ObjC) {
+if (Style.ConstStyle != FormatStyle::CS_Leave)

aaron.ballman wrote:
> This prevents us from using this in C code despite C having qualifiers that 
> can go to the left or right of the base type but still allows you to use if 
> from Objective-C. That seems incorrect.
clang-format's isCpp() covers C and C++ (and ObjectiveC and ObjectiveC++)

but you did highlight that I don't need the extra LK_ObjC check


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

https://reviews.llvm.org/D69764



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


[PATCH] D78938: Fixing all comparisons for C++20 compilation.

2020-05-25 Thread David Stone via Phabricator via cfe-commits
davidstone added a comment.

I noticed the missing return because there is a warning (not as error) that 
caught it, I think the warning about falling off the end of a 
non-void-returning function.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D78938



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


[PATCH] D78938: Fixing all comparisons for C++20 compilation.

2020-05-25 Thread JF Bastien via Phabricator via cfe-commits
jfb accepted this revision.
jfb added a comment.

One suggestions, otherwise looks good. Thanks for doing this :)




Comment at: llvm/include/llvm/ADT/DirectedGraph.h:97
+  }
+  friend bool operator!=(const NodeType &M, const NodeType &N) { !(M == N); }
 

davidstone wrote:
> Missing `return`
😱

Did this not trigger a diagnostic when building? I wonder if it's just not on?



Comment at: llvm/include/llvm/ADT/DirectedGraph.h:40
   /// Static polymorphism: delegate implementation (via isEqualTo) to the
   /// derived class.
+  bool operator==(const DGEdge &E) const {

That comment, so informative! 😐



Comment at: llvm/unittests/ADT/STLExtrasTest.cpp:466
   std::unique_ptr V2 = std::make_unique(0);
-  EXPECT_EQ(V2.get(), to_address(V2));
+  EXPECT_EQ(V2.get(), (to_address)(V2));
 

Can you add a comment above (with "fancy pointer") so mere mortals understand 
the parens?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D78938



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


[PATCH] D69764: [clang-format] Add East/West Const fixer capability

2020-05-25 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay planned changes to this revision.
MyDeveloperDay added a comment.

@steveire  I'm still working on this I have just one issue from your lit that 
is failing (see below), but I wanted to capture the other changes in the review.

  const Foo>* p = const_cast>*>(&ffi);


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

https://reviews.llvm.org/D69764



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


[clang] d0da5d2 - Change default traversal in AST Matchers to ignore invisible nodes

2020-05-25 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2020-05-25T00:18:54+01:00
New Revision: d0da5d2bbe8305d06dc01a98706fd73e11e24a9f

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

LOG: Change default traversal in AST Matchers to ignore invisible nodes

This makes many scenarios simpler by not requiring the user to write
ignoringImplicit() all the time, nor to account for non-visible
cxxConstructExpr() and cxxMemberCalExpr() nodes. This is also, in part,
inclusive of the equivalent of adding a use of ignoringParenImpCasts()
between all expr()-related matchers in an expression.

The pre-existing traverse(TK_AsIs, ...) matcher can be used to explcitly
match on implicit/invisible nodes. See

  http://lists.llvm.org/pipermail/cfe-dev/2019-December/064143.html

for more

Reviewers: aaron.ballman

Subscribers: cfe-commits

Tags: #clang

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

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/AST/ParentMapContext.h

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 16f5915856fd..c38ff0e36790 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -246,7 +246,14 @@ release of Clang. Users of the build system should adjust 
accordingly.
 AST Matchers
 
 
-- ...
+- Traversal in AST Matchers was simplified to use the
+  ``TK_IgnoreUnlessSpelledInSource`` mode by default, instead of ``TK_AsIs``.
+  This means that many uses of the ``ignoringImplicit()`` and similar matchers
+  is no longer necessary.  Clients of AST Matchers which wish to match on
+  implicit AST nodes can wrap their matcher in ``traverse(TK_AsIs, ...)`` or
+  use ``TraversalKindScope`` if appropriate.  The ``clang-query`` tool also
+  uses ``IgnoreUnlessSpelledInSource`` by default.  The mode can be changed
+  using ``set traversal AsIs`` in the ``clang-query`` environment.
 
 clang-format
 

diff  --git a/clang/include/clang/AST/ParentMapContext.h 
b/clang/include/clang/AST/ParentMapContext.h
index be4d75df7b99..5f9936b28e8f 100644
--- a/clang/include/clang/AST/ParentMapContext.h
+++ b/clang/include/clang/AST/ParentMapContext.h
@@ -67,7 +67,7 @@ class ParentMapContext {
 private:
   ASTContext &ASTCtx;
   class ParentMap;
-  TraversalKind Traversal = TK_AsIs;
+  TraversalKind Traversal = TK_IgnoreUnlessSpelledInSource;
   std::unique_ptr Parents;
 };
 



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


[PATCH] D80499: Remove obsolete ignore*() matcher uses

2020-05-25 Thread Stephen Kelly via Phabricator via cfe-commits
steveire created this revision.
steveire added a reviewer: aaron.ballman.
Herald added subscribers: cfe-commits, arphaman, kbarton, nemanjai.
Herald added a project: clang.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D80499

Files:
  clang-tools-extra/clang-tidy/abseil/DurationAdditionCheck.cpp
  clang-tools-extra/clang-tidy/abseil/DurationConversionCastCheck.cpp
  clang-tools-extra/clang-tidy/abseil/DurationFactoryScaleCheck.cpp
  clang-tools-extra/clang-tidy/abseil/DurationRewriter.cpp
  clang-tools-extra/clang-tidy/abseil/DurationUnnecessaryConversionCheck.cpp
  clang-tools-extra/clang-tidy/abseil/StringFindStartswithCheck.cpp
  
clang-tools-extra/clang-tidy/bugprone/MisplacedPointerArithmeticInAllocCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/MoveForwardingReferenceCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/SizeofContainerCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/SizeofExpressionCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/StringConstructorCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/StringIntegerAssignmentCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/StringLiteralWithEmbeddedNulCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/SuspiciousEnumUsageCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/SuspiciousMissingCommaCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/TerminatingContinueCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.cpp
  
clang-tools-extra/clang-tidy/cppcoreguidelines/ProBoundsConstantArrayIndexCheck.cpp
  
clang-tools-extra/clang-tidy/cppcoreguidelines/ProBoundsPointerArithmeticCheck.cpp
  clang-tools-extra/clang-tidy/google/ExplicitMakePairCheck.cpp
  clang-tools-extra/clang-tidy/hicpp/MultiwayPathsCoveredCheck.cpp
  clang-tools-extra/clang-tidy/hicpp/SignedBitwiseCheck.cpp
  clang-tools-extra/clang-tidy/misc/StaticAssertCheck.cpp
  clang-tools-extra/clang-tidy/misc/UnconventionalAssignOperatorCheck.cpp
  clang-tools-extra/clang-tidy/misc/UniqueptrResetReleaseCheck.cpp
  clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
  clang-tools-extra/clang-tidy/modernize/UseUncaughtExceptionsCheck.cpp
  clang-tools-extra/clang-tidy/performance/FasterStringFindCheck.cpp
  
clang-tools-extra/clang-tidy/performance/InefficientStringConcatenationCheck.cpp
  clang-tools-extra/clang-tidy/performance/InefficientVectorOperationCheck.cpp
  clang-tools-extra/clang-tidy/readability/ContainerSizeEmptyCheck.cpp
  clang-tools-extra/clang-tidy/readability/ElseAfterReturnCheck.cpp
  clang-tools-extra/clang-tidy/readability/RedundantSmartptrGetCheck.cpp
  clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
  clang-tools-extra/clang-tidy/readability/SimplifySubscriptExprCheck.cpp
  clang-tools-extra/clang-tidy/readability/UniqueptrDeleteReleaseCheck.cpp

Index: clang-tools-extra/clang-tidy/readability/UniqueptrDeleteReleaseCheck.cpp
===
--- clang-tools-extra/clang-tidy/readability/UniqueptrDeleteReleaseCheck.cpp
+++ clang-tools-extra/clang-tidy/readability/UniqueptrDeleteReleaseCheck.cpp
@@ -27,11 +27,11 @@
  hasName("std::default_delete")));
 
   Finder->addMatcher(
-  cxxDeleteExpr(has(ignoringParenImpCasts(cxxMemberCallExpr(
-on(expr(hasType(UniquePtrWithDefaultDelete),
-unless(hasType(IsSusbstituted)))
-   .bind("uptr")),
-callee(cxxMethodDecl(hasName("release")))
+  cxxDeleteExpr(
+  has(cxxMemberCallExpr(on(expr(hasType(UniquePtrWithDefaultDelete),
+unless(hasType(IsSusbstituted)))
+   .bind("uptr")),
+callee(cxxMethodDecl(hasName("release"))
   .bind("delete"),
   this);
 }
Index: clang-tools-extra/clang-tidy/readability/SimplifySubscriptExprCheck.cpp
===
--- clang-tools-extra/clang-tidy/readability/SimplifySubscriptExprCheck.cpp
+++ clang-tools-extra/clang-tidy/readability/SimplifySubscriptExprCheck.cpp
@@ -32,7 +32,7 @@
   llvm::SmallVector(Types.begin(), Types.end()));
 
   Finder->addMatcher(
-  arraySubscriptExpr(hasBase(ignoringParenImpCasts(
+  arraySubscriptExpr(hasBase(
   cxxMemberCallExpr(
   has(memberExpr().bind("member")),
   on(hasType(qualType(
@@ -40,7 +40,7 @@
hasDescendant(substTemplateTypeParmType(,
   anyOf(TypesMatcher, pointerType(pointee(TypesMatcher)),
   callee(namedDecl(hasName("data"
-  .bind("call",
+  .bind("call"))),
   this);
 }
 
Index: clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp

[clang] 52b03aa - [clang-format][PR46043] Parse git config w/ implicit values

2020-05-25 Thread Jake Merdich via cfe-commits

Author: Jake Merdich
Date: 2020-05-24T20:32:54-04:00
New Revision: 52b03aaa22f650bbd36ceb3bdae4699dae71b2b8

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

LOG: [clang-format][PR46043] Parse git config w/ implicit values

Summary:
https://bugs.llvm.org/show_bug.cgi?id=46043

Git's config is generally of the format 'key=val', but a setting
'key=true' can be written as just 'key'.  The git-clang-format script
expects a value and crashes in this case; this change handles implicit
'true' values in the script.

Reviewers: MyDeveloperDay, krasimir, sammccall

Subscribers: cfe-commits

Tags: #clang

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

Added: 


Modified: 
clang/tools/clang-format/git-clang-format

Removed: 




diff  --git a/clang/tools/clang-format/git-clang-format 
b/clang/tools/clang-format/git-clang-format
index abbe3b7b97c6..f3cd585e7f4a 100755
--- a/clang/tools/clang-format/git-clang-format
+++ b/clang/tools/clang-format/git-clang-format
@@ -192,7 +192,12 @@ def load_git_config(non_string_options=None):
   out = {}
   for entry in run('git', 'config', '--list', '--null').split('\0'):
 if entry:
-  name, value = entry.split('\n', 1)
+  if '\n' in entry:
+name, value = entry.split('\n', 1)
+  else:
+# A setting with no '=' ('\n' with --null) is implicitly 'true'
+name = entry
+value = 'true'
   if name in non_string_options:
 value = run('git', 'config', non_string_options[name], name)
   out[name] = value



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


[PATCH] D72534: Change default traversal in AST Matchers to ignore invisible nodes

2020-05-25 Thread Stephen Kelly via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGd0da5d2bbe83: Change default traversal in AST Matchers to 
ignore invisible nodes (authored by stephenkelly).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D72534

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/AST/ParentMapContext.h


Index: clang/include/clang/AST/ParentMapContext.h
===
--- clang/include/clang/AST/ParentMapContext.h
+++ clang/include/clang/AST/ParentMapContext.h
@@ -67,7 +67,7 @@
 private:
   ASTContext &ASTCtx;
   class ParentMap;
-  TraversalKind Traversal = TK_AsIs;
+  TraversalKind Traversal = TK_IgnoreUnlessSpelledInSource;
   std::unique_ptr Parents;
 };
 
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -246,7 +246,14 @@
 AST Matchers
 
 
-- ...
+- Traversal in AST Matchers was simplified to use the
+  ``TK_IgnoreUnlessSpelledInSource`` mode by default, instead of ``TK_AsIs``.
+  This means that many uses of the ``ignoringImplicit()`` and similar matchers
+  is no longer necessary.  Clients of AST Matchers which wish to match on
+  implicit AST nodes can wrap their matcher in ``traverse(TK_AsIs, ...)`` or
+  use ``TraversalKindScope`` if appropriate.  The ``clang-query`` tool also
+  uses ``IgnoreUnlessSpelledInSource`` by default.  The mode can be changed
+  using ``set traversal AsIs`` in the ``clang-query`` environment.
 
 clang-format
 


Index: clang/include/clang/AST/ParentMapContext.h
===
--- clang/include/clang/AST/ParentMapContext.h
+++ clang/include/clang/AST/ParentMapContext.h
@@ -67,7 +67,7 @@
 private:
   ASTContext &ASTCtx;
   class ParentMap;
-  TraversalKind Traversal = TK_AsIs;
+  TraversalKind Traversal = TK_IgnoreUnlessSpelledInSource;
   std::unique_ptr Parents;
 };
 
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -246,7 +246,14 @@
 AST Matchers
 
 
-- ...
+- Traversal in AST Matchers was simplified to use the
+  ``TK_IgnoreUnlessSpelledInSource`` mode by default, instead of ``TK_AsIs``.
+  This means that many uses of the ``ignoringImplicit()`` and similar matchers
+  is no longer necessary.  Clients of AST Matchers which wish to match on
+  implicit AST nodes can wrap their matcher in ``traverse(TK_AsIs, ...)`` or
+  use ``TraversalKindScope`` if appropriate.  The ``clang-query`` tool also
+  uses ``IgnoreUnlessSpelledInSource`` by default.  The mode can be changed
+  using ``set traversal AsIs`` in the ``clang-query`` environment.
 
 clang-format
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D80488: Teach `-fsanitize=fuzzer` to respect `-static` and `-static-libstdc++` when adding C++ standard libraries.

2020-05-25 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added inline comments.



Comment at: clang/lib/Driver/ToolChains/CommonArgs.cpp:754
+  if (OnlyLibstdcxxStatic)
+CmdArgs.push_back("-Bstatic");
   TC.AddCXXStdlibLibArgs(Args, CmdArgs);

This is correct. If GNU ld<2.25 compatibility is not needed, `--push-state`, 
`-Bstatic`, link, `--pop-state`


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80488



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


[PATCH] D80440: [OpenCL] Prevent fused mul and add by default

2020-05-25 Thread Serge Pavlov via Phabricator via cfe-commits
sepavloff added a comment.

Contraction is just an optimization technique. Unless a user explicitly 
requests strict FP semantics, contraction does not break C++ semantics.


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

https://reviews.llvm.org/D80440



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


[PATCH] D70411: [analyzer] CERT STR rule checkers: STR31-C

2020-05-25 Thread Csaba Dabis via Phabricator via cfe-commits
Charusso updated this revision to Diff 265959.
Charusso retitled this revision from "[analyzer] CERT: STR31-C" to "[analyzer] 
CERT STR rule checkers: STR31-C".
Charusso added a comment.

- Refactor.


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

https://reviews.llvm.org/D70411

Files:
  clang/docs/analyzer/checkers.rst
  clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
  clang/lib/StaticAnalyzer/Checkers/AllocationState.h
  clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
  clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/cert/StrChecker.cpp
  clang/test/Analysis/Inputs/system-header-simulator.h
  clang/test/Analysis/cert/str31-c-false-positive-suppression.cpp
  clang/test/Analysis/cert/str31-c-notes.cpp
  clang/test/Analysis/cert/str31-c.cpp

Index: clang/test/Analysis/cert/str31-c.cpp
===
--- /dev/null
+++ clang/test/Analysis/cert/str31-c.cpp
@@ -0,0 +1,184 @@
+// RUN: %clang_analyze_cc1 \
+// RUN:  -analyzer-checker=core,unix,alpha.security.cert.str.31c \
+// RUN:  -verify %s
+
+// See the examples on the page of STR31-C:
+// https://wiki.sei.cmu.edu/confluence/x/sNUxBQ
+
+#include "../Inputs/system-header-simulator.h"
+
+typedef __SIZE_TYPE__ size_t;
+
+void free(void *memblock);
+void *malloc(size_t size);
+
+namespace test_gets_bad {
+#define BUFFER_SIZE 1024
+
+void func(void) {
+  char buf[BUFFER_SIZE];
+  if (gets(buf)) {
+// expected-warning@-1 {{'gets' could write outside of 'buf'}}
+  }
+}
+} // namespace test_gets_bad
+
+namespace test_gets_good {
+enum { BUFFERSIZE = 32 };
+
+void func(void) {
+  char buff[BUFFERSIZE];
+
+  if (fgets(buff, sizeof(buff), stdin)) {
+  }
+}
+} // namespace test_gets_good
+
+namespace test_sprintf_bad {
+void func(const char *name) {
+  char buf[128];
+  sprintf(buf, "%s.txt", name);
+  // expected-warning@-1 {{'sprintf' could write outside of 'buf'}}
+}
+} // namespace test_sprintf_bad
+
+namespace test_sprintf_good {
+void func(const char *name) {
+  char buff[128];
+  snprintf(buff, sizeof(buff), "%s.txt", name);
+}
+} // namespace test_sprintf_good
+
+namespace test_fscanf_bad {
+enum { BUF_LENGTH = 1024 };
+
+void get_data(void) {
+  char buf[BUF_LENGTH];
+  fscanf(stdin, "%s", buf);
+  // expected-warning@-1 {{'fscanf' could write outside of 'buf'}}
+}
+} // namespace test_fscanf_bad
+
+namespace test_fscanf_good {
+enum { BUF_LENGTH = 1024 };
+
+void get_data(void) {
+  char buff[BUF_LENGTH];
+  fscanf(stdin, "%1023s", buff);
+}
+} // namespace test_fscanf_good
+
+namespace test_strcpy_bad {
+int main(int argc, char *argv[]) {
+  const char *const name = (argc && argv[0]) ? argv[0] : "";
+  char prog_name[128];
+  strcpy(prog_name, name);
+  // expected-warning@-1 {{'strcpy' could write outside of 'prog_name'}}
+  return 0;
+}
+
+void func(void) {
+  char buff[256];
+  char *editor = getenv("EDITOR");
+  if (editor != NULL) {
+strcpy(buff, editor);
+// expected-warning@-1 {{'strcpy' could write outside of 'buff'}}
+  }
+}
+} // namespace test_strcpy_bad
+
+namespace test_strcpy_good {
+int main(int argc, char *argv[]) {
+  const char *const name = (argc && argv[0]) ? argv[0] : "";
+  char *prog_name2 = (char *)malloc(strlen(name) + 1);
+  if (prog_name2 != NULL) {
+strcpy(prog_name2, name);
+  }
+
+  free(prog_name2);
+  return 0;
+}
+
+void func(void) {
+  char *buff2;
+  char *editor = getenv("EDITOR");
+  if (editor != NULL) {
+size_t len = strlen(editor) + 1;
+buff2 = (char *)malloc(len);
+if (buff2 != NULL) {
+  strcpy(buff2, editor);
+}
+
+free(buff2);
+  }
+}
+} // namespace test_strcpy_good
+
+//===--===//
+// The following are from the rule's page which we do not handle yet.
+//===--===//
+
+namespace test_loop_index_bad {
+void copy(size_t n, char src[n], char dest[n]) {
+  size_t i;
+
+  for (i = 0; src[i] && (i < n); ++i) {
+dest[i] = src[i];
+  }
+  dest[i] = '\0';
+}
+} // namespace test_loop_index_bad
+
+namespace test_loop_index_good {
+void copy(size_t n, char src[n], char dest[n]) {
+  size_t i;
+
+  for (i = 0; src[i] && (i < n - 1); ++i) {
+dest[i] = src[i];
+  }
+  dest[i] = '\0';
+}
+} // namespace test_loop_index_good
+
+namespace test_getchar_bad {
+enum { BUFFERSIZE = 32 };
+
+void func(void) {
+  char buf[BUFFERSIZE];
+  char *p;
+  int ch;
+  p = buf;
+  while ((ch = getchar()) != '\n' && ch != EOF) {
+*p++ = (char)ch;
+  }
+  *p++ = 0;
+  if (ch == EOF) {
+/* Handle EOF or error */
+  }
+}
+} // namespace test_getchar_bad
+
+namespace test_getchar_good {
+enum { BUFFERSIZE = 32 };
+
+void func(void) {
+  char buf[BUFFERSIZE];
+  int ch;
+  size_t index = 0;
+  size_t chars_read = 0;
+
+  while ((ch = getchar()) != '\n' && ch != EOF) {
+if (index < sizeof(buf) - 1) {
+  buf[index++] = (char)ch;
+}
+ 

[PATCH] D71033: [analyzer] CERT STR rule checkers: STR32-C

2020-05-25 Thread Csaba Dabis via Phabricator via cfe-commits
Charusso updated this revision to Diff 265962.
Charusso retitled this revision from "[analyzer] CERT: STR32-C" to "[analyzer] 
CERT STR rule checkers: STR32-C".
Charusso added a comment.
Herald added subscribers: ASDenysPetrov, martong, steakhal.

- Refactor.
- State out explicitly whether the Analyzer models the dynamic size.


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

https://reviews.llvm.org/D71033

Files:
  clang/docs/analyzer/checkers.rst
  clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicSize.h
  clang/lib/StaticAnalyzer/Checkers/cert/StrChecker.cpp
  clang/lib/StaticAnalyzer/Core/DynamicSize.cpp
  clang/test/Analysis/Inputs/system-header-simulator.h
  clang/test/Analysis/cert/str32-c-notes.cpp
  clang/test/Analysis/cert/str32-c.cpp
  clang/test/Analysis/malloc.c

Index: clang/test/Analysis/malloc.c
===
--- clang/test/Analysis/malloc.c
+++ clang/test/Analysis/malloc.c
@@ -9,21 +9,6 @@
 
 void clang_analyzer_eval(int);
 
-// Without -fms-compatibility, wchar_t isn't a builtin type. MSVC defines
-// _WCHAR_T_DEFINED if wchar_t is available. Microsoft recommends that you use
-// the builtin type: "Using the typedef version can cause portability
-// problems", but we're ok here because we're not actually running anything.
-// Also of note is this cryptic warning: "The wchar_t type is not supported
-// when you compile C code".
-//
-// See the docs for more:
-// https://msdn.microsoft.com/en-us/library/dh8che7s.aspx
-#if !defined(_WCHAR_T_DEFINED)
-// "Microsoft implements wchar_t as a two-byte unsigned value"
-typedef unsigned short wchar_t;
-#define _WCHAR_T_DEFINED
-#endif // !defined(_WCHAR_T_DEFINED)
-
 typedef __typeof(sizeof(int)) size_t;
 void *malloc(size_t);
 void *alloca(size_t);
Index: clang/test/Analysis/cert/str32-c.cpp
===
--- /dev/null
+++ clang/test/Analysis/cert/str32-c.cpp
@@ -0,0 +1,88 @@
+// RUN: %clang_analyze_cc1 \
+// RUN:  -analyzer-checker=core,unix,alpha.security.cert.str.32c \
+// RUN:  -verify %s
+
+// See the examples on the page of STR32-C:
+// https://wiki.sei.cmu.edu/confluence/x/r9UxBQ
+
+#include "../Inputs/system-header-simulator.h"
+
+void *realloc(void *memblock, size_t size);
+
+namespace test_strncpy_bad {
+enum { STR_SIZE = 32 };
+
+size_t func(const char *source) {
+  char c_str[STR_SIZE];
+  size_t ret = 0;
+
+  if (source) {
+c_str[sizeof(c_str) - 1] = '\0';
+strncpy(c_str, source, sizeof(c_str));
+ret = strlen(c_str);
+// expected-warning@-1 {{'c_str' is not null-terminated}}
+  }
+  return ret;
+}
+} // namespace test_strncpy_bad
+
+namespace test_strncpy_good {
+enum { STR_SIZE = 32 };
+
+size_t func(const char *src) {
+  char c_str[STR_SIZE];
+  size_t ret = 0;
+
+  if (src) {
+strncpy(c_str, src, sizeof(c_str) - 1);
+c_str[sizeof(c_str) - 1] = '\0';
+ret = strlen(c_str);
+  }
+  return ret;
+}
+} // namespace test_strncpy_good
+
+namespace test_realloc_bad {
+wchar_t *cur_msg = NULL;
+size_t cur_msg_size = 1024;
+size_t cur_msg_len = 0;
+
+void lessen_memory_usage(void) {
+  if (cur_msg == NULL)
+return;
+
+  size_t temp_size = cur_msg_size / 2 + 1;
+  wchar_t *temp = (wchar_t *)realloc(cur_msg, temp_size * sizeof(wchar_t));
+  /* temp and cur_msg may no longer be null-terminated */
+  if (temp == NULL)
+return;
+
+  cur_msg = temp;
+  cur_msg_size = temp_size;
+  cur_msg_len = wcslen(cur_msg);
+  // expected-warning@-1 {{'cur_msg' is not null-terminated}}
+}
+} // namespace test_realloc_bad
+
+namespace test_realloc_good {
+wchar_t *cur_msg = NULL;
+size_t cur_msg_size = 1024;
+size_t cur_msg_len = 0;
+
+void lessen_memory_usage(void) {
+  if (cur_msg == NULL)
+return;
+
+  size_t temp_size = cur_msg_size / 2 + 1;
+  wchar_t *temp = (wchar_t *)realloc(cur_msg, temp_size * sizeof(wchar_t));
+  /* temp and cur_msg may no longer be null-terminated */
+  if (temp == NULL)
+return;
+
+  cur_msg = temp;
+  /* Properly null-terminate cur_msg */
+  cur_msg[temp_size - 1] = L'\0';
+  cur_msg_size = temp_size;
+  cur_msg_len = wcslen(cur_msg);
+}
+} // namespace test_realloc_good
Index: clang/test/Analysis/cert/str32-c-notes.cpp
===
--- /dev/null
+++ clang/test/Analysis/cert/str32-c-notes.cpp
@@ -0,0 +1,38 @@
+// RUN: %clang_analyze_cc1 \
+// RUN:  -analyzer-checker=core,unix,alpha.security.cert.str.32c \
+// RUN:  -analyzer-output=text -verify %s
+
+// See the examples on the page of STR32-C:
+// https://wiki.sei.cmu.edu/confluence/x/r9UxBQ
+
+#include "../Inputs/system-header-simulator.h"
+
+void *realloc(void *memblock, size_t size);
+
+namespace test_realloc_bad {
+size_t cur_msg_size = 1024;
+size_t cur_msg_len = 0;
+
+void lessen_memory_usage(wchar_t *cur_msg) {
+  if (cur_msg == NULL) {
+// expected-note@-1 {{Assuming 'cur_msg' is 

[PATCH] D71155: [analyzer] CERT STR rule checkers: STR30-C

2020-05-25 Thread Csaba Dabis via Phabricator via cfe-commits
Charusso updated this revision to Diff 265963.
Charusso retitled this revision from "[analyzer] CERT: STR30-C" to "[analyzer] 
CERT STR rule checkers: STR30-C".
Charusso added a comment.
Herald added subscribers: ASDenysPetrov, martong, steakhal.

- Refactor.


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

https://reviews.llvm.org/D71155

Files:
  clang/docs/analyzer/checkers.rst
  clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
  clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/cert/StrChecker.cpp
  clang/test/Analysis/cert/str30-c-notes.cpp
  clang/test/Analysis/cert/str30-c.cpp

Index: clang/test/Analysis/cert/str30-c.cpp
===
--- /dev/null
+++ clang/test/Analysis/cert/str30-c.cpp
@@ -0,0 +1,58 @@
+// RUN: %clang_analyze_cc1 \
+// RUN:  -analyzer-checker=core,unix,alpha.security.cert.str.30c \
+// RUN:  -verify %s
+
+// See the examples on the page of STR30-C:
+// https://wiki.sei.cmu.edu/confluence/x/VtYxBQ
+
+#include "../Inputs/system-header-simulator.h"
+
+typedef __SIZE_TYPE__ size_t;
+typedef __typeof__((char *)0 - (char *)0) ptrdiff_t;
+
+void free(void *memblock);
+void *malloc(size_t size);
+
+char *strrchr(const char *str, int c);
+int puts(const char *str);
+
+namespace test_strrchr_bad {
+const char *get_dirname(const char *pathname) {
+  char *slash;
+  slash = strrchr(pathname, '/');
+  if (slash) {
+*slash = '\0'; /* Undefined behavior */
+// expected-warning@-1 {{'*slash' is pointing to a constant string}}
+  }
+  return pathname;
+}
+
+int main(void) {
+  puts(get_dirname(__FILE__));
+  return 0;
+}
+} // namespace test_strrchr_bad
+
+namespace test_strrchr_good {
+char *get_dirname(const char *pathname, char *dirname, size_t size) {
+  const char *slash;
+  slash = strrchr(pathname, '/');
+  if (slash) {
+ptrdiff_t slash_idx = slash - pathname;
+if ((size_t)slash_idx < size) {
+  memcpy(dirname, pathname, slash_idx);
+  dirname[slash_idx] = '\0';
+  return dirname;
+}
+  }
+  return 0;
+}
+
+int main(void) {
+  char dirname[260];
+  if (get_dirname(__FILE__, dirname, sizeof(dirname))) {
+puts(dirname);
+  }
+  return 0;
+}
+} // namespace test_strrchr_good
Index: clang/test/Analysis/cert/str30-c-notes.cpp
===
--- /dev/null
+++ clang/test/Analysis/cert/str30-c-notes.cpp
@@ -0,0 +1,43 @@
+// RUN: %clang_analyze_cc1 \
+// RUN:  -analyzer-checker=core,unix,alpha.security.cert.str.30c \
+// RUN:  -analyzer-output=text -verify %s
+
+// See the examples on the page of STR30-C:
+// https://wiki.sei.cmu.edu/confluence/x/VtYxBQ
+
+#include "../Inputs/system-header-simulator.h"
+
+typedef __SIZE_TYPE__ size_t;
+
+void free(void *memblock);
+void *malloc(size_t size);
+
+char *strrchr(const char *str, int c);
+int puts(const char *str);
+
+namespace test_strrchr_bad {
+const char *get_dirname(const char *pathname) {
+  char *slash;
+  slash = strrchr(pathname, '/');
+  // expected-note@-1 {{'strrchr' returns a pointer to the constant 'pathname'}}
+
+  slash = strrchr(slash, '/');
+  // expected-note@-1 {{'strrchr' returns a pointer to the constant 'slash'}}
+
+  if (slash) {
+// expected-note@-1 {{'slash' is non-null}}
+// expected-note@-2 {{Taking true branch}}
+
+*slash = '\0'; /* Undefined behavior */
+// expected-note@-1 {{'*slash' is pointing to a constant string}}
+// expected-warning@-2 {{'*slash' is pointing to a constant string}}
+  }
+  return pathname;
+}
+
+int main(void) {
+  puts(get_dirname(__FILE__));
+  // expected-note@-1 {{Calling 'get_dirname'}}
+  return 0;
+}
+} // namespace test_strrchr_bad
Index: clang/lib/StaticAnalyzer/Checkers/cert/StrChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/cert/StrChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/cert/StrChecker.cpp
@@ -12,6 +12,9 @@
 // - https://wiki.sei.cmu.edu/confluence/x/ptUxBQ
 //
 //  This checker is a base checker which consist of the following checkers:
+//  - STR30-C: Do not attempt to modify string literals:
+// - https://wiki.sei.cmu.edu/confluence/x/VtYxBQ
+//
 //  - STR31-C: Guarantee that storage for strings has sufficient space for
 //character data and the null terminator:
 // - https://wiki.sei.cmu.edu/confluence/x/sNUxBQ
@@ -83,6 +86,17 @@
 
   /// \{
   /// Check the function calls defined in 'CDM'.
+  /// STR30-C.
+  void checkMemchr(const CallEvent &Call, const CallContext &CallC,
+   CheckerContext &C) const;
+  void checkStrchr(const CallEvent &Call, const CallContext &CallC,
+   CheckerContext &C) const;
+  void checkStrrchr(const CallEvent &Call, const CallContext &CallC,
+CheckerContext &C) const;
+  void checkStrstr(const CallEvent &Call, const CallContext &CallC,
+   CheckerContext &C) const;
+  void c

[PATCH] D71155: [analyzer] CERT STR rule checkers: STR30-C

2020-05-25 Thread Csaba Dabis via Phabricator via cfe-commits
Charusso added a comment.

In D71155#1854908 , @NoQ wrote:

> Let's separate `CStringChecker` improvements into a separate patch and have a 
> separate set of tests for it.


I was thinking about creating tests, but I cannot figure out any better testing 
than a live checker that uses such features of `CStringChecker`. Also I have 
not found any real world issues with the checker, so I could not really test 
its real behavior.


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

https://reviews.llvm.org/D71155



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


[PATCH] D70805: [analyzer] SValHasDescendant: Determine whether the SVal has an SVal descendant

2020-05-25 Thread Csaba Dabis via Phabricator via cfe-commits
Charusso abandoned this revision.
Charusso added a comment.
Herald added subscribers: ASDenysPetrov, martong, steakhal.

Way more sophisticated matching: https://reviews.llvm.org/D77745


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

https://reviews.llvm.org/D70805



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


[PATCH] D79961: [PGO] Fix computation of fuction Hash

2020-05-25 Thread serge via Phabricator via cfe-commits
serge-sans-paille added a comment.

Up?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79961



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


[PATCH] D80507: [clangd] Enable cross-file-rename by default.

2020-05-25 Thread Haojian Wu via Phabricator via cfe-commits
hokein created this revision.
hokein added a reviewer: sammccall.
Herald added subscribers: usaxena95, kadircet, arphaman, jkorous, MaskRay, 
ilya-biryukov.
Herald added a project: clang.

The cross-file rename feature is stable enough to enable it (has been
rolled out internally for a few weeks).


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D80507

Files:
  clang-tools-extra/clangd/tool/ClangdMain.cpp


Index: clang-tools-extra/clangd/tool/ClangdMain.cpp
===
--- clang-tools-extra/clangd/tool/ClangdMain.cpp
+++ clang-tools-extra/clangd/tool/ClangdMain.cpp
@@ -274,11 +274,8 @@
 opt CrossFileRename{
 "cross-file-rename",
 cat(Features),
-desc("Enable cross-file rename feature. Note that this feature is "
- "experimental and may lead to broken code or incomplete rename "
- "results"),
-init(false),
-Hidden,
+desc("Enable cross-file rename feature."),
+init(true),
 };
 
 opt RecoveryAST{


Index: clang-tools-extra/clangd/tool/ClangdMain.cpp
===
--- clang-tools-extra/clangd/tool/ClangdMain.cpp
+++ clang-tools-extra/clangd/tool/ClangdMain.cpp
@@ -274,11 +274,8 @@
 opt CrossFileRename{
 "cross-file-rename",
 cat(Features),
-desc("Enable cross-file rename feature. Note that this feature is "
- "experimental and may lead to broken code or incomplete rename "
- "results"),
-init(false),
-Hidden,
+desc("Enable cross-file rename feature."),
+init(true),
 };
 
 opt RecoveryAST{
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


  1   2   3   >